diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 129d1c01..d2b079a1 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -204,6 +204,7 @@ pub fn run() {
settings::app_theme,
settings::set_theme,
updater::update_check,
+ updater::update_show,
updater::update_pending,
updater::update_fit,
updater::update_copy_command,
diff --git a/src-tauri/src/notices/rules.rs b/src-tauri/src/notices/rules.rs
index 707125ea..fc76ddce 100644
--- a/src-tauri/src/notices/rules.rs
+++ b/src-tauri/src/notices/rules.rs
@@ -48,6 +48,8 @@ const UPSTREAMS: &str = "upstreams";
const SECURITY: &str = "security";
const MCP: &str = "mcp";
const SETTINGS: &str = "settings";
+/// 设置页的「网关监听」一节(`settings:<节>`,界面滚到那一节)
+const LISTEN_SETTINGS: &str = "settings:listen";
/// 一个键默认落在哪一页(那一条已经不在列表里时用)。按键的种类,也就是冒号前那段
pub fn default_view(key: &str) -> &'static str {
@@ -306,7 +308,8 @@ pub fn from_event(ev: &Event) -> Vec {
format!("{}网关仍在 {at} 上监听。", core_text::text(e)),
format!("{} The gateway is still listening on {at}.", e.text)
))
- .view(SETTINGS),
+ // 设置页并滚到「网关监听」那一节:未生效的原因也写在那里
+ .view(LISTEN_SETTINGS),
]
}
Event::CredentialRotated {
diff --git a/src-tauri/src/notices/tests.rs b/src-tauri/src/notices/tests.rs
index 280f29fb..96dd5c8b 100644
--- a/src-tauri/src/notices/tests.rs
+++ b/src-tauri/src/notices/tests.rs
@@ -795,7 +795,7 @@ fn a_listen_change_that_did_not_take_is_raised_and_one_that_did_clears_it() {
s.body,
"127.0.0.1:8080 已被其他程序占用。网关仍在 127.0.0.1:18790 上监听。"
);
- assert_eq!(s.view, Some("settings"));
+ assert_eq!(s.view, Some("settings:listen"));
});
let ok = rules::from_event(&tw_api::Event::ListenChanged {
id: 2,
diff --git a/src-tauri/src/updater.rs b/src-tauri/src/updater.rs
index 8e797ac6..11f0afc1 100644
--- a/src-tauri/src/updater.rs
+++ b/src-tauri/src/updater.rs
@@ -241,7 +241,7 @@ pub(crate) fn show_pending_update(app: &tauri::AppHandle) {
}
}
-/// 菜单里的「检查更新…」和设置页的「立即检查」查的是同一处
+/// 菜单里的「检查更新…」和设置页「关于」里的「检查更新」查的是同一处
pub(crate) async fn find_update(app: &tauri::AppHandle) -> Result
- );
-}
-
-/**
- * 关于。
- *
- * **排查时最先要问的就是这几个**:哪个版本、数据在哪、core 从哪儿加载的。
- * 之前它们只在日志里,而用户在交出诊断包之前根本看不到自己要交什么。
- */
-function About({ remote }: { remote: RemoteCore | null }) {
- const t = useText(configText);
- const rt = useText(remoteText);
- const [info, setInfo] = useState | null>(null);
- useEffect(() => {
- void invoke>("app_info")
- .then(setInfo)
- .catch(() => {});
- }, []);
- if (!info) return null;
- // 连着远程时说连的是哪一台、它的 core 是哪一版;本机 core 的二进制那时不在用
- const rows: [string, string][] = remote
- ? [
- [t.version, info.version ?? "—"],
- [rt.connection, `${remote.name} · ${remote.addr}`],
- [rt.serverCore, remote.core ?? "—"],
- [t.dataDir, info.data_dir ?? "—"],
- ]
- : [
- [t.version, info.version ?? "—"],
- [t.dataDir, info.data_dir ?? "—"],
- [t.coreBin, info.core_bin ?? "—"],
- ];
- return (
-
- {t.aboutTitle}
-
- {rows.map(([k, v]) => (
-
- {/* 96px:中文的标签只要 80,英文的 Data directory 要 86 —— 窄了会折成两行 */}
-
- {k}
- -
- {v}
-
-
- ))}
-
-
- );
-}
-
-/**
- * 诊断包(M6+)。
- *
- * 遇到问题时一次性交出「我这儿是什么情况」,省掉来回问一轮(版本?配置?
- * 哪家上游?)—— 而每一趟都可能问漏。
- *
- * **里面的东西全部脱敏过,但仍然要求用户自己看一眼再交出去。**我们是个
- * 看得见所有 API key 的网关,这一步值得多花十秒。
- */
-function Diagnostics() {
- const t = useText(configText);
- const [path, setPath] = useState(null);
- const [busy, setBusy] = useState(false);
-
- return (
-
- {t.diagnosticsTitle}
-
- {t.diagnosticsBody((label) => (
-
-
- {label}
-
-
- ))}
-
-
- {path && (
-
- {t.saved(
{path})}
-
- {t.review((text) => (
- {text}
- ))}
-
-
- )}
-
- );
-}
-
-/**
- * 完全卸载(第二层的第三个入口)。
- *
- * **macOS 上删除应用没有卸载钩子。**拖进废纸篓就是拖进废纸篓,我们没有
- * 任何机会做清理 —— 而那时五个客户端的 `base_url` 全都指向一个已经没有
- * 东西在听的端口,所有 AI 客户端同时失效,用户很可能已经忘了是什么改的。
- *
- * 所以这个入口必须存在,而且要在他还没删应用的时候就看得见。
- *
- * 顺序是**先还原、再注销自启、最后才提删数据** —— 反过来的话,中途失败
- * 会留下一个「客户端还指着一个不在的端口」的状态,而那正是这一整节要
- * 防的事。
- */
-function Uninstall({ remote }: { remote: RemoteCore | null }) {
- const t = useText(configText);
- const rt = useText(remoteText);
- const common = useText(commonText);
- const [step, setStep] = useState<"idle" | "ask" | "done">("idle");
- const [drop, setDrop] = useState(false);
- const [log, setLog] = useState([]);
- const [busy, setBusy] = useState(false);
-
- if (step === "done") {
- return (
-
- {t.uninstalled}
-
- {log.map((l, i) => (
- - · {l}
- ))}
-
-
- );
- }
-
- return (
-
- {t.uninstallTitle}
- {step === "idle" ? (
-
-
- {t.uninstallIntro((text) => (
- {text}
- ))}
- {remote && {rt.uninstallServer(remote.name)}}
-
-
-
- ) : (
-
-
{t.willDo}
-
- - · {t.restoreClients}
- - · {t.stopAutostart}
-
-
- setDrop(c === true)}
- />
- {/* **默认不删。**请求历史和成本记录是用户自己的东西,而
- 「删了才发现还想看」是不可逆的 */}
- {t.dropData}
-
-
-
-
-
-
- )}
-
- );
-}
diff --git a/src/Language.i18n.ts b/src/Language.i18n.ts
deleted file mode 100644
index b4aea707..00000000
--- a/src/Language.i18n.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { messages } from "@/i18n";
-
-export const languageText = messages(
- {
- title: "语言",
- system: (name: string) => `跟随系统(${name})`,
- saveFailed: "无法保存语言设置",
- },
- {
- title: "Language",
- system: (name: string) => `System default (${name})`,
- saveFailed: "The language setting could not be saved",
- },
-);
diff --git a/src/Language.tsx b/src/Language.tsx
deleted file mode 100644
index 5969fa96..00000000
--- a/src/Language.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-import { useEffect, useState } from "react";
-import { invoke } from "@tauri-apps/api/core";
-import { toast } from "sonner";
-import { Field } from "@/ui/field";
-import { NativeSelect, NativeSelectOption } from "@/ui/native-select";
-import { LANG_NAMES, setLang, useText, type Lang } from "@/i18n";
-import { errorText } from "@/i18n/core.i18n";
-import { languageText } from "./Language.i18n";
-
-/** 现在用的、设置里选的(`null` 是跟随系统)、系统的 */
-interface LanguageView {
- current: Lang;
- setting: Lang | null;
- system: Lang;
-}
-
-/**
- * 设置页的语言。
- *
- * **跟随系统是一个选项,不是一个开关。**只有两种语言,三个选项放进一个
- * 下拉框就说完了;括号里写出系统现在是哪种,选它之前就知道会得到什么。
- */
-export function LanguageSection() {
- const t = useText(languageText);
- const [view, setView] = useState(null);
- useEffect(() => {
- void invoke("app_language").then(setView).catch(() => {});
- }, []);
- if (!view) return null;
-
- return (
-
- {t.title}
-
- {
- const v = e.target.value;
- const setting: Lang | null = v === "zh" || v === "en" ? v : null;
- try {
- const next = await invoke("set_language", { setting });
- setView(next);
- // 事件也会到,这里先换:不让界面等一趟往返
- setLang(next.current);
- } catch (err) {
- toast.error(errorText(err) || t.saveFailed);
- }
- }}
- >
- {t.system(LANG_NAMES[view.system])}
- {LANG_NAMES.zh}
- {LANG_NAMES.en}
-
-
-
- );
-}
diff --git a/src/MenubarSettings.i18n.ts b/src/MenubarSettings.i18n.ts
deleted file mode 100644
index 71a2f199..00000000
--- a/src/MenubarSettings.i18n.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { messages } from "@/i18n";
-
-export const menubarSettingsText = messages(
- {
- title: "菜单栏",
- full: "标识和数值",
- icon: "仅标识",
- numbers: "仅数值",
- },
- {
- title: "Menu Bar",
- full: "Icon and numbers",
- icon: "Icon only",
- numbers: "Numbers only",
- },
-);
diff --git a/src/MenubarSettings.tsx b/src/MenubarSettings.tsx
deleted file mode 100644
index cae701a4..00000000
--- a/src/MenubarSettings.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { useEffect, useState } from "react";
-import { invoke } from "@tauri-apps/api/core";
-import { toast } from "sonner";
-import { Segmented } from "@/ui/segmented";
-import { useText } from "@/i18n";
-import { isMac } from "@/platform";
-import { errorText } from "@/i18n/core.i18n";
-import { menubarSettingsText } from "./MenubarSettings.i18n";
-
-export type MenubarStyle = "full" | "icon" | "numbers";
-
-/**
- * 设置里的「菜单栏」:标识和数值 / 仅标识 / 仅数值。数值是今日 token 和今日费用。
- *
- * 和外观、提醒一样是应用自己的设置,**改了就生效**,不走配置文件的「保存」。
- */
-export default function MenubarSettings() {
- const t = useText(menubarSettingsText);
- const [style, setStyle] = useState(null);
-
- useEffect(() => {
- if (!isMac) return;
- void invoke("menubar_style")
- .then(setStyle)
- .catch(() => {});
- }, []);
-
- // **只有 macOS 有这三档。**别处的通知区只认一张正方形图标(100% DPI 下
- // 16×16),塞不下两行数字 —— 那几行在右键菜单里给。留着一个点了没反应的
- // 选择,比没有这一节糟。
- if (!isMac) return null;
- if (!style) return null;
-
- async function choose(next: MenubarStyle) {
- const before = style;
- // 先画上,以后端返回的为准 —— 存不进去的时候要弹回去
- setStyle(next);
- try {
- setStyle(await invoke("set_menubar_style", { style: next }));
- } catch (e) {
- setStyle(before);
- toast.error(errorText(e));
- }
- }
-
- return (
-
- {t.title}
-
-
- value={style}
- options={[
- { id: "full", label: t.full },
- { id: "icon", label: t.icon },
- { id: "numbers", label: t.numbers },
- ]}
- onChange={(v) => void choose(v)}
- />
-
-
- );
-}
diff --git a/src/NoticeSettings.i18n.ts b/src/NoticeSettings.i18n.ts
deleted file mode 100644
index 4d6b0689..00000000
--- a/src/NoticeSettings.i18n.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { messages } from "@/i18n";
-
-export const noticeSettingsText = messages(
- {
- title: "提醒",
- system: "系统通知",
- app: "仅在应用内",
- off: "关闭",
- },
- {
- title: "Notices",
- system: "System notification",
- app: "In app only",
- off: "Off",
- },
-);
diff --git a/src/NoticeSettings.tsx b/src/NoticeSettings.tsx
deleted file mode 100644
index f743b5bc..00000000
--- a/src/NoticeSettings.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-import { useEffect, useState } from "react";
-import { invoke } from "@tauri-apps/api/core";
-import { toast } from "sonner";
-import { Segmented } from "@/upstreams/parts";
-import { useText } from "@/i18n";
-import { noticeSettingsText } from "./NoticeSettings.i18n";
-import { errorText } from "@/i18n/core.i18n";
-
-export type NoticeMode = "system" | "app" | "off";
-
-/**
- * 设置里的「提醒」:系统通知 / 仅在应用内 / 关闭。
- *
- * **只有一个开关,不分类。**哪件事该打断人是通知总线的判断(见
- * `src-tauri/src/notices`),不该变成设置页上的一长串下拉。三档固定,
- * 所以和外观一样摆成三个按钮。
- */
-export default function NoticeSettings() {
- const t = useText(noticeSettingsText);
- const [mode, setMode] = useState(null);
-
- useEffect(() => {
- void invoke("notice_mode")
- .then(setMode)
- .catch(() => {});
- }, []);
-
- if (!mode) return null;
-
- async function choose(next: NoticeMode) {
- const before = mode;
- // 先画上,以后端返回的为准 —— 存不进去的时候要弹回去
- setMode(next);
- try {
- setMode(await invoke("set_notice_mode", { mode: next }));
- } catch (e) {
- setMode(before);
- toast.error(errorText(e));
- }
- }
-
- return (
-
- {t.title}
-
-
- value={mode}
- options={[
- { id: "system", label: t.system },
- { id: "app", label: t.app },
- { id: "off", label: t.off },
- ]}
- onChange={(v) => void choose(v)}
- />
-
-
- );
-}
diff --git a/src/Notices.tsx b/src/Notices.tsx
index b587626c..7afa2e17 100644
--- a/src/Notices.tsx
+++ b/src/Notices.tsx
@@ -9,7 +9,7 @@ import { cn } from "@/lib/utils";
import { useText } from "@/i18n";
import { noticesText } from "./Notices.i18n";
import { commonText } from "@/i18n/common.i18n";
-import type { NoticeMode } from "./NoticeSettings";
+import type { NoticeMode } from "./settings/api";
/** 一条提醒。判定在 Rust 侧,这里只负责显示 */
export interface Notice {
diff --git a/src/Update.i18n.ts b/src/Update.i18n.ts
index 27949b95..f3821ce1 100644
--- a/src/Update.i18n.ts
+++ b/src/Update.i18n.ts
@@ -1,26 +1,20 @@
import { messages } from "@/i18n";
/**
- * 更新:设置里的那一节(`Update.tsx`)、更新窗口(`UpdateWindow.tsx`),
- * 以及安装进行到哪一步(`updateFlow.ts`)。三处说的是同一件事,放在一份里。
+ * 更新窗口(`UpdateWindow.tsx`)和安装进行到哪一步(`updateFlow.ts`)。设置里
+ * 「关于」那一节的几句在 `settings/SettingsPage.i18n.tsx`。
*/
export const updateText = messages(
{
- // 设置里的「更新」
- title: "更新",
- autoCheck: "自动检查新版本",
- checkNow: "立即检查",
- checkFailed: (err: string) => `检查更新失败:${err}`,
- newer: (version: string, current: string) => `新版本 ${version} 可用,当前 ${current}`,
- latest: (version: string) => `已是最新版本 ${version}`,
- current: (version: string) => `当前版本 ${version}`,
-
// 更新窗口
+ current: (version: string) => `当前版本 ${version}`,
available: (version: string) => `ThinkWatch Lite ${version} 可用`,
closeWhileWaiting: "关闭此窗口不影响更新,更新完成后将发送通知。",
standalone: "下载完成后自动安装。网关将在进行中的请求全部结束后重新启动。",
later: "稍后",
install: "下载并安装",
+ /** 下载或安装中途失败时那条提示的标题,正文是原因 */
+ failed: "未能完成更新",
homebrew: "此应用由 Homebrew 管理,请在终端中执行以下命令完成更新:",
command: "更新命令",
copyFailed: "未能写入剪贴板。命令已选中,请按 ⌘C 复制。",
@@ -35,20 +29,14 @@ export const updateText = messages(
restarting: "正在重新启动",
},
{
- title: "Updates",
- autoCheck: "Check for updates automatically",
- checkNow: "Check now",
- checkFailed: (err: string) => `Update check failed: ${err}`,
- newer: (version: string, current: string) => `Version ${version} is available (current: ${current})`,
- latest: (version: string) => `${version} is the latest version`,
current: (version: string) => `Current version: ${version}`,
-
available: (version: string) => `ThinkWatch Lite ${version} is available`,
closeWhileWaiting: "Closing this window does not stop the update. A notification is sent when it is complete.",
standalone:
"Installs automatically after downloading. The gateway restarts once all requests in progress have finished.",
later: "Later",
install: "Download and install",
+ failed: "The update did not finish",
homebrew: "This app is managed by Homebrew. To update, run this command in Terminal:",
command: "Update command",
copyFailed: "The clipboard could not be written to. The command is selected; press ⌘C to copy it.",
diff --git a/src/Update.tsx b/src/Update.tsx
deleted file mode 100644
index 6e2e94b6..00000000
--- a/src/Update.tsx
+++ /dev/null
@@ -1,100 +0,0 @@
-import { useEffect, useState } from "react";
-import { invoke } from "@tauri-apps/api/core";
-import { listen } from "@tauri-apps/api/event";
-import { Button } from "@/ui/button";
-import { Field, FieldContent, FieldLabel } from "@/ui/field";
-import { Spinner } from "@/ui/spinner";
-import { Switch } from "@/ui/switch";
-import { toast } from "sonner";
-import { useText } from "@/i18n";
-import type { Found, UpdateView } from "./updateFlow";
-import { updateText } from "./Update.i18n";
-import { errorText } from "@/i18n/core.i18n";
-
-/**
- * 设置里的「更新」。
- *
- * **这里不装任何东西。**查到新版本时打开的是更新窗口 —— 自动检查查到的
- * 和这里手动查到的,走的是同一个窗口、同一套按钮。两处各有一套安装界面
- * 的话,其中一套迟早会和另一套说不一样的话。
- */
-export default function Update() {
- const t = useText(updateText);
- const [view, setView] = useState(null);
- /** 这次打开设置页之后查过没有 —— 「已是最新版本」只有在真查过之后才该说 */
- const [looked, setLooked] = useState(false);
- const [busy, setBusy] = useState(false);
-
- useEffect(() => {
- void invoke("update_state").then(setView).catch(() => {});
- }, []);
-
- // 后台那轮自动检查查到了,这里也要跟着显示
- useEffect(() => {
- const un = listen("update-found", (e) =>
- setView((v) => (v ? { ...v, offer: e.payload } : v)),
- );
- return () => {
- void un.then((f) => f());
- };
- }, []);
-
- if (!view) return null;
-
- const look = async () => {
- setBusy(true);
- try {
- // 查到的话 Rust 那边会把更新窗口拉起来
- const found = await invoke("update_check");
- setView((v) => (v ? { ...v, offer: found } : v));
- setLooked(true);
- } catch (e) {
- toast.error(t.checkFailed(errorText(e)));
- } finally {
- setBusy(false);
- }
- };
-
- return (
-
- {t.title}
-
-
- {
- const want = checked === true;
- const before = view;
- // 先画上,以后端返回的实际状态为准 —— 写不进去的时候
- // 开关必须弹回去(和开机自启同一条纪律)。
- setView({ ...view, check_updates: want });
- try {
- setView(await invoke("set_update_check", { on: want }));
- } catch (err) {
- setView(before);
- toast.error(errorText(err));
- }
- }}
- />
-
- {t.autoCheck}
-
-
-
-
-
-
- {view.offer
- ? t.newer(view.offer.version, view.version)
- : looked
- ? t.latest(view.version)
- : t.current(view.version)}
-
-
-
- );
-}
diff --git a/src/UpdateWindow.tsx b/src/UpdateWindow.tsx
index 6dc560f2..abcb2e92 100644
--- a/src/UpdateWindow.tsx
+++ b/src/UpdateWindow.tsx
@@ -1,11 +1,13 @@
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { getCurrentWindow } from "@tauri-apps/api/window";
+import appIcon from "../src-tauri/icons/128x128.png";
+import { Banner } from "@/ui/banner";
import { Button } from "@/ui/button";
import { Input } from "@/ui/input";
-import { Progress } from "@/ui/progress";
import { Spinner } from "@/ui/spinner";
+import { StatusDot } from "@/ui/status-dot";
import { IconCopied, IconCopy } from "@/ui/icons";
import { useText } from "@/i18n";
import { commonText } from "@/i18n/common.i18n";
@@ -19,10 +21,11 @@ const COPIED_MS = 2_000;
/**
* 更新窗口。
*
- * 由 Rust 建出来:用户点了「检查更新」或「立即检查」并查到新版本,或者
- * 点了自动检查发出的那条通知、菜单里的「安装新版本」。窗口建出来时是隐藏的 —— 这里画好、量出高度之后再亮出来。
+ * 由 Rust 建出来:用户点了「检查更新」并查到新版本、设置里点了「更新到 x…」,或者
+ * 点了自动检查发出的那条通知、菜单里的「安装新版本」。窗口建出来时是隐藏的 —— 这里
+ * 画好、量出高度之后再亮出来。
*
- * 画哪一种取决于这一份是怎么装上来的:
+ * 上面是应用图标、哪一版可用、现在是哪一版;下面画哪一种取决于这一份是怎么装上来的:
*
* · 从网页下载的:「下载并安装」,按一次之后不再问任何问题 —— 下载、
* 等网关手上的请求结束、替换、重启,全部自动。
@@ -31,6 +34,9 @@ const COPIED_MS = 2_000;
*
* **没有任何按钮默认获得焦点。**这个窗口是在用户做别的事时冒出来的;
* 他在终端里按下的回车,不该变成一次「下载并安装」。
+ *
+ * **不做展开、收起的动画**(换一步只淡入):窗口的高度跟着内容走(`update_fit`),
+ * 内容一边展开、窗口一边一格格地改尺寸,比直接换过去难看。
*/
export default function UpdateWindow() {
const t = useText(updateText);
@@ -136,92 +142,133 @@ export default function UpdateWindow() {
}
};
+ let content: ReactNode;
+ let actions: ReactNode;
+ if (canInstall(offer.install)) {
+ content = busy && step ? (
+
+ ) : (
+ <>
+ {t.standalone}
+ {failed && (
+
+ {failed}
+
+ )}
+ >
+ );
+ actions = busy ? (
+ // 等请求结束可能要几分钟:窗口可以先关掉,更新照常进行(上面那句说了)
+ step?.step === "waiting" && (
+
+ )
+ ) : (
+ <>
+
+
+ >
+ );
+ } else if (offer.install === "homebrew" && offer.command) {
+ content = (
+ <>
+ {t.homebrew}
+ {/*
+ 命令占满整行,复制放进底下那排按钮里当主操作 —— 和另一档的
+ 「稍后 / 下载并安装」同一个位置、同一个分量。按钮塞在输入框
+ 里面的话,命令就只剩一截能显示。
+ */}
+
+
e.currentTarget.select()}
+ />
+ {copyFailed &&
{t.copyFailed}
}
+
+ >
+ );
+ actions = (
+ <>
+
+
+ >
+ );
+ } else {
+ content = {t.dev}
;
+ actions = (
+
+ );
+ }
+
return (
-
-
{t.available(offer.version)}
-
{t.current(offer.current)}
-
+
+ {content}
+ {actions &&
{actions}
}
+
+
+ );
+}
- {canInstall(offer.install) ? (
- <>
- {busy ? (
-
- {/* 知道总长才画进度条 —— 一根假装知道还剩多少的进度条比没有更糟 */}
- {step?.step === "downloading" && progress[1] ? (
-
- ) : null}
-
- {!(step?.step === "downloading" && progress[1]) && }
- {step && describeStep(step, progress[0], progress[1])}
-
- {/* 这一步可能要几分钟,而且长短取决于用户自己的请求 */}
- {step?.step === "waiting" && (
-
- {t.closeWhileWaiting}
-
- )}
-
- ) : (
-
- {t.standalone}
-
- )}
- {failed && {failed}
}
- {!busy && (
-
-
-
-
- )}
- >
- ) : offer.install === "homebrew" && offer.command ? (
- <>
-
- {t.homebrew}
-
- {/*
- 命令占满整行,复制放进底下那排按钮里当主操作 —— 和另一档的
- 「稍后 / 下载并安装」同一个位置、同一个分量。按钮塞在输入框
- 里面的话,命令就只剩一截能显示。
- */}
- e.currentTarget.select()}
- />
- {copyFailed && (
- {t.copyFailed}
- )}
-
-
-
-
- >
+/**
+ * 按下安装之后走到哪一步了。**知道总长才画进度条** —— 一根假装知道还剩多少的进度条
+ * 比没有更糟;等请求结束那一步是一个在跳的点(此刻在等),下面说明窗口可以关。
+ */
+function Progressing({ step, done, total }: { step: Step; done: number; total: number | null }) {
+ const t = useText(updateText);
+ const text = describeStep(step, done, total);
+ if (step.step === "downloading" && total) {
+ const pct = Math.min(100, (done / total) * 100);
+ return (
+
+ );
+ }
+ return (
+
+
+ {step.step === "waiting" ? (
+
) : (
- <>
-
{t.dev}
-
-
-
- >
+
)}
-
+ {text}
+
+ {/* 这一步可能要几分钟,而且长短取决于用户自己的请求 */}
+ {step.step === "waiting" && {t.closeWhileWaiting}
}
);
}
diff --git a/src/connection/ConnectionsSection.tsx b/src/connection/ConnectionsSection.tsx
index d51da181..cca536aa 100644
--- a/src/connection/ConnectionsSection.tsx
+++ b/src/connection/ConnectionsSection.tsx
@@ -1,5 +1,5 @@
-import { useState } from "react";
-import { toast } from "sonner";
+import { useEffect, useState, type KeyboardEvent } from "react";
+import { PlusIcon } from "lucide-react";
import {
AlertDialog,
AlertDialogAction,
@@ -12,16 +12,23 @@ import {
} from "@/ui/alert-dialog";
import { Badge } from "@/ui/badge";
import { Button } from "@/ui/button";
-import { Segmented } from "@/ui/segmented";
import { IconLocal, IconRemote } from "@/ui/icons";
+import { rowMotion, usePresentList } from "@/ui/motion";
+import { notify } from "@/ui/notify";
+import { RowMenu, RowMenuButton, type MenuItems } from "@/ui/row-menu";
+import { Segmented } from "@/ui/segmented";
+import { StatusLabel, type StatusTone } from "@/ui/status-dot";
+import { cn } from "@/lib/utils";
import { useLang, useText } from "@/i18n";
import { commonText } from "@/i18n/common.i18n";
-import { errorText } from "@/i18n/core.i18n";
-import { FormRow, FormRows } from "@/settings/form";
+import { ListSkeleton } from "@/ui/states";
+import { Skeleton } from "@/ui/skeleton";
+import { SettingsCard, SettingsGroup, SettingsRow } from "@/settings/kit";
import { connApi, type ConnView, type Profile, type Startup } from "./api";
import { connText } from "./connection.i18n";
import { useConnections } from "./ConnectionProvider";
import { profileName } from "./describe";
+import { remoteStatus, type Tone } from "./Switcher";
/** 「9 月 20 日」/「Sep 20」 */
function day(ms: number, lang: "zh" | "en"): string {
@@ -31,80 +38,134 @@ function day(ms: number, lang: "zh" | "en"): string {
});
}
+/** 这一行此刻的状态:只有当前连着的那一条有 */
+export interface LinkStatus {
+ text: string;
+ tone: StatusTone;
+}
+
/**
- * 设置 → 连接(设计稿 ②)。**放在设置页最上方。**
+ * 侧栏切换器的三档(`Tone`)换成状态点的说法,**字也用侧栏那几个**:同一个窗口里
+ * 左下角写「已停止」、设置页写另一句,读起来像两件事。正在启动、正在连接是此刻在
+ * 发生的事,点会跳。
+ */
+export function linkStatus(s: { text: string; tone: Tone }): LinkStatus {
+ return { text: s.text, tone: s.tone === "ok" ? "ok" : s.tone === "warn" ? "pending" : "error" };
+}
+
+/**
+ * 设置 → 连接(设计稿 ②)。**放在设置页最上方**:连不上的时候用户就是来这里的。
+ *
+ * 一条连接一行,和侧栏底部的切换器同一套说法:图标、名字、地址;当前那一条挂「当前」
+ * 和它此刻的状态(本机 core 的状态,或者远程的已连接 / 正在连接 / 未连接)。别的行
+ * 右边是「切换」。编辑、删除在行尾的「…」和右键菜单里;点一下远程那一行也是编辑。
*
- * 新建和编辑一律走对话框(③),页面上不做内联表单。当前连接不能删除,要先切走;
- * 本机内置、删不掉。「启动时连接」是几个里选一个,用分段控件,和「外观」一样。
+ * 新建和编辑一律走对话框(③),页面上不做内联表单。当前连接删不掉,要先切走;本机
+ * 内置、删不掉。「启动时连接」是几个里选一个,用分段控件。
*
* **不依赖 core 的任何数据**:远程连不上时这一节照样能用 —— 这正是用户这时要来的地方。
*/
-export function ConnectionsSection() {
+export function ConnectionsSection({ local }: { local: LinkStatus }) {
const t = useText(connText);
const { view, add, edit, switchTo } = useConnections();
const [deleting, setDeleting] = useState(null);
- if (!view) return null;
-
- async function setStartup(s: Startup) {
- try {
- await connApi.setStartup(s);
- } catch (e) {
- toast.error(errorText(e));
- }
- }
+ const rows = usePresentList(view?.profiles ?? [], (p) => p.id);
return (
-
-
-
{t.title}
-
-
- {t.intro}
+ }
+ >
+
+ {view ? (
+
+ {rows.map(({ item: p, key, presence }) => (
+ switchTo(p.id)}
+ onEdit={() => edit(p)}
+ onDelete={() => setDeleting(p)}
+ />
+ ))}
+
+ ) : (
+
+ )}
+
-
- {view.profiles.map((p) => (
- switchTo(p.id)}
- onEdit={() => edit(p)}
- onDelete={() => setDeleting(p)}
- />
- ))}
-
+
+
+
+
+ setDeleting(null)} />
+
+ );
+}
- {t.startupGroup}
-
-
+/** 启动时连接:上次使用的 / 本机。先按新值画上,列表推回来之前不弹回去 */
+function StartupRow({ view }: { view: ConnView | null }) {
+ const t = useText(connText);
+ const [want, setWant] = useState(null);
+ const saved = view?.startup ?? null;
+ // 推回来的列表已经是选的那一档了:不再需要本地那一份
+ useEffect(() => {
+ if (want !== null && saved === want) setWant(null);
+ }, [saved, want]);
+ const value = want ?? saved;
+ return (
+
- value={view.startup}
+ value={value}
label={t.startupLabel}
options={[
{ id: "last", label: t.startupLast },
{ id: "local", label: t.startupLocal },
]}
- onChange={(v) => void setStartup(v)}
+ onChange={(s) => {
+ setWant(s);
+ connApi.setStartup(s).catch((e) => {
+ setWant(null);
+ notify.error(e);
+ });
+ }}
/>
-
-
-
- setDeleting(null)} />
-
+ ) : (
+ // 连接列表还没到:先占住分段控件的位置,到了不跳
+
+ )
+ }
+ />
);
}
-function Row({
+function ProfileRow({
p,
view,
+ local,
+ className,
onSwitch,
onEdit,
onDelete,
}: {
p: Profile;
view: ConnView;
+ local: LinkStatus;
+ className?: string;
onSwitch: () => void;
onEdit: () => void;
onDelete: () => void;
@@ -114,6 +175,8 @@ function Row({
const lang = useLang();
const current = p.id === view.current;
const Icon = p.local ? IconLocal : IconRemote;
+ const name = profileName(p);
+
let desc: string;
if (p.local) desc = t.localNote(view.data_dir);
else if (current && view.link.kind === "connected")
@@ -121,36 +184,74 @@ function Row({
else if (p.last_connected_at != null) desc = `${p.addr} · ${t.lastConnected(day(p.last_connected_at, lang))}`;
else desc = `${p.addr} · ${t.neverConnected}`;
- return (
-
+ const status: LinkStatus | null = !current ? null : p.local ? local : linkStatus(remoteStatus(view));
+
+ // 当前连着的删不掉,要先切走:菜单里那一项置灰,而不是点了才说不行
+ const items: MenuItems = [
+ ...(current ? [] : [{ kind: "item" as const, label: t.switchTo, onSelect: onSwitch }]),
+ ...(p.local
+ ? []
+ : [
+ { kind: "item" as const, label: common.edit, onSelect: onEdit },
+ { kind: "sep" as const },
+ { kind: "item" as const, label: common.delete, danger: true, disabled: current, onSelect: onDelete },
+ ]),
+ ];
+ // 远程那一行点一下就是编辑;本机那一行没有可编辑的东西
+ const editable = !p.local;
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (!editable || e.target !== e.currentTarget) return;
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ onEdit();
+ }
+ };
+
+ const row = (
+
+
+
+
-
-
- {profileName(p)}
+
+ {name}
{current && {t.current}}
-
{desc}
+
{desc}
-
+ {status && (
+
+ {status.text}
+
+ )}
+
e.stopPropagation()}>
{!current && (
-
- )}
- {!p.local && (
-
- )}
- {/* 当前连着的删不掉,要先切走:按钮不出现,而不是点了才说不行 */}
- {!p.local && !current && (
-
);
+ return items.length > 0 ?
{row} : row;
}
function DeleteDialog({ profile, onClose }: { profile: Profile | null; onClose: () => void }) {
@@ -160,7 +261,7 @@ function DeleteDialog({ profile, onClose }: { profile: Profile | null; onClose:
!o && onClose()}>
- {profile ? t.deleteTitle(profile.name) : ""}
+ {profile ? t.deleteTitle(profile.name) : ""}
{t.deleteBody}
@@ -168,7 +269,7 @@ function DeleteDialog({ profile, onClose }: { profile: Profile | null; onClose:
{
- if (profile) connApi.remove(profile.id).catch((e) => toast.error(errorText(e)));
+ if (profile) connApi.remove(profile.id).catch((e) => notify.error(e));
onClose();
}}
>
diff --git a/src/connection/ProfileDialog.tsx b/src/connection/ProfileDialog.tsx
index 658f72bf..43e076c1 100644
--- a/src/connection/ProfileDialog.tsx
+++ b/src/connection/ProfileDialog.tsx
@@ -1,5 +1,6 @@
import { useState } from "react";
-import { CheckIcon, XIcon } from "lucide-react";
+import { CheckIcon } from "lucide-react";
+import { Banner } from "@/ui/banner";
import { Button } from "@/ui/button";
import {
Dialog,
@@ -11,7 +12,6 @@ import {
} from "@/ui/dialog";
import { Input } from "@/ui/input";
import { Spinner } from "@/ui/spinner";
-import { cn } from "@/lib/utils";
import { useText } from "@/i18n";
import { commonText } from "@/i18n/common.i18n";
import { errorText } from "@/i18n/core.i18n";
@@ -211,33 +211,39 @@ export function ProfileDialog({
- {error && {error}
}
+
+ {error}
+
{/* 测试在左边,和保存那一组分开:它不改任何东西 */}
void run("test")}
>
{t.test}
{hint && {hint}}
-
+
{common.cancel}
void run("save")}
>
- {busy === "save" && }
{common.save}
{!isCurrent && (
- void run("switch")}>
- {busy === "switch" && }
+ void run("switch")}
+ >
{t.saveAndSwitch}
)}
@@ -261,7 +267,7 @@ export function TestResult({
const t = useText(connText);
if (testing) {
return (
-
+
{t.connecting}…
@@ -270,8 +276,8 @@ export function TestResult({
if (!result) return null;
if (result.ok) {
return (
-
-
+
+
{t.testOk(
result.info.core_version,
host ? clientGateway(host, result.info.gateway_addr) : result.info.gateway_addr,
@@ -279,20 +285,11 @@ export function TestResult({
);
}
+ // 发生了什么(标题)和下一步做什么(正文)。**不用 ×**:× 在对话框里只表示关闭
const d = describeError(result.error);
return (
-
+
+ {d.next}
+
);
}
diff --git a/src/connection/Remote.tsx b/src/connection/Remote.tsx
index 91cb64f7..c57acb37 100644
--- a/src/connection/Remote.tsx
+++ b/src/connection/Remote.tsx
@@ -1,5 +1,5 @@
-import { CircleAlertIcon, MonitorIcon } from "lucide-react";
-import { Alert, AlertDescription, AlertTitle } from "@/ui/alert";
+import { MonitorIcon } from "lucide-react";
+import { Banner } from "@/ui/banner";
import { useText } from "@/i18n";
import { coreText } from "@/i18n/core.i18n";
import type { Retargeted } from "@/types";
@@ -12,10 +12,9 @@ import { useRemote } from "./useRemote";
*/
export function RemoteNote({ children }: { children: string }) {
return (
-
-
- {children}
-
+
}>
+ {children}
+
);
}
@@ -31,21 +30,17 @@ export function RetargetReport({ name, result }: { name: string; result: Retarge
{t.retargeted(name, result.synced.map((s) => s.name))}
)}
{result.failed.length > 0 && (
-
-
- {t.retargetFailedTitle(name)}
-
-
- {result.failed.map((f) => (
- -
- {f.name}
- {t.sep}
- {coreText(f.error)}
-
- ))}
-
-
-
+
+
+ {result.failed.map((f) => (
+ -
+ {f.name}
+ {t.sep}
+ {coreText(f.error)}
+
+ ))}
+
+
)}
{result.synced.length === 0 && result.failed.length === 0 && (
{t.retargetNone}
diff --git a/src/connection/SwitchDialog.tsx b/src/connection/SwitchDialog.tsx
index ac810112..5b47c2a2 100644
--- a/src/connection/SwitchDialog.tsx
+++ b/src/connection/SwitchDialog.tsx
@@ -9,11 +9,11 @@ import {
DialogHeader,
DialogTitle,
} from "@/ui/dialog";
-import { Spinner } from "@/ui/spinner";
+import { Banner } from "@/ui/banner";
+import { notify } from "@/ui/notify";
import { useText } from "@/i18n";
import { commonText } from "@/i18n/common.i18n";
import { errorText } from "@/i18n/core.i18n";
-import { toast } from "sonner";
import type { Retargeted } from "@/types";
import { connApi, type Adopted, type ConnectError, type Profile, type ServerInfo, type SwitchError } from "./api";
import { connText } from "./connection.i18n";
@@ -103,7 +103,7 @@ export function SwitchDialog({
if (alive.current) setStage({ kind: "retargeted", result: r });
return;
}
- if (r && r.synced.length > 0) toast.success(rt.retargeted(target.name, r.synced.map((s) => s.name)));
+ if (r && r.synced.length > 0) notify.success(rt.retargeted(target.name, r.synced.map((s) => s.name)));
onClose();
} catch (e) {
const err = e as SwitchError;
@@ -144,7 +144,9 @@ export function SwitchDialog({
(stage.error ? (
) : (
-
{stage.text}
+
+ {stage.text}
+
))}
{stage.kind === "retargeted" &&
}
@@ -157,12 +159,12 @@ export function SwitchDialog({
- {t.adoptedWarn(adopted.count, adopted.local_addr ?? "127.0.0.1:8788")}
+ {t.adoptedWarn(adopted.count, adopted.local_addr)}
{t.adoptedWarnNext(target.name)}
@@ -182,22 +184,18 @@ export function SwitchDialog({
)}
+ {/* 取消在左、主操作在右。没切成时主操作是「编辑连接」:原因多半出在地址或密钥上 */}
- {stage.kind === "failed" && (
- onEdit(target)}>
- {t.editConnection}
-
- )}
{stage.kind === "retargeted" ? (
{common.close}
) : (
-
+
{stage.kind === "failed" ? common.close : common.cancel}
)}
+ {stage.kind === "failed" && onEdit(target)}>{t.editConnection}}
{stage.kind === "confirm" && (
- void commit()}>
- {busy && }
+ void commit()}>
{t.switchAction}
)}
diff --git a/src/connection/connection.i18n.tsx b/src/connection/connection.i18n.tsx
index a1da17d1..1ac002c9 100644
--- a/src/connection/connection.i18n.tsx
+++ b/src/connection/connection.i18n.tsx
@@ -37,18 +37,18 @@ export const connText = messages(
: "应用同一时间连接一个 core。连接到远程 core 时,本机的 core 停止运行,本机数据保留。",
current: "当前",
switchTo: "切换到此连接",
+ switchShort: "切换",
+ actionsFor: (name: string) => `「${name}」的操作`,
lastConnected: (when: string) => `上次连接 ${when}`,
neverConnected: "尚未连接",
coreVersion: (v: string) => `core ${v}`,
- currentOnlyDelete: "当前连接不能删除,请先切换到其他连接。",
- startupGroup: "启动",
startupLabel: "启动时连接",
startupLast: "上次使用的连接",
startupLocal: "本机",
startupHint: isLinux
? "连续两次启动未能完成时,下次启动先显示连接选择。"
: `按住 ${holdZh} 键启动应用时,先显示连接选择。`,
- deleteTitle: (name: string) => `删除连接「${name}」?`,
+ deleteTitle: (name: string) => `删除连接「${name}」`,
deleteBody: "保存在本机的密钥一并删除。服务器上的 core 不受影响。",
// 添加与编辑
@@ -104,9 +104,10 @@ export const connText = messages(
// 切换
testingTitle: (name: string) => `正在连接 ${name}…`,
failedTitle: (name: string) => `无法切换到 ${name}`,
- confirmTitle: (name: string) => `切换到 ${name}?`,
+ confirmTitle: (name: string) => `切换到 ${name}`,
switchedTo: (name: string) => `已切换到 ${name}`,
- adoptedWarn: (n: number, addr: string) => `已接管的 ${n} 个客户端仍指向本机网关 ${addr}。`,
+ adoptedWarn: (n: number, addr: string | null) =>
+ addr ? `已接管的 ${n} 个客户端仍指向本机网关 ${addr}。` : `已接管的 ${n} 个客户端仍指向本机网关。`,
adoptedWarnNext: (name: string) =>
`切换后本机网关停止,这些客户端的请求会失败,直到重新连接本机,或在客户端页将它们改为指向 ${name}。`,
retarget: (name: string) => `同时将这些客户端改为指向 ${name}`,
@@ -172,18 +173,18 @@ export const connText = messages(
: "The app connects to one core at a time. While it is connected to a remote core, the core on this computer stops running; its data is kept.",
current: "Current",
switchTo: "Switch to this connection",
+ switchShort: "Switch",
+ actionsFor: (name: string) => `Actions for “${name}”`,
lastConnected: (when: string) => `Last connected ${when}`,
neverConnected: "Never connected",
coreVersion: (v: string) => `core ${v}`,
- currentOnlyDelete: "The current connection cannot be deleted. Switch to another connection first.",
- startupGroup: "Startup",
startupLabel: "Connect at startup",
startupLast: "Last used connection",
startupLocal: isMac ? "This Mac" : "This computer",
startupHint: isLinux
? "After two startups in a row fail to finish, the next startup shows the connection choice first."
: `Hold ${holdZh} while opening the app to choose a connection first.`,
- deleteTitle: (name: string) => `Delete the connection “${name}”?`,
+ deleteTitle: (name: string) => `Delete connection “${name}”`,
deleteBody: "The key saved on this computer is deleted as well. The core on the server is not affected.",
addTitle: "Add remote connection",
@@ -240,12 +241,14 @@ export const connText = messages(
testingTitle: (name: string) => `Connecting to ${name}…`,
failedTitle: (name: string) => `Cannot switch to ${name}`,
- confirmTitle: (name: string) => `Switch to ${name}?`,
+ confirmTitle: (name: string) => `Switch to ${name}`,
switchedTo: (name: string) => `Switched to ${name}`,
- adoptedWarn: (n: number, addr: string) =>
- n === 1
- ? `1 connected client still points to the local gateway ${addr}.`
- : `${n} connected clients still point to the local gateway ${addr}.`,
+ adoptedWarn: (n: number, addr: string | null) => {
+ const at = addr ? ` ${addr}` : "";
+ return n === 1
+ ? `1 connected client still points to the local gateway${at}.`
+ : `${n} connected clients still point to the local gateway${at}.`;
+ },
adoptedWarnNext: (name: string) =>
`After the switch, the local gateway stops and their requests fail until the app switches back, or until they are pointed at ${name} on the Clients page.`,
retarget: (name: string) => `Also point these clients at ${name}`,
diff --git a/src/connection/remote.i18n.tsx b/src/connection/remote.i18n.tsx
index 23c57773..fe03f8f0 100644
--- a/src/connection/remote.i18n.tsx
+++ b/src/connection/remote.i18n.tsx
@@ -3,6 +3,8 @@ import { isMac } from "@/platform";
/** 这台机器叫什么。设计稿里写「这台 Mac」,别的平台写「这台电脑」 */
const hereZh = isMac ? "这台 Mac" : "这台电脑";
+/** 「这台 Mac 上」:拉丁字母和汉字之间留一个空格,「这台电脑上」不留 */
+const onHereZh = isMac ? "这台 Mac 上" : "这台电脑上";
const hereEn = isMac ? "this Mac" : "this computer";
const HereEn = isMac ? "This Mac" : "This computer";
@@ -17,9 +19,9 @@ export const remoteText = messages(
{
// 客户端页、MCP 页顶上的说明
clientsNote: (name: string, gateway: string) =>
- `此处检查和修改的是${hereZh}上的客户端配置,使其指向 ${name} 的网关 ${gateway};服务器上的客户端不受影响。`,
+ `此处检查和修改的是${onHereZh}的客户端配置,使其指向 ${name} 的网关 ${gateway};服务器上的客户端不受影响。`,
mcpNote: (name: string) =>
- `此处检查和修改的是${hereZh}上客户端的 MCP 配置、技能与钩子;${name} 上的不受影响。`,
+ `此处检查和修改的是${onHereZh}客户端的 MCP 配置、技能与钩子;${name} 上的不受影响。`,
// 还指着本机网关的客户端
localLeft: (n: number, addr: string) =>
@@ -27,12 +29,12 @@ export const remoteText = messages(
retargetTo: (name: string) => `改为指向 ${name}`,
retargeted: (name: string, clients: string[]) => `已改为指向 ${name}:${clients.join("、")}。`,
retargetFailedTitle: (name: string) => `以下客户端未能改为指向 ${name}`,
- retargetNone: "没有需要修改的客户端。",
+ retargetNone: "无需修改任何客户端。",
/** 客户端名和原因之间 */
sep: ":",
// 设置
- appGroup: `${hereZh}上的应用`,
+ appGroup: `${onHereZh}的应用`,
serverGroup: (name: string) => `${name} 的配置`,
controlReadOnly: "远程控制的监听与密钥只能在服务器上修改。",
connection: "连接",
diff --git a/src/palette/sections.ts b/src/palette/sections.ts
index 26fa9218..3c521010 100644
--- a/src/palette/sections.ts
+++ b/src/palette/sections.ts
@@ -1,10 +1,7 @@
import type { Messages } from "@/i18n";
-import { configText } from "@/Config.i18n";
-import { languageText } from "@/Language.i18n";
-import { appearanceText } from "@/Appearance.i18n";
-import { menubarSettingsText } from "@/MenubarSettings.i18n";
-import { updateText } from "@/Update.i18n";
-import { noticeSettingsText } from "@/NoticeSettings.i18n";
+import { isMac } from "@/platform";
+import { generalText } from "@/settings/GeneralSection.i18n";
+import { settingsText } from "@/settings/SettingsPage.i18n";
import { listenText } from "@/settings/ListenSection.i18n";
import { retentionText } from "@/settings/RetentionSection.i18n";
import { connText } from "@/connection/connection.i18n";
@@ -24,6 +21,10 @@ import { connText } from "@/connection/connection.i18n";
*
* · `core`:改的是 core 的配置(config.yaml),没连上 core 时那一节不画。
* · `local`:只在连本机时有(诊断包生成在本机的数据目录里)。
+ *
+ * 设置页上一节(`SettingsGroup`)或一行(`SettingsRow` 的 `anchor`)的锚点就是这里的
+ * `id`:语言、外观、菜单栏、开机启动、提醒是「通用」里的几行,更新、诊断包是「关于」
+ * 里的几行,其余各是一节(见 settings/kit.tsx 的 `jump`)。
*/
export type SettingsSection =
| "connections"
@@ -50,17 +51,18 @@ const pick = (m: Messages, get: (t: T) => string): Messages => ({
export const SETTINGS_SECTIONS: readonly SectionDef[] = [
{ id: "connections", title: pick(connText, (t) => t.title) },
- { id: "language", title: pick(languageText, (t) => t.title) },
- { id: "appearance", title: pick(appearanceText, (t) => t.title) },
- { id: "menubar", title: pick(menubarSettingsText, (t) => t.title) },
- { id: "autostart", title: pick(configText, (t) => t.autostartTitle) },
+ { id: "language", title: pick(generalText, (t) => t.language) },
+ { id: "appearance", title: pick(generalText, (t) => t.appearance) },
+ // 只有 macOS 有菜单栏这一行(别处的通知区放不下两行数字)
+ ...(isMac ? [{ id: "menubar" as const, title: pick(generalText, (t) => t.menubar) }] : []),
+ { id: "autostart", title: pick(generalText, (t) => t.autostart) },
+ { id: "notices", title: pick(generalText, (t) => t.notices) },
{ id: "listen", title: pick(listenText, (t) => t.title), core: true },
{ id: "retention", title: pick(retentionText, (t) => t.title), core: true },
- { id: "updates", title: pick(updateText, (t) => t.title) },
- { id: "notices", title: pick(noticeSettingsText, (t) => t.title) },
- { id: "about", title: pick(configText, (t) => t.aboutTitle) },
- { id: "diagnostics", title: pick(configText, (t) => t.diagnosticsTitle), local: true },
- { id: "uninstall", title: pick(configText, (t) => t.uninstallTitle) },
+ { id: "about", title: pick(settingsText, (t) => t.about) },
+ { id: "updates", title: pick(settingsText, (t) => t.updates) },
+ { id: "diagnostics", title: pick(settingsText, (t) => t.diagnostics), local: true },
+ { id: "uninstall", title: pick(settingsText, (t) => t.uninstallTitle) },
];
/** 某一节现在的标题(当前语言)。不是这里列的节时是 `undefined` */
diff --git a/src/settings/AboutSection.tsx b/src/settings/AboutSection.tsx
new file mode 100644
index 00000000..9c98b776
--- /dev/null
+++ b/src/settings/AboutSection.tsx
@@ -0,0 +1,246 @@
+import { useState } from "react";
+import { CheckIcon } from "lucide-react";
+import appIcon from "../../src-tauri/icons/128x128.png";
+import { Badge } from "@/ui/badge";
+import { Button } from "@/ui/button";
+import { Reveal } from "@/ui/motion";
+import { usePending } from "@/ui/notify";
+import { Skeleton } from "@/ui/skeleton";
+import { StatusLabel } from "@/ui/status-dot";
+import { Switch } from "@/ui/switch";
+import { Tip } from "@/ui/tip";
+import { useResource } from "@/lib/resource";
+import { cn } from "@/lib/utils";
+import { useText } from "@/i18n";
+import { errorText } from "@/i18n/core.i18n";
+import { remoteText } from "@/connection/remote.i18n";
+import type { RemoteCore } from "@/connection/api";
+import type { Found, UpdateView } from "@/updateFlow";
+import { APP_KEYS, settingsApi } from "./api";
+import { FLASH, Loaded, RowError, SettingsCard, SettingsGroup, SettingsRow, anchorId, useAppEvent, useWrite } from "./kit";
+import { settingsText } from "./SettingsPage.i18n";
+
+/** 「检查更新」按下去之后的结果。`idle`:这次打开设置页之后还没查过 */
+type Check = { kind: "idle" } | { kind: "checking" } | { kind: "latest" } | { kind: "failed"; error: unknown };
+
+/**
+ * 关于:应用图标、版本和更新状态,下面是排查时最先要问的几样(数据在哪、core 从
+ * 哪儿加载的)和诊断包。
+ *
+ * **这里不装任何东西。**查到新版本时打开的是更新窗口 —— 自动检查查到的和这里手动
+ * 查到的走同一个窗口、同一套按钮;两处各有一套安装界面的话,迟早说不一样的话。
+ * 已经查到了一版时按钮直接把那扇窗口拉起来,不再联网问一遍。
+ *
+ * 连着远程 core 时写连的是哪一台、它的 core 是哪一版;本机 core 的二进制那时不在
+ * 用,不列。诊断包也不给(它描述的是 core 那一侧)。
+ */
+export function AboutSection({ remote, linked }: { remote: RemoteCore | null; linked: boolean }) {
+ const t = useText(settingsText);
+ const rt = useText(remoteText);
+ const info = useResource(APP_KEYS.info, settingsApi.info);
+ const update = useResource(APP_KEYS.update, settingsApi.update);
+ const [autoPending, setAuto] = useWrite(update, (next: UpdateView) => settingsApi.setUpdateCheck(next.check_updates));
+ const [check, setCheck] = useState({ kind: "idle" });
+ const [opening, open] = usePending();
+ const { mutate, reload } = update;
+
+ // 后台那轮自动检查查到了:这里也跟着显示
+ useAppEvent("update-found", (found) => {
+ if (update.data) mutate({ ...update.data, offer: found });
+ else void reload();
+ });
+
+ async function look() {
+ setCheck({ kind: "checking" });
+ try {
+ const found = await settingsApi.checkUpdate();
+ if (update.data) mutate({ ...update.data, offer: found });
+ setCheck(found ? { kind: "idle" } : { kind: "latest" });
+ } catch (e) {
+ setCheck({ kind: "failed", error: e });
+ }
+ }
+
+ const version = info.data?.version ?? update.data?.version;
+ /** 版本从两处都读不出来:那一行说出来、给重试,不让骨架一直在那儿 */
+ const failed = version === undefined && info.error !== undefined && update.error !== undefined;
+ const offer = update.data?.offer ?? null;
+ const install = update.data?.install;
+ const checking = check.kind === "checking";
+
+ /** 版本号下面那一行:只在查过、或者知道有新版本时出现 */
+ const state = checking ? (
+ {t.checking}
+ ) : check.kind === "failed" ? (
+
+
+ {t.checkFailed}
+
+
+ ) : offer ? (
+ {t.newer(offer.version)}
+ ) : check.kind === "latest" ? (
+
+ {t.latest}
+
+ ) : null;
+
+ /** 路径这一类:读到了照抄,读不出来写「—」(为什么读不出来,版本那一行已经说了) */
+ const path = (v: string | undefined) => (v === undefined && info.error !== undefined ? "—" : v);
+
+ return (
+
+
+
+ {/* 应用图标本身(和程序坞里同一张),不是一个画出来的替身 */}
+

+
+
+ {t.appName}
+ {install === "homebrew" && {t.homebrew}}
+ {install === "dev" && {t.devBuild}}
+
+ {version ? (
+
{t.versionIs(version)}
+ ) : failed ? (
+
+ {
+ void info.reload();
+ void update.reload();
+ }}
+ />
+
+ ) : (
+
+ )}
+
+ {state}
+
+
+ {offer ? (
+
+ void open(async () => {
+ await settingsApi.showUpdate();
+ })
+ }
+ >
+ {t.updateTo(offer.version)}
+
+ ) : (
+
void look()}
+ >
+ {t.checkNow}
+
+ )}
+
+
+
+ {(v) => (
+ void setAuto({ ...v, check_updates: c === true })}
+ />
+ )}
+
+ }
+ />
+
+ {remote && (
+ <>
+ {`${remote.name} · ${remote.addr}`}} />
+ {remote.core ?? "—"}} />
+ >
+ )}
+ {path(info.data?.data_dir)}} />
+ {!remote && {path(info.data?.core_bin)}} />}
+ {!remote && }
+
+
+ );
+}
+
+/** 路径、版本这类要照抄的值:等宽、可选中、太长就折行。还没读到时一块灰 */
+function Mono({ children }: { children: string | undefined }) {
+ if (children === undefined) return ;
+ return {children};
+}
+
+/**
+ * 诊断包。遇到问题时一次性交出「这里是什么情况」,省掉来回问一轮(版本?配置?
+ * 哪个上游?)。**里面全部脱敏过,但仍然要求用户自己看一眼再交出去**:这是个
+ * 看得见所有 API key 的网关,这一步值得多花十秒。
+ *
+ * 内容由 core 给出:没连上 core 时按钮灰着,说明换成一句「连接后可生成」。
+ */
+function Diagnostics({ linked }: { linked: boolean }) {
+ const t = useText(settingsText);
+ const [busy, run] = usePending();
+ const [path, setPath] = useState(null);
+ return (
+ (
+
+ {label}
+
+ ))
+ : t.diagnosticsOffline
+ }
+ control={
+ void run(async () => setPath(await settingsApi.saveDiagnostics()))}
+ >
+ {t.generate}
+
+ }
+ >
+
+
+
+
+
+ {t.generated}
+
+
{path}
+
+ {t.review((text) => (
+ {text}
+ ))}
+
+
+
+
+
+ );
+}
diff --git a/src/settings/GeneralSection.i18n.ts b/src/settings/GeneralSection.i18n.ts
new file mode 100644
index 00000000..e4ec8ac2
--- /dev/null
+++ b/src/settings/GeneralSection.i18n.ts
@@ -0,0 +1,68 @@
+import { messages } from "@/i18n";
+import { isLinux, isWindows } from "@/platform";
+
+/** 设置 → 通用:语言、外观、菜单栏、开机启动、提醒 */
+export const generalText = messages(
+ {
+ title: "通用",
+
+ language: "语言",
+ /** 下拉里「跟随系统」那一项,括号里写出系统现在是哪种 */
+ languageSystem: (name: string) => `跟随系统(${name})`,
+
+ appearance: "外观",
+ system: "跟随系统",
+ light: "浅色",
+ dark: "深色",
+ /** 选了跟随系统时,把系统现在是哪一档写出来 */
+ systemNow: (name: string) => `系统当前为${name}。`,
+
+ menubar: "菜单栏",
+ menubarWhat: "数值为今日的 token 用量与费用。",
+ menubarFull: "标识和数值",
+ menubarIcon: "仅标识",
+ menubarNumbers: "仅数值",
+
+ autostart: "开机启动",
+ autostartWhat: isWindows
+ ? "登录后仅在通知区域显示图标,不打开窗口。"
+ : isLinux
+ ? "登录后仅在系统托盘显示图标,不打开窗口。"
+ : "登录后仅在菜单栏显示图标,不打开窗口。",
+
+ notices: "提醒",
+ noticeSystem: "系统通知",
+ noticeApp: "仅在应用内",
+ noticeOff: "关闭",
+ },
+ {
+ title: "General",
+
+ language: "Language",
+ languageSystem: (name: string) => `System default (${name})`,
+
+ appearance: "Appearance",
+ system: "System",
+ light: "Light",
+ dark: "Dark",
+ systemNow: (name: string) => `The system is currently set to ${name.toLowerCase()}.`,
+
+ menubar: "Menu bar",
+ menubarWhat: "The numbers are today's token usage and cost.",
+ menubarFull: "Icon and numbers",
+ menubarIcon: "Icon only",
+ menubarNumbers: "Numbers only",
+
+ autostart: "Launch at login",
+ autostartWhat: isWindows
+ ? "At login, only the icon appears in the notification area; no window opens."
+ : isLinux
+ ? "At login, only the icon appears in the system tray; no window opens."
+ : "At login, only the icon appears in the menu bar; no window opens.",
+
+ notices: "Notices",
+ noticeSystem: "System notification",
+ noticeApp: "In app only",
+ noticeOff: "Off",
+ },
+);
diff --git a/src/settings/GeneralSection.tsx b/src/settings/GeneralSection.tsx
new file mode 100644
index 00000000..c8ba5607
--- /dev/null
+++ b/src/settings/GeneralSection.tsx
@@ -0,0 +1,241 @@
+import { useEffect } from "react";
+import { NativeSelect, NativeSelectOption } from "@/ui/native-select";
+import { Reveal } from "@/ui/motion";
+import { Segmented } from "@/ui/segmented";
+import { Switch } from "@/ui/switch";
+import { useResource } from "@/lib/resource";
+import { LANG_NAMES, setLang, useText, type Lang } from "@/i18n";
+import { isMac } from "@/platform";
+import {
+ APP_KEYS,
+ settingsApi,
+ type LanguageView,
+ type MenubarStyle,
+ type NoticeMode,
+ type ThemeChoice,
+ type ThemeView,
+} from "./api";
+import { generalText } from "./GeneralSection.i18n";
+import { Loaded, SettingsCard, SettingsGroup, SettingsRow, useAppEvent, useWrite } from "./kit";
+
+/**
+ * 设置 → 通用。**改的是这个应用自己,点一下就换**,不走配置文件的「保存」:这几项
+ * 改错了当场就看得见,也当场改得回来(改监听、日志保留那几节才要保存,见各自的文件)。
+ *
+ * 每一项都以 Rust 交回的实际状态为准:先按新值画上,存不进去就弹回去并报错。
+ */
+export function GeneralSection() {
+ const t = useText(generalText);
+ return (
+
+
+
+
+ {/*
+ **只有 macOS 有这三档。**别处的通知区只认一张正方形图标(100% DPI 下
+ 16×16),塞不下两行数字 —— 那几行在右键菜单里给
+ */}
+ {isMac && }
+
+
+
+
+ );
+}
+
+/**
+ * 语言。**跟随系统是一个选项,不是一个开关**:只有两种语言,三个选项放进一个
+ * 下拉就说完了;括号里写出系统现在是哪种,选之前就知道会得到什么。
+ */
+function LanguageRow() {
+ const t = useText(generalText);
+ const r = useResource(APP_KEYS.language, settingsApi.language);
+ const [, set] = useWrite(r, async (next: LanguageView) => {
+ const v = await settingsApi.setLanguage(next.setting);
+ // 事件也会到,这里先换:不让界面等一趟往返
+ setLang(v.current);
+ return v;
+ });
+ // 别的窗口(或者系统语言)换了:跟着重读
+ useAppEvent("language-changed", () => void r.reload());
+ return (
+
+ {(v) => (
+ {
+ const x = e.target.value;
+ const setting: Lang | null = x === "zh" || x === "en" ? x : null;
+ void set({ ...v, setting, current: setting ?? v.system });
+ }}
+ >
+ {t.languageSystem(LANG_NAMES[v.system])}
+ {LANG_NAMES.zh}
+ {LANG_NAMES.en}
+
+ )}
+
+ }
+ />
+ );
+}
+
+/**
+ * 外观。**换的是窗口的外观,不是一套 CSS**:Rust 侧改 `NSApp` 的外观,WKWebView
+ * 继承它,`prefers-color-scheme` 跟着翻(见 `src-tauri/src/theme.rs`),界面这边
+ * 存完就结束了。
+ */
+function AppearanceRow() {
+ const t = useText(generalText);
+ const r = useResource(APP_KEYS.theme, settingsApi.theme);
+ const [, set] = useWrite(r, (next: ThemeView) => settingsApi.setTheme(next.setting));
+ const { reload } = r;
+ // 跟随系统时系统换了外观:下面那句「系统当前为…」跟着换
+ useEffect(() => {
+ if (typeof window.matchMedia !== "function") return;
+ const mq = window.matchMedia("(prefers-color-scheme: dark)");
+ const on = () => void reload();
+ mq.addEventListener("change", on);
+ return () => mq.removeEventListener("change", on);
+ }, [reload]);
+ const v = r.data;
+ const following = v !== undefined && v.setting === null;
+ return (
+
+ {t.systemNow(v.system === "dark" ? t.dark : t.light)}
+
+ )
+ }
+ control={
+
+ {(v) => (
+
+ label={t.appearance}
+ value={v.setting ?? "system"}
+ options={[
+ { id: "system", label: t.system },
+ { id: "light", label: t.light },
+ { id: "dark", label: t.dark },
+ ]}
+ onChange={(c) => {
+ const setting = c === "system" ? null : c;
+ void set({ ...v, setting, current: setting ?? v.system });
+ }}
+ />
+ )}
+
+ }
+ />
+ );
+}
+
+/** 菜单栏:标识和数值 / 仅标识 / 仅数值。数值是今日的 token 和费用 */
+function MenubarRow() {
+ const t = useText(generalText);
+ const r = useResource(APP_KEYS.menubar, settingsApi.menubar);
+ const [, set] = useWrite(r, settingsApi.setMenubar);
+ const { mutate } = r;
+ useAppEvent("menubar-style-changed", (s) => void mutate(s));
+ return (
+
+ {(style) => (
+
+ label={t.menubar}
+ value={style}
+ options={[
+ { id: "full", label: t.menubarFull },
+ { id: "icon", label: t.menubarIcon },
+ { id: "numbers", label: t.menubarNumbers },
+ ]}
+ onChange={(s) => void set(s)}
+ />
+ )}
+
+ }
+ />
+ );
+}
+
+/**
+ * 开机启动。**出厂是关的**;读到之前画一块灰,不先画一个开或关 —— 那一瞬间画错
+ * 的话,用户会以为是自己之前设的。**开关而不是复选框**:这是「打开或关掉一个系统
+ * 行为」,macOS 的系统设置里这一类一律是开关。
+ */
+function AutostartRow() {
+ const t = useText(generalText);
+ const r = useResource(APP_KEYS.autostart, settingsApi.autostart);
+ const [pending, set] = useWrite(r, settingsApi.setAutostart);
+ return (
+
+ {(on) => (
+ void set(c === true)}
+ />
+ )}
+
+ }
+ />
+ );
+}
+
+/**
+ * 提醒:系统通知 / 仅在应用内 / 关闭。**只有一个开关,不分类**:哪件事该打断人是
+ * 通知总线的判断(`src-tauri/src/notices`),不该变成设置页上的一长串下拉。
+ */
+function NoticesRow() {
+ const t = useText(generalText);
+ const r = useResource(APP_KEYS.noticeMode, settingsApi.noticeMode);
+ const [, set] = useWrite(r, settingsApi.setNoticeMode);
+ const { mutate } = r;
+ useAppEvent("notice-mode-changed", (m) => void mutate(m));
+ return (
+
+ {(mode) => (
+
+ label={t.notices}
+ value={mode}
+ options={[
+ { id: "system", label: t.noticeSystem },
+ { id: "app", label: t.noticeApp },
+ { id: "off", label: t.noticeOff },
+ ]}
+ onChange={(m) => void set(m)}
+ />
+ )}
+
+ }
+ />
+ );
+}
diff --git a/src/settings/ListenSection.i18n.ts b/src/settings/ListenSection.i18n.ts
index a945a2fe..ed56a63a 100644
--- a/src/settings/ListenSection.i18n.ts
+++ b/src/settings/ListenSection.i18n.ts
@@ -5,6 +5,9 @@ export const listenText = messages(
title: "网关监听",
current: "当前地址",
notListening: "未在监听",
+ /** 对外开放时,别的设备该用的地址(core 按网卡算好的) */
+ reachable: (addrs: string) => `其他设备使用 ${addrs} 连接。`,
+ sep: "、",
scope: "访问范围",
/**
* 三档回答的是同一个问题。
@@ -29,7 +32,6 @@ export const listenText = messages(
port: "端口",
badPort: "端口须为 1 到 65535 之间的整数。",
allowlist: "放行网段",
- saved: "监听设置已保存",
saveFailed: "未能保存",
staleTitle: "监听设置未生效",
staleBody: (why: string, addr: string) => `${why}网关仍在 ${addr} 上监听。`,
@@ -38,6 +40,8 @@ export const listenText = messages(
title: "Listening",
current: "Address",
notListening: "Not listening",
+ reachable: (addrs: string) => `Other devices connect to ${addrs}.`,
+ sep: ", ",
scope: "Reachable from",
local: "This machine",
localWhat: "Only programs on this computer can connect.",
@@ -53,7 +57,6 @@ export const listenText = messages(
port: "Port",
badPort: "The port is a whole number from 1 to 65535.",
allowlist: "Allowed ranges",
- saved: "Listen settings saved",
saveFailed: "Not saved",
staleTitle: "The listen settings have not taken effect",
staleBody: (why: string, addr: string) => `${why} The gateway is still listening on ${addr}.`,
diff --git a/src/settings/ListenSection.tsx b/src/settings/ListenSection.tsx
index e9934ac8..9ffa8dfd 100644
--- a/src/settings/ListenSection.tsx
+++ b/src/settings/ListenSection.tsx
@@ -1,15 +1,16 @@
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useState, type ReactNode } from "react";
import { call } from "@/control";
-import { toast } from "sonner";
-import { TriangleAlertIcon } from "lucide-react";
-import { Alert, AlertDescription, AlertTitle } from "@/ui/alert";
+import { useResource } from "@/lib/resource";
+import { Banner } from "@/ui/banner";
import { NativeSelect, NativeSelectOption } from "@/ui/native-select";
import { Segmented } from "@/ui/segmented";
+import { StatusLabel } from "@/ui/status-dot";
import { useText } from "@/i18n";
import { isLinux } from "@/platform";
import { coreText, errorText } from "@/i18n/core.i18n";
-import type { CoreStatus, ListenSave, ListenView, NicView } from "@/types";
-import { FormActions, FormRow, FormRows, NumberInput, intIn } from "./form";
+import type { CoreStatus, ListenSave, ListenView } from "@/types";
+import { NumberInput, intIn, useFormDraft } from "./form";
+import { RowError, SaveBar, SettingsCard, SettingsGroup, SettingsRow, useDirtyMark, useSavedFlash } from "./kit";
import { listenText } from "./ListenSection.i18n";
import { RangeList } from "./RangeList";
@@ -55,59 +56,48 @@ function same(a: Draft, b: Draft): boolean {
/**
* 网关监听:谁能连、在哪个端口。
*
- * **改完点保存才生效。**以前三个档位点下去立刻写配置、端口格子失焦就写盘
- * —— 从「仅本机」换到「局域网」再选网卡,中间那一版监听在一个用户没选过
- * 的地址上;而换到一个被占的端口,网关当场退出。现在几项一起改好再存,
- * core 在写配置之前先试着绑一下,绑不上就不写,并且说清为什么。
+ * **改完点保存才生效。**以前三个档位点下去立刻写配置、端口格子失焦就写盘 —— 从
+ * 「仅本机」换到「局域网」再选网卡,中间那一版监听在一个用户没选过的地址上;而换到
+ * 一个被占的端口,网关当场退出。现在几项一起改好再存,core 在写配置之前先试着绑一下,
+ * 绑不上就不写,并且说清为什么。
*
- * 最上面一行是网关**此刻**在听的地址:它跟着真实的监听器走,存完之后
- * 这里(和侧栏底部)就变成新的。
+ * 第一行是网关**此刻**在听的地址:它跟着真实的监听器走,存完之后这里(和侧栏底部)
+ * 就变成新的。对外开放时下面写出别的设备该用的地址(core 按网卡算好的,不是这里猜的)。
*/
export function ListenSection({
view,
status,
configVersion,
+ note,
onChanged,
}: {
view: ListenView;
status: CoreStatus | null;
configVersion: string;
+ /** 这一节最下面的一句(连着远程时:远程控制的监听只能在服务器上改) */
+ note?: ReactNode;
onChanged: () => void;
}) {
const t = useText(listenText);
- const [draft, setDraft] = useState(() => draftOf(view));
- const [nics, setNics] = useState(null);
+ const saved = draftOf(view);
+ const { draft, setDraft, dirty, commit, reset } = useFormDraft("listen", saved, same);
+ // 网卡清单每次打开这一节都重取 —— 它会变(插拔网线、换 Wi-Fi、起 VPN);取到之前先画上一次的
+ const nicList = useResource("settings:interfaces", () =>
+ call("Interfaces", null).then((list) => list.filter((n) => !n.loopback)),
+ );
+ const nics = nicList.data ?? null;
// 放弃更改时连同名单里没加进去的那一行一起清掉:换一个 key 让它重来
const [epoch, setEpoch] = useState(0);
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
-
- const saved = draftOf(view);
- const dirty = !same(draft, saved);
- // 配置换了一份(别处改的、或者刚存完):没在改的时候跟着走
- const dirtyRef = useRef(dirty);
- dirtyRef.current = dirty;
- const viewKey = JSON.stringify(view);
- useEffect(() => {
- if (!dirtyRef.current) setDraft(draftOf(JSON.parse(viewKey) as ListenView));
- }, [viewKey]);
-
- // 网卡清单每次打开这一节现拉 —— 它会变(插拔网线、换 Wi-Fi、起 VPN)
- useEffect(() => {
- let alive = true;
- void call("Interfaces", null)
- .then((list) => alive && setNics(list.filter((n) => !n.loopback)))
- .catch(() => alive && setNics([]));
- return () => {
- alive = false;
- };
- }, []);
+ const [justSaved, flash] = useSavedFlash();
+ useDirtyMark("listen", dirty);
// 选「局域网」时网卡清单还没到:到了就落到第一张,不让保存一直灰着
useEffect(() => {
const first = nics?.[0]?.name;
if (first) setDraft((d) => (d.level === "lan" && !d.nic ? { ...d, nic: first } : d));
- }, [nics]);
+ }, [nics, setDraft]);
const set = (patch: Partial) => {
setError(null);
@@ -141,11 +131,10 @@ export function ListenSection({
setError(null);
try {
await call("SaveListen", body);
- // 存上了就不算在改:配置换回来那一刻表单跟着新值走。网卡按名字存,
- // 草稿里若还是地址,先换成名字,否则配置回来之后两边对不上、表单一直显示改过
- dirtyRef.current = false;
- setDraft((d) => ({ ...d, nic: d.level === "lan" ? bind : "" }));
- toast.success(t.saved);
+ // 网卡按名字存。草稿里若还是地址,先换成名字,否则配置推回来之后两边对不上、
+ // 表单一直显示改过
+ commit({ ...draft, nic: draft.level === "lan" ? bind : "" });
+ flash();
onChanged();
} catch (e) {
setError(errorText(e));
@@ -156,113 +145,148 @@ export function ListenSection({
const what = draft.level === "local" ? t.localWhat : draft.level === "lan" ? t.lanWhat : t.allWhat;
/**
- * **防火墙那一句只在 Linux 上说。**macOS 和 Windows 的防火墙在应用第一次
- * 对外监听时会弹窗问用户放不放行,用户当场就知道有这么一道;Fedora、
- * openSUSE 默认开着的 firewalld(以及手动开了的 ufw)不问,直接丢包 ——
- * 另一台机器上只看到连接超时,而界面这边一切正常。
+ * **防火墙那一句只在 Linux 上说。**macOS 和 Windows 的防火墙在应用第一次对外监听
+ * 时会弹窗问放不放行,用户当场就知道有这么一道;Fedora、openSUSE 默认开着的
+ * firewalld(以及手动开了的 ufw)不问,直接丢包 —— 另一台机器上只看到连接超时,
+ * 而界面这边一切正常。
*/
const scopeHint = exposed && isLinux ? `${what}${t.firewall}` : what;
+ const addr = status?.gateway_addr ?? null;
+ // 别的设备该连的地址:只在配置里已经对外开放、core 也算出来了的时候写
+ const reachable = levelOf(view.bind) !== "local" ? (status?.gateway_reachable ?? []) : [];
return (
-
- {t.title}
-
-
- {status?.gateway_addr ?? t.notListening}
-
+
+ {/* 配置里写的地址没换上(手改了配置、网卡没了地址):旧地址还在服务 */}
+
+ {status?.listen_error ? t.staleBody(coreText(status.listen_error), addr ?? "") : null}
+
+
+ )}
- {error && (
-
-
- {t.saveFailed}
- {error}
-
- )}
-
- {/* 配置里写的地址没换上(手改了配置、网卡没了地址):旧地址还在服务 */}
- {!error && status?.listen_error && (
-
-
- {t.staleTitle}
-
- {t.staleBody(coreText(status.listen_error), status.gateway_addr ?? "")}
-
-
- )}
-
+ {
+ setError(null);
+ setEpoch((n) => n + 1);
+ reset();
+ }}
+ />
+
+
+
+ {error}
+
+ {note && {note}
}
+
);
}
+
diff --git a/src/settings/RangeList.i18n.ts b/src/settings/RangeList.i18n.ts
index 970fe547..33c585e4 100644
--- a/src/settings/RangeList.i18n.ts
+++ b/src/settings/RangeList.i18n.ts
@@ -7,6 +7,7 @@ export const rangeListText = messages(
/** 一行是单个地址时,右边写这个而不是起止 */
single: "单个地址",
remove: (c: string) => `删除 ${c}`,
+ removeShort: "删除",
what: "可添加多个网段或单个地址。只有这些来源的设备可以连接,本机始终可以连接。",
empty: "未放行任何网段,除本机外的设备都无法连接。",
restore: "恢复默认",
@@ -17,6 +18,7 @@ export const rangeListText = messages(
enterToAdd: "Enter to add",
single: "single address",
remove: (c: string) => `Remove ${c}`,
+ removeShort: "Remove",
what: "Add as many ranges or single addresses as needed. Only devices from these can connect; this computer always can.",
empty: "No range is allowed, so only this computer can connect.",
restore: "Restore defaults",
diff --git a/src/settings/RangeList.tsx b/src/settings/RangeList.tsx
index 0ebb424e..0760773e 100644
--- a/src/settings/RangeList.tsx
+++ b/src/settings/RangeList.tsx
@@ -1,7 +1,8 @@
import { useState } from "react";
-import { XIcon } from "lucide-react";
import { cn } from "@/lib/utils";
+import { Button } from "@/ui/button";
import { Input } from "@/ui/input";
+import { rowMotion, usePresentList } from "@/ui/motion";
import { useText } from "@/i18n";
import { Boxed } from "@/upstreams/parts";
import { parseRange, rangeText, v4Span } from "./cidr";
@@ -20,7 +21,8 @@ function sameSet(a: string[], b: string[]): boolean {
* 的话,已经加进去的几条看起来像另一个输入框,而没按回车的那一条看起来
* 像是已经加上了。
*
- * 写错的当场说,留在输入框里改;不带前缀的是单个地址。
+ * 写错的当场说,留在输入框里改;不带前缀的是单个地址。**删一条写成字**(「删除」),
+ * 不用 ×:× 在这个应用里只表示关闭。
*/
export function RangeList({
id,
@@ -37,6 +39,7 @@ export function RangeList({
onChange: (next: string[]) => void;
}) {
const t = useText(rangeListText);
+ const rows = usePresentList(value, (c) => c);
const [draft, setDraft] = useState("");
const [bad, setBad] = useState(null);
@@ -64,22 +67,27 @@ export function RangeList({
return (
- {value.map((c) => (
-
+ {rows.map(({ item: c, key, presence }) => (
+
{c}
{note(c)}
- onChange(value.filter((x) => x !== c))}
>
-
-
+ {t.removeShort}
+
))}
-
+
{value.length === 0 ? t.empty : t.what}
{!sameSet(value, defaults) && (
-
onChange(defaults)}
>
{t.restore}
-
+
)}
)}
diff --git a/src/settings/RetentionSection.i18n.ts b/src/settings/RetentionSection.i18n.ts
index 3dfc445b..897fccd3 100644
--- a/src/settings/RetentionSection.i18n.ts
+++ b/src/settings/RetentionSection.i18n.ts
@@ -9,11 +9,11 @@ export const retentionText = messages(
rowDays: "记录",
rowDaysWhat: "请求的时刻、模型、用量和费用,用于统计较长时间段的费用。",
bodyMax: "报文上限",
- bodyMaxWhat: (used: string) => `超出后从最早的一天开始删除。当前占用 ${used}。`,
+ bodyMaxWhat: "超出后从最早的一天开始删除。",
+ usage: "报文当前占用",
days: "天",
bad: "须为正整数。",
badGb: "须为正数,最多一位小数。",
- saved: "日志保留设置已保存",
saveFailed: "未能保存",
},
{
@@ -25,11 +25,11 @@ export const retentionText = messages(
rowDays: "Records",
rowDaysWhat: "Each request's time, model, usage and cost, for totals over longer periods.",
bodyMax: "Payload cap",
- bodyMaxWhat: (used: string) => `Over it, the oldest days go first. Currently in use: ${used}.`,
+ bodyMaxWhat: "Over it, the oldest days go first.",
+ usage: "Payload storage in use",
days: "days",
bad: "A positive whole number.",
badGb: "A positive number with at most one decimal place.",
- saved: "Log retention settings saved",
saveFailed: "Not saved",
},
);
diff --git a/src/settings/RetentionSection.tsx b/src/settings/RetentionSection.tsx
index 7e14409a..54ad78bb 100644
--- a/src/settings/RetentionSection.tsx
+++ b/src/settings/RetentionSection.tsx
@@ -1,12 +1,12 @@
-import { useEffect, useRef, useState } from "react";
-import { toast } from "sonner";
-import { TriangleAlertIcon } from "lucide-react";
-import { Alert, AlertDescription, AlertTitle } from "@/ui/alert";
+import { useState } from "react";
+import { cn } from "@/lib/utils";
+import { Banner } from "@/ui/banner";
import { useText } from "@/i18n";
import { errorText } from "@/i18n/core.i18n";
import { patchConfig } from "@/patch";
import type { PatchOp, RetentionView } from "@/types";
-import { FormActions, FormRow, FormRows, NumberInput, intIn } from "./form";
+import { NumberInput, intIn, useFormDraft } from "./form";
+import { SaveBar, SettingsCard, SettingsGroup, SettingsRow, useDirtyMark, useSavedFlash } from "./kit";
import { retentionText } from "./RetentionSection.i18n";
const GIB = 1024 * 1024 * 1024;
@@ -24,49 +24,46 @@ const draftOf = (r: RetentionView): Draft => ({
body_max_gb: gib(r.body_max_bytes),
});
+const same = (a: Draft, b: Draft) =>
+ a.body_days === b.body_days && a.row_days === b.row_days && a.body_max_gb === b.body_max_gb;
+
+/** 一位小数以内的正数 */
+const gbOk = (v: string) => /^\d+(\.\d)?$/.test(v) && Number(v) > 0;
+
/**
* 日志留多久。
*
- * **两个期限,因为两样东西的代价差三个数量级。**一条报文几十 KB,忙一天
- * 就是几百 MB;一行记录(时刻、模型、用量、费用)几百字节,留一个季度也
- * 不过几十 MB。合成一个期限,要么早早丢掉「上个月的费用」,要么让磁盘替
- * 报文买单。
+ * **两个期限,因为两样东西的代价差三个数量级。**一条报文几十 KB,忙一天就是几百
+ * MB;一行记录(时刻、模型、用量、费用)几百字节,留一个季度也不过几十 MB。合成
+ * 一个期限,要么早早丢掉「上个月的费用」,要么让磁盘替报文买单。
*
- * **总量上限旁边写现在占了多少。**「2 GB」这个数字,用户没法判断松还是
- * 紧 —— 除非同时看得见当下的占用。
+ * **总量上限旁边画出现在占了多少。**「2 GB」这个数字,用户没法判断松还是紧 ——
+ * 除非同时看得见当下的占用。条的长度按格子里正在填的上限算:改小之前就看得见会不会
+ * 马上被删。
*/
export function RetentionSection({
retention,
configVersion,
+ onChanged,
}: {
retention: RetentionView;
configVersion: string;
+ onChanged: () => void;
}) {
const t = useText(retentionText);
- const [draft, setDraft] = useState(() => draftOf(retention));
+ const saved = draftOf(retention);
+ const { draft, setDraft, dirty, commit, reset } = useFormDraft("retention", saved, same);
const [busy, setBusy] = useState(false);
const [error, setError] = useState
(null);
-
- const saved = draftOf(retention);
- const dirty =
- draft.body_days !== saved.body_days ||
- draft.row_days !== saved.row_days ||
- draft.body_max_gb !== saved.body_max_gb;
- const dirtyRef = useRef(dirty);
- dirtyRef.current = dirty;
- const key = JSON.stringify([retention.body_days, retention.row_days, retention.body_max_bytes]);
- useEffect(() => {
- if (!dirtyRef.current) {
- const [body_days, row_days, max] = JSON.parse(key) as [number, number, number];
- setDraft({ body_days: String(body_days), row_days: String(row_days), body_max_gb: gib(max) });
- }
- }, [key]);
+ const [justSaved, flash] = useSavedFlash();
+ useDirtyMark("retention", dirty);
const ok = {
body_days: intIn(draft.body_days, 1, 3_650),
row_days: intIn(draft.row_days, 1, 36_500),
- body_max_gb: /^\d+(\.\d)?$/.test(draft.body_max_gb) && Number(draft.body_max_gb) > 0,
+ body_max_gb: gbOk(draft.body_max_gb),
};
+ const valid = ok.body_days && ok.row_days && ok.body_max_gb;
async function save() {
const ops: PatchOp[] = [];
@@ -84,8 +81,9 @@ export function RetentionSection({
setError(null);
try {
await patchConfig(ops, configVersion);
- dirtyRef.current = false;
- toast.success(t.saved);
+ commit();
+ flash();
+ onChanged();
} catch (e) {
setError(errorText(e));
} finally {
@@ -98,65 +96,121 @@ export function RetentionSection({
setDraft((d) => ({ ...d, [k]: v }));
};
+ // 条按正在填的上限画;格子里写的不是个数时按配置里的
+ const cap = ok.body_max_gb ? Number(draft.body_max_gb) * GIB : retention.body_max_bytes;
+ const bad = (msg: string) => {msg};
+
return (
-
- {t.title}
- {t.intro}
-
-
-
+
-
-
+ }
/>
-
-
-
+ {t.bodyMaxWhat}
+
+ >
+ ) : (
+ bad(t.badGb)
+ )
+ }
+ control={
+
+ }
/>
-
- void save()}
- onDiscard={() => {
- setError(null);
- setDraft(saved);
- }}
+ {
+ setError(null);
+ reset();
+ }}
+ />
+
+
+
+ {error}
+
+
+ );
+}
+
+/**
+ * 报文现在占了上限的多少:一根细条和「412 MB / 2 GB」。**快满了才上颜色**(九成
+ * 以上),平时是灰的 —— 占用本身不是问题。
+ */
+function Usage({ used, cap, label }: { used: number; cap: number; label: string }) {
+ const ratio = cap > 0 ? Math.min(1, used / cap) : 0;
+ const near = ratio >= 0.9;
+ return (
+
+
+ 0 ? Math.max(2, ratio * 100) : 0}%` }}
/>
-
- {error && (
-
-
- {t.saveFailed}
- {error}
-
- )}
-
+
+
+ {bytes(used)} / {bytes(cap)}
+
+
);
}
diff --git a/src/settings/SettingsPage.i18n.tsx b/src/settings/SettingsPage.i18n.tsx
new file mode 100644
index 00000000..56fcf5db
--- /dev/null
+++ b/src/settings/SettingsPage.i18n.tsx
@@ -0,0 +1,162 @@
+import type { ReactNode } from "react";
+import { messages } from "@/i18n";
+import { isMac, isWindows } from "@/platform";
+
+/** 句中要套一层组件(悬浮说明、加粗)的那一段 */
+type Wrap = (text: string) => ReactNode;
+
+/** 这台机器叫什么。和远程模式那几句(`remote.i18n.tsx`)同一个说法 */
+const hereZh = isMac ? "这台 Mac" : "这台电脑";
+const hereEn = isMac ? "This Mac" : "This computer";
+
+/** 卸载做完之后用户还要做的那一步,按平台说 */
+const afterZh = isMac ? "完成后即可将应用移到废纸篓。" : isWindows ? "完成后即可卸载或删除应用。" : "完成后即可删除应用。";
+const afterEn = isMac
+ ? "Once it finishes, the app can be moved to the Trash."
+ : isWindows
+ ? "Once it finishes, the app can be uninstalled or deleted."
+ : "Once it finishes, the app can be deleted.";
+
+/**
+ * 设置页:页头、目录、「关于」和「卸载」两节。其余各节的文案在各自的词表里
+ * (`GeneralSection.i18n.ts`、`ListenSection.i18n.ts`、`RetentionSection.i18n.ts`、
+ * `connection/connection.i18n.tsx`)。
+ */
+export const settingsText = messages(
+ {
+ title: "设置",
+
+ // 页头的摘要
+ running: "运行中",
+ gateway: "网关",
+ notListening: "未在监听",
+ scopeLocal: "仅本机",
+ scopeLan: "局域网",
+ scopeAll: "所有网卡",
+ versionIs: (v: string) => `版本 ${v}`,
+ /** 页头摘要里新版本号后面那两个字 */
+ available: "可用",
+
+ // 目录里的小标题(连着远程时)
+ here: hereZh,
+
+ // 关于
+ about: "关于",
+ /** 「关于」里版本和检查更新那一块;命令面板里搜得到的那一项 */
+ updates: "更新",
+ appName: "ThinkWatch Lite",
+ latest: "已是最新版本",
+ newer: (v: string) => `新版本 ${v} 可用`,
+ checking: "正在检查更新",
+ checkFailed: "检查更新失败",
+ checkNow: "检查更新",
+ updateTo: (v: string) => `更新到 ${v}…`,
+ homebrew: "Homebrew",
+ devBuild: "开发构建",
+ autoCheck: "自动检查新版本",
+ dataDir: "数据目录",
+ coreBin: "core 二进制",
+
+ // 诊断包
+ diagnostics: "诊断包",
+ diagnosticsBody: (tip: Wrap) => (
+ <>
+ 包含版本、上游、熔断状态、近期失败记录与脱敏后的配置文件。{tip("不含请求与响应正文")}。
+ >
+ ),
+ diagnosticsTip: "不包含请求体与响应体,其中可能含有用户粘贴的内容。",
+ generate: "生成",
+ generated: "已生成",
+ /** 诊断包由 core 生成:没连上时那一行说明白 */
+ diagnosticsOffline: "连接到 core 后可生成诊断包。",
+ review: (em: Wrap) => <>其中的密钥与地址已脱敏,{em("提交前请自行核对")}。>,
+
+ // 卸载
+ uninstall: "卸载",
+ uninstallTitle: "完全卸载",
+ uninstallIntro: (em: Wrap) => (
+ <>
+ 还原所有已接管的客户端,并取消开机启动。
+ {em(isMac ? "直接将应用移到废纸篓不会执行这些操作" : "通过系统卸载或直接删除应用不会执行这些操作")},已接管的客户端将指向一个无人监听的端口。
+ >
+ ),
+ uninstallAction: "卸载…",
+ willDo: `将执行以下操作。${afterZh}`,
+ restoreClients: "还原已接管的客户端",
+ restoreNone: "当前无已接管的客户端",
+ /** 列名字时的分隔 */
+ sep: "、",
+ stopAutostart: "取消开机启动",
+ dropData: "同时删除数据目录",
+ dropDataWhat: "包括请求历史、费用记录与配置备份,删除后无法恢复。",
+ confirmUninstall: "卸载",
+ uninstalled: "卸载完成",
+ uninstallFailed: "未能完成卸载",
+ uninstalledRow: "已完成卸载。",
+ },
+ {
+ title: "Settings",
+
+ running: "Running",
+ gateway: "Gateway",
+ notListening: "Not listening",
+ scopeLocal: "This machine only",
+ scopeLan: "Local network",
+ scopeAll: "Every interface",
+ versionIs: (v: string) => `Version ${v}`,
+ available: "available",
+
+ here: hereEn,
+
+ about: "About",
+ updates: "Updates",
+ appName: "ThinkWatch Lite",
+ latest: "Up to date",
+ newer: (v: string) => `Version ${v} is available`,
+ checking: "Checking for updates",
+ checkFailed: "Update check failed",
+ checkNow: "Check for updates",
+ updateTo: (v: string) => `Update to ${v}…`,
+ homebrew: "Homebrew",
+ devBuild: "Development build",
+ autoCheck: "Check for updates automatically",
+ dataDir: "Data directory",
+ coreBin: "Core binary",
+
+ diagnostics: "Diagnostics bundle",
+ diagnosticsBody: (tip: Wrap) => (
+ <>
+ Contains the version, upstreams, circuit breaker states, recent failures and the redacted config file.{" "}
+ {tip("No request or response bodies")}.
+ >
+ ),
+ diagnosticsTip: "Request and response bodies are left out, since they may contain content the user pasted in.",
+ generate: "Generate",
+ generated: "Generated",
+ diagnosticsOffline: "A bundle can be generated once connected to a core.",
+ review: (em: Wrap) => <>Keys and addresses in it are redacted; {em("review it before sharing")}.>,
+
+ uninstall: "Uninstall",
+ uninstallTitle: "Full uninstall",
+ uninstallIntro: (em: Wrap) => (
+ <>
+ Restores every connected client and turns off launch at login.{" "}
+ {em(isMac ? "Moving the app straight to the Trash does neither" : "Uninstalling or deleting the app through the system does neither")}, leaving connected clients pointed at a port
+ where nothing is listening.
+ >
+ ),
+ uninstallAction: "Uninstall…",
+ willDo: `The following is done. ${afterEn}`,
+ restoreClients: "Restore connected clients",
+ restoreNone: "No client is connected at the moment",
+ sep: ", ",
+ stopAutostart: "Turn off launch at login",
+ dropData: "Also delete the data directory",
+ dropDataWhat: "The request history, cost records and config backups. This cannot be undone.",
+ confirmUninstall: "Uninstall",
+ uninstalled: "Uninstall complete",
+ uninstallFailed: "The uninstall did not finish",
+ uninstalledRow: "The uninstall is complete.",
+ },
+);
+
diff --git a/src/settings/SettingsPage.tsx b/src/settings/SettingsPage.tsx
new file mode 100644
index 00000000..dd683042
--- /dev/null
+++ b/src/settings/SettingsPage.tsx
@@ -0,0 +1,302 @@
+import type { ReactNode } from "react";
+import { call } from "@/control";
+import { cn } from "@/lib/utils";
+import { useResource } from "@/lib/resource";
+import { Button } from "@/ui/button";
+import { Page, PageHeader, SummaryItem } from "@/ui/page";
+import { StatusDot } from "@/ui/status-dot";
+import { IconLocal, IconRemote } from "@/ui/icons";
+import { useText } from "@/i18n";
+import { useConnections } from "@/connection/ConnectionProvider";
+import { ConnectionsSection, linkStatus, type LinkStatus } from "@/connection/ConnectionsSection";
+import { currentProfile } from "@/connection/api";
+import { connText } from "@/connection/connection.i18n";
+import { profileName } from "@/connection/describe";
+import { remoteText } from "@/connection/remote.i18n";
+import { remoteStatus, type Tone } from "@/connection/Switcher";
+import { useRemote } from "@/connection/useRemote";
+import type { CoreStatus, Overview } from "@/types";
+import { AboutSection } from "./AboutSection";
+import { APP_KEYS, settingsApi } from "./api";
+import { GeneralSection } from "./GeneralSection";
+import { generalText } from "./GeneralSection.i18n";
+import { kitText } from "./kit.i18n";
+import {
+ ErrorRow,
+ OfflineRow,
+ RowSkeleton,
+ SettingsCard,
+ SettingsGroup,
+ SettingsShell,
+ useSettingsNav,
+ type IndexItem,
+} from "./kit";
+import { ListenSection, levelOf } from "./ListenSection";
+import { listenText } from "./ListenSection.i18n";
+import { RetentionSection } from "./RetentionSection";
+import { retentionText } from "./RetentionSection.i18n";
+import { settingsText } from "./SettingsPage.i18n";
+import { UninstallSection } from "./UninstallSection";
+
+/**
+ * 设置。
+ *
+ * **两类东西,两种改法。**连接、通用(语言、外观、菜单栏、开机启动、提醒)改的是
+ * 这个应用,点一下就换;网关监听、日志保留改的是 config.yaml,改完点保存才生效 ——
+ * 它们改错的代价是客户端连不上、或者日志被删。上游、路由、密钥这些要天天看、常常改
+ * 的,各有自己的页。
+ *
+ * 左边一列目录,跟着滚动点亮当前那一节;改了没存的节在目录上挂一个点。连着远程 core
+ * 时分成两组(设计稿 ⑧):这台 Mac 上的应用,和服务器的配置 —— 混在一起的话,「语言」
+ * 和「监听」挨着,分不清哪一项改的是服务器。
+ *
+ * **连接那一节不依赖 core**:没连上 core 时整页照样打开(连接管理就在这里),只有改
+ * 配置文件的两节说明现在改不了。
+ */
+export function SettingsPage({
+ ov,
+ status,
+ local: localCore,
+ linked,
+ coreReadOnly = false,
+ onChanged,
+}: {
+ ov: Overview | null;
+ status: CoreStatus | null;
+ /** 本机 core 此刻怎么样,和侧栏左下角同一句(App 的 `describeCore`)。连本机时连接那一行和页头写它 */
+ local: { text: string; tone: Tone };
+ /** 控制面答应了。没有的话改配置文件的两节画成「连接后可修改」 */
+ linked: boolean;
+ /** 连着的远程 core 断了:改它配置的几节只读,应用自己的设置照常能改 */
+ coreReadOnly?: boolean;
+ /** 存完监听、日志保留之后叫一声,状态和概览跟着重读 */
+ onChanged: () => void;
+}) {
+ const t = useText(settingsText);
+ const ct = useText(connText);
+ const rt = useText(remoteText);
+ const gt = useText(generalText);
+ const lt = useText(listenText);
+ const et = useText(retentionText);
+ const remote = useRemote();
+ const local = linkStatus(localCore);
+
+ /*
+ 改配置文件的两节要概览(`ov`,外壳读的)。外壳读失败时只是留着 null、等下一次再读;
+ 这里自己再问一遍:问到了就先用它,问不到就在这两节里说出来、给重试 —— 不让骨架一直转
+ */
+ const probe = useResource(linked && !ov ? "settings:overview" : null, () => call("Overview", null));
+ const view = ov ?? probe.data ?? null;
+ const pending: Pending = !linked
+ ? { kind: "offline" }
+ : probe.error !== undefined
+ ? {
+ kind: "failed",
+ error: probe.error,
+ retrying: probe.loading,
+ retry: () => {
+ void probe.reload();
+ // 外壳那一份也重读:读到了这两节就换回外壳的
+ onChanged();
+ },
+ }
+ : { kind: "loading" };
+
+ const items: IndexItem[] = remote
+ ? [
+ { id: "connections", label: ct.title, caption: t.here },
+ { id: "general", label: gt.title },
+ { id: "about", label: t.about },
+ { id: "uninstall", label: t.uninstall },
+ { id: "listen", label: lt.title, caption: remote.name },
+ { id: "retention", label: et.title },
+ ]
+ : [
+ { id: "connections", label: ct.title },
+ { id: "general", label: gt.title },
+ { id: "listen", label: lt.title },
+ { id: "retention", label: et.title },
+ { id: "about", label: t.about },
+ { id: "uninstall", label: t.uninstall },
+ ];
+
+ const server = (
+ /*
+ 断线时这两节只读:`fieldset disabled` 让里面的按钮、输入框、下拉一起失效,读、
+ 滚动、悬停说明照旧。应用自己的那几节不受影响
+ */
+
+ );
+
+ return (
+
+ } />
+ }
+ >
+ {remote ? (
+ <>
+ }>{rt.appGroup}
+
+
+
+
+ }>{rt.serverGroup(remote.name)}
+ {server}
+ >
+ ) : (
+ <>
+
+
+ {server}
+
+
+ >
+ )}
+
+
+ );
+}
+
+/**
+ * 页头下面那一行:连的是哪个 core、它此刻怎么样;网关在哪个地址、谁能连;这个应用
+ * 是哪一版,有新版本时点过去就是「关于」。只有状态和数,不写说明。
+ */
+function Summary({
+ local,
+ status,
+ ov,
+ linked,
+}: {
+ local: LinkStatus;
+ status: CoreStatus | null;
+ ov: Overview | null;
+ linked: boolean;
+}) {
+ const t = useText(settingsText);
+ const ct = useText(connText);
+ const { view } = useConnections();
+ const { jump } = useSettingsNav();
+ const update = useResource(APP_KEYS.update, settingsApi.update);
+ const p = view ? currentProfile(view) : undefined;
+ const remote = p && !p.local && view ? remoteStatus(view) : null;
+ const state = remote ? linkStatus(remote) : local;
+ const name = p ? profileName(p) : ct.local;
+ /**
+ * 网关地址和侧栏左下角写同一个:连着远程时是这台 Mac 连过去要用的那个(服务器的
+ * 主机名加网关端口),不是服务器上绑的 `0.0.0.0`
+ */
+ const addr = remote && view?.link.kind === "connected" ? remote.addr : (status?.gateway_addr ?? null);
+ const scope = ov ? levelOf(ov.listen.bind) : null;
+ const offer = update.data?.offer ?? null;
+
+ // 状态、地址换了(刚存完监听、刚连上):新的那一句淡入,不是原地跳字
+ return (
+ <>
+ }
+ value={name}
+ label={
+
+ {state.text}
+
+ }
+ />
+ {linked && status && (
+
+ {addr ?? t.notListening}
+
+ }
+ label={scope === "local" ? t.scopeLocal : scope === "lan" ? t.scopeLan : scope === "all" ? t.scopeAll : ""}
+ />
+ )}
+ {offer ? (
+ // 有新版本:点过去就是「关于」,更新的按钮在那里
+ jump("about")}
+ >
+ } value={offer.version} label={t.available} />
+
+ ) : (
+ update.data &&
+ )}
+ >
+ );
+}
+
+/** 连着远程时两组之间的分隔:这台 Mac 上的应用 / 服务器的配置 */
+function ScopeHeading({ icon, children }: { icon: ReactNode; children: ReactNode }) {
+ return (
+
+ {icon}
+ {children}
+
+ );
+}
+
+/** 改配置文件的两节在拿到概览之前是什么情况 */
+type Pending =
+ | { kind: "loading" }
+ | { kind: "offline" }
+ | { kind: "failed"; error: unknown; retrying: boolean; retry: () => void };
+
+/**
+ * 改配置文件的两节在概览到之前的样子:在读就是骨架(数据马上到),没连上就说连接后
+ * 可修改,读不出来就说出来、给重试 —— 不画一张什么都读不出来的表单。
+ */
+function Placeholder({
+ id,
+ title,
+ description,
+ state,
+ rows,
+}: {
+ id: string;
+ title: string;
+ description?: string;
+ state: Pending;
+ rows: number;
+}) {
+ const kt = useText(kitText);
+ return (
+
+
+ {state.kind === "offline" ? (
+
+ ) : state.kind === "failed" ? (
+
+ ) : (
+ Array.from({ length: rows }, (_, i) => )
+ )}
+
+
+ );
+}
diff --git a/src/settings/UninstallSection.tsx b/src/settings/UninstallSection.tsx
new file mode 100644
index 00000000..fa262f84
--- /dev/null
+++ b/src/settings/UninstallSection.tsx
@@ -0,0 +1,197 @@
+import { useState } from "react";
+import { PowerOffIcon, RotateCcwIcon } from "lucide-react";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/ui/alert-dialog";
+import { Banner } from "@/ui/banner";
+import { Button } from "@/ui/button";
+import { Checkbox } from "@/ui/checkbox";
+import { Skeleton } from "@/ui/skeleton";
+import { Spinner } from "@/ui/spinner";
+import { useResource } from "@/lib/resource";
+import { useText } from "@/i18n";
+import { commonText } from "@/i18n/common.i18n";
+import { errorText } from "@/i18n/core.i18n";
+import { api as clientsApi } from "@/clients/api";
+import { remoteText } from "@/connection/remote.i18n";
+import type { RemoteCore } from "@/connection/api";
+import { APP_KEYS, settingsApi } from "./api";
+import { SettingsCard, SettingsGroup, SettingsRow } from "./kit";
+import { settingsText } from "./SettingsPage.i18n";
+
+/**
+ * 最近一次卸载每一步的结果。**放在模块里**:切到别的页再回来,这一节还记得已经
+ * 卸载过(这之后用户多半就去把应用移到废纸篓了)。
+ */
+let lastLog: string[] | null = null;
+
+/**
+ * 完全卸载。
+ *
+ * **macOS 上删除应用没有卸载钩子**:拖进废纸篓就是拖进废纸篓,没有任何机会做
+ * 清理 —— 而那时接管过的客户端全都指向一个已经没有东西在听的端口,所有 AI 客户端
+ * 同时失效,用户很可能已经忘了是什么改的。所以这个入口必须在,而且要在他还没删
+ * 应用的时候就看得见。
+ *
+ * 按下去先弹确认,**列出会发生的每一件事**(还原哪几个客户端、取消开机启动、要不
+ * 要连数据一起删);删数据默认不勾:请求历史和费用记录是用户自己的东西,删了才发现
+ * 还想看是不可逆的。做完在同一个对话框里逐条说结果。
+ */
+export function UninstallSection({ remote }: { remote: RemoteCore | null }) {
+ const t = useText(settingsText);
+ const rt = useText(remoteText);
+ const [open, setOpen] = useState(false);
+ const [log, setLog] = useState(lastLog);
+ const em = (text: string) => {text};
+ return (
+
+
+
+ {log ? (log.at(-1) ?? t.uninstalledRow) : t.uninstallIntro(em)}
+ {remote && !log && {rt.uninstallServer(remote.name)}}
+ >
+ }
+ control={
+ setOpen(true)}>
+ {t.uninstallAction}
+
+ }
+ />
+
+ {open && (
+ setOpen(false)}
+ onDone={(l) => {
+ lastLog = l;
+ setLog(l);
+ }}
+ />
+ )}
+
+ );
+}
+
+type Stage = { kind: "ask" } | { kind: "running" } | { kind: "done"; log: string[] } | { kind: "failed"; error: unknown };
+
+function UninstallDialog({ onClose, onDone }: { onClose: () => void; onDone: (log: string[]) => void }) {
+ const t = useText(settingsText);
+ const common = useText(commonText);
+ const [drop, setDrop] = useState(false);
+ const [stage, setStage] = useState({ kind: "ask" });
+ const info = useResource(APP_KEYS.info, settingsApi.info);
+ /**
+ * 会被还原的是哪几个。**读不到就不列名字**(只说「还原已接管的客户端」):
+ * 列表读不出来不该挡住卸载
+ */
+ const clients = useResource("settings:uninstall-clients", clientsApi.list);
+ const adopted = clients.data?.clients.filter((c) => c.adopted_at_ms !== null).map((c) => c.name);
+ const running = stage.kind === "running";
+ const done = stage.kind === "done";
+
+ async function run() {
+ setStage({ kind: "running" });
+ try {
+ const log = await settingsApi.uninstall(drop);
+ setStage({ kind: "done", log });
+ onDone(log);
+ } catch (e) {
+ setStage({ kind: "failed", error: e });
+ }
+ }
+
+ const names = adopted ? adopted.join(t.sep) : null;
+ return (
+ !o && !running && onClose()}>
+
+
+ {done ? t.uninstalled : t.uninstallTitle}
+ {!done && {t.willDo}}
+
+
+ {stage.kind === "done" ? (
+
+ {stage.log.map((line, i) => (
+ -
+
+ {line}
+
+ ))}
+
+ ) : (
+
+ -
+
+
+
{t.restoreClients}
+ {clients.data === undefined && clients.loading ? (
+
+ ) : names !== null ? (
+
{names || t.restoreNone}
+ ) : null}
+
+
+ -
+
+
{t.stopAutostart}
+
+ -
+ setDrop(c === true)}
+ />
+
+
+
+ )}
+
+
+ {stage.kind === "failed" ? errorText(stage.error) : null}
+
+
+
+ {done ? (
+ {common.close}
+ ) : (
+ <>
+ {common.cancel}
+ {
+ // 做完之前不关:结果要在这个对话框里逐条说
+ e.preventDefault();
+ void run();
+ }}
+ >
+ {running && }
+ {t.confirmUninstall}
+
+ >
+ )}
+
+
+
+ );
+}
diff --git a/src/settings/api.ts b/src/settings/api.ts
new file mode 100644
index 00000000..3b54fbf9
--- /dev/null
+++ b/src/settings/api.ts
@@ -0,0 +1,82 @@
+/**
+ * 设置页里「这个应用自己的」那几项:类型化的 invoke 和它们的类型。
+ *
+ * **都不经 core。**语言、外观、菜单栏、提醒、开机启动、更新、关于和卸载都是 Rust
+ * 这一侧的事(`src-tauri/src/settings.rs`、`updater.rs`、`uninstall.rs`),远程
+ * core 连不上时照样能读能改。改配置文件的两节(监听、日志保留)走 core,不在这里。
+ */
+import { invoke } from "@tauri-apps/api/core";
+import type { Lang } from "@/i18n";
+import type { Found, UpdateView } from "@/updateFlow";
+
+export type Theme = "light" | "dark";
+/** 设置里的三档:`system` 是跟随系统 */
+export type ThemeChoice = "system" | Theme;
+
+/** 现在用的、设置里选的(`null` 是跟随系统)、系统的 */
+export interface ThemeView {
+ current: Theme;
+ setting: Theme | null;
+ system: Theme;
+}
+
+/** 现在用的、设置里选的(`null` 是跟随系统)、系统的 */
+export interface LanguageView {
+ current: Lang;
+ setting: Lang | null;
+ system: Lang;
+}
+
+/** 菜单栏:标识和数值 / 仅标识 / 仅数值(只有 macOS 有) */
+export type MenubarStyle = "full" | "icon" | "numbers";
+
+/** 提醒:系统通知 / 仅在应用内 / 关闭 */
+export type NoticeMode = "system" | "app" | "off";
+
+/** `app_info`:排查时最先要问的几样 */
+export interface AppInfo {
+ version: string;
+ identifier: string;
+ data_dir: string;
+ /** core 二进制的位置;找不到时是那条错误(里面列着找过的位置) */
+ core_bin: string;
+}
+
+export const settingsApi = {
+ theme: () => invoke("app_theme"),
+ setTheme: (setting: Theme | null) => invoke("set_theme", { setting }),
+ language: () => invoke("app_language"),
+ setLanguage: (setting: Lang | null) => invoke("set_language", { setting }),
+ menubar: () => invoke("menubar_style"),
+ setMenubar: (style: MenubarStyle) => invoke("set_menubar_style", { style }),
+ noticeMode: () => invoke("notice_mode"),
+ setNoticeMode: (mode: NoticeMode) => invoke("set_notice_mode", { mode }),
+ autostart: () => invoke("autostart_enabled"),
+ /** 交回的是**实际**的状态:注册可能失败(只读的 LaunchAgents 目录、权限) */
+ setAutostart: (on: boolean) => invoke("set_autostart", { on }),
+ update: () => invoke("update_state"),
+ setUpdateCheck: (on: boolean) => invoke("set_update_check", { on }),
+ /** 查到了的话 Rust 那边会把更新窗口拉起来 */
+ checkUpdate: () => invoke("update_check"),
+ /** 已经查到了一版:直接把更新窗口拉起来,不再联网问一遍 */
+ showUpdate: () => invoke("update_show"),
+ info: () => invoke("app_info"),
+ /** 诊断包写在数据目录里,交回路径 */
+ saveDiagnostics: () => invoke("save_diagnostics"),
+ /** 还原接管、取消开机启动、按需删数据目录。交回的是每一步的结果,一步一句 */
+ uninstall: (dropData: boolean) => invoke("uninstall", { dropData }),
+};
+
+/**
+ * 这几份数据在 `useResource` 里的键。**都以 `app:` 开头**:它们属于这个应用,
+ * 不属于连着的那个 core。
+ */
+export const APP_KEYS = {
+ theme: "app:theme",
+ language: "app:language",
+ menubar: "app:menubar",
+ noticeMode: "app:notice-mode",
+ autostart: "app:autostart",
+ update: "app:update",
+ info: "app:info",
+} as const;
diff --git a/src/settings/form.tsx b/src/settings/form.tsx
index 09385301..e2979135 100644
--- a/src/settings/form.tsx
+++ b/src/settings/form.tsx
@@ -1,21 +1,14 @@
-import type { ReactNode } from "react";
+import { useCallback, useEffect, useRef, useState, type Dispatch, type ReactNode, type SetStateAction } from "react";
import { Button } from "@/ui/button";
import { Input } from "@/ui/input";
-import { Spinner } from "@/ui/spinner";
import { useText } from "@/i18n";
import { commonText } from "@/i18n/common.i18n";
+import { useConnections } from "@/connection/ConnectionProvider";
import { formText } from "./form.i18n";
/**
- * 设置页里改网关配置的那几节(监听、日志保留)共用的表单。
- *
- * **改完点保存才生效。**这几项改的是 config.yaml,改错的代价是客户端连不上
- * 或者日志被删 —— 一个选项点下去立刻生效、一个格子失焦就写盘,用户没有
- * 机会把几处一起改好再落地,也没有机会反悔。外观、提醒那几节改的是这个
- * 应用自己,点一下就换,照旧。
- *
- * 版式是两列:左边标签右对齐成一列,右边控件,控件下面一行说明。保存和
- * 放弃更改放在控件那一列的最下面,和控件对齐。
+ * 两列表单:左边标签右对齐成一列,右边控件,控件下面一行说明。连接的添加与编辑、
+ * 安全页「输出长度」的上限用它。设置页本身是一行一项的面板,见 `kit.tsx`。
*/
export function FormRows({ children }: { children: ReactNode }) {
return (
@@ -53,10 +46,9 @@ export function FormRow({
}
/**
- * 保存和放弃更改。**改过才出现**:没改的时候两个灰按钮摆在那儿,看起来
- * 像是有什么没存。存的时候两个都灰掉,存完随改动一起消失。
- *
- * `invalid` 时保存灰着:哪一格不对,那一格下面自己会说。
+ * 两列表单下面的保存和放弃更改。**改过才出现**:没改的时候两个灰按钮摆在那儿,看起来
+ * 像是有什么没存。`invalid` 时保存灰着:哪一格不对,那一格下面自己会说。设置页里
+ * 一行一项的面板用的是 `kit.tsx` 的 `SaveBar`。
*/
export function FormActions({
dirty,
@@ -78,8 +70,7 @@ export function FormActions({
<>
-
- {busy && }
+
{common.save}
@@ -90,7 +81,7 @@ export function FormActions({
);
}
-/** 一个整数(或一位小数)的格子,后面可以跟一个单位 */
+/** 一个整数(或一位小数)的格子,后面可以跟一个单位。28px,和工具条、设置里一行的其他控件一样高 */
export function NumberInput({
id,
value,
@@ -113,8 +104,9 @@ export function NumberInput({
onChange(e.target.value.trim())}
/>
- {unit && {unit}}
+ {unit && {unit}}
);
}
@@ -137,3 +129,69 @@ export function intIn(v: string, min: number, max: number): boolean {
const n = Number(v);
return n >= min && n <= max;
}
+
+/**
+ * 改到一半的表单。**切到别的页再回来接着改**:设置页换页时整个卸掉,而改了一半的
+ * 端口不该因为去流量页看了一眼就没了(目录上那一节挂着点,回来看得见)。只记在这次
+ * 运行里;按连接分开 —— 换了连接就是另一份配置。
+ */
+const drafts = new Map();
+
+/**
+ * 一节表单的草稿:`draft` 是正在改的,`saved` 是配置里现在的。
+ *
+ * · 没在改的时候跟着配置走(别处改的、或者刚存完推回来的)。
+ * · `commit(value?)`:刚存上(存的是 `value`,缺省是当前草稿)。配置推回来之前也不
+ * 算「改过」—— 保存栏不会在「已保存」和「有未保存的更改」之间闪一下。
+ * · `reset()`:放弃更改,回到配置里的值。
+ */
+export function useFormDraft(
+ name: string,
+ saved: T,
+ same: (a: T, b: T) => boolean,
+): {
+ draft: T;
+ setDraft: Dispatch>;
+ dirty: boolean;
+ commit: (value?: T) => void;
+ reset: () => void;
+} {
+ const conn = useConnections().view?.current ?? null;
+ const [draft, setDraft] = useState(() => {
+ const d = drafts.get(name);
+ return d && conn !== null && d.conn === conn ? (d.value as T) : saved;
+ });
+ /** 刚存上的那一份。配置推回来(`saved` 变了)就不用它了 */
+ const [committed, setCommitted] = useState(null);
+ const dirty = !same(draft, saved) && !(committed !== null && same(draft, committed));
+
+ const dirtyRef = useRef(dirty);
+ dirtyRef.current = dirty;
+ const savedRef = useRef(saved);
+ savedRef.current = saved;
+ const savedKey = JSON.stringify(saved);
+ useEffect(() => {
+ setCommitted(null);
+ if (!dirtyRef.current) setDraft(savedRef.current);
+ }, [savedKey]);
+
+ useEffect(() => {
+ if (dirty && conn !== null) drafts.set(name, { conn, value: draft });
+ else drafts.delete(name);
+ }, [name, conn, dirty, draft]);
+
+ const draftRef = useRef(draft);
+ draftRef.current = draft;
+ const commit = useCallback((value?: T) => {
+ const v = value === undefined ? draftRef.current : value;
+ dirtyRef.current = false;
+ setDraft(v);
+ setCommitted(v);
+ }, []);
+ const reset = useCallback(() => {
+ dirtyRef.current = false;
+ setCommitted(null);
+ setDraft(savedRef.current);
+ }, []);
+ return { draft, setDraft, dirty, commit, reset };
+}
diff --git a/src/settings/kit.i18n.ts b/src/settings/kit.i18n.ts
new file mode 100644
index 00000000..2dd598ab
--- /dev/null
+++ b/src/settings/kit.i18n.ts
@@ -0,0 +1,24 @@
+import { messages } from "@/i18n";
+
+/** 设置页的骨架(目录、分组、保存栏)自己说的几句 */
+export const kitText = messages(
+ {
+ index: "设置目录",
+ unsaved: "有未保存的更改",
+ saved: "已保存",
+ discard: "放弃更改",
+ offline: "连接到 core 后可修改此项。",
+ loadFailed: "无法读取",
+ /** 改配置文件的两节读不到网关配置时,那一行的标题 */
+ configFailed: "无法读取网关配置",
+ },
+ {
+ index: "Settings sections",
+ unsaved: "Unsaved changes",
+ saved: "Saved",
+ discard: "Discard changes",
+ offline: "Available once connected to a core.",
+ loadFailed: "Could not load",
+ configFailed: "The gateway configuration could not be read",
+ },
+);
diff --git a/src/settings/kit.tsx b/src/settings/kit.tsx
new file mode 100644
index 00000000..05e0d01c
--- /dev/null
+++ b/src/settings/kit.tsx
@@ -0,0 +1,663 @@
+import {
+ createContext,
+ Fragment,
+ useCallback,
+ useContext,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+ type RefObject,
+} from "react";
+import { listen } from "@tauri-apps/api/event";
+import { CircleAlertIcon, PlugZapIcon } from "lucide-react";
+import { cn } from "@/lib/utils";
+import type { Resource } from "@/lib/resource";
+import { Button } from "@/ui/button";
+import { Reveal, prefersReducedMotion } from "@/ui/motion";
+import { notify } from "@/ui/notify";
+import { Skeleton } from "@/ui/skeleton";
+import { StatusDot, StatusLabel } from "@/ui/status-dot";
+import { Tip } from "@/ui/tip";
+import { useText } from "@/i18n";
+import { commonText } from "@/i18n/common.i18n";
+import { errorText } from "@/i18n/core.i18n";
+import { useNavParams } from "@/nav";
+import { kitText } from "./kit.i18n";
+
+/**
+ * 设置页的骨架:左边一列目录(跟着滚动点亮当前那一节),右边一节节的分组,
+ * 每组是一块圆角面板,里面一行一项 —— 左边是名目和一行说明,右边是控件。
+ * 样子照 macOS 的系统设置,颜色照这个应用的黑白灰。
+ *
+ * }>
+ *
+ *
+ * } />
+ *
+ *
+ *
+ *
+ * 目录只在内容区够宽时出现(窗口拉窄、侧栏展开时藏起来,分组照常一节节往下排)。
+ */
+
+/** 分组在页面上的锚点。深链(`nav.open("settings", { section })`)和目录都认它 */
+export function anchorId(id: string): string {
+ return `settings-${id}`;
+}
+
+/** 跳过去之后,分组标题离滚动区顶边多远。和目录吸顶的距离(`top-5`)一样 */
+const JUMP_GAP = 20;
+/** 顶边越过这条线的最后一节算「正在看的」 */
+const SPY_LINE = JUMP_GAP + 44;
+/** 点目录滚过去的途中不跟着点亮别的节;滚动停下这么久才放开 */
+const SETTLE_MS = 160;
+/** 深链落到一行时,那一行的底色亮多久 */
+const FLASH_MS = 1_200;
+
+/** 往上找第一个会竖着滚的祖先:外壳给每一页的那一层(App.tsx) */
+function scrollParent(el: HTMLElement | null): HTMLElement | null {
+ for (let p = el?.parentElement ?? null; p; p = p.parentElement) {
+ const o = getComputedStyle(p).overflowY;
+ if (o === "auto" || o === "scroll") return p;
+ }
+ return null;
+}
+
+/**
+ * 滚到哪一节了,以及「跳到某一节」。
+ *
+ * 顶边越过判定线的最后一节算正在看的。**页尾那几节的顶边永远到不了判定线**(滚到底
+ * 了它们还在下面),就把最后一段滚动平分给它们:从最后一节够得着的开始,按顺序各轮
+ * 一段,到底正好是最后一节。以前是到底直接跳到最后一节,「关于」一次都轮不到;而让
+ * 判定线整体往下走,又会在顶上那一节还整个露着的时候就点亮下面的。
+ *
+ * **点目录的那一下不让滚动途中经过的节抢走高亮**:先把目标点亮、锁住,滚动停下再
+ * 放开。
+ */
+function useSpy(ids: readonly string[], root: RefObject) {
+ const [active, setActive] = useState(ids[0] ?? "");
+ const box = useRef(null);
+ const lock = useRef | null>(null);
+ const key = ids.join(",");
+
+ const measure = useCallback(() => {
+ const b = box.current;
+ if (!b || lock.current) return;
+ const list = key.split(",");
+ const max = Math.max(0, b.scrollHeight - b.clientHeight);
+ /** 内容顶边此刻在视口里的位置(和滚到哪儿无关的那个原点) */
+ const origin = b.getBoundingClientRect().top - b.scrollTop;
+ /** 每一节从哪个滚动位置起算「正在看的」:它的顶边到判定线的那一刻 */
+ const starts = list.map((id) => {
+ const el = document.getElementById(anchorId(id));
+ return el ? el.getBoundingClientRect().top - origin - SPY_LINE : Number.POSITIVE_INFINITY;
+ });
+ // 页尾够不着的那几节,和最后一节够得着的一起平分最后一段
+ const tail = Math.max(1, starts.findIndex((v) => v > max));
+ if (starts[tail] !== undefined && starts[tail] > max) {
+ const from = Math.min(max, Math.max(0, starts[tail - 1] ?? 0));
+ const share = (max - from) / (list.length - tail + 1);
+ for (let i = tail; i < list.length; i++) starts[i] = from + share * (i - tail + 1);
+ }
+ let cur = list[0] ?? "";
+ list.forEach((id, i) => {
+ if (b.scrollTop >= (starts[i] ?? 0) - 1) cur = id;
+ });
+ setActive(cur);
+ }, [key]);
+
+ useEffect(() => {
+ const b = scrollParent(root.current);
+ box.current = b;
+ if (!b) return;
+ const settle = () => {
+ if (lock.current) clearTimeout(lock.current);
+ lock.current = setTimeout(() => {
+ lock.current = null;
+ }, SETTLE_MS);
+ };
+ const onScroll = () => (lock.current ? settle() : measure());
+ b.addEventListener("scroll", onScroll, { passive: true });
+ measure();
+ // 内容从骨架换成数据、一节展开或收起:各节的位置都变了
+ const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => measure());
+ if (root.current) ro?.observe(root.current);
+ return () => {
+ b.removeEventListener("scroll", onScroll);
+ ro?.disconnect();
+ if (lock.current) clearTimeout(lock.current);
+ lock.current = null;
+ };
+ }, [measure, root]);
+
+ /**
+ * 滚到一节或一行。`id` 是一节(目录里那几项)或一行的锚点(`SettingsRow` 的
+ * `anchor`:「通用」里的语言、外观……,命令面板搜到的就是它们)。一行的话,目录上点亮
+ * 它所在的那一节,那一行的底色亮一下再退掉 —— 落在一节中间,要让眼睛找得到是哪一行。
+ */
+ const jump = useCallback(
+ (id: string) => {
+ const b = box.current ?? scrollParent(root.current);
+ const el = document.getElementById(anchorId(id));
+ if (!b || !el) return;
+ const group = el.closest("section[data-section]") ?? el;
+ setActive(group.dataset.section ?? id);
+ if (lock.current) clearTimeout(lock.current);
+ lock.current = setTimeout(() => {
+ lock.current = null;
+ }, SETTLE_MS * 4);
+ const top = b.getBoundingClientRect().top;
+ let delta = group.getBoundingClientRect().top - top - JUMP_GAP;
+ if (el !== group) {
+ // 那一行在这一节里很靠下、一屏放不下标题和它:让它自己靠上,上面留出一行的空
+ const row = el.getBoundingClientRect();
+ if (row.bottom - top - delta > b.clientHeight - JUMP_GAP) delta = row.top - top - JUMP_GAP * 3;
+ el.dataset.flash = "on";
+ setTimeout(() => delete el.dataset.flash, FLASH_MS);
+ }
+ b.scrollTo({ top: b.scrollTop + delta, behavior: prefersReducedMotion() ? "auto" : "smooth" });
+ // 焦点落到那一节的标题上:键盘接着按 Tab 从这一节往下走。不带滚动,滚动上面已经做了
+ group.querySelector("[data-settings-heading]")?.focus({ preventScroll: true });
+ },
+ [root],
+ );
+
+ return { active, jump };
+}
+
+interface Nav {
+ /** 这一节有没改完的表单:目录上那一项挂一个点 */
+ markDirty: (id: string, dirty: boolean) => void;
+ /** 滚到某一节(摘要里的「有新版本」点过去用) */
+ jump: (id: string) => void;
+}
+
+const NavCtx = createContext