Compare commits

...
Author SHA1 Message Date
Tunglies f0e1460a04 perf(home): build traffic range snapshots in one pass
The 200ms graph snapshot built three to four intermediate arrays on the
compressed path before posting to the worker. It now fills one
preallocated result in a single pass and only sorts when the compressed
and raw ranges actually interleave.
2026-11-19 21:46:06 +08:00
Tunglies e90f8c500f perf(log): reuse the empty logs fallback identity
A fresh [] fallback gave the subscription hook's refresh callback and
snapshot effect a new identity on every render while logs streamed; the
empty list is now a shared module constant.
2026-11-19 21:46:04 +08:00
Tunglies 36f79c6033 perf(proxy): stable group location and chain list identities
The sticky-header scroll callback depended on the render list identity,
re-creating the item renderer on every list rebuild; it now reads the
list through a stable ref callback. Rebinding no longer allocates new
chain items and arrays when values are unchanged, so the 15s proxy-view
refresh stops re-serializing identical chains to localStorage, and the
chain delay key join is memoized.
2026-11-19 21:45:54 +08:00
Tunglies d535c1b7d1 perf(proxy): stable tool callbacks and shared delay entries
Group headers and heads passed freshly-created closures into the
memoized tools, defeating it on every render; the tool callbacks are now
groupName-parameterized and forwarded directly. Cached delay entries are
write-once, so the defensive copy on read and the second copy in the
delay-state reducer were dropped.
2026-11-19 21:45:45 +08:00
Tunglies d162478100 perf(ui): hoist static dialog identities and memoize settings search
The DNS viewer rebuilt Monaco's options object per keystroke, the update
dialog rebuilt its markdown component map and plugin array per progress
chunk (remounting link and blockquote subtrees), and the settings search
rescanned the ~180-entry catalog on unrelated renders such as arrow-key
selection. These identities are now module constants or single memos;
the width-dependent minimap option is applied at editor mount.
2026-11-19 21:45:34 +08:00
Tunglies f4761e763a perf(ui): keep mutateVerge identity stable across renders
mutateVerge was a per-render closure that dozens of consumer callbacks
depended on, and its updater fell back to a render-time config snapshot.
It now keeps a stable identity, revalidates through the module-level
query helper, and passes the live cache value (preload snapshot when the
cache is still empty) to function updaters; object-form callers were
migrated to updater functions.
2026-11-19 21:45:27 +08:00
Tunglies 01e28608ef perf(profile): derive editor policy names and dedupe pasted proxies
The groups editor re-read both profile files and re-parsed three YAML
documents on every prepend/append/delete edit. The origin names are now
read once per open and folded into a memoized policy list, and batch
pasted proxy names dedupe through a Set instead of a linear scan.
2026-11-19 21:45:19 +08:00
Tunglies 0013fb3680 perf(profile): stabilize profile grid callbacks and context menus
ProfileItem is memoized, but the grid passed five freshly-created closure
props per render, so URL keystrokes and switch spinners re-rendered every
card. The callbacks are now uid/item-parameterized stable handlers, and
the context-menu label map and item literals are hoisted or gated on the
menu being open.
2026-11-19 21:45:05 +08:00
星海and❤是纱雾酱哟~ 3f7af9ab02 fix(media-unlock): avoid misleading region for Muse AI in Rule mode (#8685)
* fix(media-unlock): avoid misleading region from cloudflare trace for Muse AI

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

* chore(changelog): append missing statements

- Simply express what has changed in `Changelog.md`

Assisted-by: MAI Code 2 (high)
Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

---------

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-11-19 01:24:54 +00:00
wonfen 7b7a5947b9 feat(home): follow url-test/fallback groups picked on the node card
The card lists fallback groups again, and switching it to a url-test or
fallback group points the first select group at it without fixing a node.
2026-11-19 01:57:09 +08:00
wonfen 54119cb187 feat(proxy): follow url-test/fallback picks with the first select group
In rule mode, picking a node in a url-test or fallback group also points the first select group listing it at that group. Toggle in Misc settings, on by default.
2026-11-19 01:57:08 +08:00
renovate[bot]renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>❤是纱雾酱哟~
2e786bf2c9 chore(deps): update github/gh-aw-actions action to v1.3.1 (#8686)
* chore(deps): update github/gh-aw-actions action to v1.3.1

* chore(deps): update gh-aw extension version to v1.3.1

- Also bump version value of `with.version`

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

* chore: update gh-aw to version 1.3.1

- Updated `gh-aw` version from `1.3.0` to `1.3.1` in workflow configuration

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

* chore(gh-aw): update allowed network identifiers for better maintainability

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

* feat(gh-aw): update model routing logic

Rather than judging auto-routing standard by GitHub Copilot itself, explicitly set the cost level to "economy" to
reduce AI Credits costs of one collaborator's classic PAT.

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

---------

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-11-18 15:21:01 +00:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 4890f8eaa7 chore(deps): update dependency pnpm to v12.21.0 (#8687)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-18 14:31:52 +00:00
66 changed files with 1013 additions and 758 deletions
+1 -1
View File
@@ -5,7 +5,7 @@
"features": {
"ghcr.io/devcontainers/features/node:2": {
"version": "26.13.1",
"pnpmVersion": "12.18.0"
"pnpmVersion": "12.21.0"
},
"ghcr.io/devcontainers/features/rust:1": {
"version": "1.100.0",
+3 -3
View File
@@ -5,10 +5,10 @@
"version": "v9.0.0",
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
},
"github/gh-aw-actions/setup@v1.3.0": {
"github/gh-aw-actions/setup@v1.3.1": {
"repo": "github/gh-aw-actions/setup",
"version": "v1.3.0",
"sha": "8126d6cb07dea9221848de275af8a41474d839ca"
"version": "v1.3.1",
"sha": "dfe97a19c8249d41e2adfc95f92db2b8facea58f"
}
},
"containers": {
+2 -2
View File
@@ -31,9 +31,9 @@ jobs:
with:
persist-credentials: false
- name: Install gh-aw extension
uses: github/gh-aw-actions/setup-cli@8126d6cb07dea9221848de275af8a41474d839ca # v1.3.0
uses: github/gh-aw-actions/setup-cli@dfe97a19c8249d41e2adfc95f92db2b8facea58f # v1.3.1
with:
version: v1.3.0
version: v1.3.1
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable
with:
File diff suppressed because one or more lines are too long
+4
View File
@@ -30,6 +30,10 @@ max-ai-credits: 60
max-turns: 12
max-daily-ai-credits: 5000
# Routine, low-risk tasks such as triage, labeling, and summaries.
# See https://github.github.com/gh-aw/reference/model-routing/#setting-the-level-yourself
model: router/economy
permissions:
issues: read
pull-requests: read
File diff suppressed because one or more lines are too long
+3
View File
@@ -26,6 +26,9 @@ imports:
max-ai-credits: 60
max-turns: 12
max-daily-ai-credits: 500
# Routine, low-risk tasks such as triage, labeling, and summaries.
# See https://github.github.com/gh-aw/reference/model-routing/#setting-the-level-yourself
model: router/economy
permissions:
contents: read
issues: read
File diff suppressed because one or more lines are too long
+6 -1
View File
@@ -32,8 +32,13 @@ permissions:
max-ai-credits: 60
max-turns: 12
max-daily-ai-credits: 500
# Routine, low-risk tasks such as triage, labeling, and summaries.
# See https://github.github.com/gh-aw/reference/model-routing/#setting-the-level-yourself
model: router/economy
network:
allowed: [github, docs.rs, doc.rust-lang.org, nodejs.org, www.typescriptlang.org]
# GitHub CLI recommend using ecosystem identifiers instead of individual domain names for better maintainability,
# hence "node" is prefer than "nodejs.org"
allowed: [github, docs.rs, doc.rust-lang.org, node, www.typescriptlang.org]
steps:
- name: Load trusted metadata parser
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+1 -1
View File
@@ -1,3 +1,3 @@
nodejs 26.13.1
pnpm 12.18.0
pnpm 12.21.0
rust 1.100.0
+4
View File
@@ -38,6 +38,7 @@
- 修复「连接」页表格排序时表头换行、标题位置跳动
- 修复「TUN 设置」未手动保存时,界面显示的默认 MTU 1500 未生效
- 修复「链式代理」节点列表按名称排序,未保持订阅中的节点顺序
- 修复规则模式下 Muse AI 解锁检测显示错误的出口地区
**🍎 macOS**
@@ -55,15 +56,18 @@
<summary><strong> ✨ 新增功能 </strong></summary>
- 新增连接页面按网络协议(TCP/UDP)筛选连接
- 新增规则模式下在 `url-test` 或 `fallback` 代理组选节点时,自动将首个包含该组的 `select` 代理组切换到该组,可在「杂项设置」关闭
</details>
<details>
<summary><strong> 🚀 优化改进 </strong></summary>
- 优化首页流量图与代理、订阅、日志、设置页面的渲染效率,长列表滚动与实时刷新更流畅
- 优化连接、规则和日志筛选:切换页面后保留过滤条件
- 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组
- 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件
- 优化首页「当前节点」卡片:代理组列表加入 `fallback` 代理组,切换到 `url-test` 或 `fallback` 代理组时同样联动 `select` 代理组
**🍎 macOS**
+6 -11
View File
@@ -1,28 +1,23 @@
use reqwest::Client;
use crate::utils::{classify_restricted_status, get_trace_location};
use crate::utils::classify_restricted_status;
use super::UnlockItem;
pub(crate) const MUSE_AI_NAME: &str = "Muse AI";
const MUSE_URL: &str = "https://muse.ai";
const CLOUDFLARE_TRACE_URL: &str = "https://www.cloudflare.com/cdn-cgi/trace";
// The aymh ("Are You a Human") gateway answers plain HTTP requests with a
// generic Meta error page that always contains the Facebook logo asset.
const AYMH_ERROR_MARKERS: &[&str] = &["Sorry, something went wrong", "static.facebook.com/images/logos"];
pub(super) async fn check_muse_ai(client: &Client) -> UnlockItem {
// muse.ai itself is served by Vercel, so resolve the exit region through
// the generic Cloudflare trace endpoint instead of a service-specific one.
let region = get_trace_location(client, CLOUDFLARE_TRACE_URL)
.await
.map(|code| code.trim().to_ascii_uppercase())
.map(|code| UnlockItem::region_label(&code));
// muse.ai is served by Vercel and does not expose a service-specific region trace endpoint.
// Querying a generic third-party domain (e.g. www.cloudflare.com/cdn-cgi/trace) would report
// that domain's proxy group rather than muse.ai's actual exit in Rule mode, so leave region as None.
let Ok(response) = client.get(MUSE_URL).send().await else {
return UnlockItem::checked(MUSE_AI_NAME, "Failed (Network Connection)", region);
return UnlockItem::checked(MUSE_AI_NAME, "Failed (Network Connection)", None);
};
let status = response.status();
@@ -44,5 +39,5 @@ pub(super) async fn check_muse_ai(client: &Client) -> UnlockItem {
classify_restricted_status(status).unwrap_or("Failed")
};
UnlockItem::checked(MUSE_AI_NAME, result, region)
UnlockItem::checked(MUSE_AI_NAME, result, None)
}
+1 -1
View File
@@ -138,5 +138,5 @@
]
},
"type": "module",
"packageManager": "pnpm@12.18.0"
"packageManager": "pnpm@12.21.0"
}
+70 -61
View File
@@ -7,153 +7,162 @@ importers:
configDependencies: {}
packageManagerDependencies:
pnpm:
specifier: 12.18.0
version: 12.18.0
specifier: 12.21.0
version: 12.21.0
packages:
'@pnpm/exe.android-arm64@12.18.0':
resolution: {integrity: sha512-fOF6IwgvnUKEmVedGqiAsNPfN2Ry8GvaqzSQOiF3RJFbpBfPKO/6YT54s1GjToyYinRxw9preHHPe4y2N3SzhA==}
'@pnpm/exe.android-arm64@12.21.0':
resolution: {integrity: sha512-iaWidxR5B9NUBpwMznCQu1yUpKB6BjTY5BYX2lORj76VsfINdj8Z8XWSzSNrGI8qlxa28Jzdp5fiaspzOaJZlA==}
cpu: [arm64]
os: [android]
'@pnpm/exe.android-x64@12.18.0':
resolution: {integrity: sha512-6OiolnaCsB3/GcJ9XNrenbUH3zFHRJ+5QynrMUUEyThbgnnCzWxa199hpQlOmxN4rAXuYQ0IYgWFNUZxyzg31Q==}
'@pnpm/exe.android-x64@12.21.0':
resolution: {integrity: sha512-35e5v3wlwjIYxDywq+R6/z8CE4gLOEgRxt18yqz1tMRLmx2mnW+CFJI2Q8+srTNjn7gykXUC0x1k195JNikC5A==}
cpu: [x64]
os: [android]
'@pnpm/exe.darwin-arm64@12.18.0':
resolution: {integrity: sha512-zkq+4YzVIX39ETYLyC3W7LY7MpHEU/J3nRhHl4i2yPld2Cf2+rEKRh3ejJ4AmaQ77HHJLCktY4Z3jq0fpcxFXg==}
'@pnpm/exe.darwin-arm64@12.21.0':
resolution: {integrity: sha512-F5OyMX/6zLSowpTZEQRojbCmPS1Pq+fyRaIinslsIe6Glh3qbyQ52u+Fe0eEzSaRuIbWZkXmAAXSWh6Q5Wrlgg==}
cpu: [arm64]
os: [darwin]
'@pnpm/exe.darwin-x64@12.18.0':
resolution: {integrity: sha512-qMsL9qx92unOTa6hgkfiTJv8ceZaTx0IQg7InhYDVX2ZrTECujaVEEVypnJK5m3eGUsP1KD7Y4qIgleCwfRsYw==}
'@pnpm/exe.darwin-x64@12.21.0':
resolution: {integrity: sha512-EzpvcsaE6hrrgYeEiAFYd2rSgFybYyxXhkAY7K3y6Hg3loVfcyJ81hHczpFzi8lW5RXtUlFECRPZ8ZAMRFQYYg==}
cpu: [x64]
os: [darwin]
'@pnpm/exe.freebsd-x64@12.18.0':
resolution: {integrity: sha512-/9vy/4ms52cU4MjZ5NhHd6N2d9L9W0kARf5/ff2tweAHu0VeUzs/0qp/7ZHFuddm2Wa/m0AKQoPum9AVUCqKsw==}
'@pnpm/exe.freebsd-x64@12.21.0':
resolution: {integrity: sha512-wNjuEnmdLks4aayPu/QZWQ5tQM9Jn+odUp/vwQM8BXRYoulkTZhtZTHoD60N6mUdLWef1hgUeUh8llNGEUsimw==}
cpu: [x64]
os: [freebsd]
'@pnpm/exe.linux-arm64-musl@12.18.0':
resolution: {integrity: sha512-Vp+TIMPPyackVCXkOdEKH/RmAn/r07EcIyrgZYQK7VrkksqZOie0GnWIx+85mPqeFEYCRtXIZAFJ9L4ceTndDg==}
'@pnpm/exe.linux-arm64-musl@12.21.0':
resolution: {integrity: sha512-Ceit9zn4g5ZqCJtx1fV8eJE7p8aeXMrGZ+Dc01vRqZLIUNgNeI+Ur0ruyqxtsnJx6rGADyXzohumxPLHjaJ5AQ==}
cpu: [arm64]
os: [linux]
libc: [musl]
'@pnpm/exe.linux-arm64@12.18.0':
resolution: {integrity: sha512-2dpyVBCHT+FfpuQh9i+7MXAqNWYLCvD5vYr5p6Eimxoga8USLnjbUgyj72AOrO0hjc5ri3TEFP3jiyBHjkSZpQ==}
'@pnpm/exe.linux-arm64@12.21.0':
resolution: {integrity: sha512-4Oj/iF2TDCe2lcH0n4TupPR5sSdrNLclJB6xBElLMPCUOAvBhdf2rRlSaO5M4erJ6g4Fyy7YTXTpcmfFsKyxEA==}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-ppc64@12.18.0':
resolution: {integrity: sha512-BBOOOfNJ2QwIIya3eKqOjiN4WNTszfRz7HCvw9XggcT7+ftMjNP8XJ/GfW+ltCBeUFR9d8WBVsr2m/NLjX2CZQ==}
'@pnpm/exe.linux-ppc64@12.21.0':
resolution: {integrity: sha512-s2o7rdSDeUTBFsNqxptpZXlTgT6cojmMVUOvTQvFNSv6Easian02ha4tR32fwwD97Au4YzIIjMCwywCF4D82Sw==}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-riscv64@12.18.0':
resolution: {integrity: sha512-7kMN77xSOYJX8GPSH5RbNAc5oM61LMmcSUukDDUwllnZPXm8GRPskCNsTWy8SCw01Kr1FB+5SwGNMiTdiziLNQ==}
'@pnpm/exe.linux-riscv64@12.21.0':
resolution: {integrity: sha512-EYv3GzxeBTITCuM3yGHHbpRFpUvyulkXpQ6LsjKAQNL3iaba1E6h9iDmlouLb3Io4AMMsfdk0/uG6poQ41uewA==}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-s390x@12.18.0':
resolution: {integrity: sha512-htuSCpEcmDzhKoJqXbPkvfr176dBHU0QIF5mWcRiqxRXAB/1JoYiMYotfjWpk+ztgpB9qlx4XnWlLFAf7gzc6g==}
'@pnpm/exe.linux-s390x@12.21.0':
resolution: {integrity: sha512-8VXGNGVNEfs7pL9GTZOzFxjFEnMt4WL3rLOADR5/kPQ7ROTV9GfpVI2DPO/zArXFSkvfc9Zad/WypHLbvzoaTQ==}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-x64-musl@12.18.0':
resolution: {integrity: sha512-Uj+vzfIQ62kDP10x36yHZIXVs5ohdNtiPYwn5FhCLlNScHPo0OAI+ShGDtLofiBXKE7umu71Jmjm7N8a8zVcDw==}
'@pnpm/exe.linux-x64-musl@12.21.0':
resolution: {integrity: sha512-MnC5vpIXYubhDZCgCwlfJMg7Cg6HupN2IuouT9gD/tUmOfVdQYqeyYccWbthyo/Jeto8de1oQlxeRN1+1Hl2DQ==}
cpu: [x64]
os: [linux]
libc: [musl]
'@pnpm/exe.linux-x64@12.18.0':
resolution: {integrity: sha512-OJ+X2wcraldCwj75pCIerWARQSRpdfj0eBTs/2ODyhfeW46ylOnjTIE/GKra6Mn6E72/gBmXS8igrUioa+F9fQ==}
'@pnpm/exe.linux-x64@12.21.0':
resolution: {integrity: sha512-8eufCjHXspKbNS/kh8q4Q0gqJoOuvC4Q5pgos6XS8By/nAMtP+jf8F1Cw9er840kfAX+PJ/ts+A9qnLE91rvXQ==}
cpu: [x64]
os: [linux]
libc: [glibc]
'@pnpm/exe.win32-arm64@12.18.0':
resolution: {integrity: sha512-wEY6jiACGcbhhi5yD59doHqNTndS7AaujaPmtWAu1DKkHru2hy5fJ9yUGecW72Ypaw2/I3BEprfMOopap2NQtw==}
'@pnpm/exe.netbsd-x64@12.21.0':
resolution: {integrity: sha512-eyh1M8hQZCkLWxuva7S/fc1SbFbgqg0/5di0dgWmyiuc2Io3dbWVihDun8X+XM8zsR5uhIDvvZpbS9aZQbCovg==}
cpu: [x64]
os: [netbsd]
'@pnpm/exe.win32-arm64@12.21.0':
resolution: {integrity: sha512-7xTxxUXo/grRLivSeIl6B21gnsz7ooe5EMPcJmQqwxc8WLJVReN8MzrlHru8bqXfVr4X3+6ZGZscntKenlCBqQ==}
cpu: [arm64]
os: [win32]
'@pnpm/exe.win32-x64@12.18.0':
resolution: {integrity: sha512-5FJkghO7RLRkQpWxeVEygW9XsmnNuxzPfXbgwFWCHsFyFhpDn/vOdL88ToQEM0Kt5igdW5s6U0/IDH8Dvkt3pg==}
'@pnpm/exe.win32-x64@12.21.0':
resolution: {integrity: sha512-9TpkJemVApxJ1Z1w0ZFGN+AuSx4nJOqXSJUqMqDvaXTYwGOzvBiiWdFP9GN0ketiWCQS1Q0/pza2E7I3pP0OBQ==}
cpu: [x64]
os: [win32]
pnpm@12.18.0:
resolution: {integrity: sha512-nXiC1dyCFH7PxOBiqjSDTgrQKWcQoYN6ERWuASEn02txCeMhrBWYod0KZVl2gbHpmRfhLtDXSerpEYeUM2O+sw==}
pnpm@12.21.0:
resolution: {integrity: sha512-Zv2CeO4ok1zpUXktNDZ/869cQyonVkRYIwKVM4NbjaUpu+C+UTCv1W7QcT+4eJ5Hutgtk71a4v5UsVVi1idu8A==}
engines: {node: '>=18'}
hasBin: true
snapshots:
'@pnpm/exe.android-arm64@12.18.0':
'@pnpm/exe.android-arm64@12.21.0':
optional: true
'@pnpm/exe.android-x64@12.18.0':
'@pnpm/exe.android-x64@12.21.0':
optional: true
'@pnpm/exe.darwin-arm64@12.18.0':
'@pnpm/exe.darwin-arm64@12.21.0':
optional: true
'@pnpm/exe.darwin-x64@12.18.0':
'@pnpm/exe.darwin-x64@12.21.0':
optional: true
'@pnpm/exe.freebsd-x64@12.18.0':
'@pnpm/exe.freebsd-x64@12.21.0':
optional: true
'@pnpm/exe.linux-arm64-musl@12.18.0':
'@pnpm/exe.linux-arm64-musl@12.21.0':
optional: true
'@pnpm/exe.linux-arm64@12.18.0':
'@pnpm/exe.linux-arm64@12.21.0':
optional: true
'@pnpm/exe.linux-ppc64@12.18.0':
'@pnpm/exe.linux-ppc64@12.21.0':
optional: true
'@pnpm/exe.linux-riscv64@12.18.0':
'@pnpm/exe.linux-riscv64@12.21.0':
optional: true
'@pnpm/exe.linux-s390x@12.18.0':
'@pnpm/exe.linux-s390x@12.21.0':
optional: true
'@pnpm/exe.linux-x64-musl@12.18.0':
'@pnpm/exe.linux-x64-musl@12.21.0':
optional: true
'@pnpm/exe.linux-x64@12.18.0':
'@pnpm/exe.linux-x64@12.21.0':
optional: true
'@pnpm/exe.win32-arm64@12.18.0':
'@pnpm/exe.netbsd-x64@12.21.0':
optional: true
'@pnpm/exe.win32-x64@12.18.0':
'@pnpm/exe.win32-arm64@12.21.0':
optional: true
pnpm@12.18.0:
'@pnpm/exe.win32-x64@12.21.0':
optional: true
pnpm@12.21.0:
optionalDependencies:
'@pnpm/exe.android-arm64': 12.18.0
'@pnpm/exe.android-x64': 12.18.0
'@pnpm/exe.darwin-arm64': 12.18.0
'@pnpm/exe.darwin-x64': 12.18.0
'@pnpm/exe.freebsd-x64': 12.18.0
'@pnpm/exe.linux-arm64': 12.18.0
'@pnpm/exe.linux-arm64-musl': 12.18.0
'@pnpm/exe.linux-ppc64': 12.18.0
'@pnpm/exe.linux-riscv64': 12.18.0
'@pnpm/exe.linux-s390x': 12.18.0
'@pnpm/exe.linux-x64': 12.18.0
'@pnpm/exe.linux-x64-musl': 12.18.0
'@pnpm/exe.win32-arm64': 12.18.0
'@pnpm/exe.win32-x64': 12.18.0
'@pnpm/exe.android-arm64': 12.21.0
'@pnpm/exe.android-x64': 12.21.0
'@pnpm/exe.darwin-arm64': 12.21.0
'@pnpm/exe.darwin-x64': 12.21.0
'@pnpm/exe.freebsd-x64': 12.21.0
'@pnpm/exe.linux-arm64': 12.21.0
'@pnpm/exe.linux-arm64-musl': 12.21.0
'@pnpm/exe.linux-ppc64': 12.21.0
'@pnpm/exe.linux-riscv64': 12.21.0
'@pnpm/exe.linux-s390x': 12.21.0
'@pnpm/exe.linux-x64': 12.21.0
'@pnpm/exe.linux-x64-musl': 12.21.0
'@pnpm/exe.netbsd-x64': 12.21.0
'@pnpm/exe.win32-arm64': 12.21.0
'@pnpm/exe.win32-x64': 12.21.0
---
lockfileVersion: '9.0'
+6
View File
@@ -27,6 +27,12 @@ pub async fn switch_proxy_node(group_name: String, proxy_name: String, unfix: bo
.stringify_err()
}
#[tauri::command]
#[specta::specta]
pub async fn follow_proxy_group(group_name: String) {
crate::feat::follow_proxy_group(&group_name).await;
}
fn runtime_group_order(config: Option<&Mapping>) -> Vec<String> {
let mut seen = HashSet::new();
+4
View File
@@ -109,6 +109,8 @@ pub struct IVerge {
pub auto_close_connection: Option<bool>,
pub auto_switch_selector_group: Option<bool>,
pub auto_check_update: Option<bool>,
pub default_latency_test: Option<String>,
@@ -368,6 +370,7 @@ impl IVerge {
use_default_bypass: Some(true),
proxy_guard_duration: Some(30),
auto_close_connection: Some(true),
auto_switch_selector_group: Some(true),
auto_check_update: Some(true),
enable_builtin_enhanced: Some(true),
auto_log_clean: Some(2), // 1: 1天, 2: 7天, 3: 30天, 4: 90天
@@ -456,6 +459,7 @@ impl IVerge {
patch_opt_field!(self, patch, enable_global_hotkey);
patch_opt_field!(self, patch, auto_close_connection);
patch_opt_field!(self, patch, auto_switch_selector_group);
patch_opt_field!(self, patch, auto_check_update);
patch_opt_field!(self, patch, default_latency_test);
patch_opt_field!(self, patch, default_latency_timeout);
+1
View File
@@ -90,6 +90,7 @@ verge_registry! {
enable_global_hotkey => NoEffect;
home_cards => NoEffect;
auto_close_connection => NoEffect;
auto_switch_selector_group => NoEffect;
auto_check_update => NoEffect;
default_latency_test => NoEffect;
default_latency_timeout => NoEffect;
+118 -4
View File
@@ -9,6 +9,7 @@ use crate::{
};
use anyhow::{Result, bail};
use clash_verge_logging::{Type, logging};
use tauri_plugin_mihomo::models::ProxyType;
use tristr::alias::String;
/// Toggle proxy profile
@@ -22,9 +23,80 @@ pub async fn toggle_proxy_profile(profile_index: String) {
}
}
/// First `select` group in config order that lists `group_name`, when that group is `url-test` or `fallback`.
fn parent_selector<'a>(groups: &'a [serde_yaml_ng::Value], group_name: &str) -> Option<&'a str> {
let field = |group: &'a serde_yaml_ng::Value, key: &str| group.get(key)?.as_str();
let group = groups.iter().find(|group| field(group, "name") == Some(group_name))?;
if !matches!(field(group, "type"), Some("url-test" | "fallback")) {
return None;
}
groups
.iter()
.filter(|group| field(group, "type") == Some("select"))
.filter(|group| {
group
.get("proxies")
.and_then(|members| members.as_sequence())
.is_some_and(|members| members.iter().any(|member| member.as_str() == Some(group_name)))
})
.filter_map(|group| field(group, "name"))
.find(|name| *name != "GLOBAL")
}
/// Rule traffic enters through `select` groups, so a pick inside a `url-test`/`fallback` group only
/// carries traffic once the first `select` group listing that group points at it.
/// Returns the node that group left.
async fn follow_group_selection(group_name: &str) -> Option<std::string::String> {
if !Config::verge()
.await
.data_arc()
.auto_switch_selector_group
.unwrap_or(true)
{
return None;
}
if Config::clash()
.await
.data_arc()
.get_mode()
.is_some_and(|mode| mode != "rule")
{
return None;
}
let selector = {
let runtime = Config::runtime().await.latest_arc();
let groups = runtime.config.as_ref()?.get("proxy-groups")?.as_sequence()?;
parent_selector(groups, group_name)?.to_owned()
};
let mihomo = handle::Handle::mihomo();
let current = mihomo.get_proxy_by_name(&selector).await.ok()?;
// The runtime config can lag the core, which alone knows what this group is now.
if current.proxy_type != ProxyType::Selector {
return None;
}
let previous = current.now?;
if previous == group_name {
return None;
}
if let Err(err) = mihomo.select_node_for_group(&selector, group_name).await {
logging!(warn, Type::Core, "Failed to point {selector} at {group_name}: {err:#}");
return None;
}
if let Err(error) = crate::config::profiles::record_selected_node(&selector, group_name).await {
logging!(
warn,
Type::Config,
"Failed to persist proxy selection for {selector}: {error:#}"
);
}
Some(previous)
}
pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool) -> Result<()> {
let mihomo = handle::Handle::mihomo();
let previous_proxy = if Config::verge().await.data_arc().auto_close_connection.unwrap_or(false) {
let auto_close = Config::verge().await.data_arc().auto_close_connection.unwrap_or(false);
let previous_proxy = if auto_close {
match mihomo.get_proxy_by_name(group_name).await {
Ok(group) => group.now.filter(|name| !name.is_empty()),
Err(err) => {
@@ -58,9 +130,31 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool)
"Failed to persist proxy selection for {group_name}: {error:#}"
);
}
let mut stale_proxies: Vec<_> = previous_proxy.into_iter().collect();
if !unfix
&& let Some(left) = follow_group_selection(group_name).await
&& auto_close
{
stale_proxies.push(left);
}
finish_proxy_switch(stale_proxies).await;
Ok(())
}
/// Lets a `url-test`/`fallback` group carry rule traffic without fixing a node in it.
pub async fn follow_proxy_group(group_name: &str) {
let Some(left) = follow_group_selection(group_name).await else {
return;
};
let auto_close = Config::verge().await.data_arc().auto_close_connection.unwrap_or(false);
finish_proxy_switch(auto_close.then_some(left).into_iter().collect()).await;
}
async fn finish_proxy_switch(stale_proxies: Vec<std::string::String>) {
let mihomo = handle::Handle::mihomo();
announce(Refresh::Proxies);
if let Some(previous_proxy) = previous_proxy {
if !stale_proxies.is_empty() {
AsyncHandler::spawn(move || async move {
let connections = match mihomo.get_connections().await {
Ok(connections) => connections,
@@ -78,7 +172,7 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool)
.connections
.unwrap_or_default()
.into_iter()
.filter(|connection| connection.chains.contains(&previous_proxy))
.filter(|connection| stale_proxies.iter().any(|proxy| connection.chains.contains(proxy)))
.map(|connection| async move {
if let Err(err) = mihomo.close_connection(&connection.id).await {
logging!(
@@ -100,7 +194,6 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool)
"Failed to refresh tray after switching proxy: {err:#}"
);
}
Ok(())
}
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
@@ -280,3 +373,24 @@ pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_mannual_tr
pub async fn enhance_profiles() -> Result<ValidationOutcome> {
CoreManager::global().update_config_forced().await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_first_select_group_follows_an_auto_group() -> Result<()> {
let groups: Vec<serde_yaml_ng::Value> = serde_yaml_ng::from_str(
"
- { name: GLOBAL, type: select, proxies: [Auto, Proxy, Direct] }
- { name: Auto, type: url-test, proxies: [Node] }
- { name: Proxy, type: select, proxies: [Auto, Node] }
- { name: Direct, type: select, proxies: [DIRECT, Auto] }
",
)?;
assert_eq!(parent_selector(&groups, "Auto"), Some("Proxy"));
assert_eq!(parent_selector(&groups, "Proxy"), None);
Ok(())
}
}
+1
View File
@@ -47,6 +47,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
cmd::copy_clash_env,
cmd::record_selected_node,
cmd::switch_proxy_node,
cmd::follow_proxy_group,
cmd::save_dns_config,
cmd::apply_dns_config,
cmd::set_dns_override,
+3 -1
View File
@@ -55,6 +55,7 @@ import {
useCoreDataStatus,
useProxiesData,
} from '@/providers/app-data-context'
import { followProxyGroup } from '@/services/cmds'
import delayManager from '@/services/delay'
import {
findCurrentGroupMember,
@@ -665,7 +666,7 @@ export const CurrentProxyCard = () => {
return proxyView.groups.filter(
(group) =>
!group.hidden &&
(group.type === 'Selector' || group.type === 'URLTest'),
['Selector', 'URLTest', 'Fallback'].includes(group.type),
)
}, [proxyView])
@@ -765,6 +766,7 @@ export const CurrentProxyCard = () => {
if (isGlobalMode || isDirectMode) return
setLastGroupName(newGroupName)
writeProfileScopedItem(STORAGE_KEY_GROUP, newGroupName)
void followProxyGroup(newGroupName)
},
[isDirectMode, isGlobalMode, writeProfileScopedItem],
)
+6 -6
View File
@@ -87,18 +87,18 @@ export const TestCard = () => {
x.uid === uid ? { ...x, ...patch } : x,
)
mutateVerge({ ...verge, test_list: newList })
mutateVerge((prev) => ({ ...prev, test_list: newList }))
},
[testList, verge, mutateVerge],
[testList, mutateVerge],
)
const onDeleteTestListItem = useCallback(
(uid: string) => {
const newList = testList.filter((x) => x.uid !== uid)
patchVerge({ test_list: newList })
mutateVerge({ ...verge, test_list: newList })
mutateVerge((prev) => ({ ...prev, test_list: newList }))
},
[testList, verge, patchVerge, mutateVerge],
[testList, patchVerge, mutateVerge],
)
const onDragEnd = useCallback(
@@ -129,7 +129,7 @@ export const TestCard = () => {
newList.splice(newIndex, 0, removed)
// 优化:先本地更新,再异步 patch,避免UI卡死
mutateVerge({ ...verge, test_list: newList })
mutateVerge((prev) => ({ ...prev, test_list: newList }))
const patchFn = () => {
try {
patchVerge({ test_list: newList })
@@ -141,7 +141,7 @@ export const TestCard = () => {
setTimeout(patchFn, 0)
}
},
[testList, verge, mutateVerge, patchVerge],
[testList, mutateVerge, patchVerge],
)
// 仅在verge首次加载时初始化测试列表
+23 -11
View File
@@ -176,7 +176,10 @@ export const GroupsEditorViewer = (props: Props) => {
},
})
const [groupList, setGroupList] = useState<IProxyGroupConfig[]>([])
const [proxyPolicyList, setProxyPolicyList] = useState<string[]>([])
const [originPolicy, setOriginPolicy] = useState<{
proxyNames: string[]
groupNames: string[]
}>({ proxyNames: [], groupNames: [] })
const [proxyProviderList, setProxyProviderList] = useState<string[]>([])
const [prependSeq, setPrependSeq] = useState<IProxyGroupConfig[]>([])
const [appendSeq, setAppendSeq] = useState<IProxyGroupConfig[]>([])
@@ -353,6 +356,9 @@ export const GroupsEditorViewer = (props: Props) => {
}
}, [prependSeq, appendSeq, deleteSeq])
// Origin policy names come from profile files that this dialog never
// rewrites while open, so they are read once per open; the live seq states
// are folded in by the derived proxyPolicyList below.
const fetchProxyPolicy = useCallback(async () => {
const data = await readProfileFile(profileUid)
const proxiesData = await readProfileFile(proxiesUid)
@@ -388,17 +394,13 @@ export const GroupsEditorViewer = (props: Props) => {
(name): name is string => typeof name === 'string' && name.length > 0,
)
const computedPolicyList = builtinProxyPolicies.concat(
prependSeq.map((group: IProxyGroupConfig) => group.name),
(originGroupsObj?.['proxy-groups'] || [])
.map((group: IProxyGroupConfig) => group.name)
.filter((name) => !deleteSeq.includes(name)),
appendSeq.map((group: IProxyGroupConfig) => group.name),
setOriginPolicy({
proxyNames,
)
setProxyPolicyList(Array.from(new Set(computedPolicyList)))
}, [appendSeq, deleteSeq, prependSeq, profileUid, proxiesUid])
groupNames: (originGroupsObj?.['proxy-groups'] || []).map(
(group) => group.name,
),
})
}, [profileUid, proxiesUid])
const fetchProfile = useCallback(async () => {
const data = await readProfileFile(profileUid)
const mergeData = await readProfileFile(mergeUid)
@@ -442,6 +444,16 @@ export const GroupsEditorViewer = (props: Props) => {
fetchProxyPolicy()
}, [fetchProxyPolicy, open])
const proxyPolicyList = useMemo(() => {
const computedPolicyList = builtinProxyPolicies.concat(
prependSeq.map((group) => group.name),
originPolicy.groupNames.filter((name) => !deleteSeq.includes(name)),
appendSeq.map((group) => group.name),
originPolicy.proxyNames,
)
return Array.from(new Set(computedPolicyList))
}, [appendSeq, deleteSeq, originPolicy, prependSeq])
useEffect(() => {
if (!open) return
fetchContent()
+194 -186
View File
@@ -61,6 +61,31 @@ const round = keyframes`
to { transform: rotate(360deg); }
`
type ContextMenuItem = {
label: string
handler: () => void
disabled: boolean
}
const menuLabels: Record<string, TranslationKey> = {
home: 'profiles.components.menu.home',
select: 'profiles.components.menu.select',
shareQrCode: 'profiles.components.menu.shareQrCode',
editInfo: 'profiles.components.menu.editInfo',
editFile: 'profiles.components.menu.editFile',
editRules: 'profiles.components.menu.editRules',
editProxies: 'profiles.components.menu.editProxies',
editGroups: 'profiles.components.menu.editGroups',
extendConfig: 'profiles.components.menu.extendConfig',
extendScript: 'profiles.components.menu.extendScript',
openFile: 'profiles.components.menu.openFile',
update: 'profiles.components.menu.update',
updateViaProxy: 'profiles.components.menu.updateViaProxy',
delete: 'shared.actions.delete',
} as const
const EMPTY_CONTEXT_MENU: ContextMenuItem[] = []
export interface ProfileItemProps {
id: string
index: number
@@ -68,13 +93,13 @@ export interface ProfileItemProps {
activating: boolean
itemData: IProfileItem
mutateProfiles: () => Promise<void>
onSelect: (force: boolean) => void
onEdit: () => void
onSave?: (prev?: string, curr?: string) => void
onDelete: () => void
onSelect: (uid: string, force: boolean) => void
onEdit: (item: IProfileItem) => void
onSave?: (uid: string, prev?: string, curr?: string) => void
onDelete: (uid: string) => void
batchMode?: boolean
isSelected?: boolean
onSelectionChange?: () => void
onSelectionChange?: (uid: string) => void
timerUpdateRevision: number
completedUpdateRevision: number
}
@@ -322,7 +347,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const onEditInfo = () => {
setAnchorEl(null)
onEdit()
onEdit(itemData)
}
const onShareQrCode = () => {
@@ -362,7 +387,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const onForceSelect = () => {
setAnchorEl(null)
onSelect(true)
onSelect(id, true)
}
const onOpenFile = useLockFn(async () => {
@@ -412,175 +437,158 @@ const ProfileItemBase = (props: ProfileItemProps) => {
}
})
type ContextMenuItem = {
label: string
handler: () => void
disabled: boolean
}
const menuLabels: Record<string, TranslationKey> = {
home: 'profiles.components.menu.home',
select: 'profiles.components.menu.select',
shareQrCode: 'profiles.components.menu.shareQrCode',
editInfo: 'profiles.components.menu.editInfo',
editFile: 'profiles.components.menu.editFile',
editRules: 'profiles.components.menu.editRules',
editProxies: 'profiles.components.menu.editProxies',
editGroups: 'profiles.components.menu.editGroups',
extendConfig: 'profiles.components.menu.extendConfig',
extendScript: 'profiles.components.menu.extendScript',
openFile: 'profiles.components.menu.openFile',
update: 'profiles.components.menu.update',
updateViaProxy: 'profiles.components.menu.updateViaProxy',
delete: 'shared.actions.delete',
} as const
const urlModeMenu: ContextMenuItem[] = [
...(hasHome
? [
{
label: menuLabels.home,
handler: onOpenHome,
disabled: false,
} satisfies ContextMenuItem,
]
: []),
{
label: menuLabels.select,
handler: onForceSelect,
disabled: false,
},
{
label: menuLabels.shareQrCode,
handler: onShareQrCode,
disabled: false,
},
{
label: menuLabels.editInfo,
handler: onEditInfo,
disabled: false,
},
{
label: menuLabels.editFile,
handler: onEditFile,
disabled: false,
},
{
label: menuLabels.editRules,
handler: onEditRules,
disabled: !option?.rules,
},
{
label: menuLabels.editProxies,
handler: onEditProxies,
disabled: !option?.proxies,
},
{
label: menuLabels.editGroups,
handler: onEditGroups,
disabled: !option?.groups,
},
{
label: menuLabels.extendConfig,
handler: onEditMerge,
disabled: !option?.merge,
},
{
label: menuLabels.extendScript,
handler: onEditScript,
disabled: !option?.script,
},
{
label: menuLabels.openFile,
handler: onOpenFile,
disabled: false,
},
{
label: menuLabels.update,
handler: () => onUpdate(0),
disabled: false,
},
{
label: menuLabels.updateViaProxy,
handler: () => onUpdate(2),
disabled: false,
},
{
label: menuLabels.delete,
handler: () => {
setAnchorEl(null)
if (batchMode) {
if (onSelectionChange) {
onSelectionChange()
}
} else {
setConfirmOpen(true)
}
},
disabled: false,
},
]
const fileModeMenu: ContextMenuItem[] = [
{
label: menuLabels.select,
handler: onForceSelect,
disabled: false,
},
{
label: menuLabels.editInfo,
handler: onEditInfo,
disabled: false,
},
{
label: menuLabels.editFile,
handler: onEditFile,
disabled: false,
},
{
label: menuLabels.editRules,
handler: onEditRules,
disabled: !option?.rules,
},
{
label: menuLabels.editProxies,
handler: onEditProxies,
disabled: !option?.proxies,
},
{
label: menuLabels.editGroups,
handler: onEditGroups,
disabled: !option?.groups,
},
{
label: menuLabels.extendConfig,
handler: onEditMerge,
disabled: !option?.merge,
},
{
label: menuLabels.extendScript,
handler: onEditScript,
disabled: !option?.script,
},
{
label: menuLabels.openFile,
handler: onOpenFile,
disabled: false,
},
{
label: menuLabels.delete,
handler: () => {
setAnchorEl(null)
if (batchMode) {
if (onSelectionChange) {
onSelectionChange()
}
} else {
setConfirmOpen(true)
}
},
disabled: false,
},
]
// The context menu is closed on almost every render; building its items
// only while open keeps the idle path allocation-free.
const menuItems: ContextMenuItem[] =
anchorEl === null
? EMPTY_CONTEXT_MENU
: hasUrl
? [
...(hasHome
? [
{
label: menuLabels.home,
handler: onOpenHome,
disabled: false,
} satisfies ContextMenuItem,
]
: []),
{
label: menuLabels.select,
handler: onForceSelect,
disabled: false,
},
{
label: menuLabels.shareQrCode,
handler: onShareQrCode,
disabled: false,
},
{
label: menuLabels.editInfo,
handler: onEditInfo,
disabled: false,
},
{
label: menuLabels.editFile,
handler: onEditFile,
disabled: false,
},
{
label: menuLabels.editRules,
handler: onEditRules,
disabled: !option?.rules,
},
{
label: menuLabels.editProxies,
handler: onEditProxies,
disabled: !option?.proxies,
},
{
label: menuLabels.editGroups,
handler: onEditGroups,
disabled: !option?.groups,
},
{
label: menuLabels.extendConfig,
handler: onEditMerge,
disabled: !option?.merge,
},
{
label: menuLabels.extendScript,
handler: onEditScript,
disabled: !option?.script,
},
{
label: menuLabels.openFile,
handler: onOpenFile,
disabled: false,
},
{
label: menuLabels.update,
handler: () => onUpdate(0),
disabled: false,
},
{
label: menuLabels.updateViaProxy,
handler: () => onUpdate(2),
disabled: false,
},
{
label: menuLabels.delete,
handler: () => {
setAnchorEl(null)
if (batchMode) {
if (onSelectionChange) {
onSelectionChange(id)
}
} else {
setConfirmOpen(true)
}
},
disabled: false,
},
]
: [
{
label: menuLabels.select,
handler: onForceSelect,
disabled: false,
},
{
label: menuLabels.editInfo,
handler: onEditInfo,
disabled: false,
},
{
label: menuLabels.editFile,
handler: onEditFile,
disabled: false,
},
{
label: menuLabels.editRules,
handler: onEditRules,
disabled: !option?.rules,
},
{
label: menuLabels.editProxies,
handler: onEditProxies,
disabled: !option?.proxies,
},
{
label: menuLabels.editGroups,
handler: onEditGroups,
disabled: !option?.groups,
},
{
label: menuLabels.extendConfig,
handler: onEditMerge,
disabled: !option?.merge,
},
{
label: menuLabels.extendScript,
handler: onEditScript,
disabled: !option?.script,
},
{
label: menuLabels.openFile,
handler: onOpenFile,
disabled: false,
},
{
label: menuLabels.delete,
handler: () => {
setAnchorEl(null)
if (batchMode) {
if (onSelectionChange) {
onSelectionChange(id)
}
} else {
setConfirmOpen(true)
}
},
disabled: false,
},
]
const boxStyle = {
height: 26,
@@ -599,7 +607,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
await profileDocument.reload()
return
}
onSave?.(profileDocument.savedValue, currentValue)
onSave?.(id, profileDocument.savedValue, currentValue)
profileDocument.markSaved(currentValue)
})
@@ -614,7 +622,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
await mergeDocument.reload()
return
}
onSave?.(mergeDocument.savedValue, currentValue)
onSave?.(id, mergeDocument.savedValue, currentValue)
mergeDocument.markSaved(currentValue)
})
@@ -632,7 +640,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
await scriptDocument.reload()
return
}
onSave?.(scriptDocument.savedValue, currentValue)
onSave?.(id, scriptDocument.savedValue, currentValue)
scriptDocument.markSaved(currentValue)
})
@@ -646,7 +654,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
e.stopPropagation()
return
}
onSelect(false)
onSelect(id, false)
}}
onContextMenu={(event) => {
const { clientX, clientY } = event
@@ -687,7 +695,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
onClick={(e) => {
e.stopPropagation()
if (onSelectionChange) {
onSelectionChange()
onSelectionChange(id)
}
}}
>
@@ -853,7 +861,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
e.preventDefault()
}}
>
{(hasUrl ? urlModeMenu : fileModeMenu).map((item) => (
{menuItems.map((item) => (
<MenuItem
key={item.label}
onClick={item.handler}
@@ -897,7 +905,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
profileUid={uid!}
property={option?.rules ?? ''}
open={true}
onSave={onSave}
onSave={(prev, curr) => onSave?.(id, prev, curr)}
onClose={() => setRulesOpen(false)}
/>
)}
@@ -906,7 +914,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
profileUid={uid!}
property={option?.proxies ?? ''}
open={true}
onSave={onSave}
onSave={(prev, curr) => onSave?.(id, prev, curr)}
onClose={() => setProxiesOpen(false)}
/>
)}
@@ -917,7 +925,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
profileUid={uid!}
property={option?.groups ?? ''}
open={true}
onSave={onSave}
onSave={(prev, curr) => onSave?.(id, prev, curr)}
onClose={() => {
setGroupsOpen(false)
}}
@@ -963,7 +971,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
onCancel={() => setConfirmOpen(false)}
onClose={() => setConfirmOpen(false)}
onOk={() => {
onDelete()
onDelete(id)
setConfirmOpen(false)
}}
>
@@ -180,7 +180,7 @@ export const ProxiesEditorViewer = (props: Props) => {
// 优化:异步分片解析,避免主线程阻塞,解析完成后批量setState
const handleParseAsync = (cb: (proxies: IProxyConfig[]) => void) => {
const proxies: IProxyConfig[] = []
const names: string[] = []
const names = new Set<string>()
let uris: string
try {
uris = atob(proxyUri)
@@ -198,9 +198,9 @@ export const ProxiesEditorViewer = (props: Props) => {
const uri = lines[idx]
try {
const proxy = parseUri(uri.trim())
if (!names.includes(proxy.name)) {
if (!names.has(proxy.name)) {
proxies.push(proxy)
names.push(proxy.name)
names.add(proxy.name)
}
} catch (err) {
console.warn(
+32 -6
View File
@@ -3,6 +3,7 @@ import * as yaml from 'js-yaml'
import {
getRecord,
rebindNode,
sameSource,
type ProxyNodeView,
type ProxyViewV1,
} from '@/types/proxy-view'
@@ -20,22 +21,47 @@ export const rebindProxyChainItems = (
items: readonly ProxyChainItem[],
candidates: readonly ProxyNodeView[],
proxyView: ProxyViewV1,
): ProxyChainItem[] =>
items.map((item) => {
): ProxyChainItem[] => {
// The proxy view refreshes on a fixed cadence; reusing item and array
// identities while the rebound values are equal keeps persistence effects
// and memoized chain rows from reprocessing identical content.
let reboundItems: ProxyChainItem[] | undefined
items.forEach((item, index) => {
const rebound = rebindNode(candidates, {
name: item.name,
source: item.source,
})
const record =
rebound === undefined ? undefined : getRecord(proxyView, rebound.recordId)
return {
const source = rebound?.source ?? item.source
const type = rebound?.type ?? item.type
const delay = record?.history.at(-1)?.delay
const sourceReused =
item.source === source ||
(item.source !== undefined &&
source !== undefined &&
sameSource(item.source, source))
if (
item.recordId === rebound?.recordId &&
sourceReused &&
item.type === type &&
item.delay === delay
) {
return
}
reboundItems ??= [...items]
reboundItems[index] = {
...item,
recordId: rebound?.recordId,
source: rebound?.source ?? item.source,
type: rebound?.type ?? item.type,
delay: record?.history.at(-1)?.delay,
source,
type,
delay,
}
})
return reboundItems ?? (items as ProxyChainItem[])
}
interface ParsedChainConfig {
proxies?: Array<{
+19 -17
View File
@@ -31,9 +31,9 @@ interface Props {
url?: string
groupName: string
headState: HeadState
onLocation: () => void
onCheckDelay: () => void
onHeadState: (val: Partial<HeadState>) => void
onLocation: (groupName: string) => void
onCheckDelay: (groupName: string) => void
onHeadState: (groupName: string, val: Partial<HeadState>) => void
}
export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
@@ -76,7 +76,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
// 因此对写入 headState 的动作做防抖,避免每输入一个字符就过滤一次。
const { run: applyFilter, flush: flushFilter } = useDebounceFn(
(state: SearchState) => {
onHeadState({
onHeadState(groupName, {
filterText: state.text,
filterMatchCase: state.matchCase,
filterMatchWholeWord: state.matchWholeWord,
@@ -125,7 +125,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.preventDefault()
e.stopPropagation()
}}
onChange={(e) => onHeadState({ testUrl: e.target.value })}
onChange={(e) => onHeadState(groupName, { testUrl: e.target.value })}
sx={{ flex: '1 1 auto', input: { py: 0.65, px: 1 } }}
/>
)}
@@ -155,8 +155,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
onLocation()
flushSync(() => onHeadState(groupName, { open: true }))
onLocation(groupName)
}}
>
<MyLocationRounded fontSize="inherit" />
@@ -171,16 +171,16 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
flushSync(() => onHeadState(groupName, { open: true }))
// Remind the user that it is custom test url
if (testUrl?.trim() && textState !== 'filter') {
onHeadState({ textState: 'url' })
onHeadState(groupName, { textState: 'url' })
}
if (testUrl?.trim() && !isValidUrl(testUrl)) {
showNotice.warning('proxies.feedback.warnings.invalidTestUrl')
return
}
onCheckDelay()
onCheckDelay(groupName)
}}
>
<NetworkCheckRounded fontSize="inherit" />
@@ -201,8 +201,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
onHeadState({
flushSync(() => onHeadState(groupName, { open: true }))
onHeadState(groupName, {
sortType: ((sortType + 1) % 3) as ProxySortType,
})
}}
@@ -219,7 +219,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
onHeadState({
onHeadState(groupName, {
textState: textState === 'url' ? null : 'url',
})
setTimeout(() => inputRef.current?.focus())
@@ -245,8 +245,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
onHeadState({ showType: !showType })
flushSync(() => onHeadState(groupName, { open: true }))
onHeadState(groupName, { showType: !showType })
}}
>
{showType ? (
@@ -265,8 +265,10 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation()
if (!headState.open && textState !== 'filter')
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
onHeadState({ textState: textState === 'filter' ? null : 'filter' })
flushSync(() => onHeadState(groupName, { open: true }))
onHeadState(groupName, {
textState: textState === 'filter' ? null : 'filter',
})
setTimeout(() => inputRef.current?.focus())
}}
>
+2 -2
View File
@@ -93,7 +93,7 @@ interface ProxyGroupsChainProps {
// Shared callbacks
onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onLocation: (group: any) => void
onLocation: (groupName: string) => void
onGroupSelect: (groupName: string) => void
onScrollToTop: () => void
}
@@ -245,7 +245,7 @@ function ProxyVirtualList({
activeStickyIndex: number | null
isChainMode?: boolean
measureElement: (node: Element | null) => void
onLocation: (group: any) => void
onLocation: (groupName: string) => void
onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onChangeProxy: (group: ProxyGroupView, member: ResolvedProxyMember) => void
+33 -26
View File
@@ -324,16 +324,20 @@ function ChainProxyGroups(props: {
scrollTopRef.current = 0
}, [])
const handleLocation = useStableCallback((group: ProxyGroupView) => {
if (!group) return
const { name, now } = group
const handleLocation = useStableCallback((groupName: string) => {
// Flat (type 1) headers such as GLOBAL carry the same live group.
const headerIndex = renderList.findIndex(
(e) => (e.type === 0 || e.type === 1) && e.group?.name === groupName,
)
const now = renderList[headerIndex]?.group?.now
if (!now) return
const index = renderList.findIndex(
(item) =>
item.group?.name === name &&
((item.type === 2 && item.member?.member.ref.name === now) ||
(item.type === 4 &&
item.memberCol?.some(({ member }) => member.ref.name === now))),
(e) =>
e.group?.name === groupName &&
((e.type === 2 && e.member?.member.ref.name === now) ||
(e.type === 4 &&
e.memberCol?.some(({ member }) => member.ref.name === now))),
)
if (index >= 0) {
@@ -496,13 +500,17 @@ function NormalProxyGroups(props: { mode: string }) {
[globalGroupName, select, setHeadState],
)
const handleLocation = useStableCallback((group: ProxyGroupView) => {
if (!group) return
const { name, now } = group
const handleLocation = useStableCallback((groupName: string) => {
// Flat (type 1) headers such as GLOBAL carry the same live group.
const headerIndex = renderList.findIndex(
(e) => (e.type === 0 || e.type === 1) && e.group?.name === groupName,
)
const now = renderList[headerIndex]?.group?.now
if (!now) return
const index = renderList.findIndex(
(e) =>
e.group?.name === name &&
e.group?.name === groupName &&
((e.type === 2 && e.member?.member.ref.name === now) ||
(e.type === 4 &&
e.memberCol?.some(({ member }) => member.ref.name === now))),
@@ -516,21 +524,20 @@ function NormalProxyGroups(props: { mode: string }) {
}
})
const handleGroupLocationByName = useCallback(
(groupName: string) => {
const index = renderList.findIndex(
(item) => item.type === 0 && item.group?.name === groupName,
)
// Stable identity: this feeds the sticky-header render callback; a
// [renderList] dep would re-create it on every list rebuild.
const handleGroupLocationByName = useStableCallback((groupName: string) => {
const index = renderList.findIndex(
(item) => item.type === 0 && item.group?.name === groupName,
)
if (index >= 0) {
stickyListRef.current?.scrollToIndex(index, {
align: 'start',
behavior: 'smooth',
})
}
},
[renderList],
)
if (index >= 0) {
stickyListRef.current?.scrollToIndex(index, {
align: 'start',
behavior: 'smooth',
})
}
})
const proxyGroupNames = useMemo(() => {
const names = renderList
+18 -12
View File
@@ -30,9 +30,9 @@ interface Props {
url?: string
groupName: string
headState: HeadState
onLocation: () => void
onCheckDelay: () => void
onHeadState: (val: Partial<HeadState>) => void
onLocation: (groupName: string) => void
onCheckDelay: (groupName: string) => void
onHeadState: (groupName: string, val: Partial<HeadState>) => void
}
const defaultSx: SxProps = {}
@@ -81,7 +81,7 @@ export const ProxyHead = ({
size="small"
color="inherit"
title={t('proxies.page.tooltips.locate')}
onClick={onLocation}
onClick={() => onLocation(groupName)}
>
<MyLocationRounded />
</IconButton>
@@ -95,13 +95,13 @@ export const ProxyHead = ({
// Remind the user that it is custom test url
if (testUrl?.trim() && textState !== 'filter') {
debugLog(`[ProxyHead] 使用自定义测试URL: ${testUrl}`)
onHeadState({ textState: 'url' })
onHeadState(groupName, { textState: 'url' })
}
if (testUrl?.trim() && !isValidUrl(testUrl)) {
showNotice.warning('proxies.feedback.warnings.invalidTestUrl')
return
}
onCheckDelay()
onCheckDelay(groupName)
}}
>
<NetworkCheckRounded />
@@ -118,7 +118,9 @@ export const ProxyHead = ({
][sortType]
}
onClick={() =>
onHeadState({ sortType: ((sortType + 1) % 3) as ProxySortType })
onHeadState(groupName, {
sortType: ((sortType + 1) % 3) as ProxySortType,
})
}
>
{sortType !== 1 && sortType !== 2 && <SortRounded />}
@@ -131,7 +133,9 @@ export const ProxyHead = ({
color="inherit"
title={t('proxies.page.tooltips.delayCheckUrl')}
onClick={() =>
onHeadState({ textState: textState === 'url' ? null : 'url' })
onHeadState(groupName, {
textState: textState === 'url' ? null : 'url',
})
}
>
{textState === 'url' ? (
@@ -149,7 +153,7 @@ export const ProxyHead = ({
? t('proxies.page.tooltips.showBasic')
: t('proxies.page.tooltips.showDetail')
}
onClick={() => onHeadState({ showType: !showType })}
onClick={() => onHeadState(groupName, { showType: !showType })}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
@@ -159,7 +163,9 @@ export const ProxyHead = ({
color="inherit"
title={t('proxies.page.tooltips.filter')}
onClick={() =>
onHeadState({ textState: textState === 'filter' ? null : 'filter' })
onHeadState(groupName, {
textState: textState === 'filter' ? null : 'filter',
})
}
>
{textState === 'filter' ? <SearchOffRounded /> : <SearchRounded />}
@@ -176,7 +182,7 @@ export const ProxyHead = ({
useRegularExpression: filterUseRegularExpression,
}}
onSearch={(_, state) =>
onHeadState({
onHeadState(groupName, {
filterText: state.text,
filterMatchCase: state.matchCase,
filterMatchWholeWord: state.matchWholeWord,
@@ -197,7 +203,7 @@ export const ProxyHead = ({
size="small"
variant="outlined"
placeholder={t('proxies.page.placeholders.delayCheckUrl')}
onChange={(e) => onHeadState({ testUrl: e.target.value })}
onChange={(e) => onHeadState(groupName, { testUrl: e.target.value })}
sx={{ ml: 0.5, flex: '1 1 auto', input: { py: 0.65, px: 1 } }}
/>
)}
+7 -7
View File
@@ -33,7 +33,7 @@ interface RenderProps {
item: IRenderItem
stickyed?: boolean
isChainMode?: boolean
onLocation: (group: IRenderItem['group']) => void
onLocation: (groupName: string) => void
onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onChangeProxy: (
@@ -179,9 +179,9 @@ const ProxyGroupHeader = (props: RenderProps) => {
url={group.testUrl!}
groupName={group.name}
headState={headState!}
onLocation={() => onLocation(group)}
onCheckDelay={() => onCheckAll(group.name)}
onHeadState={(p) => onHeadState(group.name, p)}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onHeadState={onHeadState}
/>
{!toolsOnLeft && proxyCount}
</ProxyGroupHeaderBlock>
@@ -270,9 +270,9 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
url={group.testUrl!}
groupName={group.name}
headState={headState!}
onLocation={() => onLocation(group)}
onCheckDelay={() => onCheckAll(group.name)}
onHeadState={(p) => onHeadState(group.name, p)}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onHeadState={onHeadState}
/>
)
}
+13 -9
View File
@@ -175,15 +175,19 @@ export const useRenderList = (
chainOccurrencesRef.current = chainOccurrences
const chainDelayGroup =
mode === 'rule' && selectedGroup ? selectedGroup : CHAIN_DELAY_GROUP
const chainDelayKey = chainOccurrences
.map(({ member }) => {
if (member.kind !== 'node') return `${member.kind}:${member.ref.name}`
const source = member.node.source
return source.kind === 'provider'
? `provider:${source.providerName}:${source.proxyName}`
: `core:${source.proxyName}`
})
.join('\u0000')
const chainDelayKey = useMemo(
() =>
chainOccurrences
.map(({ member }) => {
if (member.kind !== 'node') return `${member.kind}:${member.ref.name}`
const source = member.node.source
return source.kind === 'provider'
? `provider:${source.providerName}:${source.proxyName}`
: `core:${source.proxyName}`
})
.join('\u0000'),
[chainOccurrences],
)
useEffect(() => {
if (!isChainMode || !chainDelayKey) return
+35 -23
View File
@@ -51,6 +51,25 @@ const Item = styled(ListItem)(() => ({
},
}))
// Static editor settings; a per-render object would re-trigger Monaco's
// updateOptions and listener resubscription on every keystroke. The minimap
// depends on the live window width and is applied at editor mount instead.
const MONACO_OPTIONS = {
tabSize: 2,
mouseWheelZoom: true,
quickSuggestions: {
strings: true,
comments: true,
other: true,
},
padding: {
top: 33,
},
fontFamily: MONACO_FONT_FAMILY,
fontLigatures: false,
smoothScrolling: true,
} as const
type NameserverPolicy = Record<string, any>
function parseNameserverPolicy(str: string): NameserverPolicy {
@@ -520,9 +539,21 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
}
})
const handleYamlChange = (value?: string) => {
const handleYamlChange = useCallback((value?: string) => {
setYamlContent(value || '')
}
}, [])
const handleEditorMount = useCallback(
(editorInstance: MonacoEditorInstance) => {
editorRef.current = editorInstance
editorInstance.updateOptions({
minimap: {
enabled: document.documentElement.clientWidth >= 1500,
},
})
},
[],
)
const handleChange = (field: string) => (event: any) => {
const value =
@@ -1052,27 +1083,8 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
value={yamlContent}
theme={themeMode === 'light' ? 'light' : 'vs-dark'}
className="flex-grow"
onMount={(editorInstance) => {
editorRef.current = editorInstance
}}
options={{
tabSize: 2,
minimap: {
enabled: document.documentElement.clientWidth >= 1500,
},
mouseWheelZoom: true,
quickSuggestions: {
strings: true,
comments: true,
other: true,
},
padding: {
top: 33,
},
fontFamily: MONACO_FONT_FAMILY,
fontLigatures: false,
smoothScrolling: true,
}}
onMount={handleEditorMount}
options={MONACO_OPTIONS}
onChange={handleYamlChange}
/>
)}
@@ -109,7 +109,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
showNotice.error(err)
}
const onChangeData = (patch: Partial<IVergeConfig>) => {
mutateVerge({ ...verge, ...patch })
mutateVerge((prev) => ({ ...prev, ...patch }))
}
return (
@@ -22,6 +22,7 @@ const buildInitialValues = (verge?: IVergeConfig | null) => ({
appLogMaxSize: verge?.app_log_max_size ?? 128,
appLogMaxCount: verge?.app_log_max_count ?? 8,
autoCloseConnection: verge?.auto_close_connection ?? true,
autoSwitchSelectorGroup: verge?.auto_switch_selector_group ?? true,
autoCheckUpdate: verge?.auto_check_update ?? true,
enableBuiltinEnhanced: verge?.enable_builtin_enhanced ?? true,
proxyLayoutColumn: verge?.proxy_layout_column || 6,
@@ -55,6 +56,7 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
app_log_max_size: values.appLogMaxSize,
app_log_max_count: values.appLogMaxCount,
auto_close_connection: values.autoCloseConnection,
auto_switch_selector_group: values.autoSwitchSelectorGroup,
auto_check_update: values.autoCheckUpdate,
enable_builtin_enhanced: values.enableBuiltinEnhanced,
proxy_layout_column: values.proxyLayoutColumn,
@@ -202,6 +204,28 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
/>
</ListItem>
<ListItem
data-setting-target="settings.modals.misc.fields.autoSwitchSelectorGroup"
sx={{ padding: '5px 2px' }}
>
<ListItemText
primary={t('settings.modals.misc.fields.autoSwitchSelectorGroup')}
sx={{ maxWidth: 'fit-content' }}
/>
<TooltipIcon
title={t('settings.modals.misc.tooltips.autoSwitchSelectorGroup')}
sx={{ opacity: '0.7' }}
/>
<Switch
edge="end"
checked={values.autoSwitchSelectorGroup}
onChange={(_, c) =>
setValues((v) => ({ ...v, autoSwitchSelectorGroup: c }))
}
sx={{ marginLeft: 'auto' }}
/>
</ListItem>
<ListItem
data-setting-target="settings.modals.misc.fields.autoCheckUpdate"
sx={{ padding: '5px 2px' }}
@@ -326,7 +326,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
Promise.resolve().then(async () => {
try {
if (Object.keys(patch).length > 0) {
mutateVerge({ ...verge, ...patch })
mutateVerge((prev) => ({ ...prev, ...patch }))
}
if (Object.keys(patch).length > 0) {
await patchVerge(patch)
+82 -83
View File
@@ -114,6 +114,84 @@ const getAlertTypeFromClassName = (
return match?.[1] as GitHubAlertType | null
}
const openUrlWithNotice = (url: string) => {
void openExternalUrl(url).catch(showNotice.error)
}
// Renderer map is static; a per-render identity would remount every link and
// blockquote subtree while download progress re-renders the dialog.
const MARKDOWN_COMPONENTS: ReactMarkdownOptions['components'] = {
a: ({ href, children, ...props }) => {
const isFragment = href?.startsWith('#') ?? false
const renderedHref = isFragment
? `#${UPDATE_MARKDOWN_ID_PREFIX}${href?.slice(1)}`
: href
? '#'
: undefined
return (
<a
{...props}
href={renderedHref}
target={undefined}
rel={undefined}
onClick={(event) => {
if (isFragment) return
event.preventDefault()
if (!href) return
openUrlWithNotice(href)
}}
onAuxClick={(event) => {
if (isFragment) return
event.preventDefault()
if (event.button === 1 && href) {
openUrlWithNotice(href)
}
}}
>
{children}
</a>
)
},
blockquote: ({ className, children }) => {
const alertType = getAlertTypeFromClassName(className)
if (!alertType) {
return <blockquote className={className}>{children}</blockquote>
}
return (
<Box
component="blockquote"
className={className}
sx={(theme) => {
const color = GITHUB_ALERTS[alertType].color
return {
m: '12px 0 18px',
px: 2,
py: 1,
borderLeft: `4px solid ${color}`,
borderRadius: 1,
bgcolor: alpha(color, theme.palette.mode === 'dark' ? 0.16 : 0.08),
'& p': {
my: 0.75,
},
'& .markdown-alert-title': {
display: 'flex',
alignItems: 'center',
gap: 0.75,
fontWeight: 700,
lineHeight: 1.4,
},
}
}}
>
{children}
</Box>
)
},
}
const findFirstTextNode = (node: MarkdownNode): MarkdownNode | null => {
if (node.type === 'text') return node
for (const child of node.children ?? []) {
@@ -185,10 +263,6 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
})
const { downloaded, total } = download
const openUrlWithNotice = (url: string) => {
void openExternalUrl(url).catch(showNotice.error)
}
const progress = useMemo(() => {
if (total <= 0) return 0
return Math.min((downloaded / total) * 100, 100)
@@ -212,8 +286,8 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
) as Record<GitHubAlertType, string>,
[t],
)
const remarkGitHubAlertsPlugin = useMemo(
() => () => remarkGitHubAlerts(githubAlertLabels),
const remarkPlugins = useMemo(
() => [() => remarkGitHubAlerts(githubAlertLabels)],
[githubAlertLabels],
)
@@ -475,83 +549,8 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
{open && (
<Suspense fallback={<LinearProgress />}>
<LazyReactMarkdown
remarkPlugins={[remarkGitHubAlertsPlugin]}
components={{
a: ({ href, children, ...props }) => {
const isFragment = href?.startsWith('#') ?? false
const renderedHref = isFragment
? `#${UPDATE_MARKDOWN_ID_PREFIX}${href?.slice(1)}`
: href
? '#'
: undefined
return (
<a
{...props}
href={renderedHref}
target={undefined}
rel={undefined}
onClick={(event) => {
if (isFragment) return
event.preventDefault()
if (!href) return
openUrlWithNotice(href)
}}
onAuxClick={(event) => {
if (isFragment) return
event.preventDefault()
if (event.button === 1 && href) {
openUrlWithNotice(href)
}
}}
>
{children}
</a>
)
},
blockquote: ({ className, children }) => {
const alertType = getAlertTypeFromClassName(className)
if (!alertType) {
return (
<blockquote className={className}>{children}</blockquote>
)
}
return (
<Box
component="blockquote"
className={className}
sx={(theme) => {
const color = GITHUB_ALERTS[alertType].color
return {
m: '12px 0 18px',
px: 2,
py: 1,
borderLeft: `4px solid ${color}`,
borderRadius: 1,
bgcolor: alpha(
color,
theme.palette.mode === 'dark' ? 0.16 : 0.08,
),
'& p': {
my: 0.75,
},
'& .markdown-alert-title': {
display: 'flex',
alignItems: 'center',
gap: 0.75,
fontWeight: 700,
lineHeight: 1.4,
},
}
}}
>
{children}
</Box>
)
},
}}
remarkPlugins={remarkPlugins}
components={MARKDOWN_COMPONENTS}
>
{markdownContent}
</LazyReactMarkdown>
+1 -1
View File
@@ -25,7 +25,7 @@ const SettingSystem = ({ onError }: Props) => {
value: boolean,
) => value
const onChangeData = (patch: Partial<IVergeConfig>) => {
mutateVerge({ ...verge, ...patch })
mutateVerge((prev) => ({ ...prev, ...patch }))
}
return (
@@ -72,7 +72,7 @@ const SettingVergeBasic = ({ onError }: Props) => {
const backupRef = useRef<DialogRef>(null)
const onChangeData = (patch: any) => {
mutateVerge({ ...verge, ...patch })
mutateVerge((prev) => ({ ...prev, ...patch }))
}
const onCopyClashEnv = useCallback(async () => {
@@ -480,6 +480,8 @@ const settingsCatalog: readonly SettingEntry[] = [
'settings.modals.misc.fields.appLogMaxCount': 'app log max count',
'settings.modals.misc.fields.autoCloseConnections':
'auto close connections',
'settings.modals.misc.fields.autoSwitchSelectorGroup':
'auto switch select group',
'settings.modals.misc.fields.autoCheckUpdate': 'auto check update',
'settings.modals.misc.fields.enableBuiltinEnhanced':
'enable builtin enhanced',
+15 -6
View File
@@ -10,7 +10,7 @@ import {
TextField,
Typography,
} from '@mui/material'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import getSystem from '@/utils/get-system'
@@ -21,6 +21,9 @@ import {
type SearchDialog,
} from './settings-search-context'
// Constant for the runtime; module-level like the other getSystem() callers.
const OS = getSystem()
export function SettingsSearch({
children,
}: {
@@ -40,11 +43,17 @@ export function SettingsSearch({
const originalScrollRef = useRef(0)
const resultScrollRef = useRef(0)
const cancelLocateRef = useRef<() => void>(() => {})
const results = searchSettings(
query,
getSystem(),
(key) => t(key),
(key) => t(key, { lng: 'en' }),
// The catalog scan touches every entry with translations; memoizing keeps
// unrelated state (arrow-key selection) from re-running it.
const results = useMemo(
() =>
searchSettings(
query,
OS,
(key) => t(key),
(key) => t(key, { lng: 'en' }),
),
[query, t],
)
const searching = !!query.trim()
const scroller = () =>
@@ -163,7 +163,7 @@ const ProxyControlSwitches = ({
})
return false
}
mutateVerge({ ...verge, enable_tun_mode: value })
mutateVerge((prev) => ({ ...prev, enable_tun_mode: value }))
await patchVerge({ enable_tun_mode: value })
}
+4 -1
View File
@@ -12,6 +12,9 @@ const FLUSH_DELAY_MS = 50
type LogType = ILogItem['type']
const DEFAULT_LOG_TYPES: LogType[] = ['debug', 'info', 'warning', 'error']
// Shared empty fallback: a fresh [] would give `refresh` a new identity on
// every render and re-run the snapshot effect while logs stream.
const EMPTY_LOGS: ILogItem[] = []
const LOG_LEVEL_FILTERS: Record<LogLevel, LogType[]> = {
DEBUG: DEFAULT_LOG_TYPES,
INFO: ['info', 'warning', 'error'],
@@ -55,7 +58,7 @@ export const useLogData = () => {
const { response, refresh, setData } = useMihomoWsSubscription<ILogItem[]>({
subscriptionKey: enableLog ? 'getClashLog' : null,
fallbackData: [],
fallbackData: EMPTY_LOGS,
connect: () => MihomoWebSocket.connect_logs(logLevel),
setupHandlers: ({ next, scheduleReconnect, isMounted }) => {
let flushTimer: ReturnType<typeof setTimeout> | null = null
+1 -1
View File
@@ -61,7 +61,7 @@ export function useProxyDelayState(
}
const cachedUpdate = delayManager.getDelayUpdate(name, groupName)
if (cachedUpdate) {
setDelayState({ ...cachedUpdate })
setDelayState(cachedUpdate)
return
}
+25 -19
View File
@@ -3,12 +3,16 @@ import { useCallback } from 'react'
import { getVergeConfig, patchVergeConfig } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { getPreloadConfig, setPreloadConfig } from '@/services/preload'
import { setCacheData, useQuery } from '@/services/query-client'
import {
revalidateQuery,
setCacheData,
useQuery,
} from '@/services/query-client'
export const useVerge = () => {
const initialVergeConfig = getPreloadConfig()
const { data: verge, refetch } = useQuery({
const { data: verge } = useQuery({
queryKey: ['getVergeConfig'],
queryFn: async () => {
const config = await getVergeConfig()
@@ -20,23 +24,25 @@ export const useVerge = () => {
staleTime: 5000,
})
const mutateVerge = (
updaterOrData?:
| IVergeConfig
| ((prev: IVergeConfig | undefined) => IVergeConfig | undefined)
| undefined,
) => {
if (updaterOrData === undefined) {
void refetch()
return
}
void setCacheData<IVergeConfig>(
['getVergeConfig'],
typeof updaterOrData === 'function'
? (current) => updaterOrData(current ?? verge)
: updaterOrData,
)
}
// Stable identity: many consumers list mutateVerge in their own callback
// deps, so a per-render closure here would churn their memoization too.
// The updater receives the live cache value (preload snapshot when the
// cache is still empty) instead of a render-time snapshot, so an older
// render cannot clobber a newer cache write.
const mutateVerge = useCallback(
(
updater?: (prev: IVergeConfig | undefined) => IVergeConfig | undefined,
) => {
if (updater === undefined) {
void revalidateQuery(['getVergeConfig'])
return
}
void setCacheData<IVergeConfig>(['getVergeConfig'], (current) =>
updater(current ?? getPreloadConfig() ?? undefined),
)
},
[],
)
// Callers own the error toast (GuardState onCatch / page onError), so the
// funnel must not add a second one.
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "إغلاق الاتصالات تلقائيًا",
"autoSwitchSelectorGroup": "تبديل مجموعة select تلقائيًا",
"autoCheckUpdate": "فحص التحديث تلقائيًا",
"enableBuiltinEnhanced": "تفعيل التحسين المدمج",
"proxyLayoutColumns": "أعمدة عرض الوكيل",
@@ -422,6 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "إنهاء الاتصالات القائمة عند تغيير اختيار مجموعة الوكيل أو وضع الوكيل",
"autoSwitchSelectorGroup": "في وضع القواعد، عند اختيار عقدة في مجموعة url-test أو fallback يتم أيضًا تحويل أول مجموعة select تحتوي عليها إلى تلك المجموعة",
"enableBuiltinEnhanced": "معالجة توافق ملف التكوين",
"autoDelayDetection": "يختبر زمن استجابة العقدة الحالية على نحو دوري في الخلفية",
"defaultLatencyTest": "يُستخدم فقط لاختبار طلب HTTP العميل. لن يؤثر على ملف التكوين"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "Maximale Größe des Anwendungsprotokolls",
"appLogMaxCount": "Maximale Anzahl der Anwendungsprotokolle",
"autoCloseConnections": "Verbindungen automatisch schließen",
"autoSwitchSelectorGroup": "Select-Gruppe automatisch umschalten",
"autoCheckUpdate": "Automatisch auf Updates prüfen",
"enableBuiltinEnhanced": "Eingebaute Verbesserungen aktivieren",
"proxyLayoutColumns": "Anzahl der Spalten im Proxy-Layout",
@@ -422,6 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Wenn der ausgewählte Knoten in der Proxy-Gruppe oder der Proxy-Modus geändert wird, werden die bestehenden Verbindungen geschlossen.",
"autoSwitchSelectorGroup": "Wird im Regelmodus ein Knoten in einer url-test- oder fallback-Gruppe gewählt, wechselt auch die erste select-Gruppe, die diese Gruppe enthält, auf diese Gruppe.",
"enableBuiltinEnhanced": "Kompatibilitätsbehandlung der Konfigurationsdatei",
"autoDelayDetection": "Überprüft regelmäßig im Hintergrund die Latenz des aktuellen Knotens",
"defaultLatencyTest": "Dies wird nur für HTTP-Client-Anfragentests verwendet und hat keine Auswirkungen auf die Konfigurationsdatei."
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "Auto Close Connections",
"autoSwitchSelectorGroup": "Auto Switch Select Group",
"autoCheckUpdate": "Auto Check Update",
"enableBuiltinEnhanced": "Enable Builtin Enhanced",
"proxyLayoutColumns": "Proxy Layout Columns",
@@ -422,6 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Terminate established connections when the proxy group selection or proxy mode changes",
"autoSwitchSelectorGroup": "In rule mode, selecting a node in a url-test or fallback group also switches the first select group containing it to that group",
"enableBuiltinEnhanced": "Compatibility handling for the configuration file",
"autoDelayDetection": "Periodically test the current node latency in the background",
"defaultLatencyTest": "Used for HTTP client request testing only and won't make a difference to the configuration file"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "Cerrar conexiones automáticamente",
"autoSwitchSelectorGroup": "Cambiar grupo select automáticamente",
"autoCheckUpdate": "Comprobar actualizaciones automáticamente",
"enableBuiltinEnhanced": "Habilitar funciones mejoradas integradas",
"proxyLayoutColumns": "Número de columnas en la disposición de la página de proxy",
@@ -422,6 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Cierra las conexiones establecidas cuando se cambia el nodo seleccionado en el grupo de proxy o el modo de proxy.",
"autoSwitchSelectorGroup": "En modo de reglas, al elegir un nodo en un grupo url-test o fallback, el primer grupo select que lo contiene también cambia a ese grupo.",
"enableBuiltinEnhanced": "Procesamiento de compatibilidad de archivos de configuración",
"autoDelayDetection": "Prueba periódicamente la latencia del nodo actual en segundo plano",
"defaultLatencyTest": "Solo se utiliza para pruebas de solicitudes de clientes HTTP y no afectará al archivo de configuración."
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "بستن خودکار اتصالات",
"autoSwitchSelectorGroup": "تغییر خودکار گروه select",
"autoCheckUpdate": "بررسی خودکار به‌روزرسانی",
"enableBuiltinEnhanced": "فعال کردن تقویت داخلی",
"proxyLayoutColumns": "ستون چیدمان پراکسی",
@@ -422,6 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "اتصالات برقرار شده را هنگام تغییر انتخاب گروه پروکسی یا حالت پروکسی خاتمه دهید",
"autoSwitchSelectorGroup": "در حالت قانون، با انتخاب یک گره در گروه url-test یا fallback، اولین گروه select شامل آن نیز به همان گروه تغییر می‌کند",
"enableBuiltinEnhanced": "مدیریت سازگاری برای فایل پیکربندی",
"autoDelayDetection": "به‌صورت دوره‌ای تأخیر گره فعلی را در پس‌زمینه آزمایش می‌کند",
"defaultLatencyTest": "فقط برای تست درخواست‌های کلاینت HTTP استفاده می‌شود و بر فایل پیکربندی تأثیری نخواهد داشت"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "Tutup Koneksi Otomatis",
"autoSwitchSelectorGroup": "Alihkan Grup Select Otomatis",
"autoCheckUpdate": "Periksa Pembaruan Otomatis",
"enableBuiltinEnhanced": "Aktifkan Peningkatan Bawaan",
"proxyLayoutColumns": "Kolom Tata Letak Proksi",
@@ -422,6 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Hentikan koneksi yang sudah ada saat pemilihan grup proksi atau mode proksi berubah",
"autoSwitchSelectorGroup": "Dalam mode aturan, memilih node di grup url-test atau fallback juga mengalihkan grup select pertama yang memuatnya ke grup tersebut",
"enableBuiltinEnhanced": "Penanganan kompatibilitas untuk file konfigurasi",
"autoDelayDetection": "Secara berkala menguji latensi node saat ini di latar belakang",
"defaultLatencyTest": "Digunakan hanya untuk pengujian permintaan klien HTTP dan tidak akan mempengaruhi file konfigurasi"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "接続を自動的に閉じる",
"autoSwitchSelectorGroup": "ノード選択時にグループを連動",
"autoCheckUpdate": "自動更新チェック",
"enableBuiltinEnhanced": "組み込み拡張機能を有効にする",
"proxyLayoutColumns": "プロキシページのレイアウト列数",
@@ -422,6 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "プロキシグループで選択されたノードまたはプロキシモードが変更されたときに、既存の接続を閉じます。",
"autoSwitchSelectorGroup": "ルールモードで url-test または fallback グループのノードを選択すると、そのグループを含む最初の select グループも当該グループに切り替えます。",
"enableBuiltinEnhanced": "設定ファイルの互換性処理",
"autoDelayDetection": "バックグラウンドで現在のノードのレイテンシーを定期的にテストします",
"defaultLatencyTest": "HTTPクライアントリクエストテストにのみ使用され、設定ファイルには影響しません。"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "앱 로그 최대 크기",
"appLogMaxCount": "앱 로그 최대 개수",
"autoCloseConnections": "연결 자동 종료",
"autoSwitchSelectorGroup": "노드 선택 시 그룹 연동",
"autoCheckUpdate": "업데이트 자동 확인",
"enableBuiltinEnhanced": "내장 향상 기능 사용",
"proxyLayoutColumns": "프록시 레이아웃 열 수",
@@ -422,6 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "프록시 그룹 선택 또는 프록시 모드 변경 시 기존 연결을 종료합니다",
"autoSwitchSelectorGroup": "규칙 모드에서 url-test 또는 fallback 그룹의 노드를 선택하면 해당 그룹을 포함하는 첫 번째 select 그룹도 그 그룹으로 전환합니다",
"enableBuiltinEnhanced": "구성 파일에 대한 호환성 처리를 수행합니다",
"autoDelayDetection": "백그라운드에서 현재 노드의 지연을 주기적으로 검사합니다",
"defaultLatencyTest": "HTTP 클라이언트 요청 테스트에만 사용되며 구성 파일에는 영향을 주지 않습니다"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "Tamanho Máximo do Log do Aplicativo",
"appLogMaxCount": "Quantidade Máxima de Logs do Aplicativo",
"autoCloseConnections": "Fechar Conexões Automaticamente",
"autoSwitchSelectorGroup": "Alternar Grupo Select Automaticamente",
"autoCheckUpdate": "Verificar Atualizações Automaticamente",
"enableBuiltinEnhanced": "Ativar Aprimoramento Integrado",
"proxyLayoutColumns": "Colunas do Layout de Proxy",
@@ -422,6 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Encerra as conexões estabelecidas quando a seleção do grupo de proxy ou o modo de proxy muda",
"autoSwitchSelectorGroup": "No modo de regras, ao escolher um nó em um grupo url-test ou fallback, o primeiro grupo select que o contém também muda para esse grupo",
"enableBuiltinEnhanced": "Tratamento de compatibilidade para o arquivo de configuração",
"autoDelayDetection": "Testa periodicamente a latência do nó atual em segundo plano",
"defaultLatencyTest": "Usado apenas para testes de requisição do cliente HTTP e não afeta o arquivo de configuração"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "Максимальный размер журнала приложения",
"appLogMaxCount": "Максимальное количество файлов журнала",
"autoCloseConnections": "Автоматическое закрытие соединений",
"autoSwitchSelectorGroup": "Автопереключение группы select",
"autoCheckUpdate": "Автоматическая проверка обновлений",
"enableBuiltinEnhanced": "Включить встроенные улучшения",
"proxyLayoutColumns": "Количество столбцов в макете прокси",
@@ -422,6 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Закрывать установленные соединения при изменении выбора группы прокси или режима прокси",
"autoSwitchSelectorGroup": "В режиме правил при выборе узла в группе url-test или fallback первая группа select, содержащая эту группу, также переключается на неё",
"enableBuiltinEnhanced": "Обработка совместимости для файла конфигурации",
"autoDelayDetection": "Периодически проверяет задержку текущего узла в фоновом режиме",
"defaultLatencyTest": "Используется только для тестирования HTTP-запросов клиента и не влияет на файл конфигурации"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "Uygulama Günlüğü En Büyük Boyutu",
"appLogMaxCount": "Uygulama Günlüğü En Fazla Dosya Sayısı",
"autoCloseConnections": "Bağlantıları Otomatik Kapat",
"autoSwitchSelectorGroup": "Select Grubunu Otomatik Değiştir",
"autoCheckUpdate": "Otomatik Güncelleme Kontrolü",
"enableBuiltinEnhanced": "Yerleşik Geliştirilmiş Modu Etkinleştir",
"proxyLayoutColumns": "Vekil Düzeni Sütunları",
@@ -422,6 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Vekil grup seçimi veya vekil modu değiştiğinde kurulan bağlantıları sonlandır",
"autoSwitchSelectorGroup": "Kural modunda url-test veya fallback grubunda bir düğüm seçildiğinde, bu grubu içeren ilk select grubu da o gruba geçer",
"enableBuiltinEnhanced": "Yapılandırma dosyası için uyumluluk işleme",
"autoDelayDetection": "Arka planda mevcut düğümün gecikmesini periyodik olarak test eder",
"defaultLatencyTest": "Yalnızca HTTP istemci isteği testi için kullanılır ve yapılandırma dosyasında bir fark yaratmaz"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "App Log Max Size",
"appLogMaxCount": "App Log Max Count",
"autoCloseConnections": "Тоташуларны автоматик ябу",
"autoSwitchSelectorGroup": "Select төркемен автоматик күчерү",
"autoCheckUpdate": "Яңартуларны автоматик тикшерү",
"enableBuiltinEnhanced": "Эчке камилләштерүне кабызу",
"proxyLayoutColumns": "Прокси күрсәтү баганалары саны",
@@ -422,6 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "Прокси төркеме яисә режимын үзгәрткәндә актив тоташуларны өзү",
"autoSwitchSelectorGroup": "Кагыйдәләр режимында url-test яки fallback төркемендә төен сайлаганда, аны эченә алган беренче select төркеме дә шул төркемгә күчә",
"enableBuiltinEnhanced": "Конфигурация файлы белән туры килә торган өстәмә оптимизация",
"autoDelayDetection": "Фон режимында хәзерге төен тоткарлыгын периодик тикшерә",
"defaultLatencyTest": "Бу фәкать клиентның HTTP сораулары тесты өчен кулланыла, конфигурация файлына йогынты ясамый"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "应用日志最大大小",
"appLogMaxCount": "应用日志最大数量",
"autoCloseConnections": "自动关闭连接",
"autoSwitchSelectorGroup": "选择节点时联动代理组",
"autoCheckUpdate": "自动检查更新",
"enableBuiltinEnhanced": "内置增强功能",
"proxyLayoutColumns": "代理页布局列数",
@@ -422,6 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "当代理组选中节点或代理模式变动时,关闭已建立的连接",
"autoSwitchSelectorGroup": "规则模式下,在 url-test 或 fallback 代理组中选择节点时,将首个包含该组的 select 代理组切换到该组",
"enableBuiltinEnhanced": "配置文件的兼容性处理",
"autoDelayDetection": "后台定时检测当前节点延迟",
"defaultLatencyTest": "仅用于 HTTP 客户端请求测试,不会对配置文件产生影响"
+2
View File
@@ -411,6 +411,7 @@
"appLogMaxSize": "應用程式日誌最大大小",
"appLogMaxCount": "應用程式日誌最大數量",
"autoCloseConnections": "自動關閉連線",
"autoSwitchSelectorGroup": "選擇節點時聯動代理組",
"autoCheckUpdate": "自動檢查更新",
"enableBuiltinEnhanced": "內建增強功能",
"proxyLayoutColumns": "代理頁面欄數",
@@ -422,6 +423,7 @@
},
"tooltips": {
"autoCloseConnections": "當代理組選中節點或代理模式變動時,關閉已建立的連線",
"autoSwitchSelectorGroup": "規則模式下,在 url-test 或 fallback 代理組中選擇節點時,將首個包含該組的 select 代理組切換到該組",
"enableBuiltinEnhanced": "配置檔案的相容性處理",
"autoDelayDetection": "在背景定時偵測目前節點延遲",
"defaultLatencyTest": "僅用於 HTTP 客戶端請求測試,不會對配置檔案產生影響"
+46 -20
View File
@@ -462,9 +462,12 @@ const ProfilePage = () => {
[runProfileSwitchQueue],
)
const onSelect = async (profile: string, force: boolean) => {
await activateProfile(profile, true, force)
}
const onSelect = useCallback(
async (profile: string, force: boolean) => {
await activateProfile(profile, true, force)
},
[activateProfile],
)
useEffect(() => {
let cancelled = false
@@ -594,7 +597,7 @@ const ProfilePage = () => {
}
}
const toggleProfileSelection = (uid: string) => {
const toggleProfileSelection = useCallback((uid: string) => {
setSelectedProfiles((prev) => {
const newSet = new Set(prev)
if (newSet.has(uid)) {
@@ -604,7 +607,40 @@ const ProfilePage = () => {
}
return newSet
})
}
}, [])
// Item-grid callbacks stay identity-stable so ProfileItem's memo holds
// across unrelated page state (URL input keystrokes, switch spinners).
// onEnhance/onDelete are useLockFn wrappers whose identity changes every
// render, so they are read through refs here.
const onEnhanceRef = useRef(onEnhance)
onEnhanceRef.current = onEnhance
const onDeleteRef = useRef(onDelete)
onDeleteRef.current = onDelete
const handleItemEdit = useCallback((item: IProfileItem) => {
viewerRef.current?.edit(item)
}, [])
const handleItemSave = useCallback(
async (uid: string, prev?: string, curr?: string) => {
if (prev !== curr && profiles.current === uid) {
await onEnhanceRef.current(false)
}
},
[profiles],
)
const handleItemDelete = useCallback(
(uid: string) => {
if (batchMode) {
toggleProfileSelection(uid)
} else {
onDeleteRef.current(uid)
}
},
[batchMode, toggleProfileSelection],
)
const selectAllProfiles = () => {
setSelectedProfiles(new Set(profileItems.map((item) => item.uid!)))
@@ -908,23 +944,13 @@ const ProfilePage = () => {
completedUpdateRevisions.get(item.uid!) ?? 0
}
mutateProfiles={mutateProfiles}
onSelect={(f) => onSelect(item.uid!, f)}
onEdit={() => viewerRef.current?.edit(item)}
onSave={async (prev, curr) => {
if (prev !== curr && profiles.current === item.uid) {
await onEnhance(false)
}
}}
onDelete={() => {
if (batchMode) {
toggleProfileSelection(item.uid!)
} else {
onDelete(item.uid!)
}
}}
onSelect={onSelect}
onEdit={handleItemEdit}
onSave={handleItemSave}
onDelete={handleItemDelete}
batchMode={batchMode}
isSelected={selectedProfiles.has(item.uid!)}
onSelectionChange={() => toggleProfileSelection(item.uid!)}
onSelectionChange={toggleProfileSelection}
/>
))}
</Box>
+4
View File
@@ -83,6 +83,8 @@ export const commands = {
__TAURI_INVOKE<null>('record_selected_node', { groupName, node }),
switchProxyNode: (groupName: string, proxyName: string, unfix: boolean) =>
__TAURI_INVOKE<null>('switch_proxy_node', { groupName, proxyName, unfix }),
followProxyGroup: (groupName: string) =>
__TAURI_INVOKE<void>('follow_proxy_group', { groupName }),
saveDnsConfig: (dnsConfig: YamlMapping) =>
__TAURI_INVOKE<null>('save_dns_config', { dnsConfig }),
applyDnsConfig: (apply: boolean) =>
@@ -416,6 +418,7 @@ export type IVerge_Deserialize = {
enable_global_hotkey?: boolean | null
home_cards?: JsonValue | null
auto_close_connection?: boolean | null
auto_switch_selector_group?: boolean | null
auto_check_update?: boolean | null
default_latency_test?: string | null
default_latency_timeout?: number | null
@@ -506,6 +509,7 @@ export type IVerge_Serialize = {
enable_global_hotkey: boolean | null
home_cards: JsonValue | null
auto_close_connection: boolean | null
auto_switch_selector_group: boolean | null
auto_check_update: boolean | null
default_latency_test: string | null
default_latency_timeout: number | null
+4
View File
@@ -165,6 +165,10 @@ export async function switchProxyNode(
return commands.switchProxyNode(groupName, proxyName, unfix)
}
export async function followProxyGroup(groupName: string) {
return commands.followProxyGroup(groupName)
}
export async function getProxyView(): Promise<ProxyViewV1> {
const view = await commands.getProxyView()
if (view.schemaVersion !== 1) {
+3 -1
View File
@@ -237,7 +237,9 @@ class DelayManager {
return undefined
}
return { ...entry }
// Entries are replaced, never mutated, so the cached object is shared
// directly; readers treat it as immutable.
return entry
}
getDelay(name: string, group: string) {
+2
View File
@@ -652,6 +652,7 @@ export const translationKeys = [
'settings.modals.misc.fields.appLogMaxSize',
'settings.modals.misc.fields.appLogMaxCount',
'settings.modals.misc.fields.autoCloseConnections',
'settings.modals.misc.fields.autoSwitchSelectorGroup',
'settings.modals.misc.fields.autoCheckUpdate',
'settings.modals.misc.fields.enableBuiltinEnhanced',
'settings.modals.misc.fields.proxyLayoutColumns',
@@ -661,6 +662,7 @@ export const translationKeys = [
'settings.modals.misc.fields.defaultLatencyTest',
'settings.modals.misc.fields.defaultLatencyTimeout',
'settings.modals.misc.tooltips.autoCloseConnections',
'settings.modals.misc.tooltips.autoSwitchSelectorGroup',
'settings.modals.misc.tooltips.enableBuiltinEnhanced',
'settings.modals.misc.tooltips.autoDelayDetection',
'settings.modals.misc.tooltips.defaultLatencyTest',
+2
View File
@@ -1123,6 +1123,7 @@ export interface TranslationResources {
autoDelayDetection: string
autoDelayDetectionInterval: string
autoLogClean: string
autoSwitchSelectorGroup: string
defaultLatencyTest: string
defaultLatencyTimeout: string
enableBuiltinEnhanced: string
@@ -1141,6 +1142,7 @@ export interface TranslationResources {
tooltips: {
autoCloseConnections: string
autoDelayDetection: string
autoSwitchSelectorGroup: string
defaultLatencyTest: string
enableBuiltinEnhanced: string
}
+1 -1
View File
@@ -156,7 +156,7 @@ export const selectRuleChainMembers = (
})
}
const sameSource = (
export const sameSource = (
left: ProxyNodeView['source'],
right: ProxyNodeView['source'],
) =>
+34 -13
View File
@@ -124,10 +124,10 @@ export class TrafficDataSampler {
) {
rawStart++
}
const rawData = this.rawBuffer.slice(rawStart)
const rawCount = this.rawBuffer.length - rawStart
if (minutes <= this.config.rawDataMinutes) {
return rawData
return this.rawBuffer.slice(rawStart)
}
const compressedCutoffUpper =
@@ -140,19 +140,40 @@ export class TrafficDataSampler {
) {
compressedStart++
}
let compressedEnd = compressedStart
while (
compressedEnd < this.compressedBuffer.length &&
this.compressedBuffer[compressedEnd].timestamp <= compressedCutoffUpper
) {
compressedEnd++
}
const compressedData = this.compressedBuffer
.slice(compressedStart)
.filter((p) => p.timestamp <= compressedCutoffUpper)
.map((p) => ({
up: p.up,
down: p.down,
timestamp: p.timestamp,
}))
// Single preallocated result; raw entries keep their stored identity.
const compressedCount = compressedEnd - compressedStart
const result: ITrafficDataPoint[] = new Array(compressedCount + rawCount)
for (let i = 0; i < compressedCount; i++) {
const point = this.compressedBuffer[compressedStart + i]
result[i] = {
up: point.up,
down: point.down,
timestamp: point.timestamp,
}
}
for (let i = 0; i < rawCount; i++) {
result[compressedCount + i] = this.rawBuffer[rawStart + i]
}
return [...compressedData, ...rawData].sort(
(a, b) => a.timestamp - b.timestamp,
)
// Compressed points precede raw ones except across the trim boundary;
// sort only when the two ranges actually interleave.
if (
compressedCount > 0 &&
rawCount > 0 &&
this.compressedBuffer[compressedEnd - 1].timestamp >
this.rawBuffer[rawStart].timestamp
) {
result.sort((a, b) => a.timestamp - b.timestamp)
}
return result
}
getStats(): ISamplerStats {