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, String> { find(app).await } @@ -250,7 +250,7 @@ pub(crate) fn present_update(app: &tauri::AppHandle, found: Found) { present(app, found); } -/// 「立即检查」。查到了就把更新窗口拉起来。 +/// 设置页的「检查更新」。查到了就把更新窗口拉起来。 #[tauri::command] pub async fn update_check(app: tauri::AppHandle) -> Out> { let found = find(&app).await?; @@ -260,6 +260,22 @@ pub async fn update_check(app: tauri::AppHandle) -> Out> { Ok(found) } +/// 设置页的「更新到 x…」:已经查到了一版,把更新窗口拉起来。 +/// +/// **不再联网问一遍**(`update_check` 会):那一版已经记在这里,再问一遍只会让这个 +/// 按钮在没网的时候失灵,而窗口里的「下载并安装」反正会自己去取。 +#[tauri::command] +pub fn update_show(app: tauri::AppHandle) -> Out<()> { + if pending_update(&app).is_none() { + return Err(tr!( + "尚无可安装的新版本", + "No new version is waiting to be installed" + ) + .into()); + } + show_update_window(&app).map_err(|e| e.to_string().into()) +} + /// 更新窗口打开时来读:要画的是哪一版、这一份该怎么装。 #[tauri::command] pub fn update_pending(app: tauri::AppHandle) -> Option { @@ -557,7 +573,7 @@ pub(crate) const UPDATE_EVERY: std::time::Duration = std::time::Duration::from_s /// 自动检查。查到了就发一条系统通知。 /// /// **开发构建不自己去查。**每次 `tauri dev` 之后两分钟弹一个窗,写代码的 -/// 人学会的只是把它关掉。「立即检查」在开发构建里照样能用。 +/// 人学会的只是把它关掉。「检查更新」在开发构建里照样能用。 pub(crate) async fn update_loop(app: tauri::AppHandle) { tokio::time::sleep(UPDATE_FIRST_LOOK).await; loop { diff --git a/src/App.tsx b/src/App.tsx index bd531b44..028b0317 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -6,7 +6,7 @@ import { call } from "@/control"; import { useRequests } from "./useRequests"; import { useStableState } from "./useStable"; import { EMPTY_FILTER } from "./requestTable"; -import Config from "./Config"; +import { SettingsPage } from "./settings/SettingsPage"; import { ConfigFileDialog, VersionHistoryDialog } from "./ConfigDialogs"; import UpstreamsPage from "./upstreams/UpstreamsPage"; import ClientsPage from "./clients/ClientsPage"; @@ -406,6 +406,8 @@ function Shell({ first }: { first: boolean }) { if (!(SURFACES as readonly string[]).includes(page ?? "")) return; // `requests:42`:打开流量页并展开那一条(菜单栏里点了一个进行中的请求) if (page === "requests" && id) openRef.current("requests", { request: Number(id) }); + // `settings:listen`:设置页并滚到那一节(「监听设置未生效」) + else if (page === "settings" && id) openRef.current("settings", { section: id }); else openRef.current(page as Surface); }; void invoke("take_pending_view") @@ -613,7 +615,15 @@ function Shell({ first }: { first: boolean }) { const changed = useCallback(() => setNudge((n) => n + 1), []); const openConfigFile = useCallback((focus: string | null) => setConfigFile({ focus }), []); - const go = useCallback((to: string) => open(to as Surface), [open]); + /** 页面、提醒要落到别的页时用。`settings:listen`:设置页并滚到那一节 */ + const go = useCallback( + (to: string) => { + const [page, section] = to.split(":"); + if (page === "settings" && section) open("settings", { section }); + else open(to as Surface); + }, + [open], + ); /** 命令面板里只有外壳做得了的几件事。**引用不变**:面板按它们建条目,变了就要重建 */ const paletteShell = useMemo( @@ -950,7 +960,7 @@ function Shell({ first }: { first: boolean }) { {/* 断线时整块只读:`fieldset disabled` 让里面的按钮、输入框、下拉一起失效, 读、滚动、悬停说明照旧。设置页不整页只读:连接管理在那里,断线时正要来 - 这里(换密钥、切回本机);那一页里改服务器配置的几节自己只读,见 `Config` + 这里(换密钥、切回本机);那一页里改服务器配置的几节自己只读,见 `SettingsPage` */}
+ ) : ( ) @@ -1029,7 +1039,14 @@ function Shell({ first }: { first: boolean }) { skeleton ) ) : tab === "settings" ? ( - + ) : ( setConfigFile(null)} onJump={(section) => { setConfigFile(null); - open(surfaceOf(section)); + // 监听、日志保留是设置页里的两节:直接滚到那一节 + if (section === "listen" || section === "retention") open("settings", { section }); + else open(surfaceOf(section)); }} /> )} diff --git a/src/Appearance.i18n.ts b/src/Appearance.i18n.ts deleted file mode 100644 index 1b9150d5..00000000 --- a/src/Appearance.i18n.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { messages } from "@/i18n"; - -export const appearanceText = messages( - { - title: "外观", - system: "跟随系统", - light: "浅色", - dark: "深色", - /** 选了跟随系统时,把系统现在是哪一档写出来 */ - systemNow: (name: string) => `系统当前为${name}。`, - saveFailed: "无法保存外观设置", - }, - { - title: "Appearance", - system: "System", - light: "Light", - dark: "Dark", - systemNow: (name: string) => `The system is currently set to ${name.toLowerCase()}.`, - saveFailed: "The appearance setting could not be saved", - }, -); diff --git a/src/Appearance.tsx b/src/Appearance.tsx deleted file mode 100644 index 436f8c00..00000000 --- a/src/Appearance.tsx +++ /dev/null @@ -1,70 +0,0 @@ -import { useEffect, useState } from "react"; -import { invoke } from "@tauri-apps/api/core"; -import { toast } from "sonner"; -import { useText } from "@/i18n"; -import { errorText } from "@/i18n/core.i18n"; -import { Segmented } from "@/upstreams/parts"; -import { appearanceText } from "./Appearance.i18n"; - -type Theme = "light" | "dark"; -type Choice = "system" | Theme; - -/** 现在用的、设置里选的(`null` 是跟随系统)、系统的 */ -interface ThemeView { - current: Theme; - setting: Theme | null; - system: Theme; -} - -/** - * 设置页的外观。 - * - * **换的是窗口的外观,不是一套 CSS。**Rust 侧改 `NSApp` 的外观,WKWebView - * 继承它,`prefers-color-scheme` 跟着翻 —— 界面这边什么都不用做,也不需要 - * 在 `` 上挂类(见 `src/index.css` 开头和 `src-tauri/src/theme.rs`)。 - * 所以这里存完就结束了,没有第二步。 - * - * **三个按钮,不是下拉。**一共就这三档,摆出来点一下就换;语言那边是下拉, - * 因为语种还会增加。 - */ -export function AppearanceSection() { - const t = useText(appearanceText); - const [view, setView] = useState(null); - useEffect(() => { - void invoke("app_theme").then(setView).catch(() => {}); - }, []); - if (!view) return null; - - async function choose(v: Choice) { - const setting: Theme | null = v === "system" ? null : v; - try { - setView(await invoke("set_theme", { setting })); - } catch (err) { - toast.error(errorText(err) || t.saveFailed); - } - } - - return ( -
-

{t.title}

-
- - value={view.setting ?? "system"} - options={[ - { id: "system", label: t.system }, - { id: "light", label: t.light }, - { id: "dark", label: t.dark }, - ]} - onChange={(v) => void choose(v)} - /> - {/* 跟随系统时写出系统现在是哪一档 —— 否则这一行只说了「跟着走」, - 没说会走到哪里去 */} - {view.setting == null && ( -

- {t.systemNow(view.system === "dark" ? t.dark : t.light)} -

- )} -
-
- ); -} diff --git a/src/Config.i18n.tsx b/src/Config.i18n.tsx deleted file mode 100644 index a715800e..00000000 --- a/src/Config.i18n.tsx +++ /dev/null @@ -1,95 +0,0 @@ -import type { ReactNode } from "react"; -import { messages } from "@/i18n"; -import { isLinux, isMac, isWindows } from "@/platform"; - -/** 句中要套一层组件(悬浮说明、加粗)的那一段 */ -type Wrap = (text: string) => ReactNode; - -export const configText = messages( - { - // 开机启动 - autostartTitle: "开机启动", - autostartLabel: "开机时自动启动", - autostartNote: isWindows - ? "登录后仅在通知区域显示图标,不打开窗口。" - : isLinux - ? "登录后仅在系统托盘显示图标,不打开窗口。" - : "登录后仅在菜单栏显示图标,不打开窗口。", - - // 关于 - aboutTitle: "关于", - version: "版本", - dataDir: "数据目录", - coreBin: "core 二进制", - - // 诊断包 - diagnosticsTitle: "诊断包", - diagnosticsBody: (tip: Wrap) => ( - <> - 包含版本、上游、熔断状态、近期失败记录与脱敏后的配置文件。{tip("不含请求与响应正文")}。 - - ), - diagnosticsTip: "不包含请求体与响应体,其中可能含有用户粘贴的内容。", - generate: "生成", - saved: (path: ReactNode) => <>已生成:{path}, - review: (em: Wrap) => <>其中的密钥与地址已脱敏,{em("提交前请自行核对")}。, - - // 完全卸载 - uninstalled: "卸载完成", - uninstallTitle: "完全卸载", - uninstallIntro: (em: Wrap) => ( - <> - 还原所有已接管的客户端,并取消开机启动。 - {em(isMac ? "直接将应用移到废纸篓不会执行这些操作" : "通过系统卸载或直接删除应用不会执行这些操作")},已接管的客户端将指向一个无人监听的端口。 - - ), - uninstall: "卸载…", - willDo: "将执行以下操作:", - restoreClients: "将所有已接管的客户端还原为接管前的配置", - stopAutostart: "取消开机启动", - dropData: "同时删除数据目录(请求历史、费用记录、配置备份)", - confirmUninstall: "确认卸载", - }, - { - autostartTitle: "Launch at login", - autostartLabel: "Launch automatically at login", - autostartNote: 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.", - - aboutTitle: "About", - version: "Version", - dataDir: "Data directory", - coreBin: "Core binary", - - diagnosticsTitle: "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", - saved: (path: ReactNode) => <>Saved to {path}, - review: (em: Wrap) => <>Keys and addresses in it are redacted; {em("review it before sharing")}., - - uninstalled: "Uninstall complete", - 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. - - ), - uninstall: "Uninstall…", - willDo: "Uninstalling will:", - restoreClients: "Restore every connected client to the configuration it had before being connected", - stopAutostart: "Turn off launch at login", - dropData: "Also delete the data directory (request history, cost records, config backups)", - confirmUninstall: "Uninstall", - }, -); diff --git a/src/Config.tsx b/src/Config.tsx deleted file mode 100644 index fa9b5bae..00000000 --- a/src/Config.tsx +++ /dev/null @@ -1,416 +0,0 @@ -import { useState } from "react"; -import { invoke } from "@tauri-apps/api/core"; -import { useEffect } from "react"; -import Update from "./Update"; -import NoticeSettings from "./NoticeSettings"; -import { LanguageSection } from "./Language"; -import { AppearanceSection } from "./Appearance"; -import MenubarSettings from "./MenubarSettings"; -import { ListenSection } from "./settings/ListenSection"; -import { RetentionSection } from "./settings/RetentionSection"; -import { ConnectionsSection } from "./connection/ConnectionsSection"; -import type { CoreStatus, Overview } from "./types"; -import { Button } from "@/ui/button"; -import { Checkbox } from "@/ui/checkbox"; -import { Field, FieldContent, FieldDescription, FieldLabel } from "@/ui/field"; -import { Spinner } from "@/ui/spinner"; -import { Switch } from "@/ui/switch"; -import { ButtonGroup } from "@/ui/button-group"; -import { Tip } from "@/ui/tip"; -import { toast } from "sonner"; -import { useText } from "@/i18n"; -import { commonText } from "@/i18n/common.i18n"; -import { configText } from "./Config.i18n"; -import { errorText } from "@/i18n/core.i18n"; -import { useRemote } from "@/connection/useRemote"; -import { remoteText } from "@/connection/remote.i18n"; -import type { RemoteCore } from "@/connection/api"; -import { revealSection, useNavParams } from "@/nav"; -import { getLang } from "@/i18n"; -import { sectionTitle } from "@/palette/sections"; - -/** - * 设置:这个应用自己的,和网关那几项配一次就不动的。 - * - * **两类东西,两种改法。**语言、外观、开机启动、提醒改的是这个应用,点一下 - * 就换;监听、日志保留改的是 config.yaml,改完点保存才生效 —— 它们 - * 改错的代价是客户端连不上、或者日志被删。上游、路由、密钥这些要天天看、 - * 常常改的,各有自己的页。 - */ -export default function Config({ - ov, - status, - coreReadOnly = false, - onChanged, -}: { - ov: Overview | null; - status: CoreStatus | null; - /** 连着的远程 core 断了:改它配置的几节只读,应用自己的设置照常能改 */ - coreReadOnly?: boolean; - /** 存完监听设置之后叫一声,状态和概览跟着重读 */ - onChanged: () => void; -}) { - const t = useText(configText); - const rt = useText(remoteText); - const remote = useRemote(); - // 命令面板送来的「设置 › 外观」:滚到那一节。节是陆续画出来的,`revealSection` 会等它 - useNavParams("settings", (p) => { - if (p.section) revealSection(p.section, sectionTitle(p.section, getLang())); - }); - useEffect(() => { - void invoke("autostart_enabled") - .then(setAutostart) - .catch(() => setAutostart(false)); - }, []); - // 开机自启。**出厂是关的** —— null 表示还没读到,别在读到之前先画一个 - // 勾或不勾出来:那一瞬间画错的话,用户会以为是自己之前设的。 - const [autostart, setAutostart] = useState(null); - const autostartSection = ( -
-

{t.autostartTitle}

- - {/* - **开关而不是复选框。**复选框是「在一组里挑几个」,而这是 - 「打开或关掉一个系统行为」—— macOS 的系统设置里这一类一律 - 是开关。`Field` 的 horizontal 布局两者通用。 - */} - { - const want = checked === true; - // 先乐观地画上,失败再弹回去 —— 但**以后端返回的实际 - // 状态为准**,不是以这里传出去的那个为准。注册可能失败 - // (只读的 LaunchAgents 目录、权限),那时勾必须弹回去。 - setAutostart(want); - try { - setAutostart( - await invoke("set_autostart", { on: want }), - ); - } catch (err) { - setAutostart(!want); - toast.error(errorText(err)); - } - }} - /> - - {t.autostartLabel} - - {/* - 一句话说清开了会怎样,不用悬停才看得到。出厂是关的(装完就往 - 登录项里写东西的工具,用户第一次发现它是在系统设置里看到一个 - 自己没同意过的条目),但开关本身就显示着关,不用再写一遍。 - */} - {t.autostartNote} - - - -
- ); - const serverSections = ( - <> - {/* 监听原来在「接入」页上,和密钥同屏。它是配一次就不动的网关设置, - 和密钥(要天天拿去填客户端)不是一类东西 */} -
- {ov && ( - - )} - - {/* - 日志保留归设置,不归流量页。**它管的是「留多久」,不是「看哪一段」** - —— 那一页上曾经有个时间范围选择器,而让人先选一段才能开始搜, - 等于在一个本来就不大的集合前面加一道门。 - */} - {ov && ( - - )} -
- - ); - - /* - **连着远程 core 时分成两组**(设计稿 ⑧):改这个应用自己的,和改服务器配置的。 - 混在一起的话,「语言」和「监听」挨着,用户分不清哪一项改的是服务器。诊断包在 - 这时不给:它生成在服务器的文件系统上,远程拿不到。 - */ - if (remote) { - return ( -
- - - - - - {autostartSection} - - - - - - - {serverSections} -

{rt.controlReadOnly}

-
-
- ); - } - - return ( -
- {/* 最上面:连不上的时候用户就是来这里的 */} - - - - - - - - - {autostartSection} - - {serverSections} - - - - - {/* 诊断包和卸载改的是这个应用本身,归「设置」 */} - - - - - -
- ); -} - -/** 远程模式下设置页的一组。组名比各节标题低一档,只是分隔 */ -function Group({ title, children }: { title: string; children: React.ReactNode }) { - return ( -
-

{title}

- {children} -
- ); -} - -/** - * 关于。 - * - * **排查时最先要问的就是这几个**:哪个版本、数据在哪、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)}

-
+
+ {/* 应用图标本身(和程序坞里同一张) */} + +
+

{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 ( +
+
+
+
+

{text}

+
+ ); + } + 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 && ( - )} + {items.length > 0 && }
  • ); + 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} + {/* 测试在左边,和保存那一组分开:它不改任何东西 */} {hint && {hint}} - {!isCurrent && ( - )} @@ -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.title}

    -

    {d.next}

    -
    -
    + + {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" && ( - - )} {stage.kind === "retargeted" ? ( ) : ( - )} + {stage.kind === "failed" && } {stage.kind === "confirm" && ( - )} 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 ? ( + + ) : ( + + )} +
    + + + {(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={ + + } + > + +
    +
    +

    + + {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} + +
    { + e.preventDefault(); + if (dirty && !busy && portOk && nicOk) void save(); + }} + > + + 0 ? t.reachable(reachable.join(t.sep)) : undefined} + control={ + addr ? ( + + {addr} + + ) : ( + {t.notListening} + ) + } + /> - - + + label={t.scope} + value={draft.level} + disabled={busy} + options={[ + { id: "local", label: t.local }, + { id: "lan", label: t.lan }, + { id: "all", label: t.all }, + ]} + onChange={pick} + /> + } /> - - {draft.level === "lan" && ( - - set({ nic: e.target.value })} - > - {/* 配置里写着一张当前枚举不到的网卡 —— 网线拔了、换了网络。 - **必须列出来**,否则选单会显示成别的网卡,看起来像是它变了 */} - {selected && !known && ( - {t.nicMissing(selected)} - )} - {nics?.map((n) => ( - - {t.nicOption(n.name, n.addr)} - - ))} - - - )} + {draft.level === "lan" && ( + void nicList.reload()} /> + ) : ( + set({ nic: e.target.value })} + > + {/* 配置里写着一张当前枚举不到的网卡 —— 网线拔了、换了网络。 + **必须列出来**,否则选单会显示成别的网卡,看起来像是它变了 */} + {selected && !known && ( + {t.nicMissing(selected)} + )} + {nics?.map((n) => ( + + {t.nicOption(n.name, n.addr)} + + ))} + + ) + } + /> + )} - - set({ port })} + {t.badPort}} + control={ + set({ port })} + /> + } /> - - {exposed && ( - - set({ allow })} + {exposed && ( + set({ allow })} + /> + } /> - - )} - - void save()} - onDiscard={() => { - setError(null); - setEpoch((n) => n + 1); - setDraft(saved); - }} - /> - + )} - {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)} - + {t.removeShort} +
    ))} -
    +
    {value.length === 0 ? t.empty : t.what} {!sameSet(value, defaults) && ( - + )}

    )} 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}

    - - - +
    { + e.preventDefault(); + if (dirty && !busy && valid) void save(); + }} + > + + + } /> - - - + } /> - - - + {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` 让里面的按钮、输入框、下拉一起失效,读、 + 滚动、悬停说明照旧。应用自己的那几节不受影响 + */ +
    + {view ? ( + + ) : ( + + )} + {view ? ( + + ) : ( + + )} +
    + ); + + 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 ? ( + // 有新版本:点过去就是「关于」,更新的按钮在那里 + + ) : ( + 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={ + + } + /> + + {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({ <>
    - + + ))} +
    + + ); +} + +/** + * 一节。标题(和目录里那一项同一个词)、可选的一行说明和右侧的操作,下面是一块或 + * 几块面板。`badge`:标题后面的小标记(连着远程时写这一节改的是哪台服务器)。 + */ +export function SettingsGroup({ + id, + title, + description, + actions, + badge, + className, + children, +}: { + id: string; + title: ReactNode; + description?: ReactNode; + actions?: ReactNode; + badge?: ReactNode; + className?: string; + children: ReactNode; +}) { + const a = anchorId(id); + return ( +
    +
    +
    +

    + {title} + {badge} +

    + {description &&

    {description}

    } +
    + {actions &&
    {actions}
    } +
    + {children} +
    + ); +} + +/** + * 一块面板:一组行。细边、圆角,行与行之间一条缩进的细线。 + * + * **底色比页面高一档,用的是菜单那一档(`popover`)**:浅色下是白的,深色下比窗口底 + * 亮一点 —— 和 macOS 系统设置里的分组一个样。`surface` 在浅色下比页面暗,分段控件 + * 的灰底(`muted`)落在上面几乎看不见。 + */ +export function SettingsCard({ className, children }: { className?: string; children: ReactNode }) { + return ( +
    + {children} +
    + ); +} + +/** 深链落到这一行时底色亮一下(`jump` 挂上、过一会儿摘掉 `data-flash`),退掉时走过渡 */ +export const FLASH = "transition-colors duration-(--motion-slow) data-[flash=on]:bg-muted"; + +/** 行与行之间的细线:两头各缩进 16px,第一行上面没有 */ +const DIVIDER = + "relative before:pointer-events-none before:absolute before:inset-x-4 before:top-0 before:border-t before:border-border first:before:hidden"; + +/** + * 一行设置。 + * + * · 默认:名目和说明在左,控件在右,竖着居中。窄到放不下时控件折到下一行。 + * · `stack`:控件在名目下面、占满整行(名单这类自己有好几行的控件)。 + * · `children`:行里再往下接的东西(生成完的路径、试连的结果)。 + */ +export function SettingsRow({ + label, + description, + htmlFor, + anchor, + control, + stack, + className, + children, +}: { + label: ReactNode; + description?: ReactNode; + /** 控件的 id。给了的话点名目会聚焦控件(开关会被拨动) */ + htmlFor?: string; + /** 这一行自己的锚点:`nav.open("settings", { section: anchor })` 直接落到这一行 */ + anchor?: string; + control?: ReactNode; + stack?: boolean; + className?: string; + children?: ReactNode; +}) { + const head = ( +
    +
    {htmlFor ? : label}
    + {description &&
    {description}
    } +
    + ); + return ( +
    + {stack ? ( + <> + {head} + {control &&
    {control}
    } + + ) : ( +
    + {head} + {/* 窄到折行时控件落在下一行的右边:一列控件始终靠右对齐 */} + {control &&
    {control}
    } +
    + )} + {children} +
    + ); +} + +/** 读取中的一行:名目和控件的位置各一块灰,数据到了不跳 */ +export function RowSkeleton({ control = "w-40", description }: { control?: string; description?: boolean }) { + return ( +
    +
    +
    + + {description && } +
    + +
    +
    + ); +} + +/** + * 一份 `useResource` 画在控件那一格:有数据画控件;还在读画一块同样大的灰;读 + * 不出来说一声,给重试。**不整行消失**:以前这几项读到之前是 null,读到了才冒出来, + * 整页往下一跳。 + */ +export function Loaded({ + r, + width = "w-40", + children, +}: { + r: Resource; + /** 骨架的宽度,和控件差不多宽 */ + width?: string; + children: (data: T) => ReactNode; +}) { + if (r.data !== undefined) return <>{children(r.data)}; + if (r.error !== undefined && !r.loading) return void r.reload()} />; + return ; +} + +/** 控件那一格读不出来:一句话,原因在悬停说明里,旁边是重试 */ +export function RowError({ error, onRetry }: { error: unknown; onRetry: () => void }) { + const t = useText(kitText); + const common = useText(commonText); + return ( + + + + + {t.loadFailed} + + + + + ); +} + +/** 没连上 core 时,改配置文件的那几节:说明白现在改不了,不画一张空表单 */ +export function OfflineRow() { + const t = useText(kitText); + return ( +
    + + {t.offline} +
    + ); +} + +/** + * 一整节读不出来:一行说什么没读到、为什么,右边是重试。**不画骨架等下去**:读不 + * 出来的时候骨架会一直转,看起来像还在读。 + */ +export function ErrorRow({ + title, + error, + onRetry, + retrying, +}: { + title: ReactNode; + error: unknown; + onRetry: () => void; + retrying?: boolean; +}) { + const common = useText(commonText); + return ( +
    + +
    +

    {title}

    +

    {errorText(error)}

    +
    + +
    + ); +} + +/** + * 改配置文件的那几节底下的保存栏。**改过才出现**(没改的时候两个按钮摆在那儿, + * 看起来像有什么没存);存上之后停一下写「已保存」,再收起来。 + * + * 保存按钮是表单的 submit:在输入框里按回车也是保存。 + */ +export function SaveBar({ + dirty, + pending, + saved, + invalid, + onDiscard, +}: { + dirty: boolean; + pending: boolean; + /** 刚存上:停在「已保存」上 */ + saved: boolean; + /** 哪一格不对:那一格下面自己会说,这里只是保存按不下去 */ + invalid?: boolean; + onDiscard: () => void; +}) { + const t = useText(kitText); + const common = useText(commonText); + const editing = dirty || pending; + return ( + +
    + {editing ? ( + + {t.unsaved} + + ) : ( + + {t.saved} + + )} + {editing && ( +
    + + +
    + )} +
    +
    + ); +} + +/** 「已保存」停多久 */ +const SAVED_MS = 1_600; + +/** + * 表单刚存上的那一下:`flash()` 之后 `saved` 亮一会儿再灭。切走再回来不会再亮。 + */ +export function useSavedFlash(): [boolean, () => void] { + const [saved, setSaved] = useState(false); + const timer = useRef | null>(null); + useEffect(() => () => { + if (timer.current) clearTimeout(timer.current); + }, []); + const flash = useCallback(() => { + if (timer.current) clearTimeout(timer.current); + setSaved(true); + timer.current = setTimeout(() => setSaved(false), SAVED_MS); + }, []); + return [saved, flash]; +} + +/** + * 改一项「这个应用自己的」设置:先按新值画上,等 Rust 回话,以它交回的**实际** + * 状态为准;失败就弹回去并报错。`pending` 给开关用(滑块明暗)。 + */ +export function useWrite(r: Resource, write: (next: T) => Promise): [boolean, (next: T) => Promise] { + const [pending, setPending] = useState(false); + const w = useRef(write); + w.current = write; + const { mutate } = r; + const set = useCallback( + async (next: T) => { + const rollback = mutate(next); + setPending(true); + try { + mutate(await w.current(next)); + } catch (e) { + rollback(); + notify.error(e); + } finally { + setPending(false); + } + }, + [mutate], + ); + return [pending, set]; +} + +/** + * 听一个 Rust 那边发的应用事件(`language-changed`、`notice-mode-changed`…)。它们 + * 不是 core 的事件,`useResource` 的 `events` 管不到。不在应用里时什么都不做。 + */ +export function useAppEvent(name: string, cb: (payload: T) => void) { + const f = useRef(cb); + f.current = cb; + useEffect(() => { + let off: (() => void) | null = null; + let dead = false; + listen(name, (e) => f.current(e.payload)) + .then((un) => { + if (dead) un(); + else off = un; + }) + .catch(() => {}); + return () => { + dead = true; + off?.(); + }; + }, [name]); +}