mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-21 19:52:12 +08:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4969630f57 | ||
|
|
50fd66925a | ||
|
|
5d2e69ba6c | ||
|
|
71444c9815 | ||
|
|
02a1998b8d |
Generated
+17
-27
@@ -1118,7 +1118,6 @@ dependencies = [
|
|||||||
"open",
|
"open",
|
||||||
"parking_lot 0.13.0",
|
"parking_lot 0.13.0",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"quick-xml 0.42.0",
|
|
||||||
"reqwest 0.13.5",
|
"reqwest 0.13.5",
|
||||||
"reqwest_dav",
|
"reqwest_dav",
|
||||||
"rfd 0.18.0",
|
"rfd 0.18.0",
|
||||||
@@ -5265,7 +5264,7 @@ checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"indexmap 2.14.0",
|
"indexmap 2.14.0",
|
||||||
"quick-xml 0.41.0",
|
"quick-xml",
|
||||||
"serde",
|
"serde",
|
||||||
"time",
|
"time",
|
||||||
]
|
]
|
||||||
@@ -5535,15 +5534,6 @@ dependencies = [
|
|||||||
"memchr",
|
"memchr",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "quick-xml"
|
|
||||||
version = "0.42.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
|
|
||||||
dependencies = [
|
|
||||||
"memchr",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quinn"
|
name = "quinn"
|
||||||
version = "0.11.11"
|
version = "0.11.11"
|
||||||
@@ -7247,9 +7237,9 @@ checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri"
|
name = "tauri"
|
||||||
version = "2.12.7"
|
version = "2.12.5"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "30fbfbb9dc9a2697b0e96d909ddc295fb18d2d82a58ed542ab8d9eba2edbe6da"
|
checksum = "5fb0244332cfb9cee7e2a568bf5da29a36ed8fdbd717f6f47a66b6b7b358c072"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"bytes",
|
"bytes",
|
||||||
@@ -7302,9 +7292,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-build"
|
name = "tauri-build"
|
||||||
version = "2.7.6"
|
version = "2.7.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "73d80784e874fa117b9b00a6680cf2f9b8a51bbd14406bea980cf8f328b00646"
|
checksum = "adddb0e648752aaac5da9c3c3c6a68e1e87cab55e3b757b18a9441ef8c3ac614"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"cargo_toml",
|
"cargo_toml",
|
||||||
@@ -7325,9 +7315,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-codegen"
|
name = "tauri-codegen"
|
||||||
version = "2.7.6"
|
version = "2.7.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c5dc6caab4da5646f57648f39b794bae118f0dd4a4305eeb8c892966171f4852"
|
checksum = "fb37631cf71dab5e8ab55e1bdd701e18a52653d90b78e71d0e5598b1e0a61316"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.23.1",
|
"base64 0.23.1",
|
||||||
"brotli",
|
"brotli",
|
||||||
@@ -7340,7 +7330,7 @@ dependencies = [
|
|||||||
"semver 1.0.28",
|
"semver 1.0.28",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2 0.11.1",
|
"sha2 0.10.9",
|
||||||
"syn 2.0.119",
|
"syn 2.0.119",
|
||||||
"tauri-utils",
|
"tauri-utils",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.20",
|
||||||
@@ -7352,9 +7342,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-macros"
|
name = "tauri-macros"
|
||||||
version = "2.7.6"
|
version = "2.7.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2831c5da8603a96b1efc0b650c2cb6decc69b6cda257d815fe70c7f5be53818e"
|
checksum = "0cc38db58854c10fb5f91a887ed8bf82d3239bb92b5d8db86eda09e96d9963d1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"heck 0.5.0",
|
"heck 0.5.0",
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
@@ -7727,9 +7717,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-runtime"
|
name = "tauri-runtime"
|
||||||
version = "2.12.4"
|
version = "2.12.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "60c2b14bd5265b63993cdc34ad526fb836e0fd0cf64a4634a895db0784844d5e"
|
checksum = "7c55766d99cea69055904d1735b93c2049302b2e09effd462120deb5581d78e9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cookie",
|
"cookie",
|
||||||
"dpi",
|
"dpi",
|
||||||
@@ -7752,9 +7742,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-runtime-wry"
|
name = "tauri-runtime-wry"
|
||||||
version = "2.12.5"
|
version = "2.12.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b8c14a025255cc9816d401635035075b09b6cc9973b7b8fd7b8fcb8753f30f92"
|
checksum = "e1aa9d8b7a120f879f44fdc1053f7b7dbf416bf0bbc6a72b714dec46b782b52f"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"gtk",
|
"gtk",
|
||||||
"http",
|
"http",
|
||||||
@@ -7810,9 +7800,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-utils"
|
name = "tauri-utils"
|
||||||
version = "2.10.4"
|
version = "2.10.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "28d1d33d4453c5df0bf1672dbc7ada69d8ed74f56a4316d964a4aa73d4ecd3ad"
|
checksum = "362ab21cd4cc713f2a02b1a9b5688198b1541cfb6907c4281e9190e0f0ef4aa3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"brotli",
|
"brotli",
|
||||||
@@ -9008,7 +8998,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
|
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quick-xml 0.41.0",
|
"quick-xml",
|
||||||
"quote",
|
"quote",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -61,7 +61,7 @@ tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", bra
|
|||||||
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
|
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
|
||||||
tracing = "0.1.44"
|
tracing = "0.1.44"
|
||||||
|
|
||||||
tauri = { version = "2.12.7" }
|
tauri = { version = "2.12.5" }
|
||||||
tauri-plugin-clipboard-manager = "2.5.0"
|
tauri-plugin-clipboard-manager = "2.5.0"
|
||||||
parking_lot = "0.13.0"
|
parking_lot = "0.13.0"
|
||||||
anyhow = "1.0.104"
|
anyhow = "1.0.104"
|
||||||
|
|||||||
+3
-7
@@ -39,11 +39,6 @@
|
|||||||
- 修复「TUN 设置」未手动保存时,界面显示的默认 MTU 1500 未生效
|
- 修复「TUN 设置」未手动保存时,界面显示的默认 MTU 1500 未生效
|
||||||
- 修复「链式代理」节点列表按名称排序,未保持订阅中的节点顺序
|
- 修复「链式代理」节点列表按名称排序,未保持订阅中的节点顺序
|
||||||
- 修复规则模式下 Muse AI 解锁检测显示错误的出口地区
|
- 修复规则模式下 Muse AI 解锁检测显示错误的出口地区
|
||||||
- 修复使用系统代理时 IP 信息显示直连地址
|
|
||||||
|
|
||||||
**🖥️ Windows**
|
|
||||||
|
|
||||||
- 修复 Windows 普通用户因权限不足无法开启「开机自启」
|
|
||||||
|
|
||||||
**🍎 macOS**
|
**🍎 macOS**
|
||||||
|
|
||||||
@@ -61,7 +56,7 @@
|
|||||||
<summary><strong> ✨ 新增功能 </strong></summary>
|
<summary><strong> ✨ 新增功能 </strong></summary>
|
||||||
|
|
||||||
- 新增连接页面按网络协议(TCP/UDP)筛选连接
|
- 新增连接页面按网络协议(TCP/UDP)筛选连接
|
||||||
- 新增规则模式下在规则流量未经过的代理组选节点时,自动将首个包含该组的 `select` 代理组切换到该组,可在「杂项设置」关闭
|
- 新增规则模式下在 `url-test` 或 `fallback` 代理组选节点时,自动将首个包含该组的 `select` 代理组切换到该组,可在「杂项设置」关闭
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
@@ -71,7 +66,8 @@
|
|||||||
- 优化连接、规则和日志筛选:切换页面后保留过滤条件
|
- 优化连接、规则和日志筛选:切换页面后保留过滤条件
|
||||||
- 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组
|
- 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组
|
||||||
- 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件
|
- 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件
|
||||||
- 优化首页「当前节点」卡片:按规则指向的代理组逐级显示和切换实际生效的节点,选中后下拉菜单自动收起
|
- 优化首页「当前节点」卡片:代理组列表加入 `fallback` 代理组,切换到 `url-test` 或 `fallback` 代理组时同样联动 `select` 代理组
|
||||||
|
- 优化主页流量图表与日志、代理列表的实时刷新和滚动占用,降低高频更新时的 CPU 负载
|
||||||
|
|
||||||
**🍎 macOS**
|
**🍎 macOS**
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -50,7 +50,7 @@
|
|||||||
"@mui/icons-material": "^9.4.0",
|
"@mui/icons-material": "^9.4.0",
|
||||||
"@mui/material": "^9.4.0",
|
"@mui/material": "^9.4.0",
|
||||||
"@tanstack/react-virtual": "^3.14.13",
|
"@tanstack/react-virtual": "^3.14.13",
|
||||||
"@tauri-apps/api": "2.12.5",
|
"@tauri-apps/api": "2.12.4",
|
||||||
"@tauri-apps/plugin-clipboard-manager": "2.5.0",
|
"@tauri-apps/plugin-clipboard-manager": "2.5.0",
|
||||||
"@tauri-apps/plugin-dialog": "2.8.4",
|
"@tauri-apps/plugin-dialog": "2.8.4",
|
||||||
"@tauri-apps/plugin-fs": "2.7.1",
|
"@tauri-apps/plugin-fs": "2.7.1",
|
||||||
@@ -90,7 +90,7 @@
|
|||||||
"@biomejs/biome": "^2.5.14",
|
"@biomejs/biome": "^2.5.14",
|
||||||
"@eslint-react/eslint-plugin": "^5.20.5",
|
"@eslint-react/eslint-plugin": "^5.20.5",
|
||||||
"@eslint/js": "^10.0.1",
|
"@eslint/js": "^10.0.1",
|
||||||
"@tauri-apps/cli": "2.12.6",
|
"@tauri-apps/cli": "2.12.4",
|
||||||
"@types/lodash-es": "^4.17.12",
|
"@types/lodash-es": "^4.17.12",
|
||||||
"@types/node": "^26.0.0",
|
"@types/node": "^26.0.0",
|
||||||
"@types/react": "19.3.0",
|
"@types/react": "19.3.0",
|
||||||
|
|||||||
Generated
+66
-66
@@ -209,8 +209,8 @@ importers:
|
|||||||
specifier: ^3.14.13
|
specifier: ^3.14.13
|
||||||
version: 3.14.13(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
version: 3.14.13(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||||
'@tauri-apps/api':
|
'@tauri-apps/api':
|
||||||
specifier: 2.12.5
|
specifier: 2.12.4
|
||||||
version: 2.12.5
|
version: 2.12.4
|
||||||
'@tauri-apps/plugin-clipboard-manager':
|
'@tauri-apps/plugin-clipboard-manager':
|
||||||
specifier: 2.5.0
|
specifier: 2.5.0
|
||||||
version: 2.5.0
|
version: 2.5.0
|
||||||
@@ -303,7 +303,7 @@ importers:
|
|||||||
version: 2.5.1(react@19.3.1)
|
version: 2.5.1(react@19.3.1)
|
||||||
tauri-plugin-mihomo-api:
|
tauri-plugin-mihomo-api:
|
||||||
specifier: github:clash-verge-rev/tauri-plugin-mihomo#main
|
specifier: github:clash-verge-rev/tauri-plugin-mihomo#main
|
||||||
version: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f
|
version: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/e49bbedcc67d60da2c10e81bc6433b0f8e8fa232
|
||||||
types-pac:
|
types-pac:
|
||||||
specifier: ^1.0.3
|
specifier: ^1.0.3
|
||||||
version: 1.0.3
|
version: 1.0.3
|
||||||
@@ -324,8 +324,8 @@ importers:
|
|||||||
specifier: ^10.0.1
|
specifier: ^10.0.1
|
||||||
version: 10.0.1(eslint@10.11.0(jiti@2.7.0)(supports-color@7.2.0))
|
version: 10.0.1(eslint@10.11.0(jiti@2.7.0)(supports-color@7.2.0))
|
||||||
'@tauri-apps/cli':
|
'@tauri-apps/cli':
|
||||||
specifier: 2.12.6
|
specifier: 2.12.4
|
||||||
version: 2.12.6
|
version: 2.12.4
|
||||||
'@types/lodash-es':
|
'@types/lodash-es':
|
||||||
specifier: ^4.17.12
|
specifier: ^4.17.12
|
||||||
version: 4.17.12
|
version: 4.17.12
|
||||||
@@ -2072,82 +2072,82 @@ packages:
|
|||||||
'@tanstack/virtual-core@3.17.11':
|
'@tanstack/virtual-core@3.17.11':
|
||||||
resolution: {integrity: sha512-+ILjvtHup6Y2hzQ6YzwMgX1Q+oQpxEGOXCEsCNaPoIP0VxMbizIBTmYTDtkerkIQS8/CbP1BRuyt8V/8BCsy1g==}
|
resolution: {integrity: sha512-+ILjvtHup6Y2hzQ6YzwMgX1Q+oQpxEGOXCEsCNaPoIP0VxMbizIBTmYTDtkerkIQS8/CbP1BRuyt8V/8BCsy1g==}
|
||||||
|
|
||||||
'@tauri-apps/api@2.12.5':
|
'@tauri-apps/api@2.12.4':
|
||||||
resolution: {integrity: sha512-G9QIMt5fzED+aS4QhVK3w1HWLKpLIwH/MnpCr9z1ugGEHnS2ORmqrLkc0uALOjRK4qXJy+4Yiw8LDl/KicC1Hg==}
|
resolution: {integrity: sha512-pVmfis+4zT8H0Qhp3xPZx9Ju7kpzvA6rr/PSJPyuwfvucTQ8sVt61NYU9KMkK703UFlYadFmjKA4HhybOtN0gg==}
|
||||||
|
|
||||||
'@tauri-apps/cli-darwin-arm64@2.12.6':
|
'@tauri-apps/cli-darwin-arm64@2.12.4':
|
||||||
resolution: {integrity: sha512-Uokwk1hFfJoG54+kD8iU0St33jAIkNvojnjEfBZ6UbL5rnM10AiFwUS/2DHTJ9R4/Kba4U44v7djfMuWFTQgeg==}
|
resolution: {integrity: sha512-OxqKSckIkoJ6vX2AjifIJpTasFC0Hbdoo7gEiCmAjauABO3U8m2MRsLWe+QTiBwDx1mIrvgA+rvI7tvDnbnHVg==}
|
||||||
engines: {node: '>= 10'}
|
engines: {node: '>= 10'}
|
||||||
cpu: [arm64]
|
cpu: [arm64]
|
||||||
os: [darwin]
|
os: [darwin]
|
||||||
|
|
||||||
'@tauri-apps/cli-darwin-x64@2.12.6':
|
'@tauri-apps/cli-darwin-x64@2.12.4':
|
||||||
resolution: {integrity: sha512-WhahqzcyHCpCzh4Taf0ZbBm6nGkvuOSh5ffrgOO7EdYaYe+RBQK8LOlFu+bbjul5v9cdLDi3kco+0+7IlZtTVA==}
|
resolution: {integrity: sha512-fz76/77wMMJOaaUN6n3CybRG0P/MTEjjqYk81mGPyhi9m6Ue5T+LWBnJP/AkPooNatBPI2vtulGqomyMJ44lCQ==}
|
||||||
engines: {node: '>= 10'}
|
engines: {node: '>= 10'}
|
||||||
cpu: [x64]
|
cpu: [x64]
|
||||||
os: [darwin]
|
os: [darwin]
|
||||||
|
|
||||||
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.6':
|
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.4':
|
||||||
resolution: {integrity: sha512-GB6weN+iFHxiFZ9SOKW6fINis7gnxohoOldR7sryBe7uaavkFGaMCa0yQs5njeXPWvzlE9WTQ13z8oDjmqK+Ww==}
|
resolution: {integrity: sha512-K0w8Bof6Lt8QKLAYhRy0yy36ZH5iA/35VuSOvnxyjvCUZ+A3JKsUTlALviH/sVgAlisaPzzmeJSH8XOn4Q2HBA==}
|
||||||
engines: {node: '>= 10'}
|
engines: {node: '>= 10'}
|
||||||
cpu: [arm]
|
cpu: [arm]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
|
||||||
'@tauri-apps/cli-linux-arm64-gnu@2.12.6':
|
'@tauri-apps/cli-linux-arm64-gnu@2.12.4':
|
||||||
resolution: {integrity: sha512-mdHoUFYKfztUtPKE0C2hhGkEo7j6swXjg+5yRRKSD7A2gLkRPQFIXWD/DAYhiJdeAkyA8MCP6nvvKvg/4YryWQ==}
|
resolution: {integrity: sha512-j5rOnjmRUwWrm1oosf0zBYl4D+fqydgUROFCk0hvKZxvbTT8SOERes0QB7rBV/XWNy+kM6pCKzb3oSm2sRglzg==}
|
||||||
engines: {node: '>= 10'}
|
engines: {node: '>= 10'}
|
||||||
cpu: [arm64]
|
cpu: [arm64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
libc: [glibc]
|
libc: [glibc]
|
||||||
|
|
||||||
'@tauri-apps/cli-linux-arm64-musl@2.12.6':
|
'@tauri-apps/cli-linux-arm64-musl@2.12.4':
|
||||||
resolution: {integrity: sha512-2BxB+9a3JRN0eJ0t0qGe8IKJfgBLOZDE8a499OXH+yg4J9bMpSK1oHXBxnHuSHFWhby4QnQ/t+sBf7tRC0UZeA==}
|
resolution: {integrity: sha512-aOue3Fy6Jb7+oWcfAVUsVHfeTybSCt2CZoU06aO4jv4d2Ks/KnaTPwMAK3CLEduGOvBLY1lbBBrIyomqLLH5Sg==}
|
||||||
engines: {node: '>= 10'}
|
engines: {node: '>= 10'}
|
||||||
cpu: [arm64]
|
cpu: [arm64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
libc: [musl]
|
libc: [musl]
|
||||||
|
|
||||||
'@tauri-apps/cli-linux-riscv64-gnu@2.12.6':
|
'@tauri-apps/cli-linux-riscv64-gnu@2.12.4':
|
||||||
resolution: {integrity: sha512-sb58RsNHex9QVqHdN1cf9MMlamUWAtk1NzuxTZalUnBUHfblIbe71hfmdI6whDZ84MufgOdeg/bzvhrbZS1r0w==}
|
resolution: {integrity: sha512-Fx6GShY/RvST+t6LMlTHAwd66+1tEaAAGrnU7cysVfaiRP1BKng5Vl6rVmO6rSLOA1Sp1dRzNYM4f0OWQGb7qA==}
|
||||||
engines: {node: '>= 10'}
|
engines: {node: '>= 10'}
|
||||||
cpu: [riscv64]
|
cpu: [riscv64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
libc: [glibc]
|
libc: [glibc]
|
||||||
|
|
||||||
'@tauri-apps/cli-linux-x64-gnu@2.12.6':
|
'@tauri-apps/cli-linux-x64-gnu@2.12.4':
|
||||||
resolution: {integrity: sha512-ZAb4/CHRma3ErjL2RGfHjITTUBIs4zySf0hIli9BddOtEdSx0ze0hEgxl+HfBVc5OEW/QmbiZ2E2+CkkHc8Pcg==}
|
resolution: {integrity: sha512-tNzZSa79Z1nRpHxEpQ38lsAFpKlFlYvoXzjTV+lRRn/zSf3wrdUC3wnLcq2XEadchPu4ttK0zivhYzr+XGD19Q==}
|
||||||
engines: {node: '>= 10'}
|
engines: {node: '>= 10'}
|
||||||
cpu: [x64]
|
cpu: [x64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
libc: [glibc]
|
libc: [glibc]
|
||||||
|
|
||||||
'@tauri-apps/cli-linux-x64-musl@2.12.6':
|
'@tauri-apps/cli-linux-x64-musl@2.12.4':
|
||||||
resolution: {integrity: sha512-ueSzM2Du6r4i1d/lby9kEvrhPnXw5zM/VYvcW1ldEWSpkUyVohsBXkmD+U7vMskEW5tXeCUenki7nYVxyGBGpQ==}
|
resolution: {integrity: sha512-jmZ1pr0xEqUhuEusWtt9Yt+GF6lCnGHUmIL+KIknpbjK/XQ2qkhDBhaxK/JMHM2A8dAacVXCxXJk2EXpwhQUfA==}
|
||||||
engines: {node: '>= 10'}
|
engines: {node: '>= 10'}
|
||||||
cpu: [x64]
|
cpu: [x64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
libc: [musl]
|
libc: [musl]
|
||||||
|
|
||||||
'@tauri-apps/cli-win32-arm64-msvc@2.12.6':
|
'@tauri-apps/cli-win32-arm64-msvc@2.12.4':
|
||||||
resolution: {integrity: sha512-6bmOt2BQSe0Bba+5CJcTKSML7VOYDxyiAKyBrjo86VxMdC1usIQmklu3Xc83s3QoK1rOMwwbANlPF6i5R2mvIg==}
|
resolution: {integrity: sha512-fGo8pgEHZxdSYgZ/J98m1usJ7NHKmKbq7k6uT0x1rpOq6Bg2YVzzpaAblWk710f5LHYBJIL5QIFS5IrD+4gmTg==}
|
||||||
engines: {node: '>= 10'}
|
engines: {node: '>= 10'}
|
||||||
cpu: [arm64]
|
cpu: [arm64]
|
||||||
os: [win32]
|
os: [win32]
|
||||||
|
|
||||||
'@tauri-apps/cli-win32-ia32-msvc@2.12.6':
|
'@tauri-apps/cli-win32-ia32-msvc@2.12.4':
|
||||||
resolution: {integrity: sha512-9q9ZFNuFreBczwyJuhhlrEOBzGClwWUYirQ2GBl66Y6EaNl17IdLH8TRqoY9wYB1LnctNBi+Fa/WMGtFA4BtFQ==}
|
resolution: {integrity: sha512-ezl8sQIcjYsye3TUnTH5VcWmWzccZASlQm7hlZt0dYyj1XD0qpVW47u2xYVrIKui0F8uQv/7QGZixdWiClBsbg==}
|
||||||
engines: {node: '>= 10'}
|
engines: {node: '>= 10'}
|
||||||
cpu: [ia32]
|
cpu: [ia32]
|
||||||
os: [win32]
|
os: [win32]
|
||||||
|
|
||||||
'@tauri-apps/cli-win32-x64-msvc@2.12.6':
|
'@tauri-apps/cli-win32-x64-msvc@2.12.4':
|
||||||
resolution: {integrity: sha512-ion7Chbj21ROxMRpjQ7G8rz5sIOaI7IoBQum1oq5sl1V5zGWyc/oYnCrQhVqO2TxK/lBDWxt648BzLi02SY3Xg==}
|
resolution: {integrity: sha512-DJhDeCqjLDNMWYFy7ZS8cfeAHX2RK0RbQMLiA3bMVVkXRDJ4NBYiHriGqsUhsr9iG41aTb+dJGkFPmPw1gWwVw==}
|
||||||
engines: {node: '>= 10'}
|
engines: {node: '>= 10'}
|
||||||
cpu: [x64]
|
cpu: [x64]
|
||||||
os: [win32]
|
os: [win32]
|
||||||
|
|
||||||
'@tauri-apps/cli@2.12.6':
|
'@tauri-apps/cli@2.12.4':
|
||||||
resolution: {integrity: sha512-/cOeQgqq8PBDPODOjjT0YHs4qxKCHcQMWMiBm4rLM3JNr9mZE+PHNKOK4zAkhIUtYMNL/0fweW48VNvzD1AbqA==}
|
resolution: {integrity: sha512-JI9bHfudSRJikGOrjbXEm6RjzzvmKuLc+JixB1NE8hNzQkNlCCIC3pTES3uypkR9lxHrsbxzcnSwhI2IxBQphw==}
|
||||||
engines: {node: '>= 10'}
|
engines: {node: '>= 10'}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
@@ -4015,9 +4015,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==}
|
resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
tauri-plugin-mihomo-api@https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f:
|
tauri-plugin-mihomo-api@https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/e49bbedcc67d60da2c10e81bc6433b0f8e8fa232:
|
||||||
resolution: {gitHosted: true, integrity: sha512-4nRJ9eBOdd+mT9KaqEhUNya8bh/zaHHAJMBRgFR62KxSZ0S77mcjkB6Bz2xmHqPdYrhbi58aD6UcybEp4a6UyA==, tarball: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f}
|
resolution: {gitHosted: true, integrity: sha512-fy5wxkEBj+L3c1ZefPpU6F9Wmhsx9iLJI3xBeYlvpGg7Iqzo6+qR2KcWpGilgHbpJWcPb6c22QMxyLR369vkeQ==, tarball: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/e49bbedcc67d60da2c10e81bc6433b0f8e8fa232}
|
||||||
version: 0.7.1
|
version: 0.7.0
|
||||||
|
|
||||||
terser@5.51.2:
|
terser@5.51.2:
|
||||||
resolution: {integrity: sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==}
|
resolution: {integrity: sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==}
|
||||||
@@ -5970,78 +5970,78 @@ snapshots:
|
|||||||
|
|
||||||
'@tanstack/virtual-core@3.17.11': {}
|
'@tanstack/virtual-core@3.17.11': {}
|
||||||
|
|
||||||
'@tauri-apps/api@2.12.5': {}
|
'@tauri-apps/api@2.12.4': {}
|
||||||
|
|
||||||
'@tauri-apps/cli-darwin-arm64@2.12.6':
|
'@tauri-apps/cli-darwin-arm64@2.12.4':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
'@tauri-apps/cli-darwin-x64@2.12.6':
|
'@tauri-apps/cli-darwin-x64@2.12.4':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.6':
|
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.4':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
'@tauri-apps/cli-linux-arm64-gnu@2.12.6':
|
'@tauri-apps/cli-linux-arm64-gnu@2.12.4':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
'@tauri-apps/cli-linux-arm64-musl@2.12.6':
|
'@tauri-apps/cli-linux-arm64-musl@2.12.4':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
'@tauri-apps/cli-linux-riscv64-gnu@2.12.6':
|
'@tauri-apps/cli-linux-riscv64-gnu@2.12.4':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
'@tauri-apps/cli-linux-x64-gnu@2.12.6':
|
'@tauri-apps/cli-linux-x64-gnu@2.12.4':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
'@tauri-apps/cli-linux-x64-musl@2.12.6':
|
'@tauri-apps/cli-linux-x64-musl@2.12.4':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
'@tauri-apps/cli-win32-arm64-msvc@2.12.6':
|
'@tauri-apps/cli-win32-arm64-msvc@2.12.4':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
'@tauri-apps/cli-win32-ia32-msvc@2.12.6':
|
'@tauri-apps/cli-win32-ia32-msvc@2.12.4':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
'@tauri-apps/cli-win32-x64-msvc@2.12.6':
|
'@tauri-apps/cli-win32-x64-msvc@2.12.4':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
'@tauri-apps/cli@2.12.6':
|
'@tauri-apps/cli@2.12.4':
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@tauri-apps/cli-darwin-arm64': 2.12.6
|
'@tauri-apps/cli-darwin-arm64': 2.12.4
|
||||||
'@tauri-apps/cli-darwin-x64': 2.12.6
|
'@tauri-apps/cli-darwin-x64': 2.12.4
|
||||||
'@tauri-apps/cli-linux-arm-gnueabihf': 2.12.6
|
'@tauri-apps/cli-linux-arm-gnueabihf': 2.12.4
|
||||||
'@tauri-apps/cli-linux-arm64-gnu': 2.12.6
|
'@tauri-apps/cli-linux-arm64-gnu': 2.12.4
|
||||||
'@tauri-apps/cli-linux-arm64-musl': 2.12.6
|
'@tauri-apps/cli-linux-arm64-musl': 2.12.4
|
||||||
'@tauri-apps/cli-linux-riscv64-gnu': 2.12.6
|
'@tauri-apps/cli-linux-riscv64-gnu': 2.12.4
|
||||||
'@tauri-apps/cli-linux-x64-gnu': 2.12.6
|
'@tauri-apps/cli-linux-x64-gnu': 2.12.4
|
||||||
'@tauri-apps/cli-linux-x64-musl': 2.12.6
|
'@tauri-apps/cli-linux-x64-musl': 2.12.4
|
||||||
'@tauri-apps/cli-win32-arm64-msvc': 2.12.6
|
'@tauri-apps/cli-win32-arm64-msvc': 2.12.4
|
||||||
'@tauri-apps/cli-win32-ia32-msvc': 2.12.6
|
'@tauri-apps/cli-win32-ia32-msvc': 2.12.4
|
||||||
'@tauri-apps/cli-win32-x64-msvc': 2.12.6
|
'@tauri-apps/cli-win32-x64-msvc': 2.12.4
|
||||||
|
|
||||||
'@tauri-apps/plugin-clipboard-manager@2.5.0':
|
'@tauri-apps/plugin-clipboard-manager@2.5.0':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@tauri-apps/api': 2.12.5
|
'@tauri-apps/api': 2.12.4
|
||||||
|
|
||||||
'@tauri-apps/plugin-dialog@2.8.4':
|
'@tauri-apps/plugin-dialog@2.8.4':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@tauri-apps/api': 2.12.5
|
'@tauri-apps/api': 2.12.4
|
||||||
|
|
||||||
'@tauri-apps/plugin-fs@2.7.1':
|
'@tauri-apps/plugin-fs@2.7.1':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@tauri-apps/api': 2.12.5
|
'@tauri-apps/api': 2.12.4
|
||||||
|
|
||||||
'@tauri-apps/plugin-http@2.9.0':
|
'@tauri-apps/plugin-http@2.9.0':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@tauri-apps/api': 2.12.5
|
'@tauri-apps/api': 2.12.4
|
||||||
|
|
||||||
'@tauri-apps/plugin-opener@2.7.3':
|
'@tauri-apps/plugin-opener@2.7.3':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@tauri-apps/api': 2.12.5
|
'@tauri-apps/api': 2.12.4
|
||||||
|
|
||||||
'@tauri-apps/plugin-updater@2.14.1':
|
'@tauri-apps/plugin-updater@2.14.1':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@tauri-apps/api': 2.12.5
|
'@tauri-apps/api': 2.12.4
|
||||||
|
|
||||||
'@tsrs/darwin-arm64@0.20.0-ts7.1.0-beta':
|
'@tsrs/darwin-arm64@0.20.0-ts7.1.0-beta':
|
||||||
optional: true
|
optional: true
|
||||||
@@ -8120,9 +8120,9 @@ snapshots:
|
|||||||
minizlib: 3.1.0
|
minizlib: 3.1.0
|
||||||
yallist: 5.0.0
|
yallist: 5.0.0
|
||||||
|
|
||||||
tauri-plugin-mihomo-api@https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f:
|
tauri-plugin-mihomo-api@https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/e49bbedcc67d60da2c10e81bc6433b0f8e8fa232:
|
||||||
dependencies:
|
dependencies:
|
||||||
'@tauri-apps/api': 2.12.5
|
'@tauri-apps/api': 2.12.4
|
||||||
|
|
||||||
terser@5.51.2:
|
terser@5.51.2:
|
||||||
dependencies:
|
dependencies:
|
||||||
|
|||||||
+1
-1
@@ -220,7 +220,7 @@ pub fn run() -> std::process::ExitCode {
|
|||||||
.set_activation_policy(tauri::ActivationPolicy::Prohibited)?;
|
.set_activation_policy(tauri::ActivationPolicy::Prohibited)?;
|
||||||
let scenario = std::env::var("PERF_SCENARIO").unwrap_or_else(|_| "traffic".into());
|
let scenario = std::env::var("PERF_SCENARIO").unwrap_or_else(|_| "traffic".into());
|
||||||
let layer = std::env::var("PERF_LAYER").unwrap_or_else(|_| "component".into());
|
let layer = std::env::var("PERF_LAYER").unwrap_or_else(|_| "component".into());
|
||||||
if !matches!(scenario.as_str(), "traffic" | "logs" | "connections")
|
if !matches!(scenario.as_str(), "traffic" | "logs" | "connections" | "proxy")
|
||||||
|| !matches!(layer.as_str(), "page" | "component" | "dom")
|
|| !matches!(layer.as_str(), "page" | "component" | "dom")
|
||||||
{
|
{
|
||||||
return Err("invalid perf scene".into());
|
return Err("invalid perf scene".into());
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import { layer, scenario, startReplay } from './replay'
|
|||||||
|
|
||||||
if (scenario === 'traffic') {
|
if (scenario === 'traffic') {
|
||||||
await import('./traffic')
|
await import('./traffic')
|
||||||
|
} else if (scenario === 'proxy') {
|
||||||
|
await import('./proxy')
|
||||||
} else {
|
} else {
|
||||||
const root = document.getElementById('root')!
|
const root = document.getElementById('root')!
|
||||||
document.body.style.cssText = 'margin:0;font:14px -apple-system,sans-serif'
|
document.body.style.cssText = 'margin:0;font:14px -apple-system,sans-serif'
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
// Only this perf build aliases '@tauri-apps/api/core' to a shim that serves
|
||||||
|
// these responses for the proxy scenario; the normal application never
|
||||||
|
// imports it. The runtime-injected __TAURI_INTERNALS__ is read-only, so
|
||||||
|
// interception happens at import resolution instead. Unknown commands pass
|
||||||
|
// through to the real backend (perf_state, event plugin), keeping harness
|
||||||
|
// ownership probes and lifecycle commands working. The proxy scenario is
|
||||||
|
// therefore a JavaScript invoke adapter, not native plugin IPC.
|
||||||
|
|
||||||
|
const GROUP_COUNT = 40
|
||||||
|
const NODES_PER_GROUP = 24
|
||||||
|
|
||||||
|
const capabilities = {
|
||||||
|
udp: true,
|
||||||
|
xudp: false,
|
||||||
|
tfo: false,
|
||||||
|
mptcp: false,
|
||||||
|
smux: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
const history = (delay: number) => [{ time: '2026-11-19T00:00:00Z', delay }]
|
||||||
|
|
||||||
|
const buildProxyView = () => {
|
||||||
|
const records: Record<string, unknown> = {}
|
||||||
|
const groups: {
|
||||||
|
name: string
|
||||||
|
type: string
|
||||||
|
now: string
|
||||||
|
hidden: boolean
|
||||||
|
history: { time: string; delay: number }[]
|
||||||
|
members: unknown[]
|
||||||
|
}[] = []
|
||||||
|
|
||||||
|
for (let g = 0; g < GROUP_COUNT; g++) {
|
||||||
|
const members: unknown[] = []
|
||||||
|
for (let n = 0; n < NODES_PER_GROUP; n++) {
|
||||||
|
const name = `node-${g}-${n}`
|
||||||
|
const recordId = `record-${g}-${n}`
|
||||||
|
records[recordId] = {
|
||||||
|
recordId,
|
||||||
|
name,
|
||||||
|
type: n % 3 === 0 ? 'Shadowsocks' : n % 3 === 1 ? 'Vmess' : 'Trojan',
|
||||||
|
history: history(30 + ((g * 7 + n * 13) % 40) * 10),
|
||||||
|
source: { kind: 'core', proxyName: name },
|
||||||
|
...capabilities,
|
||||||
|
}
|
||||||
|
members.push({ kind: 'node', name, recordId })
|
||||||
|
}
|
||||||
|
groups.push({
|
||||||
|
name: `group-${String(g).padStart(2, '0')}`,
|
||||||
|
type: g % 2 === 0 ? 'Selector' : 'URLTest',
|
||||||
|
now: `node-${g}-0`,
|
||||||
|
hidden: false,
|
||||||
|
history: history(20),
|
||||||
|
members,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
schemaVersion: 1,
|
||||||
|
orderSource: 'runtime',
|
||||||
|
providerState: 'ready',
|
||||||
|
global: {
|
||||||
|
name: 'GLOBAL',
|
||||||
|
type: 'Selector',
|
||||||
|
now: 'group-00',
|
||||||
|
hidden: true,
|
||||||
|
history: [],
|
||||||
|
members: groups.map((group) => ({ kind: 'group', name: group.name })),
|
||||||
|
...capabilities,
|
||||||
|
},
|
||||||
|
direct: 'DIRECT',
|
||||||
|
groups: groups.map((group) => ({ ...group, ...capabilities })),
|
||||||
|
records,
|
||||||
|
standalone: [],
|
||||||
|
providers: [],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handlers: Record<string, () => unknown> = {
|
||||||
|
get_proxy_view: buildProxyView,
|
||||||
|
get_verge_config: () => ({
|
||||||
|
language: 'en',
|
||||||
|
theme_mode: 'light',
|
||||||
|
proxy_layout_column: 2,
|
||||||
|
default_latency_timeout: 10000,
|
||||||
|
enable_hover_jump_navigator: true,
|
||||||
|
hover_jump_navigator_delay: 200,
|
||||||
|
pause_render_traffic_stats_on_blur: false,
|
||||||
|
}),
|
||||||
|
get_profiles: () => ({
|
||||||
|
current: 'perf-profile',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
uid: 'perf-profile',
|
||||||
|
type: 'remote',
|
||||||
|
name: 'Perf Profile',
|
||||||
|
desc: '',
|
||||||
|
url: '',
|
||||||
|
selected: true,
|
||||||
|
extra: {},
|
||||||
|
option: { update_interval: 0 },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
get_clash_info: () => ({
|
||||||
|
mixed_port: 7897,
|
||||||
|
socks_port: 0,
|
||||||
|
port: 0,
|
||||||
|
server: '127.0.0.1:9097',
|
||||||
|
secret: null,
|
||||||
|
}),
|
||||||
|
get_runtime_config: () => null,
|
||||||
|
get_sys_proxy: () => ({ enable: false, bypass: '', pac_file: '' }),
|
||||||
|
get_runtime_state: () => ({
|
||||||
|
mode: 'Sidecar',
|
||||||
|
service: 'ready',
|
||||||
|
serviceUnavailableReason: null,
|
||||||
|
pendingAction: null,
|
||||||
|
sidecarAllowed: true,
|
||||||
|
isAdmin: false,
|
||||||
|
opInFlight: false,
|
||||||
|
serviceUsable: true,
|
||||||
|
tunCapable: false,
|
||||||
|
serviceNeedsAttention: false,
|
||||||
|
}),
|
||||||
|
get_sidecar_failure: () => null,
|
||||||
|
get_pending_failures: () => [],
|
||||||
|
'plugin:mihomo|get_configs': () => ({ mode: 'rule', 'mixed-port': 7897 }),
|
||||||
|
'plugin:mihomo|get_rule_providers': () => ({ providers: {} }),
|
||||||
|
'plugin:mihomo|get_rules': () => ({ rules: [] }),
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns the mocked response, or undefined to pass through to the backend. */
|
||||||
|
export const mockCommand = (cmd: string): unknown => {
|
||||||
|
const handler = handlers[cmd]
|
||||||
|
return handler ? handler() : undefined
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import { ThemeProvider, createTheme } from '@mui/material'
|
||||||
|
import { useEffect } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
import { SWRConfig } from 'swr'
|
||||||
|
|
||||||
|
import { AppDataProvider } from '../../src/providers/app-data-provider'
|
||||||
|
import { initializeLanguage } from '../../src/services/i18n'
|
||||||
|
import { setPreloadConfig } from '../../src/services/preload'
|
||||||
|
import { swrConfig } from '../../src/services/query-client'
|
||||||
|
import { AppStoreProvider } from '../../src/store/app-store'
|
||||||
|
|
||||||
|
import '../../src/assets/styles/page.scss'
|
||||||
|
|
||||||
|
const root = document.getElementById('root')!
|
||||||
|
document.body.style.cssText = 'margin:0;font:14px -apple-system,sans-serif'
|
||||||
|
root.style.cssText = 'width:1000px;height:700px;overflow:hidden'
|
||||||
|
new MutationObserver(() => {
|
||||||
|
document.documentElement.dataset.perfDraw = String(Date.now())
|
||||||
|
}).observe(root, { childList: true, characterData: true, subtree: true })
|
||||||
|
|
||||||
|
setPreloadConfig({
|
||||||
|
language: 'en',
|
||||||
|
theme_mode: 'light',
|
||||||
|
pause_render_traffic_stats_on_blur: false,
|
||||||
|
} as IVergeConfig)
|
||||||
|
await initializeLanguage('en')
|
||||||
|
|
||||||
|
const ProxyPage = (await import('../../src/pages/proxies')).default
|
||||||
|
|
||||||
|
const findScroller = () => {
|
||||||
|
const elements = document.querySelectorAll<HTMLElement>('#root *')
|
||||||
|
for (const element of elements) {
|
||||||
|
const { overflowY } = getComputedStyle(element)
|
||||||
|
if (
|
||||||
|
(overflowY === 'auto' || overflowY === 'scroll') &&
|
||||||
|
element.scrollHeight > element.clientHeight
|
||||||
|
) {
|
||||||
|
return element
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deterministic sawtooth scrolling keeps the virtualizer measuring, the
|
||||||
|
// throttled scroll-position save running and the DOM mutating so the perfDraw
|
||||||
|
// marker tracks view-input delivery. Each applied scroll step counts as one
|
||||||
|
// delivered view input; the interval keeps delivering (throttled by the
|
||||||
|
// browser) while the window is hidden and rAF is suspended.
|
||||||
|
export const ScrollDriver = () => {
|
||||||
|
useEffect(() => {
|
||||||
|
const data = document.documentElement.dataset
|
||||||
|
let stopped = false
|
||||||
|
const step = () => {
|
||||||
|
const scroller = findScroller()
|
||||||
|
if (scroller) {
|
||||||
|
const max = scroller.scrollHeight - scroller.clientHeight
|
||||||
|
if (max > 0) {
|
||||||
|
const next =
|
||||||
|
scroller.scrollTop + 36 > max - 36 ? 0 : scroller.scrollTop + 36
|
||||||
|
scroller.scrollTop = next
|
||||||
|
data.perfScroll = String(Number(data.perfScroll || 0) + 1)
|
||||||
|
data.perfDelivered = String(Number(data.perfDelivered || 0) + 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const drive = () => {
|
||||||
|
if (stopped) return
|
||||||
|
step()
|
||||||
|
requestAnimationFrame(drive)
|
||||||
|
}
|
||||||
|
const handle = requestAnimationFrame(drive)
|
||||||
|
const timer = window.setInterval(step, 250)
|
||||||
|
return () => {
|
||||||
|
stopped = true
|
||||||
|
cancelAnimationFrame(handle)
|
||||||
|
window.clearInterval(timer)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
createRoot(root).render(
|
||||||
|
<SWRConfig value={swrConfig}>
|
||||||
|
<ThemeProvider theme={createTheme()}>
|
||||||
|
<AppStoreProvider>
|
||||||
|
<AppDataProvider>
|
||||||
|
<ProxyPage />
|
||||||
|
<ScrollDriver />
|
||||||
|
</AppDataProvider>
|
||||||
|
</AppStoreProvider>
|
||||||
|
</ThemeProvider>
|
||||||
|
</SWRConfig>,
|
||||||
|
)
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { startReplay } from './replay'
|
||||||
|
|
||||||
|
// Thin loader: error handlers must precede scene module evaluation so any
|
||||||
|
// startup failure surfaces in perfError.
|
||||||
|
const data = document.documentElement.dataset
|
||||||
|
window.addEventListener('error', (event) => {
|
||||||
|
data.perfError = event.message
|
||||||
|
})
|
||||||
|
window.addEventListener('unhandledrejection', (event) => {
|
||||||
|
data.perfError = String(event.reason)
|
||||||
|
})
|
||||||
|
|
||||||
|
data.perfStage = 'loader'
|
||||||
|
await import('./proxy-scene')
|
||||||
|
data.perfStage = 'scene'
|
||||||
|
startReplay()
|
||||||
|
data.perfStage = 'replay'
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
// Aliased in place of '@tauri-apps/api/core' only by the perf build. The
|
||||||
|
// direct relative import keeps the original module outside the alias so this
|
||||||
|
// shim can forward to it. Invocation stays byte-identical for every scenario
|
||||||
|
// except proxy, which needs the JavaScript invoke adapter.
|
||||||
|
import {
|
||||||
|
Channel,
|
||||||
|
convertFileSrc,
|
||||||
|
invoke as realInvoke,
|
||||||
|
type InvokeArgs,
|
||||||
|
type InvokeOptions,
|
||||||
|
} from '../../node_modules/@tauri-apps/api/core.js'
|
||||||
|
|
||||||
|
import { mockCommand } from './invoke-mock'
|
||||||
|
import { scenario } from './replay'
|
||||||
|
|
||||||
|
const proxied = scenario === 'proxy'
|
||||||
|
|
||||||
|
export const invoke = async <T>(
|
||||||
|
cmd: string,
|
||||||
|
args?: InvokeArgs,
|
||||||
|
options?: InvokeOptions,
|
||||||
|
): Promise<T> => {
|
||||||
|
if (proxied) {
|
||||||
|
const mocked = mockCommand(cmd)
|
||||||
|
if (mocked !== undefined) return mocked as T
|
||||||
|
}
|
||||||
|
return realInvoke(cmd, args, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Channel, convertFileSrc }
|
||||||
@@ -6,5 +6,11 @@ export default mergeConfig(
|
|||||||
defineConfig({
|
defineConfig({
|
||||||
root: 'scripts/perf',
|
root: 'scripts/perf',
|
||||||
build: { outDir: '../../target/perf/dist', target: 'safari16' },
|
build: { outDir: '../../target/perf/dist', target: 'safari16' },
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
'@tauri-apps/api/core': new URL('./tauri-core-shim.ts', import.meta.url)
|
||||||
|
.pathname,
|
||||||
|
},
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
|
|||||||
identifier = "io.github.clash-verge-rev.clash-verge-rev"
|
identifier = "io.github.clash-verge-rev.clash-verge-rev"
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
tauri-build = { version = "2.7.6", features = [] }
|
tauri-build = { version = "2.7.4", features = [] }
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
clash-verge-draft = { workspace = true }
|
clash-verge-draft = { workspace = true }
|
||||||
@@ -140,16 +140,10 @@ objc2-app-kit = { version = "0.3.2", features = [
|
|||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
deelevate = { workspace = true }
|
deelevate = { workspace = true }
|
||||||
quick-xml = "0.42.0"
|
|
||||||
runas = "=1.2.0"
|
runas = "=1.2.0"
|
||||||
winreg = "0.56.0"
|
winreg = "0.56.0"
|
||||||
windows-service = "0.8.1"
|
windows-service = "0.8.1"
|
||||||
windows = { version = "0.62.2", features = [
|
windows = { version = "0.62.2", features = ["Win32_Globalization"] }
|
||||||
"Win32_System_Com",
|
|
||||||
"Win32_System_Ole",
|
|
||||||
"Win32_System_TaskScheduler",
|
|
||||||
"Win32_System_Variant",
|
|
||||||
] }
|
|
||||||
windows-sys.workspace = true
|
windows-sys.workspace = true
|
||||||
|
|
||||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||||
|
|||||||
@@ -70,7 +70,6 @@ ${StrLoc}
|
|||||||
|
|
||||||
Var PassiveMode
|
Var PassiveMode
|
||||||
Var UpdateMode
|
Var UpdateMode
|
||||||
Var KeepAutoLaunch
|
|
||||||
Var NoShortcutMode
|
Var NoShortcutMode
|
||||||
Var WixMode
|
Var WixMode
|
||||||
Var OldMainBinaryName
|
Var OldMainBinaryName
|
||||||
@@ -334,9 +333,6 @@ Function PageLeaveReinstall
|
|||||||
${EndIf}
|
${EndIf}
|
||||||
|
|
||||||
reinst_uninstall:
|
reinst_uninstall:
|
||||||
${If} $R0 = 1
|
|
||||||
StrCpy $KeepAutoLaunch 1
|
|
||||||
${EndIf}
|
|
||||||
!insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
|
!insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}"
|
||||||
|
|
||||||
HideWindow
|
HideWindow
|
||||||
@@ -349,7 +345,6 @@ Function PageLeaveReinstall
|
|||||||
ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
|
ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" ""
|
||||||
ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
|
ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString"
|
||||||
${IfThen} $UpdateMode = 1 ${|} StrCpy $R1 "$R1 /UPDATE" ${|} ; append /UPDATE
|
${IfThen} $UpdateMode = 1 ${|} StrCpy $R1 "$R1 /UPDATE" ${|} ; append /UPDATE
|
||||||
${IfThen} $KeepAutoLaunch = 1 ${|} StrCpy $R1 "$R1 /KEEPAUTOLAUNCH" ${|}
|
|
||||||
${IfThen} $PassiveMode = 1 ${|} StrCpy $R1 "$R1 /P" ${|} ; append /P
|
${IfThen} $PassiveMode = 1 ${|} StrCpy $R1 "$R1 /P" ${|} ; append /P
|
||||||
StrCpy $R1 "$R1 _?=$4" ; append uninstall directory
|
StrCpy $R1 "$R1 _?=$4" ; append uninstall directory
|
||||||
ExecWait '$R1' $0
|
ExecWait '$R1' $0
|
||||||
@@ -1103,11 +1098,6 @@ Function un.onInit
|
|||||||
${IfNot} ${Errors}
|
${IfNot} ${Errors}
|
||||||
StrCpy $UpdateMode 1
|
StrCpy $UpdateMode 1
|
||||||
${EndIf}
|
${EndIf}
|
||||||
|
|
||||||
${GetOptions} $CMDLINE "/KEEPAUTOLAUNCH" $KeepAutoLaunch
|
|
||||||
${IfNot} ${Errors}
|
|
||||||
StrCpy $KeepAutoLaunch 1
|
|
||||||
${EndIf}
|
|
||||||
FunctionEnd
|
FunctionEnd
|
||||||
|
|
||||||
Section Uninstall
|
Section Uninstall
|
||||||
@@ -1301,24 +1291,6 @@ Section Uninstall
|
|||||||
DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}"
|
DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}"
|
||||||
${EndIf}
|
${EndIf}
|
||||||
|
|
||||||
${If} $UpdateMode <> 1
|
|
||||||
${AndIf} $KeepAutoLaunch <> 1
|
|
||||||
; UAC can run the uninstaller under a different account from the desktop user.
|
|
||||||
StrCpy $R0 0
|
|
||||||
${Do}
|
|
||||||
EnumRegKey $R1 HKU "" $R0
|
|
||||||
${If} $R1 == ""
|
|
||||||
${ExitDo}
|
|
||||||
${EndIf}
|
|
||||||
StrCpy $R3 "$R1\Software\Microsoft\Windows\CurrentVersion\Run"
|
|
||||||
ReadRegStr $R2 HKU "$R3" "Clash Verge Auto Launch"
|
|
||||||
${If} $R2 == "$\"$INSTDIR\${MAINBINARYNAME}.exe$\""
|
|
||||||
DeleteRegValue HKU "$R3" "Clash Verge Auto Launch"
|
|
||||||
${EndIf}
|
|
||||||
IntOp $R0 $R0 + 1
|
|
||||||
${Loop}
|
|
||||||
${EndIf}
|
|
||||||
|
|
||||||
; Delete app data if the checkbox is selected
|
; Delete app data if the checkbox is selected
|
||||||
; and if not updating
|
; and if not updating
|
||||||
${If} $DeleteAppDataCheckboxState = 1
|
${If} $DeleteAppDataCheckboxState = 1
|
||||||
|
|||||||
@@ -27,6 +27,12 @@ pub async fn switch_proxy_node(group_name: String, proxy_name: String, unfix: bo
|
|||||||
.stringify_err()
|
.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> {
|
fn runtime_group_order(config: Option<&Mapping>) -> Vec<String> {
|
||||||
let mut seen = HashSet::new();
|
let mut seen = HashSet::new();
|
||||||
|
|
||||||
|
|||||||
@@ -1,31 +1,34 @@
|
|||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
use crate::utils::schtasks;
|
||||||
use crate::{config::Config, core::handle::Handle};
|
use crate::{config::Config, core::handle::Handle};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
use clash_verge_logging::logging_error;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
use tauri_plugin_autostart::ManagerExt as _;
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
use tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin;
|
||||||
|
|
||||||
pub async fn update_launch() -> Result<()> {
|
pub async fn update_launch() -> Result<()> {
|
||||||
let enable_auto_launch = { Config::verge().await.latest_arc().enable_auto_launch };
|
let enable_auto_launch = { Config::verge().await.latest_arc().enable_auto_launch };
|
||||||
let is_enable = enable_auto_launch.unwrap_or(false);
|
let is_enable = enable_auto_launch.unwrap_or(false);
|
||||||
logging!(info, Type::System, "Setting auto-launch enabled state to: {is_enable}");
|
logging!(info, Type::System, "Setting auto-launch enabled state to: {is_enable}");
|
||||||
|
|
||||||
let app_handle = Handle::app_handle();
|
#[cfg(target_os = "windows")]
|
||||||
cfg_select! {
|
{
|
||||||
target_os = "windows" => {
|
let is_admin = is_current_app_handle_admin(Handle::app_handle());
|
||||||
use crate::utils::schtasks;
|
schtasks::set_auto_launch(is_enable, is_admin).await?;
|
||||||
use tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin;
|
}
|
||||||
|
|
||||||
let is_admin = is_current_app_handle_admin(app_handle);
|
#[cfg(not(target_os = "windows"))]
|
||||||
schtasks::set_auto_launch(is_enable, is_admin).await?;
|
{
|
||||||
}
|
let app_handle = Handle::app_handle();
|
||||||
_ => {
|
let autostart_manager = app_handle.autolaunch();
|
||||||
use clash_verge_logging::logging_error;
|
if is_enable {
|
||||||
use tauri_plugin_autostart::ManagerExt as _;
|
logging_error!(Type::System, "{:?}", autostart_manager.enable());
|
||||||
|
} else {
|
||||||
let autostart_manager = app_handle.autolaunch();
|
logging_error!(Type::System, "{:?}", autostart_manager.disable());
|
||||||
if is_enable {
|
|
||||||
logging_error!(Type::System, "{:?}", autostart_manager.enable());
|
|
||||||
} else {
|
|
||||||
logging_error!(Type::System, "{:?}", autostart_manager.disable());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -48,13 +48,10 @@ fn windows_owner_credentials(app_data_root: &Path) -> Result<(OwnerIdentity, Opt
|
|||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
fn windows_current_identity() -> Result<OwnerIdentity> {
|
fn windows_current_identity() -> Result<OwnerIdentity> {
|
||||||
Ok(OwnerIdentity::Windows {
|
Ok(OwnerIdentity::Windows {
|
||||||
sid: current_user_sid()?,
|
sid: windows_owner::current_sid()?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(windows)]
|
|
||||||
pub(crate) use windows_owner::{account_sid, current_sid as current_user_sid};
|
|
||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
pub(crate) fn create_private_current_user_file(path: &Path) -> Result<std::fs::File> {
|
pub(crate) fn create_private_current_user_file(path: &Path) -> Result<std::fs::File> {
|
||||||
windows_owner::create_private_file(path)
|
windows_owner::create_private_file(path)
|
||||||
@@ -96,8 +93,8 @@ mod windows_owner {
|
|||||||
use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _};
|
use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _};
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use windows_sys::Win32::Foundation::{
|
use windows_sys::Win32::Foundation::{
|
||||||
CloseHandle, ERROR_ACCESS_DENIED, ERROR_FILE_EXISTS, ERROR_FILE_NOT_FOUND, ERROR_INSUFFICIENT_BUFFER,
|
CloseHandle, ERROR_ACCESS_DENIED, ERROR_FILE_EXISTS, ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND, GENERIC_READ,
|
||||||
ERROR_PATH_NOT_FOUND, GENERIC_READ, GENERIC_WRITE, GetLastError, INVALID_HANDLE_VALUE, LocalFree,
|
GENERIC_WRITE, GetLastError, INVALID_HANDLE_VALUE, LocalFree,
|
||||||
};
|
};
|
||||||
use windows_sys::Win32::Security::Authorization::{
|
use windows_sys::Win32::Security::Authorization::{
|
||||||
ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, GetSecurityInfo, SDDL_REVISION_1,
|
ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, GetSecurityInfo, SDDL_REVISION_1,
|
||||||
@@ -106,9 +103,8 @@ mod windows_owner {
|
|||||||
use windows_sys::Win32::Security::{
|
use windows_sys::Win32::Security::{
|
||||||
ACCESS_ALLOWED_ACE, ACL, DACL_SECURITY_INFORMATION, EqualSid, GetAce, GetSecurityDescriptorControl,
|
ACCESS_ALLOWED_ACE, ACL, DACL_SECURITY_INFORMATION, EqualSid, GetAce, GetSecurityDescriptorControl,
|
||||||
GetSecurityDescriptorDacl, GetSecurityDescriptorOwner, GetTokenInformation, IsValidSid, IsWellKnownSid,
|
GetSecurityDescriptorDacl, GetSecurityDescriptorOwner, GetTokenInformation, IsValidSid, IsWellKnownSid,
|
||||||
LookupAccountNameW, OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR,
|
OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID, SE_DACL_PROTECTED,
|
||||||
PSID, SE_DACL_PROTECTED, SECURITY_ATTRIBUTES, TOKEN_QUERY, TOKEN_USER, TokenUser, WinBuiltinAdministratorsSid,
|
SECURITY_ATTRIBUTES, TOKEN_QUERY, TOKEN_USER, TokenUser, WinBuiltinAdministratorsSid, WinLocalSystemSid,
|
||||||
WinLocalSystemSid,
|
|
||||||
};
|
};
|
||||||
use windows_sys::Win32::Storage::FileSystem::{
|
use windows_sys::Win32::Storage::FileSystem::{
|
||||||
BY_HANDLE_FILE_INFORMATION, CREATE_NEW, CreateFileW, FILE_ALL_ACCESS, FILE_ATTRIBUTE_DIRECTORY,
|
BY_HANDLE_FILE_INFORMATION, CREATE_NEW, CreateFileW, FILE_ALL_ACCESS, FILE_ATTRIBUTE_DIRECTORY,
|
||||||
@@ -127,7 +123,7 @@ mod windows_owner {
|
|||||||
crate::utils::server::INSTANCE_LOCK_FILE,
|
crate::utils::server::INSTANCE_LOCK_FILE,
|
||||||
];
|
];
|
||||||
|
|
||||||
pub(crate) fn current_sid() -> Result<String> {
|
pub(super) fn current_sid() -> Result<String> {
|
||||||
let mut token = std::ptr::null_mut();
|
let mut token = std::ptr::null_mut();
|
||||||
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
|
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
|
||||||
return Err(std::io::Error::last_os_error()).context("failed to open process token");
|
return Err(std::io::Error::last_os_error()).context("failed to open process token");
|
||||||
@@ -149,44 +145,6 @@ mod windows_owner {
|
|||||||
sid_to_string(token_user.User.Sid)
|
sid_to_string(token_user.User.Sid)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn account_sid(account: &str) -> Result<String> {
|
|
||||||
let wide_account: Vec<_> = account.encode_utf16().chain([0]).collect();
|
|
||||||
let mut sid_size = 0;
|
|
||||||
let mut domain_len = 0;
|
|
||||||
let mut account_type = 0;
|
|
||||||
unsafe {
|
|
||||||
LookupAccountNameW(
|
|
||||||
std::ptr::null(),
|
|
||||||
wide_account.as_ptr(),
|
|
||||||
std::ptr::null_mut(),
|
|
||||||
&mut sid_size,
|
|
||||||
std::ptr::null_mut(),
|
|
||||||
&mut domain_len,
|
|
||||||
&mut account_type,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if unsafe { GetLastError() } != ERROR_INSUFFICIENT_BUFFER {
|
|
||||||
return Err(std::io::Error::last_os_error()).context("failed to size account SID buffer");
|
|
||||||
}
|
|
||||||
let mut sid = vec![0_usize; (sid_size as usize).div_ceil(std::mem::size_of::<usize>())];
|
|
||||||
let mut domain = vec![0_u16; domain_len as usize];
|
|
||||||
if unsafe {
|
|
||||||
LookupAccountNameW(
|
|
||||||
std::ptr::null(),
|
|
||||||
wide_account.as_ptr(),
|
|
||||||
sid.as_mut_ptr().cast(),
|
|
||||||
&mut sid_size,
|
|
||||||
domain.as_mut_ptr(),
|
|
||||||
&mut domain_len,
|
|
||||||
&mut account_type,
|
|
||||||
)
|
|
||||||
} == 0
|
|
||||||
{
|
|
||||||
return Err(std::io::Error::last_os_error()).context("failed to look up account SID");
|
|
||||||
}
|
|
||||||
sid_to_string(sid.as_mut_ptr().cast())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn load_or_create_token(app_data_root: &Path, sid: &str) -> Result<String> {
|
pub(super) fn load_or_create_token(app_data_root: &Path, sid: &str) -> Result<String> {
|
||||||
let token_path = app_data_root.join(OWNER_TOKEN_FILE_NAME);
|
let token_path = app_data_root.join(OWNER_TOKEN_FILE_NAME);
|
||||||
let descriptor = LocalSecurityDescriptor::from_sid(sid)?;
|
let descriptor = LocalSecurityDescriptor::from_sid(sid)?;
|
||||||
@@ -682,12 +640,12 @@ mod windows_owner {
|
|||||||
fn sid_to_string(sid: PSID) -> Result<String> {
|
fn sid_to_string(sid: PSID) -> Result<String> {
|
||||||
let mut value = std::ptr::null_mut();
|
let mut value = std::ptr::null_mut();
|
||||||
if unsafe { ConvertSidToStringSidW(sid, &mut value) } == 0 || value.is_null() {
|
if unsafe { ConvertSidToStringSidW(sid, &mut value) } == 0 || value.is_null() {
|
||||||
return Err(std::io::Error::last_os_error()).context("failed to format Windows SID");
|
return Err(std::io::Error::last_os_error()).context("failed to format process SID");
|
||||||
}
|
}
|
||||||
let value = LocalWideString(value);
|
let value = LocalWideString(value);
|
||||||
let length = (0..).take_while(|index| unsafe { *value.0.add(*index) } != 0).count();
|
let length = (0..).take_while(|index| unsafe { *value.0.add(*index) } != 0).count();
|
||||||
String::from_utf16(unsafe { std::slice::from_raw_parts(value.0, length) })
|
String::from_utf16(unsafe { std::slice::from_raw_parts(value.0, length) })
|
||||||
.context("Windows SID is not valid UTF-16")
|
.context("process SID is not valid UTF-16")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn encode_token(token: &[u8; TOKEN_BYTES]) -> String {
|
fn encode_token(token: &[u8; TOKEN_BYTES]) -> String {
|
||||||
|
|||||||
@@ -9,8 +9,7 @@ use crate::{
|
|||||||
};
|
};
|
||||||
use anyhow::{Result, bail};
|
use anyhow::{Result, bail};
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use std::collections::{HashMap, HashSet};
|
use tauri_plugin_mihomo::models::ProxyType;
|
||||||
use tauri_plugin_mihomo::models::{Proxy, ProxyType, Rule};
|
|
||||||
use tristr::alias::String;
|
use tristr::alias::String;
|
||||||
|
|
||||||
/// Toggle proxy profile
|
/// Toggle proxy profile
|
||||||
@@ -24,9 +23,13 @@ pub async fn toggle_proxy_profile(profile_index: String) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// First `select` group in config order that lists `group_name`.
|
/// 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> {
|
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 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
|
groups
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|group| field(group, "type") == Some("select"))
|
.filter(|group| field(group, "type") == Some("select"))
|
||||||
@@ -40,24 +43,9 @@ fn parent_selector<'a>(groups: &'a [serde_yaml_ng::Value], group_name: &str) ->
|
|||||||
.find(|name| *name != "GLOBAL")
|
.find(|name| *name != "GLOBAL")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether rule traffic passes through `group_name`, following each group's current selection.
|
/// Rule traffic enters through `select` groups, so a pick inside a `url-test`/`fallback` group only
|
||||||
fn rules_reach(groups: &[Proxy], rules: &[Rule], group_name: &str) -> bool {
|
/// carries traffic once the first `select` group listing that group points at it.
|
||||||
let by_name: HashMap<&str, &Proxy> = groups.iter().map(|group| (group.name.as_str(), group)).collect();
|
/// Returns the node that group left.
|
||||||
let mut seen = HashSet::new();
|
|
||||||
rules.iter().any(|rule| {
|
|
||||||
let mut hop = by_name.get(rule.proxy.as_str()).copied();
|
|
||||||
while let Some(group) = hop.filter(|group| seen.insert(group.name.as_str())) {
|
|
||||||
if group.name == group_name {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
hop = group.now.as_deref().and_then(|now| by_name.get(now).copied());
|
|
||||||
}
|
|
||||||
false
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A pick in a group no rule reaches only carries traffic once the first `select` group listing that group
|
|
||||||
/// points at it. Returns that `select` group, whose connections are then stale.
|
|
||||||
async fn follow_group_selection(group_name: &str) -> Option<std::string::String> {
|
async fn follow_group_selection(group_name: &str) -> Option<std::string::String> {
|
||||||
if !Config::verge()
|
if !Config::verge()
|
||||||
.await
|
.await
|
||||||
@@ -82,15 +70,13 @@ async fn follow_group_selection(group_name: &str) -> Option<std::string::String>
|
|||||||
};
|
};
|
||||||
|
|
||||||
let mihomo = handle::Handle::mihomo();
|
let mihomo = handle::Handle::mihomo();
|
||||||
let groups = mihomo.get_groups().await.ok()?.proxies;
|
let current = mihomo.get_proxy_by_name(&selector).await.ok()?;
|
||||||
let current = groups.iter().find(|group| group.name == selector)?;
|
|
||||||
// The runtime config can lag the core, which alone knows what this group is now.
|
// The runtime config can lag the core, which alone knows what this group is now.
|
||||||
if current.proxy_type != ProxyType::Selector {
|
if current.proxy_type != ProxyType::Selector {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
if current.now.as_deref() == Some(group_name)
|
let previous = current.now?;
|
||||||
|| rules_reach(&groups, &mihomo.get_rules().await.ok()?.rules, group_name)
|
if previous == group_name {
|
||||||
{
|
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
if let Err(err) = mihomo.select_node_for_group(&selector, group_name).await {
|
if let Err(err) = mihomo.select_node_for_group(&selector, group_name).await {
|
||||||
@@ -104,7 +90,7 @@ async fn follow_group_selection(group_name: &str) -> Option<std::string::String>
|
|||||||
"Failed to persist proxy selection for {selector}: {error:#}"
|
"Failed to persist proxy selection for {selector}: {error:#}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Some(selector)
|
Some(previous)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool) -> Result<()> {
|
pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool) -> Result<()> {
|
||||||
@@ -146,15 +132,24 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str, unfix: bool)
|
|||||||
}
|
}
|
||||||
let mut stale_proxies: Vec<_> = previous_proxy.into_iter().collect();
|
let mut stale_proxies: Vec<_> = previous_proxy.into_iter().collect();
|
||||||
if !unfix
|
if !unfix
|
||||||
&& let Some(followed) = follow_group_selection(group_name).await
|
&& let Some(left) = follow_group_selection(group_name).await
|
||||||
&& auto_close
|
&& auto_close
|
||||||
{
|
{
|
||||||
stale_proxies.push(followed);
|
stale_proxies.push(left);
|
||||||
}
|
}
|
||||||
finish_proxy_switch(stale_proxies).await;
|
finish_proxy_switch(stale_proxies).await;
|
||||||
Ok(())
|
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>) {
|
async fn finish_proxy_switch(stale_proxies: Vec<std::string::String>) {
|
||||||
let mihomo = handle::Handle::mihomo();
|
let mihomo = handle::Handle::mihomo();
|
||||||
announce(Refresh::Proxies);
|
announce(Refresh::Proxies);
|
||||||
@@ -384,7 +379,7 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn only_the_first_select_group_follows_a_group() -> Result<()> {
|
fn only_the_first_select_group_follows_an_auto_group() -> Result<()> {
|
||||||
let groups: Vec<serde_yaml_ng::Value> = serde_yaml_ng::from_str(
|
let groups: Vec<serde_yaml_ng::Value> = serde_yaml_ng::from_str(
|
||||||
"
|
"
|
||||||
- { name: GLOBAL, type: select, proxies: [Auto, Proxy, Direct] }
|
- { name: GLOBAL, type: select, proxies: [Auto, Proxy, Direct] }
|
||||||
@@ -398,20 +393,4 @@ mod tests {
|
|||||||
assert_eq!(parent_selector(&groups, "Proxy"), None);
|
assert_eq!(parent_selector(&groups, "Proxy"), None);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rules_reach_the_groups_on_their_current_path() -> Result<()> {
|
|
||||||
let groups: Vec<Proxy> = serde_yaml_ng::from_str(
|
|
||||||
"
|
|
||||||
- { name: Proxy, type: Selector, now: Auto }
|
|
||||||
- { name: Auto, type: URLTest, now: Node }
|
|
||||||
- { name: Spare, type: Selector, now: Node }
|
|
||||||
",
|
|
||||||
)?;
|
|
||||||
let rules: Vec<Rule> = serde_yaml_ng::from_str("[{ proxy: DIRECT }, { proxy: Proxy }]")?;
|
|
||||||
|
|
||||||
assert!(rules_reach(&groups, &rules, "Auto"));
|
|
||||||
assert!(!rules_reach(&groups, &rules, "Spare"));
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
|||||||
cmd::copy_clash_env,
|
cmd::copy_clash_env,
|
||||||
cmd::record_selected_node,
|
cmd::record_selected_node,
|
||||||
cmd::switch_proxy_node,
|
cmd::switch_proxy_node,
|
||||||
|
cmd::follow_proxy_group,
|
||||||
cmd::save_dns_config,
|
cmd::save_dns_config,
|
||||||
cmd::apply_dns_config,
|
cmd::apply_dns_config,
|
||||||
cmd::set_dns_override,
|
cmd::set_dns_override,
|
||||||
|
|||||||
+278
-283
@@ -1,38 +1,21 @@
|
|||||||
use crate::{
|
use crate::utils::dirs::{self, PathBufExec as _};
|
||||||
core::owner_identity::{account_sid, current_user_sid},
|
use anyhow::{Context as _, Result, anyhow};
|
||||||
utils::dirs::PathBufExec as _,
|
|
||||||
};
|
|
||||||
use anyhow::{Context as _, Result, anyhow, bail, ensure};
|
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use quick_xml::escape::escape;
|
use std::fs;
|
||||||
use std::ffi::OsString;
|
use std::os::windows::process::CommandExt as _;
|
||||||
use std::io::ErrorKind;
|
|
||||||
use std::os::windows::ffi::OsStrExt as _;
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use windows::{
|
use std::process::{Command, Output};
|
||||||
Win32::{
|
use windows::Win32::Globalization::{GetACP, GetOEMCP, MULTI_BYTE_TO_WIDE_CHAR_FLAGS, MultiByteToWideChar};
|
||||||
Foundation::{E_ACCESSDENIED, ERROR_FILE_NOT_FOUND},
|
|
||||||
System::{
|
|
||||||
Com::{CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize},
|
|
||||||
TaskScheduler::{
|
|
||||||
ITaskFolder, ITaskService, TASK_CREATE, TASK_CREATION, TASK_LOGON_INTERACTIVE_TOKEN, TASK_UPDATE,
|
|
||||||
TaskScheduler,
|
|
||||||
},
|
|
||||||
Variant::VARIANT,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
core::{BSTR, Error as WindowsError},
|
|
||||||
};
|
|
||||||
use winreg::{
|
|
||||||
RegKey,
|
|
||||||
enums::{HKEY_CURRENT_USER, KEY_QUERY_VALUE, KEY_SET_VALUE},
|
|
||||||
};
|
|
||||||
|
|
||||||
const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
|
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||||
const RUN_VALUE: &str = "Clash Verge Auto Launch";
|
const TASK_NAME_USER: &str = "Clash Verge";
|
||||||
|
const TASK_NAME_ADMIN: &str = "Clash Verge (Admin)";
|
||||||
|
const TASK_XML_DIR: &str = "tasks";
|
||||||
|
const TASK_XML_USER: &str = "clash-verge-task-user.xml";
|
||||||
|
const TASK_XML_ADMIN: &str = "clash-verge-task-admin.xml";
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
#[derive(Clone, Copy)]
|
||||||
enum TaskMode {
|
pub enum TaskMode {
|
||||||
User,
|
User,
|
||||||
Admin,
|
Admin,
|
||||||
}
|
}
|
||||||
@@ -40,8 +23,15 @@ enum TaskMode {
|
|||||||
impl TaskMode {
|
impl TaskMode {
|
||||||
const fn name(self) -> &'static str {
|
const fn name(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
Self::User => "Clash Verge",
|
Self::User => TASK_NAME_USER,
|
||||||
Self::Admin => "Clash Verge (Admin)",
|
Self::Admin => TASK_NAME_ADMIN,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::User => "user",
|
||||||
|
Self::Admin => "admin",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,6 +41,42 @@ impl TaskMode {
|
|||||||
Self::Admin => "HighestAvailable",
|
Self::Admin => "HighestAvailable",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const fn xml_file_name(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::User => TASK_XML_USER,
|
||||||
|
Self::Admin => TASK_XML_ADMIN,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_exe_path() -> Result<PathBuf> {
|
||||||
|
let exe_path = std::env::current_exe().map_err(|e| anyhow!("failed to get exe path: {}", e))?;
|
||||||
|
Ok(exe_path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_task_user_id() -> Result<String> {
|
||||||
|
let username = std::env::var_os("USERNAME")
|
||||||
|
.or_else(|| std::env::var_os("USER"))
|
||||||
|
.ok_or_else(|| anyhow!("failed to get current user name"))?;
|
||||||
|
let username = username.to_string_lossy();
|
||||||
|
let username = username.trim();
|
||||||
|
if username.is_empty() {
|
||||||
|
return Err(anyhow!("current user name is empty"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let domain = std::env::var_os("USERDOMAIN")
|
||||||
|
.or_else(|| std::env::var_os("COMPUTERNAME"))
|
||||||
|
.map(|value| value.to_string_lossy().to_string());
|
||||||
|
|
||||||
|
if let Some(domain) = domain {
|
||||||
|
let domain = domain.trim();
|
||||||
|
if !domain.is_empty() {
|
||||||
|
return Ok(format!("{domain}\\{username}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(username.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_startup_dir() -> Result<PathBuf> {
|
fn get_startup_dir() -> Result<PathBuf> {
|
||||||
@@ -85,23 +111,45 @@ async fn cleanup_legacy_shortcuts() -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_task_xml(mode: TaskMode, user_sid: &str, exe: &Path) -> String {
|
fn task_xml_path(mode: TaskMode) -> Result<PathBuf> {
|
||||||
let exe_path = escape(exe.to_string_lossy());
|
let dir = dirs::app_home_dir()?.join(TASK_XML_DIR);
|
||||||
let run_level = mode.xml_run_level();
|
fs::create_dir_all(&dir).map_err(|e| anyhow!("failed to create task xml dir: {}", e))?;
|
||||||
format!(
|
Ok(dir.join(mode.xml_file_name()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn xml_escape(value: &str) -> String {
|
||||||
|
let mut escaped = String::with_capacity(value.len());
|
||||||
|
for ch in value.chars() {
|
||||||
|
match ch {
|
||||||
|
'&' => escaped.push_str("&"),
|
||||||
|
'<' => escaped.push_str("<"),
|
||||||
|
'>' => escaped.push_str(">"),
|
||||||
|
'"' => escaped.push_str("""),
|
||||||
|
'\'' => escaped.push_str("'"),
|
||||||
|
_ => escaped.push(ch),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
escaped
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_task_xml(mode: TaskMode) -> Result<String> {
|
||||||
|
let exe_path = get_exe_path()?.to_string_lossy().to_string();
|
||||||
|
let exe_path = xml_escape(&exe_path);
|
||||||
|
let user_id = xml_escape(&get_task_user_id()?);
|
||||||
|
Ok(format!(
|
||||||
r#"<?xml version="1.0" encoding="UTF-16"?>
|
r#"<?xml version="1.0" encoding="UTF-16"?>
|
||||||
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
||||||
<Triggers>
|
<Triggers>
|
||||||
<LogonTrigger>
|
<LogonTrigger>
|
||||||
<Enabled>true</Enabled>
|
<Enabled>true</Enabled>
|
||||||
<UserId>{user_sid}</UserId>
|
<UserId>{}</UserId>
|
||||||
</LogonTrigger>
|
</LogonTrigger>
|
||||||
</Triggers>
|
</Triggers>
|
||||||
<Principals>
|
<Principals>
|
||||||
<Principal id="Author">
|
<Principal id="Author">
|
||||||
<UserId>{user_sid}</UserId>
|
<UserId>{}</UserId>
|
||||||
<LogonType>InteractiveToken</LogonType>
|
<LogonType>InteractiveToken</LogonType>
|
||||||
<RunLevel>{run_level}</RunLevel>
|
<RunLevel>{}</RunLevel>
|
||||||
</Principal>
|
</Principal>
|
||||||
</Principals>
|
</Principals>
|
||||||
<Settings>
|
<Settings>
|
||||||
@@ -125,262 +173,209 @@ fn build_task_xml(mode: TaskMode, user_sid: &str, exe: &Path) -> String {
|
|||||||
</Settings>
|
</Settings>
|
||||||
<Actions Context="Author">
|
<Actions Context="Author">
|
||||||
<Exec>
|
<Exec>
|
||||||
<Command>{exe_path}</Command>
|
<Command>{}</Command>
|
||||||
</Exec>
|
</Exec>
|
||||||
</Actions>
|
</Actions>
|
||||||
</Task>
|
</Task>
|
||||||
"#
|
"#,
|
||||||
)
|
user_id,
|
||||||
|
user_id,
|
||||||
|
mode.xml_run_level(),
|
||||||
|
exe_path
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ComApartment;
|
fn encode_utf16le_with_bom(content: &str) -> Vec<u8> {
|
||||||
|
let mut bytes = Vec::with_capacity(2 + content.len() * 2);
|
||||||
|
bytes.extend_from_slice(&[0xFF, 0xFE]);
|
||||||
|
for unit in content.encode_utf16() {
|
||||||
|
bytes.extend_from_slice(&unit.to_le_bytes());
|
||||||
|
}
|
||||||
|
bytes
|
||||||
|
}
|
||||||
|
|
||||||
impl ComApartment {
|
fn write_task_xml(mode: TaskMode) -> Result<PathBuf> {
|
||||||
fn initialize() -> Result<Self> {
|
let task_xml = build_task_xml(mode)?;
|
||||||
unsafe { CoInitializeEx(None, COINIT_MULTITHREADED).ok() }.context("failed to initialize COM")?;
|
let task_xml_path = task_xml_path(mode)?;
|
||||||
Ok(Self)
|
let encoded = encode_utf16le_with_bom(&task_xml);
|
||||||
|
fs::write(&task_xml_path, encoded).map_err(|e| anyhow!("failed to write task xml: {}", e))?;
|
||||||
|
Ok(task_xml_path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode_with_code_page(bytes: &[u8], code_page: u32) -> Option<String> {
|
||||||
|
if bytes.is_empty() {
|
||||||
|
return Some(String::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
let len = bytes.len();
|
||||||
|
if len > i32::MAX as usize {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let required = unsafe { MultiByteToWideChar(code_page, MULTI_BYTE_TO_WIDE_CHAR_FLAGS(0), bytes, None) };
|
||||||
|
|
||||||
|
if required <= 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut wide = vec![0u16; required as usize];
|
||||||
|
let written = unsafe { MultiByteToWideChar(code_page, MULTI_BYTE_TO_WIDE_CHAR_FLAGS(0), bytes, Some(&mut wide)) };
|
||||||
|
|
||||||
|
if written <= 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
wide.truncate(written as usize);
|
||||||
|
Some(String::from_utf16_lossy(&wide))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode_console_output(bytes: &[u8]) -> String {
|
||||||
|
if let Ok(text) = std::str::from_utf8(bytes) {
|
||||||
|
return text.to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
let oem = unsafe { GetOEMCP() };
|
||||||
|
if let Some(text) = decode_with_code_page(bytes, oem) {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
let acp = unsafe { GetACP() };
|
||||||
|
if let Some(text) = decode_with_code_page(bytes, acp) {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
String::from_utf8_lossy(bytes).to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn output_message(output: &Output) -> String {
|
||||||
|
let stdout = decode_console_output(&output.stdout);
|
||||||
|
let stderr = decode_console_output(&output.stderr);
|
||||||
|
let stdout = stdout.trim();
|
||||||
|
let stderr = stderr.trim();
|
||||||
|
|
||||||
|
match (stdout.is_empty(), stderr.is_empty()) {
|
||||||
|
(true, true) => "unknown error".to_string(),
|
||||||
|
(false, true) => stdout.to_string(),
|
||||||
|
(true, false) => stderr.to_string(),
|
||||||
|
(false, false) => format!("{stdout} | {stderr}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for ComApartment {
|
fn schtasks_output(mut cmd: Command) -> Result<Output> {
|
||||||
fn drop(&mut self) {
|
cmd.creation_flags(CREATE_NO_WINDOW)
|
||||||
unsafe { CoUninitialize() };
|
.output()
|
||||||
}
|
.map_err(|e| anyhow!("failed to execute schtasks: {}", e))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
pub fn is_task_enabled(mode: TaskMode) -> Result<bool> {
|
||||||
enum TaskOwner {
|
let output = schtasks_output({
|
||||||
Missing,
|
let mut cmd = Command::new("schtasks");
|
||||||
CurrentUser,
|
cmd.args(["/Query", "/TN", mode.name()]);
|
||||||
OtherUser,
|
cmd
|
||||||
}
|
|
||||||
|
|
||||||
struct ScheduledTasks {
|
|
||||||
folder: ITaskFolder,
|
|
||||||
user_sid: String,
|
|
||||||
// Drop the COM interface before uninitializing the apartment.
|
|
||||||
_com: ComApartment,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ScheduledTasks {
|
|
||||||
fn connect() -> Result<Self> {
|
|
||||||
let com = ComApartment::initialize()?;
|
|
||||||
let service: ITaskService = unsafe { CoCreateInstance(&TaskScheduler, None, CLSCTX_INPROC_SERVER) }
|
|
||||||
.context("failed to open Task Scheduler")?;
|
|
||||||
let empty = VARIANT::default();
|
|
||||||
unsafe { service.Connect(&empty, &empty, &empty, &empty) }.context("failed to connect to Task Scheduler")?;
|
|
||||||
let folder =
|
|
||||||
unsafe { service.GetFolder(&BSTR::from(r"\")) }.context("failed to open the Task Scheduler root folder")?;
|
|
||||||
Ok(Self {
|
|
||||||
folder,
|
|
||||||
user_sid: current_user_sid()?,
|
|
||||||
_com: com,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn owner(&self, mode: TaskMode) -> Result<TaskOwner> {
|
|
||||||
let task = match unsafe { self.folder.GetTask(&BSTR::from(mode.name())) } {
|
|
||||||
Ok(task) => task,
|
|
||||||
Err(error) if task_missing(&error) => return Ok(TaskOwner::Missing),
|
|
||||||
Err(error) => return Err(error).with_context(|| format!("failed to find the {} task", mode.name())),
|
|
||||||
};
|
|
||||||
let principal_sid = (|| {
|
|
||||||
let principal = unsafe { task.Definition()?.Principal()? };
|
|
||||||
let mut user = BSTR::new();
|
|
||||||
unsafe { principal.UserId(&mut user)? };
|
|
||||||
let user = String::try_from(&user)?;
|
|
||||||
if user.starts_with("S-1-") {
|
|
||||||
return Ok(user);
|
|
||||||
}
|
|
||||||
account_sid(&user)
|
|
||||||
})()
|
|
||||||
.with_context(|| format!("failed to identify the owner of the {} task", mode.name()))?;
|
|
||||||
|
|
||||||
Ok(if principal_sid == self.user_sid {
|
|
||||||
TaskOwner::CurrentUser
|
|
||||||
} else {
|
|
||||||
TaskOwner::OtherUser
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn has_current_user_task(&self) -> Result<bool> {
|
|
||||||
let user_task = self.owner(TaskMode::User)?;
|
|
||||||
let admin_task = self.owner(TaskMode::Admin)?;
|
|
||||||
Ok(user_task == TaskOwner::CurrentUser || admin_task == TaskOwner::CurrentUser)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn register(&self, mode: TaskMode, exe: &Path, flags: TASK_CREATION) -> windows::core::Result<()> {
|
|
||||||
let xml = BSTR::from(build_task_xml(mode, &self.user_sid, exe));
|
|
||||||
let empty = VARIANT::default();
|
|
||||||
unsafe {
|
|
||||||
self.folder.RegisterTask(
|
|
||||||
&BSTR::from(mode.name()),
|
|
||||||
&xml,
|
|
||||||
flags.0,
|
|
||||||
&empty,
|
|
||||||
&empty,
|
|
||||||
TASK_LOGON_INTERACTIVE_TOKEN,
|
|
||||||
&empty,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
.map(drop)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn remove(&self, mode: TaskMode) -> Result<()> {
|
|
||||||
match unsafe { self.folder.DeleteTask(&BSTR::from(mode.name()), 0) } {
|
|
||||||
Ok(()) => {
|
|
||||||
logging!(info, Type::Setup, "Removed the {} auto-launch task", mode.name());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
Err(error) if task_missing(&error) => Ok(()),
|
|
||||||
Err(error) => Err(error).with_context(|| format!("failed to remove the {} task", mode.name())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn task_missing(error: &WindowsError) -> bool {
|
|
||||||
error.code() == ERROR_FILE_NOT_FOUND.to_hresult()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write_startup_entry(exe: &Path) -> Result<()> {
|
|
||||||
let mut command = OsString::from("\"");
|
|
||||||
command.push(exe);
|
|
||||||
command.push("\"");
|
|
||||||
ensure!(
|
|
||||||
command.encode_wide().count() <= 260,
|
|
||||||
"the startup command exceeds the Windows Run entry limit"
|
|
||||||
);
|
|
||||||
|
|
||||||
let (key, _) = RegKey::predef(HKEY_CURRENT_USER)
|
|
||||||
.create_subkey_with_flags(RUN_KEY, KEY_SET_VALUE)
|
|
||||||
.context("failed to open the current user's Run key for writing")?;
|
|
||||||
key.set_value(RUN_VALUE, &command)
|
|
||||||
.context("failed to write the per-user startup entry")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn startup_entry_for_removal() -> Result<Option<RegKey>> {
|
|
||||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
|
||||||
let entry = hkcu
|
|
||||||
.open_subkey_with_flags(RUN_KEY, KEY_QUERY_VALUE)
|
|
||||||
.and_then(|key| key.get_raw_value(RUN_VALUE));
|
|
||||||
match entry {
|
|
||||||
Ok(_) => hkcu
|
|
||||||
.open_subkey_with_flags(RUN_KEY, KEY_SET_VALUE)
|
|
||||||
.map(Some)
|
|
||||||
.context("failed to open the current user's Run key for cleanup"),
|
|
||||||
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
|
|
||||||
Err(error) => Err(error).context("failed to inspect the per-user startup entry"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn remove_startup_entry(key: Option<RegKey>) -> Result<()> {
|
|
||||||
if let Some(key) = key {
|
|
||||||
match key.delete_value(RUN_VALUE) {
|
|
||||||
Ok(()) => (),
|
|
||||||
Err(error) if error.kind() == ErrorKind::NotFound => (),
|
|
||||||
Err(error) => return Err(error).context("failed to remove the per-user startup entry"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn enable_auto_launch(
|
|
||||||
tasks: &ScheduledTasks,
|
|
||||||
mode: TaskMode,
|
|
||||||
user_task: TaskOwner,
|
|
||||||
admin_task: TaskOwner,
|
|
||||||
) -> Result<()> {
|
|
||||||
let target = match mode {
|
|
||||||
TaskMode::User => user_task,
|
|
||||||
TaskMode::Admin => admin_task,
|
|
||||||
};
|
|
||||||
|
|
||||||
ensure!(
|
|
||||||
target != TaskOwner::OtherUser,
|
|
||||||
"the {} auto-launch task belongs to another Windows account",
|
|
||||||
mode.name()
|
|
||||||
);
|
|
||||||
let exe = std::env::current_exe().context("failed to get the app executable path")?;
|
|
||||||
let exe = dunce::simplified(&exe);
|
|
||||||
let fallback = startup_entry_for_removal()?;
|
|
||||||
let is_new_task = target == TaskOwner::Missing;
|
|
||||||
let flags = if is_new_task { TASK_CREATE } else { TASK_UPDATE };
|
|
||||||
if let Err(error) = tasks.register(mode, exe, flags) {
|
|
||||||
let can_fallback = mode == TaskMode::User && is_new_task && error.code() == E_ACCESSDENIED;
|
|
||||||
// A task could have appeared after the first lookup and may already launch the app.
|
|
||||||
if can_fallback && !tasks.has_current_user_task()? {
|
|
||||||
write_startup_entry(exe).with_context(|| format!("Task Scheduler denied registration ({error})"))?;
|
|
||||||
logging!(
|
|
||||||
info,
|
|
||||||
Type::Setup,
|
|
||||||
"Using the per-user startup entry after Task Scheduler denied registration"
|
|
||||||
);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
return Err(error).with_context(|| format!("failed to register the {} task", mode.name()));
|
|
||||||
}
|
|
||||||
|
|
||||||
let cleanup = (|| {
|
|
||||||
if mode == TaskMode::Admin && user_task == TaskOwner::CurrentUser {
|
|
||||||
tasks.remove(TaskMode::User)?;
|
|
||||||
}
|
|
||||||
remove_startup_entry(fallback)
|
|
||||||
})();
|
|
||||||
if let Err(error) = cleanup {
|
|
||||||
if is_new_task && let Err(rollback) = tasks.remove(mode) {
|
|
||||||
return Err(error.context(format!(
|
|
||||||
"failed to roll back the new {} task: {rollback:#}",
|
|
||||||
mode.name()
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
return Err(error);
|
|
||||||
}
|
|
||||||
logging!(info, Type::Setup, "Registered the {} auto-launch task", mode.name());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn configure_auto_launch(enabled: bool, mode: TaskMode) -> Result<()> {
|
|
||||||
let tasks = ScheduledTasks::connect()?;
|
|
||||||
let admin_task = tasks.owner(TaskMode::Admin)?;
|
|
||||||
if mode == TaskMode::User && admin_task == TaskOwner::CurrentUser {
|
|
||||||
bail!("run Clash Verge as administrator to manage its existing elevated auto-launch task");
|
|
||||||
}
|
|
||||||
let user_task = tasks.owner(TaskMode::User)?;
|
|
||||||
if enabled {
|
|
||||||
return enable_auto_launch(&tasks, mode, user_task, admin_task);
|
|
||||||
}
|
|
||||||
|
|
||||||
let fallback = startup_entry_for_removal()?;
|
|
||||||
if admin_task == TaskOwner::CurrentUser {
|
|
||||||
tasks.remove(TaskMode::Admin)?;
|
|
||||||
}
|
|
||||||
if user_task == TaskOwner::CurrentUser {
|
|
||||||
tasks.remove(TaskMode::User)?;
|
|
||||||
}
|
|
||||||
remove_startup_entry(fallback)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn set_auto_launch(enabled: bool, is_admin: bool) -> Result<()> {
|
|
||||||
let mode = if is_admin { TaskMode::Admin } else { TaskMode::User };
|
|
||||||
let result = tokio::task::spawn_blocking(move || configure_auto_launch(enabled, mode)).await?;
|
|
||||||
result.map_err(|error| {
|
|
||||||
if mode == TaskMode::User
|
|
||||||
&& error
|
|
||||||
.downcast_ref::<WindowsError>()
|
|
||||||
.is_some_and(|error| error.code() == E_ACCESSDENIED)
|
|
||||||
{
|
|
||||||
error.context("run Clash Verge as administrator to manage its scheduled auto-launch tasks")
|
|
||||||
} else {
|
|
||||||
error
|
|
||||||
}
|
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
if let Err(error) = cleanup_legacy_shortcuts().await {
|
Ok(output.status.success())
|
||||||
logging!(
|
}
|
||||||
warn,
|
|
||||||
Type::Setup,
|
pub fn create_task(mode: TaskMode) -> Result<()> {
|
||||||
"Failed to clean up legacy startup shortcuts: {error:#}"
|
let task_xml_path = write_task_xml(mode)?;
|
||||||
);
|
let output = schtasks_output({
|
||||||
|
let mut cmd = Command::new("schtasks");
|
||||||
|
cmd.args(["/Create", "/TN", mode.name(), "/XML"]);
|
||||||
|
cmd.arg(&task_xml_path);
|
||||||
|
cmd.arg("/F");
|
||||||
|
cmd
|
||||||
|
})?;
|
||||||
|
|
||||||
|
if !output.status.success() {
|
||||||
|
return Err(anyhow!(
|
||||||
|
"failed to create {} task: {}",
|
||||||
|
mode.label(),
|
||||||
|
output_message(&output)
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
logging!(info, Type::Setup, "Created {} auto-launch task", mode.label());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_task(mode: TaskMode) -> Result<()> {
|
||||||
|
let output = schtasks_output({
|
||||||
|
let mut cmd = Command::new("schtasks");
|
||||||
|
cmd.args(["/Delete", "/TN", mode.name(), "/F"]);
|
||||||
|
cmd
|
||||||
|
})?;
|
||||||
|
|
||||||
|
if output.status.success() {
|
||||||
|
logging!(info, Type::Setup, "Removed {} auto-launch task", mode.label());
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
if !is_task_enabled(mode)? {
|
||||||
|
logging!(
|
||||||
|
info,
|
||||||
|
Type::Setup,
|
||||||
|
"{} auto-launch task not found, skipping removal",
|
||||||
|
mode.label()
|
||||||
|
);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
Err(anyhow!(
|
||||||
|
"failed to remove {} task: {}",
|
||||||
|
mode.label(),
|
||||||
|
output_message(&output)
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_auto_launch(is_enable: bool, is_admin: bool) -> Result<()> {
|
||||||
|
let target = if is_admin { TaskMode::Admin } else { TaskMode::User };
|
||||||
|
let other = if is_admin { TaskMode::User } else { TaskMode::Admin };
|
||||||
|
|
||||||
|
if let Err(err) = cleanup_legacy_shortcuts().await {
|
||||||
|
logging!(warn, Type::Setup, "Failed to cleanup legacy startup shortcuts: {err:#}");
|
||||||
|
}
|
||||||
|
|
||||||
|
if is_enable {
|
||||||
|
if is_admin {
|
||||||
|
create_task(target)?;
|
||||||
|
if let Err(err) = remove_task(other) {
|
||||||
|
let _ = remove_task(target);
|
||||||
|
return Err(err);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if is_task_enabled(other)? {
|
||||||
|
return Err(anyhow!(
|
||||||
|
"admin auto-launch task exists; run the app as administrator to remove it before creating a user task"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
create_task(target)?;
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
if is_admin {
|
||||||
|
let mut errors = Vec::new();
|
||||||
|
if let Err(err) = remove_task(TaskMode::User) {
|
||||||
|
errors.push(err);
|
||||||
|
}
|
||||||
|
if let Err(err) = remove_task(TaskMode::Admin) {
|
||||||
|
errors.push(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(err) = errors.into_iter().next() {
|
||||||
|
return Err(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
remove_task(TaskMode::User)?;
|
||||||
|
if is_task_enabled(TaskMode::Admin)? {
|
||||||
|
return Err(anyhow!(
|
||||||
|
"admin auto-launch task exists; run the app as administrator to remove it"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,8 +54,8 @@ import {
|
|||||||
useClashConfigData,
|
useClashConfigData,
|
||||||
useCoreDataStatus,
|
useCoreDataStatus,
|
||||||
useProxiesData,
|
useProxiesData,
|
||||||
useRulesData,
|
|
||||||
} from '@/providers/app-data-context'
|
} from '@/providers/app-data-context'
|
||||||
|
import { followProxyGroup } from '@/services/cmds'
|
||||||
import delayManager from '@/services/delay'
|
import delayManager from '@/services/delay'
|
||||||
import {
|
import {
|
||||||
findCurrentGroupMember,
|
findCurrentGroupMember,
|
||||||
@@ -63,9 +63,7 @@ import {
|
|||||||
isInteractableMember,
|
isInteractableMember,
|
||||||
memberDetails,
|
memberDetails,
|
||||||
resolveMember,
|
resolveMember,
|
||||||
type InteractableProxyMemberOccurrence,
|
|
||||||
type ProxyGroupView,
|
type ProxyGroupView,
|
||||||
type ProxyViewV1,
|
|
||||||
type ResolvedProxyMember,
|
type ResolvedProxyMember,
|
||||||
} from '@/types/proxy-view'
|
} from '@/types/proxy-view'
|
||||||
import { debugLog } from '@/utils/debug'
|
import { debugLog } from '@/utils/debug'
|
||||||
@@ -120,37 +118,7 @@ interface ProxyOption {
|
|||||||
disabled: boolean
|
disabled: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
interface RuleEntry {
|
type OpenSelect = 'group' | 'proxy' | null
|
||||||
group: ProxyGroupView
|
|
||||||
ruleCount: number
|
|
||||||
isDefault: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ChainLevel {
|
|
||||||
group: Pick<ProxyGroupView, 'name' | 'members' | 'fixed'>
|
|
||||||
current?: InteractableProxyMemberOccurrence
|
|
||||||
}
|
|
||||||
|
|
||||||
const SELECTABLE_GROUP_TYPES = ['Selector', 'URLTest', 'Fallback']
|
|
||||||
|
|
||||||
const ENTRY_SELECT = 'entry'
|
|
||||||
const levelSelect = (groupName: string) => `level:${groupName}`
|
|
||||||
|
|
||||||
const resolveChain = (view: ProxyViewV1, entry: ProxyGroupView) => {
|
|
||||||
const levels: ChainLevel[] = []
|
|
||||||
let group: ProxyGroupView | undefined = entry
|
|
||||||
while (group) {
|
|
||||||
const current = findCurrentGroupMember(view, group)
|
|
||||||
levels.push({ group, current })
|
|
||||||
// A load-balance member has no single active node, so the chain ends on it.
|
|
||||||
group =
|
|
||||||
current?.member.kind === 'group' &&
|
|
||||||
SELECTABLE_GROUP_TYPES.includes(current.member.group.type)
|
|
||||||
? current.member.group
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
return levels
|
|
||||||
}
|
|
||||||
|
|
||||||
function convertDelayColor(
|
function convertDelayColor(
|
||||||
delayValue: number,
|
delayValue: number,
|
||||||
@@ -443,13 +411,6 @@ const PersistentSelect = ({
|
|||||||
role="listbox"
|
role="listbox"
|
||||||
aria-labelledby={labelId}
|
aria-labelledby={labelId}
|
||||||
variant="selectedMenu"
|
variant="selectedMenu"
|
||||||
onClick={(event) => {
|
|
||||||
// A disabled option passes its click to the list itself.
|
|
||||||
if (!(event.target as Element).closest('[role="option"]'))
|
|
||||||
return
|
|
||||||
onOpenChange(false)
|
|
||||||
anchorRef.current?.focus({ preventScroll: true })
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
{open && renderOptions()}
|
{open && renderOptions()}
|
||||||
</MenuList>
|
</MenuList>
|
||||||
@@ -462,11 +423,13 @@ const PersistentSelect = ({
|
|||||||
|
|
||||||
interface PersistentProxySelectProps
|
interface PersistentProxySelectProps
|
||||||
extends Omit<PersistentSelectProps, 'displayValue' | 'renderOptions'> {
|
extends Omit<PersistentSelectProps, 'displayValue' | 'renderOptions'> {
|
||||||
view: ProxyViewV1
|
value: string
|
||||||
level: ChainLevel
|
selectedName: string
|
||||||
sortType: ProxySortType
|
groupName: string
|
||||||
latencyTimeout?: number
|
fixed?: string | null
|
||||||
onChange: (groupName: string, proxyName: string, fixed?: string) => void
|
selectedDelay: number
|
||||||
|
options: ProxyOption[]
|
||||||
|
onChange: (value: string) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
const ProxyMenuOption = memo(function ProxyMenuOption({
|
const ProxyMenuOption = memo(function ProxyMenuOption({
|
||||||
@@ -482,7 +445,7 @@ const ProxyMenuOption = memo(function ProxyMenuOption({
|
|||||||
isFixed: boolean
|
isFixed: boolean
|
||||||
fixedProxyInUsed: boolean
|
fixedProxyInUsed: boolean
|
||||||
delay: number
|
delay: number
|
||||||
onChange: (proxyName: string) => void
|
onChange: (value: string) => void
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<MenuItem
|
<MenuItem
|
||||||
@@ -491,7 +454,7 @@ const ProxyMenuOption = memo(function ProxyMenuOption({
|
|||||||
selected={selected}
|
selected={selected}
|
||||||
disabled={option.disabled}
|
disabled={option.disabled}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!option.disabled) onChange(option.name)
|
if (!option.disabled) onChange(option.value)
|
||||||
}}
|
}}
|
||||||
sx={{
|
sx={{
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
@@ -536,49 +499,17 @@ const ProxyMenuOption = memo(function ProxyMenuOption({
|
|||||||
})
|
})
|
||||||
|
|
||||||
const PersistentProxySelect = ({
|
const PersistentProxySelect = ({
|
||||||
view,
|
groupName,
|
||||||
level: { group, current },
|
fixed,
|
||||||
sortType,
|
selectedName,
|
||||||
latencyTimeout,
|
selectedDelay,
|
||||||
|
options,
|
||||||
|
value,
|
||||||
onChange,
|
onChange,
|
||||||
...props
|
...props
|
||||||
}: PersistentProxySelectProps) => {
|
}: PersistentProxySelectProps) => {
|
||||||
const groupName = group.name
|
|
||||||
const fixed = group.fixed
|
|
||||||
const selectedName = current?.member.ref.name ?? ''
|
|
||||||
const value = current ? optionValue(current.memberIndex, current.member) : ''
|
|
||||||
const fixedProxyInUsed = selectedName === fixed
|
const fixedProxyInUsed = selectedName === fixed
|
||||||
|
|
||||||
const delays = useGroupDelays(groupName, current?.member, props.open)
|
|
||||||
const selectedDelay =
|
|
||||||
typeof delays === 'number'
|
|
||||||
? delays
|
|
||||||
: current
|
|
||||||
? delays.of(current.member)
|
|
||||||
: -1
|
|
||||||
|
|
||||||
const options = useMemo(() => {
|
|
||||||
if (typeof delays === 'number') return []
|
|
||||||
const unsorted = group.members.map((memberRef, memberIndex) => {
|
|
||||||
const member = resolveMember(view, memberRef)
|
|
||||||
return {
|
|
||||||
memberIndex,
|
|
||||||
member,
|
|
||||||
value: optionValue(memberIndex, member),
|
|
||||||
name: member.ref.name,
|
|
||||||
disabled: !isInteractableMember(member),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
return sortType === 2
|
|
||||||
? unsorted.sort((a, b) => a.name.localeCompare(b.name))
|
|
||||||
: sortProxyOptions(unsorted, sortType, delays.of, latencyTimeout)
|
|
||||||
}, [delays, group.members, latencyTimeout, sortType, view])
|
|
||||||
|
|
||||||
const handleChange = useCallback(
|
|
||||||
(proxyName: string) => onChange(groupName, proxyName, fixed),
|
|
||||||
[fixed, groupName, onChange],
|
|
||||||
)
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PersistentSelect
|
<PersistentSelect
|
||||||
{...props}
|
{...props}
|
||||||
@@ -626,7 +557,7 @@ const PersistentProxySelect = ({
|
|||||||
isFixed={isFixed}
|
isFixed={isFixed}
|
||||||
fixedProxyInUsed={fixedProxyInUsed}
|
fixedProxyInUsed={fixedProxyInUsed}
|
||||||
delay={delay}
|
delay={delay}
|
||||||
onChange={handleChange}
|
onChange={onChange}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
@@ -640,7 +571,6 @@ export const CurrentProxyCard = () => {
|
|||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const theme = useTheme()
|
const theme = useTheme()
|
||||||
const { proxyView } = useProxiesData()
|
const { proxyView } = useProxiesData()
|
||||||
const { rules } = useRulesData()
|
|
||||||
const { clashConfig } = useClashConfigData()
|
const { clashConfig } = useClashConfigData()
|
||||||
const { refreshProxy } = useAppRefreshers()
|
const { refreshProxy } = useAppRefreshers()
|
||||||
const { isCoreDataPending } = useCoreDataStatus()
|
const { isCoreDataPending } = useCoreDataStatus()
|
||||||
@@ -719,8 +649,8 @@ export const CurrentProxyCard = () => {
|
|||||||
return savedSortType ? (Number(savedSortType) as ProxySortType) : 0
|
return savedSortType ? (Number(savedSortType) as ProxySortType) : 0
|
||||||
})
|
})
|
||||||
|
|
||||||
const [pickedGroupName, setPickedGroupName] = useState('')
|
const [lastGroupName, setLastGroupName] = useState('')
|
||||||
const [openSelect, setOpenSelect] = useState<string | null>(null)
|
const [openSelect, setOpenSelect] = useState<OpenSelect>(null)
|
||||||
const [openSelectMode, setOpenSelectMode] = useState(mode)
|
const [openSelectMode, setOpenSelectMode] = useState(mode)
|
||||||
if (openSelectMode !== mode) {
|
if (openSelectMode !== mode) {
|
||||||
setOpenSelectMode(mode)
|
setOpenSelectMode(mode)
|
||||||
@@ -731,130 +661,151 @@ export const CurrentProxyCard = () => {
|
|||||||
|
|
||||||
const autoCheckInProgressRef = useRef(false)
|
const autoCheckInProgressRef = useRef(false)
|
||||||
|
|
||||||
const entries = useMemo<RuleEntry[]>(() => {
|
const selectableGroups = useMemo(() => {
|
||||||
if (!proxyView) return []
|
if (!proxyView) return []
|
||||||
const isSelectable = (group: ProxyGroupView) =>
|
return proxyView.groups.filter(
|
||||||
!group.hidden && SELECTABLE_GROUP_TYPES.includes(group.type)
|
(group) =>
|
||||||
const ruleCounts = new Map<string, number>()
|
!group.hidden &&
|
||||||
for (const { proxy } of rules) {
|
['Selector', 'URLTest', 'Fallback'].includes(group.type),
|
||||||
ruleCounts.set(proxy, (ruleCounts.get(proxy) ?? 0) + 1)
|
)
|
||||||
}
|
}, [proxyView])
|
||||||
const matchTarget = rules.find(({ type }) => type === 'Match')?.proxy
|
|
||||||
// The view keeps GLOBAL out of `groups`, yet rules may name it.
|
|
||||||
const ruleEntries = [
|
|
||||||
...proxyView.groups,
|
|
||||||
...(proxyView.global ? [proxyView.global] : []),
|
|
||||||
]
|
|
||||||
.filter(isSelectable)
|
|
||||||
.flatMap((group) => {
|
|
||||||
const ruleCount = ruleCounts.get(group.name)
|
|
||||||
return ruleCount
|
|
||||||
? [{ group, ruleCount, isDefault: group.name === matchTarget }]
|
|
||||||
: []
|
|
||||||
})
|
|
||||||
// Rules that failed to load, or that name no selectable group, leave nothing to anchor on.
|
|
||||||
return ruleEntries.length > 0
|
|
||||||
? ruleEntries
|
|
||||||
: proxyView.groups.filter(isSelectable).map((group) => ({
|
|
||||||
group,
|
|
||||||
ruleCount: 0,
|
|
||||||
isDefault: false,
|
|
||||||
}))
|
|
||||||
}, [proxyView, rules])
|
|
||||||
|
|
||||||
const selectedGroupName = useMemo(() => {
|
const selectedGroupName = useMemo(() => {
|
||||||
if (isDirectMode) return 'DIRECT'
|
if (isDirectMode) return 'DIRECT'
|
||||||
if (!proxyView) return ''
|
if (!proxyView) return lastGroupName
|
||||||
if (isGlobalMode) return proxyView.global?.name ?? 'GLOBAL'
|
if (isGlobalMode) return proxyView.global?.name ?? 'GLOBAL'
|
||||||
|
|
||||||
const hasEntry = (name: string | null) =>
|
const hasGroup = (name: string | null) =>
|
||||||
!!name && entries.some(({ group }) => group.name === name)
|
!!name && selectableGroups.some((group) => group.name === name)
|
||||||
if (hasEntry(pickedGroupName)) return pickedGroupName
|
if (hasGroup(lastGroupName)) return lastGroupName
|
||||||
const savedGroup = readProfileScopedItem(STORAGE_KEY_GROUP)
|
const savedGroup = readProfileScopedItem(STORAGE_KEY_GROUP)
|
||||||
if (hasEntry(savedGroup)) return savedGroup!
|
if (hasGroup(savedGroup)) return savedGroup!
|
||||||
|
|
||||||
const defaultEntry =
|
const primaryKeywords = ['auto', 'select', 'proxy', '节点选择', '自动选择']
|
||||||
entries.find(({ isDefault }) => isDefault) ??
|
const primaryGroup =
|
||||||
entries.reduce<RuleEntry | undefined>(
|
selectableGroups.find((group) =>
|
||||||
(most, entry) =>
|
primaryKeywords.some((keyword) =>
|
||||||
most && most.ruleCount >= entry.ruleCount ? most : entry,
|
group.name.toLowerCase().includes(keyword.toLowerCase()),
|
||||||
undefined,
|
),
|
||||||
)
|
) ?? selectableGroups[0]
|
||||||
return defaultEntry?.group.name ?? ''
|
return primaryGroup?.name ?? ''
|
||||||
}, [
|
}, [
|
||||||
entries,
|
|
||||||
isDirectMode,
|
isDirectMode,
|
||||||
isGlobalMode,
|
isGlobalMode,
|
||||||
pickedGroupName,
|
lastGroupName,
|
||||||
proxyView,
|
proxyView,
|
||||||
readProfileScopedItem,
|
readProfileScopedItem,
|
||||||
|
selectableGroups,
|
||||||
|
])
|
||||||
|
// Keep the shown group, auto picks included, until it leaves the profile.
|
||||||
|
if (proxyView && lastGroupName !== selectedGroupName) {
|
||||||
|
setLastGroupName(selectedGroupName)
|
||||||
|
}
|
||||||
|
|
||||||
|
const selectedGroup = useMemo<ProxyGroupView | null>(() => {
|
||||||
|
if (!proxyView || isDirectMode) return null
|
||||||
|
if (isGlobalMode) return proxyView.global
|
||||||
|
return (
|
||||||
|
selectableGroups.find(({ name }) => name === selectedGroupName) ?? null
|
||||||
|
)
|
||||||
|
}, [
|
||||||
|
isDirectMode,
|
||||||
|
isGlobalMode,
|
||||||
|
proxyView,
|
||||||
|
selectableGroups,
|
||||||
|
selectedGroupName,
|
||||||
])
|
])
|
||||||
|
|
||||||
const selectedEntry =
|
const optionsForGroup = useCallback(
|
||||||
isGlobalMode || isDirectMode
|
(group: ProxyGroupView | null): ProxyOption[] =>
|
||||||
? undefined
|
proxyView && group
|
||||||
: entries.find(({ group }) => group.name === selectedGroupName)
|
? group.members.map((memberRef, memberIndex) => {
|
||||||
const selectedGroup = isGlobalMode ? proxyView?.global : selectedEntry?.group
|
const member = resolveMember(proxyView, memberRef)
|
||||||
|
return {
|
||||||
|
memberIndex,
|
||||||
|
member,
|
||||||
|
value: optionValue(memberIndex, member),
|
||||||
|
name: member.ref.name,
|
||||||
|
disabled: !isInteractableMember(member),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
: [],
|
||||||
|
[proxyView],
|
||||||
|
)
|
||||||
|
|
||||||
const levels = useMemo<ChainLevel[]>(() => {
|
const unsortedProxyOptions = useMemo(
|
||||||
if (!proxyView) return []
|
() => optionsForGroup(selectedGroup),
|
||||||
|
[optionsForGroup, selectedGroup],
|
||||||
|
)
|
||||||
|
|
||||||
|
const currentOption = useMemo(() => {
|
||||||
|
if (!proxyView) return undefined
|
||||||
if (isDirectMode) {
|
if (isDirectMode) {
|
||||||
const node =
|
const node =
|
||||||
proxyView.direct == null
|
proxyView.direct == null
|
||||||
? undefined
|
? undefined
|
||||||
: getRecord(proxyView, proxyView.direct)
|
: getRecord(proxyView, proxyView.direct)
|
||||||
return node
|
return node
|
||||||
? [
|
? ({
|
||||||
{
|
memberIndex: 0,
|
||||||
group: { name: 'DIRECT', members: [] },
|
member: {
|
||||||
current: {
|
kind: 'node',
|
||||||
memberIndex: 0,
|
ref: { kind: 'node', name: node.name, recordId: node.recordId },
|
||||||
member: {
|
node,
|
||||||
kind: 'node',
|
|
||||||
ref: {
|
|
||||||
kind: 'node',
|
|
||||||
name: node.name,
|
|
||||||
recordId: node.recordId,
|
|
||||||
},
|
|
||||||
node,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
]
|
} satisfies Pick<ProxyOption, 'memberIndex' | 'member'>)
|
||||||
: []
|
: undefined
|
||||||
}
|
}
|
||||||
return selectedGroup ? resolveChain(proxyView, selectedGroup) : []
|
return selectedGroup
|
||||||
|
? findCurrentGroupMember(proxyView, selectedGroup)
|
||||||
|
: undefined
|
||||||
}, [isDirectMode, proxyView, selectedGroup])
|
}, [isDirectMode, proxyView, selectedGroup])
|
||||||
// A chain deeper than two groups shares one row above the node list so the card stays three rows tall.
|
|
||||||
const levelRows =
|
|
||||||
levels.length > 2
|
|
||||||
? [levels.slice(0, -1), levels.slice(-1)]
|
|
||||||
: levels.map((level) => [level])
|
|
||||||
const leafLevel = levels.at(-1)
|
|
||||||
const leafGroupName = leafLevel?.group.name ?? ''
|
|
||||||
|
|
||||||
const handleGroupChange = useCallback(
|
const handleGroupChange = useCallback(
|
||||||
(newGroupName: string) => {
|
(newGroupName: string) => {
|
||||||
if (isGlobalMode || isDirectMode) return
|
if (isGlobalMode || isDirectMode) return
|
||||||
setPickedGroupName(newGroupName)
|
setLastGroupName(newGroupName)
|
||||||
writeProfileScopedItem(STORAGE_KEY_GROUP, newGroupName)
|
writeProfileScopedItem(STORAGE_KEY_GROUP, newGroupName)
|
||||||
|
void followProxyGroup(newGroupName)
|
||||||
},
|
},
|
||||||
[isDirectMode, isGlobalMode, writeProfileScopedItem],
|
[isDirectMode, isGlobalMode, writeProfileScopedItem],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const handleProxyChange = useCallback(
|
||||||
|
(value: string) => {
|
||||||
|
if (isDirectMode) return
|
||||||
|
const option = unsortedProxyOptions.find(
|
||||||
|
(candidate) => candidate.value === value,
|
||||||
|
)
|
||||||
|
if (!selectedGroup || !option || !isInteractableMember(option.member)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const nextName = option.member.ref.name
|
||||||
|
// The profile selection is the durable source across core restarts and run modes.
|
||||||
|
select(selectedGroup.name, nextName, selectedGroup.fixed!)
|
||||||
|
},
|
||||||
|
[isDirectMode, select, selectedGroup, unsortedProxyOptions],
|
||||||
|
)
|
||||||
|
|
||||||
const goToProxies = useCallback(() => {
|
const goToProxies = useCallback(() => {
|
||||||
navigate('/proxies')
|
navigate('/proxies')
|
||||||
}, [navigate])
|
}, [navigate])
|
||||||
|
|
||||||
const currentMember = leafLevel?.current?.member
|
const currentMember = currentOption?.member
|
||||||
const currentProxy = currentMember ? memberDetails(currentMember) : undefined
|
const currentProxy = currentMember ? memberDetails(currentMember) : undefined
|
||||||
const selectedProxyName = currentMember?.ref.name ?? ''
|
const selectedProxyName = currentMember?.ref.name ?? ''
|
||||||
|
|
||||||
const currentDelay = useGroupDelays(
|
const delays = useGroupDelays(
|
||||||
leafGroupName,
|
selectedGroupName,
|
||||||
currentMember,
|
currentMember,
|
||||||
false,
|
openSelect === 'proxy',
|
||||||
) as number
|
)
|
||||||
|
const currentDelay =
|
||||||
|
typeof delays === 'number'
|
||||||
|
? delays
|
||||||
|
: currentMember
|
||||||
|
? delays.of(currentMember)
|
||||||
|
: -1
|
||||||
|
|
||||||
const signalInfo =
|
const signalInfo =
|
||||||
currentProxy && selectedGroupName
|
currentProxy && selectedGroupName
|
||||||
@@ -869,11 +820,18 @@ export const CurrentProxyCard = () => {
|
|||||||
if (autoCheckInProgressRef.current) return
|
if (autoCheckInProgressRef.current) return
|
||||||
if (isDirectMode) return
|
if (isDirectMode) return
|
||||||
|
|
||||||
const groupName = leafGroupName
|
const groupName = selectedGroupName
|
||||||
const proxyName = selectedProxyName
|
const proxyName = selectedProxyName
|
||||||
const proxyMember = currentMember
|
|
||||||
|
|
||||||
if (!groupName || !proxyMember) return
|
if (!groupName || !proxyName) return
|
||||||
|
|
||||||
|
const proxyMember = currentOption?.member
|
||||||
|
if (!proxyMember || !isInteractableMember(proxyMember)) {
|
||||||
|
debugLog(
|
||||||
|
`[CurrentProxyCard] 自动延迟检测跳过,组: ${groupName}, 节点: ${proxyName} 未找到`,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
autoCheckInProgressRef.current = true
|
autoCheckInProgressRef.current = true
|
||||||
|
|
||||||
@@ -898,7 +856,7 @@ export const CurrentProxyCard = () => {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isDirectMode) return
|
if (isDirectMode) return
|
||||||
if (!autoDelayEnabled) return
|
if (!autoDelayEnabled) return
|
||||||
if (!leafGroupName || !selectedProxyName) return
|
if (!selectedGroupName || !selectedProxyName) return
|
||||||
|
|
||||||
let disposed = false
|
let disposed = false
|
||||||
let intervalTimer: ReturnType<typeof setTimeout> | null = null
|
let intervalTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
@@ -925,7 +883,7 @@ export const CurrentProxyCard = () => {
|
|||||||
}, [
|
}, [
|
||||||
autoDelayIntervalMs,
|
autoDelayIntervalMs,
|
||||||
isDirectMode,
|
isDirectMode,
|
||||||
leafGroupName,
|
selectedGroupName,
|
||||||
selectedProxyName,
|
selectedProxyName,
|
||||||
autoDelayEnabled,
|
autoDelayEnabled,
|
||||||
])
|
])
|
||||||
@@ -936,21 +894,16 @@ export const CurrentProxyCard = () => {
|
|||||||
localStorage.setItem(STORAGE_KEY_SORT_TYPE, newSortType.toString())
|
localStorage.setItem(STORAGE_KEY_SORT_TYPE, newSortType.toString())
|
||||||
}, [sortType])
|
}, [sortType])
|
||||||
|
|
||||||
// The button keeps an open list open, so it tests the list being looked at.
|
|
||||||
const delayLevel =
|
|
||||||
levels.find(({ group }) => openSelect === levelSelect(group.name)) ??
|
|
||||||
leafLevel
|
|
||||||
|
|
||||||
const handleCheckDelay = useLockFn(async () => {
|
const handleCheckDelay = useLockFn(async () => {
|
||||||
if (!proxyView || !delayLevel || isDirectMode) return
|
const groupName = selectedGroupName
|
||||||
const groupName = delayLevel.group.name
|
if (!groupName || isDirectMode) return
|
||||||
|
|
||||||
debugLog(`[CurrentProxyCard] 开始测试所有延迟,组: ${groupName}`)
|
debugLog(`[CurrentProxyCard] 开始测试所有延迟,组: ${groupName}`)
|
||||||
|
|
||||||
const timeout = verge?.default_latency_timeout || 10000
|
const timeout = verge?.default_latency_timeout || 10000
|
||||||
|
|
||||||
const interactable = delayLevel.group.members
|
const interactable = unsortedProxyOptions
|
||||||
.map((member) => resolveMember(proxyView, member))
|
.map(({ member }) => member)
|
||||||
.filter(isInteractableMember)
|
.filter(isInteractableMember)
|
||||||
.filter(({ ref }) => ref.name !== 'DIRECT' && ref.name !== 'REJECT')
|
.filter(({ ref }) => ref.name !== 'DIRECT' && ref.name !== 'REJECT')
|
||||||
|
|
||||||
@@ -972,14 +925,35 @@ export const CurrentProxyCard = () => {
|
|||||||
refreshProxy()
|
refreshProxy()
|
||||||
})
|
})
|
||||||
|
|
||||||
const entrySummary = ({ ruleCount, isDefault }: RuleEntry) => {
|
const nameSortedProxyOptions = useMemo(
|
||||||
const count = t('home.components.currentProxy.labels.ruleCount', {
|
() =>
|
||||||
count: ruleCount,
|
!isDirectMode && openSelect === 'proxy' && sortType === 2
|
||||||
})
|
? [...unsortedProxyOptions].sort((a, b) => a.name.localeCompare(b.name))
|
||||||
return isDefault
|
: unsortedProxyOptions,
|
||||||
? `${t('home.components.currentProxy.labels.defaultRoute')} · ${count}`
|
[isDirectMode, openSelect, sortType, unsortedProxyOptions],
|
||||||
: count
|
)
|
||||||
}
|
const proxyOptions = useMemo(
|
||||||
|
() =>
|
||||||
|
isDirectMode || openSelect !== 'proxy' || typeof delays === 'number'
|
||||||
|
? []
|
||||||
|
: sortType === 2
|
||||||
|
? nameSortedProxyOptions
|
||||||
|
: sortProxyOptions(
|
||||||
|
unsortedProxyOptions,
|
||||||
|
sortType,
|
||||||
|
delays.of,
|
||||||
|
defaultLatencyTimeout!,
|
||||||
|
),
|
||||||
|
[
|
||||||
|
delays,
|
||||||
|
nameSortedProxyOptions,
|
||||||
|
isDirectMode,
|
||||||
|
openSelect,
|
||||||
|
unsortedProxyOptions,
|
||||||
|
sortType,
|
||||||
|
defaultLatencyTimeout,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
const getSortIcon = (): React.ReactElement => {
|
const getSortIcon = (): React.ReactElement => {
|
||||||
switch (sortType) {
|
switch (sortType) {
|
||||||
@@ -1033,7 +1007,7 @@ export const CurrentProxyCard = () => {
|
|||||||
size="small"
|
size="small"
|
||||||
color="inherit"
|
color="inherit"
|
||||||
onClick={handleCheckDelay}
|
onClick={handleCheckDelay}
|
||||||
disabled={isDirectMode || !delayLevel?.group.members.length}
|
disabled={isDirectMode || unsortedProxyOptions.length === 0}
|
||||||
aria-label={t(
|
aria-label={t(
|
||||||
'home.components.currentProxy.actions.refreshDelay',
|
'home.components.currentProxy.actions.refreshDelay',
|
||||||
)}
|
)}
|
||||||
@@ -1143,101 +1117,48 @@ export const CurrentProxyCard = () => {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
|
<Box sx={{ mb: 1.5 }}>
|
||||||
<PersistentSelect
|
<PersistentSelect
|
||||||
label={t(
|
label={t('home.components.currentProxy.labels.group')}
|
||||||
selectedEntry?.ruleCount
|
displayValue={<Typography noWrap>{selectedGroupName}</Typography>}
|
||||||
? 'home.components.currentProxy.labels.ruleTarget'
|
open={openSelect === 'group'}
|
||||||
: 'home.components.currentProxy.labels.group',
|
|
||||||
)}
|
|
||||||
displayValue={
|
|
||||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
|
||||||
<Typography noWrap sx={{ minWidth: 0, flex: 1 }}>
|
|
||||||
{selectedGroupName}
|
|
||||||
</Typography>
|
|
||||||
{!!selectedEntry?.ruleCount && (
|
|
||||||
<Typography
|
|
||||||
variant="caption"
|
|
||||||
sx={{ flexShrink: 0, color: 'text.secondary' }}
|
|
||||||
>
|
|
||||||
{entrySummary(selectedEntry)}
|
|
||||||
</Typography>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
}
|
|
||||||
open={openSelect === ENTRY_SELECT}
|
|
||||||
disabled={isGlobalMode || isDirectMode}
|
disabled={isGlobalMode || isDirectMode}
|
||||||
keepOpenRef={delayButtonRef}
|
keepOpenRef={delayButtonRef}
|
||||||
onOpenChange={(open) => setOpenSelect(open ? ENTRY_SELECT : null)}
|
onOpenChange={(open) => setOpenSelect(open ? 'group' : null)}
|
||||||
renderOptions={() =>
|
renderOptions={() =>
|
||||||
entries.map((entry) => {
|
selectableGroups.map((group) => (
|
||||||
const { group, ruleCount } = entry
|
<MenuItem
|
||||||
const activeName = resolveChain(proxyView!, group).at(-1)
|
key={group.name}
|
||||||
?.current?.member.ref.name
|
role="option"
|
||||||
return (
|
aria-selected={group.name === selectedGroupName}
|
||||||
<MenuItem
|
selected={group.name === selectedGroupName}
|
||||||
key={group.name}
|
onClick={() => handleGroupChange(group.name)}
|
||||||
role="option"
|
>
|
||||||
aria-selected={group.name === selectedGroupName}
|
<Typography noWrap>{group.name}</Typography>
|
||||||
selected={group.name === selectedGroupName}
|
</MenuItem>
|
||||||
onClick={() => handleGroupChange(group.name)}
|
))
|
||||||
sx={{ gap: 1 }}
|
|
||||||
>
|
|
||||||
<Box sx={{ minWidth: 0, flex: 1 }}>
|
|
||||||
<Typography noWrap>{group.name}</Typography>
|
|
||||||
{activeName && (
|
|
||||||
<Typography
|
|
||||||
noWrap
|
|
||||||
component="div"
|
|
||||||
variant="caption"
|
|
||||||
sx={{ color: 'text.secondary' }}
|
|
||||||
>
|
|
||||||
→ {activeName}
|
|
||||||
</Typography>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
{ruleCount > 0 && (
|
|
||||||
<Typography
|
|
||||||
variant="caption"
|
|
||||||
sx={{ flexShrink: 0, color: 'text.secondary' }}
|
|
||||||
>
|
|
||||||
{entrySummary(entry)}
|
|
||||||
</Typography>
|
|
||||||
)}
|
|
||||||
</MenuItem>
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
{levelRows.map((row) => (
|
|
||||||
<Box key={row[0].group.name} sx={{ display: 'flex', gap: 1 }}>
|
|
||||||
{row.map((level) => (
|
|
||||||
<Box key={level.group.name} sx={{ minWidth: 0, flex: 1 }}>
|
|
||||||
<PersistentProxySelect
|
|
||||||
label={t(
|
|
||||||
level === leafLevel
|
|
||||||
? 'home.components.currentProxy.labels.proxy'
|
|
||||||
: 'home.components.currentProxy.labels.group',
|
|
||||||
)}
|
|
||||||
view={proxyView!}
|
|
||||||
level={level}
|
|
||||||
sortType={sortType}
|
|
||||||
latencyTimeout={defaultLatencyTimeout ?? undefined}
|
|
||||||
open={openSelect === levelSelect(level.group.name)}
|
|
||||||
disabled={isDirectMode}
|
|
||||||
keepOpenRef={delayButtonRef}
|
|
||||||
onOpenChange={(open) =>
|
|
||||||
setOpenSelect(
|
|
||||||
open ? levelSelect(level.group.name) : null,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
onChange={select}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
))}
|
|
||||||
</Box>
|
|
||||||
))}
|
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
|
<PersistentProxySelect
|
||||||
|
label={t('home.components.currentProxy.labels.proxy')}
|
||||||
|
groupName={selectedGroupName}
|
||||||
|
fixed={selectedGroup?.fixed}
|
||||||
|
value={
|
||||||
|
currentOption
|
||||||
|
? optionValue(currentOption.memberIndex, currentOption.member)
|
||||||
|
: ''
|
||||||
|
}
|
||||||
|
selectedName={selectedProxyName}
|
||||||
|
selectedDelay={currentDelay}
|
||||||
|
options={proxyOptions}
|
||||||
|
open={openSelect === 'proxy'}
|
||||||
|
disabled={isDirectMode}
|
||||||
|
keepOpenRef={delayButtonRef}
|
||||||
|
onOpenChange={(open) => setOpenSelect(open ? 'proxy' : null)}
|
||||||
|
onChange={handleProxyChange}
|
||||||
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
) : (
|
) : (
|
||||||
<Box sx={{ textAlign: 'center', py: 4 }}>
|
<Box sx={{ textAlign: 'center', py: 4 }}>
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
useEffectEvent,
|
useEffectEvent,
|
||||||
useImperativeHandle,
|
useImperativeHandle,
|
||||||
useMemo,
|
useMemo,
|
||||||
useReducer,
|
|
||||||
useRef,
|
useRef,
|
||||||
useState,
|
useState,
|
||||||
} from 'react'
|
} from 'react'
|
||||||
@@ -20,7 +19,6 @@ import {
|
|||||||
formatTrafficHourMinute,
|
formatTrafficHourMinute,
|
||||||
formatTrafficMinuteSecond,
|
formatTrafficMinuteSecond,
|
||||||
formatTrafficName,
|
formatTrafficName,
|
||||||
isSameTrafficData,
|
|
||||||
} from '@/utils/traffic-sampler'
|
} from '@/utils/traffic-sampler'
|
||||||
|
|
||||||
export interface EnhancedCanvasTrafficGraphRef {
|
export interface EnhancedCanvasTrafficGraphRef {
|
||||||
@@ -74,16 +72,200 @@ const GRAPH_CONFIG = {
|
|||||||
|
|
||||||
const STALE_DATA_THRESHOLD = 2500 // ms without fresh data => drop FPS
|
const STALE_DATA_THRESHOLD = 2500 // ms without fresh data => drop FPS
|
||||||
|
|
||||||
|
// Static sx/style identities keep the emotion cache effective; the remaining
|
||||||
|
// dynamic props (tooltip position, legend colors) stay inline or memoized.
|
||||||
|
const rootSx = {
|
||||||
|
width: '100%',
|
||||||
|
height: '100%',
|
||||||
|
position: 'relative',
|
||||||
|
bgcolor: 'action.hover',
|
||||||
|
borderRadius: 1,
|
||||||
|
cursor: 'pointer',
|
||||||
|
overflow: 'hidden',
|
||||||
|
}
|
||||||
|
|
||||||
|
const canvasStyle = {
|
||||||
|
width: '100%',
|
||||||
|
height: '100%',
|
||||||
|
display: 'block',
|
||||||
|
} as const
|
||||||
|
|
||||||
|
const hoverCanvasStyle = {
|
||||||
|
position: 'absolute',
|
||||||
|
inset: 0,
|
||||||
|
width: '100%',
|
||||||
|
height: '100%',
|
||||||
|
display: 'block',
|
||||||
|
pointerEvents: 'none',
|
||||||
|
} as const
|
||||||
|
|
||||||
|
const overlaySx = {
|
||||||
|
position: 'absolute',
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
bottom: 0,
|
||||||
|
pointerEvents: 'none',
|
||||||
|
}
|
||||||
|
|
||||||
|
const timeRangeBadgeSx = {
|
||||||
|
position: 'absolute',
|
||||||
|
top: 6,
|
||||||
|
left: 40,
|
||||||
|
fontSize: '11px',
|
||||||
|
fontWeight: 'bold',
|
||||||
|
color: 'text.secondary',
|
||||||
|
cursor: 'pointer',
|
||||||
|
pointerEvents: 'all',
|
||||||
|
px: 1,
|
||||||
|
py: 0.5,
|
||||||
|
borderRadius: 0.5,
|
||||||
|
bgcolor: 'rgba(0,0,0,0.05)',
|
||||||
|
'&:hover': {
|
||||||
|
bgcolor: 'rgba(0,0,0,0.1)',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
const legendsSx = {
|
||||||
|
position: 'absolute',
|
||||||
|
top: 6,
|
||||||
|
right: 8,
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
gap: 0.5,
|
||||||
|
}
|
||||||
|
|
||||||
|
const chartStyleHintSx = {
|
||||||
|
position: 'absolute',
|
||||||
|
bottom: 6,
|
||||||
|
right: 8,
|
||||||
|
fontSize: '10px',
|
||||||
|
color: 'text.disabled',
|
||||||
|
opacity: 0.7,
|
||||||
|
}
|
||||||
|
|
||||||
|
const diagnosticsSx = {
|
||||||
|
position: 'absolute',
|
||||||
|
bottom: 6,
|
||||||
|
left: 8,
|
||||||
|
fontSize: '9px',
|
||||||
|
color: 'text.disabled',
|
||||||
|
opacity: 0.6,
|
||||||
|
lineHeight: 1.2,
|
||||||
|
}
|
||||||
|
|
||||||
|
const tooltipTimeSx = { color: 'text.secondary', mb: 0.2 }
|
||||||
|
const tooltipUpSx = { color: 'secondary.main', fontWeight: 500 }
|
||||||
|
const tooltipDownSx = { color: 'primary.main', fontWeight: 500 }
|
||||||
|
|
||||||
|
interface TimeDisplayStrategy {
|
||||||
|
maxLabels: number
|
||||||
|
formatTime: (timestamp: number) => string
|
||||||
|
intervalSeconds: number
|
||||||
|
minPixelDistance: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const TIME_DISPLAY_STRATEGIES: Record<TimeRange, TimeDisplayStrategy> = {
|
||||||
|
1: {
|
||||||
|
maxLabels: 6,
|
||||||
|
formatTime: formatTrafficMinuteSecond,
|
||||||
|
intervalSeconds: 10,
|
||||||
|
minPixelDistance: 35,
|
||||||
|
},
|
||||||
|
5: {
|
||||||
|
maxLabels: 6,
|
||||||
|
formatTime: formatTrafficHourMinute,
|
||||||
|
intervalSeconds: 30,
|
||||||
|
minPixelDistance: 38,
|
||||||
|
},
|
||||||
|
10: {
|
||||||
|
maxLabels: 8,
|
||||||
|
formatTime: formatTrafficHourMinute,
|
||||||
|
intervalSeconds: 60,
|
||||||
|
minPixelDistance: 40,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Per-draw buffers live at module scope: drawing runs synchronously on the
|
||||||
|
// main thread, so slots never overlap a concurrent reader.
|
||||||
|
const yAxisTicks = [
|
||||||
|
{ label: '', y: 0 },
|
||||||
|
{ label: '', y: 0 },
|
||||||
|
{ label: '', y: 0 },
|
||||||
|
]
|
||||||
|
const yAxisTickLabels = new Map<number, string>()
|
||||||
|
const formatYAxisTickLabel = (bytes: number): string => {
|
||||||
|
const cached = yAxisTickLabels.get(bytes)
|
||||||
|
if (cached !== undefined) return cached
|
||||||
|
|
||||||
|
const label =
|
||||||
|
bytes === 0
|
||||||
|
? '0'
|
||||||
|
: bytes < 1024
|
||||||
|
? `${Math.round(bytes)}B`
|
||||||
|
: bytes < 1024 * 1024
|
||||||
|
? `${Math.round(bytes / 1024)}KB`
|
||||||
|
: `${(bytes / (1024 * 1024)).toFixed(1)}MB`
|
||||||
|
if (yAxisTickLabels.size >= 256) yAxisTickLabels.clear()
|
||||||
|
yAxisTickLabels.set(bytes, label)
|
||||||
|
return label
|
||||||
|
}
|
||||||
|
|
||||||
|
const getYAxisTicks = (
|
||||||
|
topValue: number,
|
||||||
|
bottomValue: number,
|
||||||
|
height: number,
|
||||||
|
) => {
|
||||||
|
const padding = GRAPH_CONFIG.padding
|
||||||
|
|
||||||
|
const topY = padding.top + 10
|
||||||
|
const bottomY = height - padding.bottom - 5
|
||||||
|
const middleY = (topY + bottomY) / 2
|
||||||
|
const middleValue = (bottomValue + topValue) / 2
|
||||||
|
|
||||||
|
const [bottomTick, middleTick, topTick] = yAxisTicks
|
||||||
|
bottomTick.label = formatYAxisTickLabel(bottomValue)
|
||||||
|
bottomTick.y = bottomY
|
||||||
|
middleTick.label = formatYAxisTickLabel(middleValue)
|
||||||
|
middleTick.y = middleY
|
||||||
|
topTick.label = formatYAxisTickLabel(topValue)
|
||||||
|
topTick.y = topY
|
||||||
|
|
||||||
|
return yAxisTicks
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TimeAxisPoint {
|
||||||
|
x: number
|
||||||
|
label: string
|
||||||
|
}
|
||||||
|
const timeAxisPoints: TimeAxisPoint[] = []
|
||||||
|
const resetTimeAxisPoints = () => {
|
||||||
|
timeAxisPoints.length = 0
|
||||||
|
}
|
||||||
|
const pushTimeAxisPoint = (x: number, label: string) => {
|
||||||
|
let slot = timeAxisPoints[timeAxisPoints.length]
|
||||||
|
if (!slot) {
|
||||||
|
slot = { x: 0, label: '' }
|
||||||
|
timeAxisPoints.push(slot)
|
||||||
|
}
|
||||||
|
slot.x = x
|
||||||
|
slot.label = label
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gradient stop strings are pure functions of the theme color; the colors
|
||||||
|
// memo builds them once per theme.
|
||||||
|
const GRADIENT_ALPHA_HEX = Math.round(GRAPH_CONFIG.alpha.gradient * 255)
|
||||||
|
.toString(16)
|
||||||
|
.padStart(2, '0')
|
||||||
|
const makeGradientStops = (color: string) => ({
|
||||||
|
start: `${color}${GRADIENT_ALPHA_HEX}`,
|
||||||
|
end: `${color}00`,
|
||||||
|
})
|
||||||
|
|
||||||
interface EnhancedCanvasTrafficGraphProps {
|
interface EnhancedCanvasTrafficGraphProps {
|
||||||
ref?: Ref<EnhancedCanvasTrafficGraphRef>
|
ref?: Ref<EnhancedCanvasTrafficGraphRef>
|
||||||
}
|
}
|
||||||
|
|
||||||
const displayDataReducer = (
|
|
||||||
current: ITrafficDataPoint[],
|
|
||||||
payload: ITrafficDataPoint[],
|
|
||||||
): ITrafficDataPoint[] =>
|
|
||||||
isSameTrafficData(current, payload) ? current : payload
|
|
||||||
|
|
||||||
export const EnhancedCanvasTrafficGraph = memo(
|
export const EnhancedCanvasTrafficGraph = memo(
|
||||||
function EnhancedCanvasTrafficGraph({
|
function EnhancedCanvasTrafficGraph({
|
||||||
ref,
|
ref,
|
||||||
@@ -94,11 +276,9 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
const pause_render_traffic_stats_on_blur =
|
const pause_render_traffic_stats_on_blur =
|
||||||
verge.verge?.pause_render_traffic_stats_on_blur ?? true
|
verge.verge?.pause_render_traffic_stats_on_blur ?? true
|
||||||
|
|
||||||
const { dataPoints, requestRange, samplerStats } =
|
|
||||||
useTrafficGraphDataEnhanced()
|
|
||||||
|
|
||||||
const [timeRange, setTimeRange] = useState<TimeRange>(10)
|
const [timeRange, setTimeRange] = useState<TimeRange>(10)
|
||||||
const [chartStyle, setChartStyle] = useState<'bezier' | 'line'>('bezier')
|
const [chartStyle, setChartStyle] = useState<'bezier' | 'line'>('bezier')
|
||||||
|
const [badgeStats, setBadgeStats] = useState({ points: 0, compressed: 0 })
|
||||||
|
|
||||||
const initialFocusState =
|
const initialFocusState =
|
||||||
typeof document !== 'undefined' ? !document.hidden : true
|
typeof document !== 'undefined' ? !document.hidden : true
|
||||||
@@ -129,66 +309,49 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
const lastDataTimestampRef = useRef<number>(0)
|
const lastDataTimestampRef = useRef<number>(0)
|
||||||
const dataStaleRef = useRef<boolean>(false)
|
const dataStaleRef = useRef<boolean>(false)
|
||||||
|
|
||||||
const [displayData, dispatchDisplayData] = useReducer(
|
// Live snapshot data for the rAF draw path; React state only tracks the
|
||||||
displayDataReducer,
|
// diagnostics badge inputs so steady-state snapshots stop re-rendering.
|
||||||
[],
|
const displayDataRef = useRef<ITrafficDataPoint[]>([])
|
||||||
)
|
const yScaleRef = useRef<{ topValue: number; bottomValue: number }>({
|
||||||
const debounceTimeoutRef = useRef<number | null>(null)
|
topValue: 1024,
|
||||||
|
bottomValue: 0,
|
||||||
|
})
|
||||||
|
|
||||||
const colors = useMemo(
|
const colors = useMemo(() => {
|
||||||
() => ({
|
const base = {
|
||||||
up: theme.palette.secondary.main,
|
up: theme.palette.secondary.main,
|
||||||
down: theme.palette.primary.main,
|
down: theme.palette.primary.main,
|
||||||
grid: theme.palette.divider,
|
grid: theme.palette.divider,
|
||||||
text: theme.palette.text.secondary,
|
text: theme.palette.text.secondary,
|
||||||
background: theme.palette.background.paper,
|
background: theme.palette.background.paper,
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
gradient: {
|
||||||
|
up: makeGradientStops(base.up),
|
||||||
|
down: makeGradientStops(base.down),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}, [theme])
|
||||||
|
|
||||||
|
const legendSx = useMemo(
|
||||||
|
() => ({
|
||||||
|
up: {
|
||||||
|
fontSize: '11px',
|
||||||
|
fontWeight: 'bold',
|
||||||
|
color: colors.up,
|
||||||
|
textAlign: 'right',
|
||||||
|
},
|
||||||
|
down: {
|
||||||
|
fontSize: '11px',
|
||||||
|
fontWeight: 'bold',
|
||||||
|
color: colors.down,
|
||||||
|
textAlign: 'right',
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
[theme],
|
[colors],
|
||||||
)
|
)
|
||||||
|
|
||||||
const updateDisplayData = useCallback((newData: ITrafficDataPoint[]) => {
|
|
||||||
if (debounceTimeoutRef.current !== null) {
|
|
||||||
window.clearTimeout(debounceTimeoutRef.current)
|
|
||||||
}
|
|
||||||
debounceTimeoutRef.current = window.setTimeout(() => {
|
|
||||||
dispatchDisplayData(newData)
|
|
||||||
}, 50)
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
updateDisplayData(dataPoints)
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
if (debounceTimeoutRef.current !== null) {
|
|
||||||
window.clearTimeout(debounceTimeoutRef.current)
|
|
||||||
debounceTimeoutRef.current = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [dataPoints, updateDisplayData])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
requestRange(timeRange)
|
|
||||||
}, [requestRange, timeRange])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (displayData.length === 0) {
|
|
||||||
lastDataTimestampRef.current = 0
|
|
||||||
dataStaleRef.current = false
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const latestTimestamp =
|
|
||||||
displayData[displayData.length - 1]?.timestamp ?? null
|
|
||||||
if (latestTimestamp) {
|
|
||||||
lastDataTimestampRef.current = latestTimestamp
|
|
||||||
const age = Date.now() - latestTimestamp
|
|
||||||
const stale = age > STALE_DATA_THRESHOLD
|
|
||||||
dataStaleRef.current = stale
|
|
||||||
} else {
|
|
||||||
dataStaleRef.current = false
|
|
||||||
}
|
|
||||||
}, [displayData])
|
|
||||||
|
|
||||||
const handleFocusStateChange = useEffectEvent((focused: boolean) => {
|
const handleFocusStateChange = useEffectEvent((focused: boolean) => {
|
||||||
isWindowFocusedRef.current = focused
|
isWindowFocusedRef.current = focused
|
||||||
|
|
||||||
@@ -270,14 +433,9 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
[],
|
[],
|
||||||
)
|
)
|
||||||
|
|
||||||
const yScale = useMemo(
|
|
||||||
() => computeYScale(displayData),
|
|
||||||
[computeYScale, displayData],
|
|
||||||
)
|
|
||||||
|
|
||||||
const handleMouseMove = useCallback(
|
const handleMouseMove = useCallback(
|
||||||
(event: React.MouseEvent<HTMLElement>) => {
|
(event: React.MouseEvent<HTMLElement>) => {
|
||||||
if (displayData.length === 0) return
|
if (displayDataRef.current.length === 0) return
|
||||||
|
|
||||||
pendingMousePositionRef.current = {
|
pendingMousePositionRef.current = {
|
||||||
clientX: event.clientX,
|
clientX: event.clientX,
|
||||||
@@ -294,7 +452,8 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
if (!pendingMousePosition) return
|
if (!pendingMousePosition) return
|
||||||
|
|
||||||
const canvas = canvasRef.current
|
const canvas = canvasRef.current
|
||||||
if (!canvas || displayData.length === 0) return
|
const data = displayDataRef.current
|
||||||
|
if (!canvas || data.length === 0) return
|
||||||
|
|
||||||
const rect = canvas.getBoundingClientRect()
|
const rect = canvas.getBoundingClientRect()
|
||||||
const mouseX = pendingMousePosition.clientX - rect.left
|
const mouseX = pendingMousePosition.clientX - rect.left
|
||||||
@@ -309,11 +468,11 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
0,
|
0,
|
||||||
Math.min(1, relativeMouseX / effectiveWidth),
|
Math.min(1, relativeMouseX / effectiveWidth),
|
||||||
)
|
)
|
||||||
const dataIndex = Math.round(ratio * (displayData.length - 1))
|
const dataIndex = Math.round(ratio * (data.length - 1))
|
||||||
|
|
||||||
if (dataIndex < 0 || dataIndex >= displayData.length) return
|
if (dataIndex < 0 || dataIndex >= data.length) return
|
||||||
|
|
||||||
const dataPoint = displayData[dataIndex]
|
const dataPoint = data[dataIndex]
|
||||||
|
|
||||||
const [upValue, upUnit] = parseTraffic(dataPoint.up)
|
const [upValue, upUnit] = parseTraffic(dataPoint.up)
|
||||||
const [downValue, downUnit] = parseTraffic(dataPoint.down)
|
const [downValue, downUnit] = parseTraffic(dataPoint.down)
|
||||||
@@ -322,7 +481,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
? formatTrafficName(dataPoint.timestamp)
|
? formatTrafficName(dataPoint.timestamp)
|
||||||
: t('home.components.traffic.unknownTime')
|
: t('home.components.traffic.unknownTime')
|
||||||
|
|
||||||
const { topValue: tvH, bottomValue: bvH } = yScale
|
const { topValue: tvH, bottomValue: bvH } = yScaleRef.current
|
||||||
const upY = calculateY(dataPoint.up, rect.height, tvH, bvH)
|
const upY = calculateY(dataPoint.up, rect.height, tvH, bvH)
|
||||||
const downY = calculateY(dataPoint.down, rect.height, tvH, bvH)
|
const downY = calculateY(dataPoint.down, rect.height, tvH, bvH)
|
||||||
const highlightY =
|
const highlightY =
|
||||||
@@ -359,7 +518,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
[displayData, calculateY, yScale, t],
|
[calculateY, t],
|
||||||
)
|
)
|
||||||
|
|
||||||
const handleMouseLeave = useCallback(() => {
|
const handleMouseLeave = useCallback(() => {
|
||||||
@@ -375,45 +534,6 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
)
|
)
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const getYAxisTicks = useCallback(
|
|
||||||
(topValue: number, bottomValue: number, height: number) => {
|
|
||||||
const formatTrafficValue = (bytes: number): string => {
|
|
||||||
if (bytes === 0) return '0'
|
|
||||||
if (bytes < 1024) return `${Math.round(bytes)}B`
|
|
||||||
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)}KB`
|
|
||||||
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`
|
|
||||||
}
|
|
||||||
|
|
||||||
const padding = GRAPH_CONFIG.padding
|
|
||||||
|
|
||||||
const topY = padding.top + 10
|
|
||||||
const bottomY = height - padding.bottom - 5
|
|
||||||
const middleY = (topY + bottomY) / 2
|
|
||||||
const middleValue = (bottomValue + topValue) / 2
|
|
||||||
|
|
||||||
const ticks = [
|
|
||||||
{
|
|
||||||
value: bottomValue,
|
|
||||||
label: formatTrafficValue(bottomValue),
|
|
||||||
y: bottomY,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
value: middleValue,
|
|
||||||
label: formatTrafficValue(middleValue),
|
|
||||||
y: middleY,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
value: topValue,
|
|
||||||
label: formatTrafficValue(topValue),
|
|
||||||
y: topY,
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
return ticks
|
|
||||||
},
|
|
||||||
[],
|
|
||||||
)
|
|
||||||
|
|
||||||
const drawYAxis = useCallback(
|
const drawYAxis = useCallback(
|
||||||
(
|
(
|
||||||
ctx: CanvasRenderingContext2D,
|
ctx: CanvasRenderingContext2D,
|
||||||
@@ -425,8 +545,6 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
const padding = GRAPH_CONFIG.padding
|
const padding = GRAPH_CONFIG.padding
|
||||||
const ticks = getYAxisTicks(topValue, bottomValue, height)
|
const ticks = getYAxisTicks(topValue, bottomValue, height)
|
||||||
|
|
||||||
if (ticks.length === 0) return
|
|
||||||
|
|
||||||
ctx.save()
|
ctx.save()
|
||||||
|
|
||||||
ticks.forEach((tick, index) => {
|
ticks.forEach((tick, index) => {
|
||||||
@@ -470,37 +588,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
|
|
||||||
ctx.restore()
|
ctx.restore()
|
||||||
},
|
},
|
||||||
[colors.grid, colors.text, colors.background, getYAxisTicks],
|
[colors.grid, colors.text, colors.background],
|
||||||
)
|
|
||||||
|
|
||||||
const getTimeDisplayStrategy = useCallback(
|
|
||||||
(timeRangeMinutes: TimeRange) => {
|
|
||||||
switch (timeRangeMinutes) {
|
|
||||||
case 1:
|
|
||||||
return {
|
|
||||||
maxLabels: 6,
|
|
||||||
formatTime: formatTrafficMinuteSecond,
|
|
||||||
intervalSeconds: 10,
|
|
||||||
minPixelDistance: 35,
|
|
||||||
}
|
|
||||||
case 5:
|
|
||||||
return {
|
|
||||||
maxLabels: 6,
|
|
||||||
formatTime: formatTrafficHourMinute,
|
|
||||||
intervalSeconds: 30,
|
|
||||||
minPixelDistance: 38,
|
|
||||||
}
|
|
||||||
case 10:
|
|
||||||
default:
|
|
||||||
return {
|
|
||||||
maxLabels: 8,
|
|
||||||
formatTime: formatTrafficHourMinute,
|
|
||||||
intervalSeconds: 60,
|
|
||||||
minPixelDistance: 40,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[],
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const drawTimeAxis = useCallback(
|
const drawTimeAxis = useCallback(
|
||||||
@@ -516,7 +604,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
const effectiveWidth = width - padding.left - padding.right
|
const effectiveWidth = width - padding.left - padding.right
|
||||||
const timeAxisY = height - padding.bottom + 14
|
const timeAxisY = height - padding.bottom + 14
|
||||||
|
|
||||||
const strategy = getTimeDisplayStrategy(timeRange)
|
const strategy = TIME_DISPLAY_STRATEGIES[timeRange]
|
||||||
|
|
||||||
ctx.save()
|
ctx.save()
|
||||||
ctx.fillStyle = colors.text
|
ctx.fillStyle = colors.text
|
||||||
@@ -533,15 +621,13 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
Math.ceil((data.length * minPixelDistance) / effectiveWidth),
|
Math.ceil((data.length * minPixelDistance) / effectiveWidth),
|
||||||
)
|
)
|
||||||
|
|
||||||
const timePoints: Array<{ index: number; x: number; label: string }> =
|
resetTimeAxisPoints()
|
||||||
[]
|
|
||||||
|
|
||||||
if (data.length > 0 && data[0].timestamp) {
|
if (data.length > 0 && data[0].timestamp) {
|
||||||
timePoints.push({
|
pushTimeAxisPoint(
|
||||||
index: 0,
|
padding.left,
|
||||||
x: padding.left,
|
strategy.formatTime(data[0].timestamp),
|
||||||
label: strategy.formatTime(data[0].timestamp),
|
)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for (
|
for (
|
||||||
@@ -553,41 +639,37 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
if (!point.timestamp) continue
|
if (!point.timestamp) continue
|
||||||
|
|
||||||
const x = padding.left + (i / (data.length - 1)) * effectiveWidth
|
const x = padding.left + (i / (data.length - 1)) * effectiveWidth
|
||||||
timePoints.push({
|
pushTimeAxisPoint(x, strategy.formatTime(point.timestamp))
|
||||||
index: i,
|
|
||||||
x,
|
|
||||||
label: strategy.formatTime(point.timestamp),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.length > 1 && data[data.length - 1].timestamp) {
|
if (data.length > 1 && data[data.length - 1].timestamp) {
|
||||||
const lastX = width - padding.right
|
const lastX = width - padding.right
|
||||||
const lastPoint = timePoints[timePoints.length - 1]
|
const lastPoint = timeAxisPoints[timeAxisPoints.length - 1]
|
||||||
|
|
||||||
if (!lastPoint || lastX - lastPoint.x >= minPixelDistance) {
|
if (!lastPoint || lastX - lastPoint.x >= minPixelDistance) {
|
||||||
timePoints.push({
|
pushTimeAxisPoint(
|
||||||
index: data.length - 1,
|
lastX,
|
||||||
x: lastX,
|
strategy.formatTime(data[data.length - 1].timestamp),
|
||||||
label: strategy.formatTime(data[data.length - 1].timestamp),
|
)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
timePoints.forEach((point, index) => {
|
for (let i = 0; i < timeAxisPoints.length; i++) {
|
||||||
if (index === 0) {
|
const point = timeAxisPoints[i]
|
||||||
|
if (i === 0) {
|
||||||
ctx.textAlign = 'left'
|
ctx.textAlign = 'left'
|
||||||
} else if (index === timePoints.length - 1) {
|
} else if (i === timeAxisPoints.length - 1) {
|
||||||
ctx.textAlign = 'right'
|
ctx.textAlign = 'right'
|
||||||
} else {
|
} else {
|
||||||
ctx.textAlign = 'center'
|
ctx.textAlign = 'center'
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx.fillText(point.label, point.x, timeAxisY)
|
ctx.fillText(point.label, point.x, timeAxisY)
|
||||||
})
|
}
|
||||||
|
|
||||||
ctx.restore()
|
ctx.restore()
|
||||||
},
|
},
|
||||||
[colors.text, timeRange, getTimeDisplayStrategy],
|
[colors.text, timeRange],
|
||||||
)
|
)
|
||||||
|
|
||||||
const drawGrid = useCallback(
|
const drawGrid = useCallback(
|
||||||
@@ -632,6 +714,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
width: number,
|
width: number,
|
||||||
height: number,
|
height: number,
|
||||||
color: string,
|
color: string,
|
||||||
|
gradientStops: { start: string; end: string },
|
||||||
withGradient = false,
|
withGradient = false,
|
||||||
topValue: number,
|
topValue: number,
|
||||||
bottomValue: number,
|
bottomValue: number,
|
||||||
@@ -655,13 +738,8 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
0,
|
0,
|
||||||
height - padding.bottom,
|
height - padding.bottom,
|
||||||
)
|
)
|
||||||
gradient.addColorStop(
|
gradient.addColorStop(0, gradientStops.start)
|
||||||
0,
|
gradient.addColorStop(1, gradientStops.end)
|
||||||
`${color}${Math.round(GRAPH_CONFIG.alpha.gradient * 255)
|
|
||||||
.toString(16)
|
|
||||||
.padStart(2, '0')}`,
|
|
||||||
)
|
|
||||||
gradient.addColorStop(1, `${color}00`)
|
|
||||||
|
|
||||||
ctx.beginPath()
|
ctx.beginPath()
|
||||||
ctx.moveTo(getX(0), getY(0))
|
ctx.moveTo(getX(0), getY(0))
|
||||||
@@ -752,6 +830,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
|
|
||||||
const drawGraph = useCallback(() => {
|
const drawGraph = useCallback(() => {
|
||||||
const canvas = canvasRef.current
|
const canvas = canvasRef.current
|
||||||
|
const displayData = displayDataRef.current
|
||||||
if (!canvas || displayData.length === 0) {
|
if (!canvas || displayData.length === 0) {
|
||||||
clearCanvas(canvasRef.current)
|
clearCanvas(canvasRef.current)
|
||||||
clearCanvas(hoverCanvasRef.current)
|
clearCanvas(hoverCanvasRef.current)
|
||||||
@@ -765,7 +844,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
// Clear using CSS dimensions; context is already scaled by DPR.
|
// Clear using CSS dimensions; context is already scaled by DPR.
|
||||||
ctx.clearRect(0, 0, cssWidth, cssHeight)
|
ctx.clearRect(0, 0, cssWidth, cssHeight)
|
||||||
|
|
||||||
const { topValue, bottomValue } = yScale
|
const { topValue, bottomValue } = yScaleRef.current
|
||||||
|
|
||||||
drawYAxis(ctx, cssWidth, cssHeight, topValue, bottomValue)
|
drawYAxis(ctx, cssWidth, cssHeight, topValue, bottomValue)
|
||||||
|
|
||||||
@@ -780,6 +859,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
cssWidth,
|
cssWidth,
|
||||||
cssHeight,
|
cssHeight,
|
||||||
colors.down,
|
colors.down,
|
||||||
|
colors.gradient.down,
|
||||||
true,
|
true,
|
||||||
topValue,
|
topValue,
|
||||||
bottomValue,
|
bottomValue,
|
||||||
@@ -792,6 +872,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
cssWidth,
|
cssWidth,
|
||||||
cssHeight,
|
cssHeight,
|
||||||
colors.up,
|
colors.up,
|
||||||
|
colors.gradient.up,
|
||||||
true,
|
true,
|
||||||
topValue,
|
topValue,
|
||||||
bottomValue,
|
bottomValue,
|
||||||
@@ -804,9 +885,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
)
|
)
|
||||||
canvas.dataset.perfDraw = String(displayData.at(-1)?.timestamp ?? 0)
|
canvas.dataset.perfDraw = String(displayData.at(-1)?.timestamp ?? 0)
|
||||||
}, [
|
}, [
|
||||||
displayData,
|
|
||||||
colors,
|
colors,
|
||||||
yScale,
|
|
||||||
drawYAxis,
|
drawYAxis,
|
||||||
drawGrid,
|
drawGrid,
|
||||||
drawTimeAxis,
|
drawTimeAxis,
|
||||||
@@ -817,6 +896,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
|
|
||||||
const drawHoverOverlay = useCallback(() => {
|
const drawHoverOverlay = useCallback(() => {
|
||||||
const canvas = hoverCanvasRef.current
|
const canvas = hoverCanvasRef.current
|
||||||
|
const displayData = displayDataRef.current
|
||||||
if (!canvas || displayData.length < 2) {
|
if (!canvas || displayData.length < 2) {
|
||||||
clearCanvas(canvas)
|
clearCanvas(canvas)
|
||||||
return
|
return
|
||||||
@@ -854,7 +934,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
|
|
||||||
ctx.restore()
|
ctx.restore()
|
||||||
}
|
}
|
||||||
}, [displayData, colors, syncCanvasSize, clearCanvas])
|
}, [colors, syncCanvasSize, clearCanvas])
|
||||||
|
|
||||||
const shouldSkipGraphDraw = useCallback(() => {
|
const shouldSkipGraphDraw = useCallback(() => {
|
||||||
if (!isDocumentVisibleRef.current) return true
|
if (!isDocumentVisibleRef.current) return true
|
||||||
@@ -897,6 +977,55 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
})
|
})
|
||||||
}, [drawGraph, drawHoverOverlay, shouldSkipGraphDraw])
|
}, [drawGraph, drawHoverOverlay, shouldSkipGraphDraw])
|
||||||
|
|
||||||
|
const handleSnapshot = useCallback(
|
||||||
|
(message: ITrafficWorkerSnapshotMessage) => {
|
||||||
|
const data = message.dataPoints
|
||||||
|
displayDataRef.current = data
|
||||||
|
yScaleRef.current = computeYScale(data)
|
||||||
|
|
||||||
|
if (data.length === 0) {
|
||||||
|
lastDataTimestampRef.current = 0
|
||||||
|
dataStaleRef.current = false
|
||||||
|
} else {
|
||||||
|
const latestTimestamp = data[data.length - 1]?.timestamp ?? null
|
||||||
|
if (latestTimestamp) {
|
||||||
|
lastDataTimestampRef.current = latestTimestamp
|
||||||
|
const age = Date.now() - latestTimestamp
|
||||||
|
const stale = age > STALE_DATA_THRESHOLD
|
||||||
|
dataStaleRef.current = stale
|
||||||
|
} else {
|
||||||
|
dataStaleRef.current = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
scheduleDrawGraph()
|
||||||
|
// The badge is the only snapshot content that still renders; keeping
|
||||||
|
// its state here confines re-renders to actual badge changes, and the
|
||||||
|
// visibility gate skips hidden-phase renders — the re-prime snapshot
|
||||||
|
// on regaining visibility refreshes it.
|
||||||
|
if (!isDocumentVisibleRef.current) return
|
||||||
|
setBadgeStats((prev) =>
|
||||||
|
prev.points === data.length &&
|
||||||
|
prev.compressed === message.samplerStats.compressedBufferSize
|
||||||
|
? prev
|
||||||
|
: {
|
||||||
|
points: data.length,
|
||||||
|
compressed: message.samplerStats.compressedBufferSize,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
},
|
||||||
|
[computeYScale, scheduleDrawGraph],
|
||||||
|
)
|
||||||
|
|
||||||
|
const { requestRange } = useTrafficGraphDataEnhanced({
|
||||||
|
subscribe: false,
|
||||||
|
onSnapshot: handleSnapshot,
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
requestRange(timeRange)
|
||||||
|
}, [requestRange, timeRange])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
tooltipDataRef.current = tooltipData
|
tooltipDataRef.current = tooltipData
|
||||||
scheduleHoverDraw()
|
scheduleHoverDraw()
|
||||||
@@ -966,119 +1095,36 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Box
|
<Box
|
||||||
sx={{
|
sx={rootSx}
|
||||||
width: '100%',
|
|
||||||
height: '100%',
|
|
||||||
position: 'relative',
|
|
||||||
bgcolor: 'action.hover',
|
|
||||||
borderRadius: 1,
|
|
||||||
cursor: 'pointer',
|
|
||||||
overflow: 'hidden',
|
|
||||||
}}
|
|
||||||
onClick={toggleStyle}
|
onClick={toggleStyle}
|
||||||
onMouseMove={handleMouseMove}
|
onMouseMove={handleMouseMove}
|
||||||
onMouseLeave={handleMouseLeave}
|
onMouseLeave={handleMouseLeave}
|
||||||
>
|
>
|
||||||
<canvas
|
<canvas ref={canvasRef} style={canvasStyle} onClick={toggleStyle} />
|
||||||
ref={canvasRef}
|
|
||||||
style={{
|
|
||||||
width: '100%',
|
|
||||||
height: '100%',
|
|
||||||
display: 'block',
|
|
||||||
}}
|
|
||||||
onClick={toggleStyle}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{tooltipData.visible && (
|
{tooltipData.visible && (
|
||||||
<canvas
|
<canvas ref={hoverCanvasRef} style={hoverCanvasStyle} />
|
||||||
ref={hoverCanvasRef}
|
|
||||||
style={{
|
|
||||||
position: 'absolute',
|
|
||||||
inset: 0,
|
|
||||||
width: '100%',
|
|
||||||
height: '100%',
|
|
||||||
display: 'block',
|
|
||||||
pointerEvents: 'none',
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Box
|
<Box sx={overlaySx}>
|
||||||
sx={{
|
|
||||||
position: 'absolute',
|
|
||||||
top: 0,
|
|
||||||
left: 0,
|
|
||||||
right: 0,
|
|
||||||
bottom: 0,
|
|
||||||
pointerEvents: 'none',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Box
|
<Box
|
||||||
component="div"
|
component="div"
|
||||||
onClick={handleTimeRangeClick}
|
onClick={handleTimeRangeClick}
|
||||||
sx={{
|
sx={timeRangeBadgeSx}
|
||||||
position: 'absolute',
|
|
||||||
top: 6,
|
|
||||||
left: 40,
|
|
||||||
fontSize: '11px',
|
|
||||||
fontWeight: 'bold',
|
|
||||||
color: 'text.secondary',
|
|
||||||
cursor: 'pointer',
|
|
||||||
pointerEvents: 'all',
|
|
||||||
px: 1,
|
|
||||||
py: 0.5,
|
|
||||||
borderRadius: 0.5,
|
|
||||||
bgcolor: 'rgba(0,0,0,0.05)',
|
|
||||||
'&:hover': {
|
|
||||||
bgcolor: 'rgba(0,0,0,0.1)',
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
{getTimeRangeText()}
|
{getTimeRangeText()}
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<Box
|
<Box sx={legendsSx}>
|
||||||
sx={{
|
<Box sx={legendSx.up}>
|
||||||
position: 'absolute',
|
|
||||||
top: 6,
|
|
||||||
right: 8,
|
|
||||||
display: 'flex',
|
|
||||||
flexDirection: 'column',
|
|
||||||
gap: 0.5,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
fontSize: '11px',
|
|
||||||
fontWeight: 'bold',
|
|
||||||
color: colors.up,
|
|
||||||
textAlign: 'right',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{t('home.components.traffic.legends.upload')}
|
{t('home.components.traffic.legends.upload')}
|
||||||
</Box>
|
</Box>
|
||||||
<Box
|
<Box sx={legendSx.down}>
|
||||||
sx={{
|
|
||||||
fontSize: '11px',
|
|
||||||
fontWeight: 'bold',
|
|
||||||
color: colors.down,
|
|
||||||
textAlign: 'right',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{t('home.components.traffic.legends.download')}
|
{t('home.components.traffic.legends.download')}
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<Box
|
<Box sx={chartStyleHintSx}>
|
||||||
sx={{
|
|
||||||
position: 'absolute',
|
|
||||||
bottom: 6,
|
|
||||||
right: 8,
|
|
||||||
fontSize: '10px',
|
|
||||||
color: 'text.disabled',
|
|
||||||
opacity: 0.7,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{t(
|
{t(
|
||||||
chartStyle === 'bezier'
|
chartStyle === 'bezier'
|
||||||
? 'home.components.traffic.chartStyles.smooth'
|
? 'home.components.traffic.chartStyles.smooth'
|
||||||
@@ -1086,20 +1132,10 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<Box
|
<Box sx={diagnosticsSx}>
|
||||||
sx={{
|
|
||||||
position: 'absolute',
|
|
||||||
bottom: 6,
|
|
||||||
left: 8,
|
|
||||||
fontSize: '9px',
|
|
||||||
color: 'text.disabled',
|
|
||||||
opacity: 0.6,
|
|
||||||
lineHeight: 1.2,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{t('home.components.traffic.diagnostics', {
|
{t('home.components.traffic.diagnostics', {
|
||||||
points: displayData.length,
|
points: badgeStats.points,
|
||||||
compressed: samplerStats.compressedBufferSize,
|
compressed: badgeStats.compressed,
|
||||||
fps: GRAPH_CONFIG.targetFPS,
|
fps: GRAPH_CONFIG.targetFPS,
|
||||||
})}
|
})}
|
||||||
</Box>
|
</Box>
|
||||||
@@ -1127,15 +1163,9 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
whiteSpace: 'nowrap',
|
whiteSpace: 'nowrap',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Box sx={{ color: 'text.secondary', mb: 0.2 }}>
|
<Box sx={tooltipTimeSx}>{tooltipData.timestamp}</Box>
|
||||||
{tooltipData.timestamp}
|
<Box sx={tooltipUpSx}>↑ {tooltipData.upSpeed}</Box>
|
||||||
</Box>
|
<Box sx={tooltipDownSx}>↓ {tooltipData.downSpeed}</Box>
|
||||||
<Box sx={{ color: 'secondary.main', fontWeight: 500 }}>
|
|
||||||
↑ {tooltipData.upSpeed}
|
|
||||||
</Box>
|
|
||||||
<Box sx={{ color: 'primary.main', fontWeight: 500 }}>
|
|
||||||
↓ {tooltipData.downSpeed}
|
|
||||||
</Box>
|
|
||||||
</Box>
|
</Box>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@@ -131,6 +131,15 @@ const CompactStatCard = memo(
|
|||||||
// 添加显示名称
|
// 添加显示名称
|
||||||
CompactStatCard.displayName = 'CompactStatCard'
|
CompactStatCard.displayName = 'CompactStatCard'
|
||||||
|
|
||||||
|
// Element identity is stable, so CompactStatCard's memo comparison holds
|
||||||
|
// across per-second parsedData updates.
|
||||||
|
const uploadSpeedIcon = <ArrowUpwardRounded fontSize="small" />
|
||||||
|
const downloadSpeedIcon = <ArrowDownwardRounded fontSize="small" />
|
||||||
|
const activeConnectionsIcon = <LinkRounded fontSize="small" />
|
||||||
|
const uploadedIcon = <CloudUploadRounded fontSize="small" />
|
||||||
|
const downloadedIcon = <CloudDownloadRounded fontSize="small" />
|
||||||
|
const memoryUsageIcon = <MemoryRounded fontSize="small" />
|
||||||
|
|
||||||
const fallbackSx = {
|
const fallbackSx = {
|
||||||
p: 2,
|
p: 2,
|
||||||
minHeight: 200,
|
minHeight: 200,
|
||||||
@@ -252,35 +261,35 @@ export const EnhancedTrafficStats = () => {
|
|||||||
const statCards = useMemo(() => {
|
const statCards = useMemo(() => {
|
||||||
const cards: StatCardProps[] = [
|
const cards: StatCardProps[] = [
|
||||||
{
|
{
|
||||||
icon: <ArrowUpwardRounded fontSize="small" />,
|
icon: uploadSpeedIcon,
|
||||||
title: t('home.components.traffic.metrics.uploadSpeed'),
|
title: t('home.components.traffic.metrics.uploadSpeed'),
|
||||||
value: parsedData.up,
|
value: parsedData.up,
|
||||||
unit: `${parsedData.upUnit}/s`,
|
unit: `${parsedData.upUnit}/s`,
|
||||||
color: 'secondary' as const,
|
color: 'secondary' as const,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
icon: <ArrowDownwardRounded fontSize="small" />,
|
icon: downloadSpeedIcon,
|
||||||
title: t('home.components.traffic.metrics.downloadSpeed'),
|
title: t('home.components.traffic.metrics.downloadSpeed'),
|
||||||
value: parsedData.down,
|
value: parsedData.down,
|
||||||
unit: `${parsedData.downUnit}/s`,
|
unit: `${parsedData.downUnit}/s`,
|
||||||
color: 'primary' as const,
|
color: 'primary' as const,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
icon: <LinkRounded fontSize="small" />,
|
icon: activeConnectionsIcon,
|
||||||
title: t('home.components.traffic.metrics.activeConnections'),
|
title: t('home.components.traffic.metrics.activeConnections'),
|
||||||
value: parsedData.connectionsCount,
|
value: parsedData.connectionsCount,
|
||||||
unit: '',
|
unit: '',
|
||||||
color: 'success' as const,
|
color: 'success' as const,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
icon: <CloudUploadRounded fontSize="small" />,
|
icon: uploadedIcon,
|
||||||
title: t('shared.labels.uploaded'),
|
title: t('shared.labels.uploaded'),
|
||||||
value: parsedData.uploadTotal,
|
value: parsedData.uploadTotal,
|
||||||
unit: parsedData.uploadTotalUnit,
|
unit: parsedData.uploadTotalUnit,
|
||||||
color: 'secondary' as const,
|
color: 'secondary' as const,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
icon: <CloudDownloadRounded fontSize="small" />,
|
icon: downloadedIcon,
|
||||||
title: t('shared.labels.downloaded'),
|
title: t('shared.labels.downloaded'),
|
||||||
value: parsedData.downloadTotal,
|
value: parsedData.downloadTotal,
|
||||||
unit: parsedData.downloadTotalUnit,
|
unit: parsedData.downloadTotalUnit,
|
||||||
@@ -290,7 +299,7 @@ export const EnhancedTrafficStats = () => {
|
|||||||
|
|
||||||
if (displayMemory) {
|
if (displayMemory) {
|
||||||
cards.push({
|
cards.push({
|
||||||
icon: <MemoryRounded fontSize="small" />,
|
icon: memoryUsageIcon,
|
||||||
title: t('home.components.traffic.metrics.memoryUsage'),
|
title: t('home.components.traffic.metrics.memoryUsage'),
|
||||||
value: parsedData.inuse,
|
value: parsedData.inuse,
|
||||||
unit: parsedData.inuseUnit,
|
unit: parsedData.inuseUnit,
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ export const SystemInfoCard = () => {
|
|||||||
try {
|
try {
|
||||||
await patchVerge({ enable_auto_launch: !verge.enable_auto_launch })
|
await patchVerge({ enable_auto_launch: !verge.enable_auto_launch })
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
showNotice.error(err)
|
console.error('切换开机自启动状态失败:', err)
|
||||||
}
|
}
|
||||||
}, [verge, patchVerge])
|
}, [verge, patchVerge])
|
||||||
|
|
||||||
|
|||||||
@@ -42,6 +42,39 @@ const TrafficUnavailableFallback = () => {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Stable identities keep the emotion sx cache effective across the ~1Hz
|
||||||
|
// traffic-driven re-renders of LayoutTraffic.
|
||||||
|
const boxStyle: Pick<BoxProps, 'sx'> = {
|
||||||
|
sx: {
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
whiteSpace: 'nowrap',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
const memoryBoxStyle: Pick<BoxProps, 'sx'> = {
|
||||||
|
sx: {
|
||||||
|
...boxStyle.sx,
|
||||||
|
cursor: 'auto',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
const iconStyle: Pick<SvgIconProps, 'sx'> = {
|
||||||
|
sx: { mr: '8px', fontSize: 16 },
|
||||||
|
}
|
||||||
|
const valStyle: Pick<TypographyProps, 'component' | 'sx'> = {
|
||||||
|
component: 'span',
|
||||||
|
sx: { flex: '1 1 56px', userSelect: 'none', textAlign: 'center' },
|
||||||
|
}
|
||||||
|
const unitStyle: Pick<TypographyProps, 'component' | 'color' | 'sx'> = {
|
||||||
|
component: 'span',
|
||||||
|
color: 'grey.500',
|
||||||
|
sx: {
|
||||||
|
flex: '0 1 27px',
|
||||||
|
userSelect: 'none',
|
||||||
|
fontSize: '12px',
|
||||||
|
textAlign: 'right',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
export const LayoutTraffic = () => {
|
export const LayoutTraffic = () => {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const { verge } = useVerge()
|
const { verge } = useVerge()
|
||||||
@@ -74,31 +107,6 @@ export const LayoutTraffic = () => {
|
|||||||
const [down, downUnit] = parseTraffic(traffic?.down || 0)
|
const [down, downUnit] = parseTraffic(traffic?.down || 0)
|
||||||
const [inuse, inuseUnit] = parseTraffic(memory?.inuse || 0)
|
const [inuse, inuseUnit] = parseTraffic(memory?.inuse || 0)
|
||||||
|
|
||||||
const boxStyle: Pick<BoxProps, 'sx'> = {
|
|
||||||
sx: {
|
|
||||||
display: 'flex',
|
|
||||||
alignItems: 'center',
|
|
||||||
whiteSpace: 'nowrap',
|
|
||||||
},
|
|
||||||
}
|
|
||||||
const iconStyle: Pick<SvgIconProps, 'sx'> = {
|
|
||||||
sx: { mr: '8px', fontSize: 16 },
|
|
||||||
}
|
|
||||||
const valStyle: Pick<TypographyProps, 'component' | 'sx'> = {
|
|
||||||
component: 'span',
|
|
||||||
sx: { flex: '1 1 56px', userSelect: 'none', textAlign: 'center' },
|
|
||||||
}
|
|
||||||
const unitStyle: Pick<TypographyProps, 'component' | 'color' | 'sx'> = {
|
|
||||||
component: 'span',
|
|
||||||
color: 'grey.500',
|
|
||||||
sx: {
|
|
||||||
flex: '0 1 27px',
|
|
||||||
userSelect: 'none',
|
|
||||||
fontSize: '12px',
|
|
||||||
textAlign: 'right',
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ErrorBoundary
|
<ErrorBoundary
|
||||||
FallbackComponent={TrafficUnavailableFallback}
|
FallbackComponent={TrafficUnavailableFallback}
|
||||||
@@ -120,9 +128,6 @@ export const LayoutTraffic = () => {
|
|||||||
<Box
|
<Box
|
||||||
title={`${t('home.components.traffic.metrics.uploadSpeed')}`}
|
title={`${t('home.components.traffic.metrics.uploadSpeed')}`}
|
||||||
{...boxStyle}
|
{...boxStyle}
|
||||||
sx={{
|
|
||||||
...boxStyle.sx,
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<ArrowUpwardRounded
|
<ArrowUpwardRounded
|
||||||
{...iconStyle}
|
{...iconStyle}
|
||||||
@@ -137,9 +142,6 @@ export const LayoutTraffic = () => {
|
|||||||
<Box
|
<Box
|
||||||
title={`${t('home.components.traffic.metrics.downloadSpeed')}`}
|
title={`${t('home.components.traffic.metrics.downloadSpeed')}`}
|
||||||
{...boxStyle}
|
{...boxStyle}
|
||||||
sx={{
|
|
||||||
...boxStyle.sx,
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<ArrowDownwardRounded
|
<ArrowDownwardRounded
|
||||||
{...iconStyle}
|
{...iconStyle}
|
||||||
@@ -154,11 +156,7 @@ export const LayoutTraffic = () => {
|
|||||||
{displayMemory && (
|
{displayMemory && (
|
||||||
<Box
|
<Box
|
||||||
title={`${t('home.components.traffic.metrics.memoryUsage')} `}
|
title={`${t('home.components.traffic.metrics.memoryUsage')} `}
|
||||||
{...boxStyle}
|
{...memoryBoxStyle}
|
||||||
sx={{
|
|
||||||
...boxStyle.sx,
|
|
||||||
cursor: 'auto',
|
|
||||||
}}
|
|
||||||
color={'disabled'}
|
color={'disabled'}
|
||||||
>
|
>
|
||||||
<MemoryRounded {...iconStyle} />
|
<MemoryRounded {...iconStyle} />
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { styled, Box } from '@mui/material'
|
|||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
|
|
||||||
import type { SearchState } from '@/components/base'
|
import type { SearchState } from '@/components/base'
|
||||||
|
import { buildRegex } from '@/utils/search-matcher'
|
||||||
|
|
||||||
const Item = styled(Box)(({ theme: { palette, typography } }) => ({
|
const Item = styled(Box)(({ theme: { palette, typography } }) => ({
|
||||||
padding: '8px 0',
|
padding: '8px 0',
|
||||||
@@ -47,62 +48,74 @@ interface Props {
|
|||||||
searchState?: SearchState
|
searchState?: SearchState
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Compiling per row multiplied by high-frequency log appends; searchState is
|
||||||
|
// React state, so identity reuse is safe until the search inputs change.
|
||||||
|
let highlightRegexCache: { state: SearchState; regex: RegExp | null } | null =
|
||||||
|
null
|
||||||
|
|
||||||
|
const getHighlightRegex = (searchState: SearchState): RegExp | null => {
|
||||||
|
if (highlightRegexCache?.state === searchState)
|
||||||
|
return highlightRegexCache.regex
|
||||||
|
|
||||||
|
const searchText = searchState.text
|
||||||
|
let pattern: string
|
||||||
|
|
||||||
|
if (searchState.useRegularExpression) {
|
||||||
|
try {
|
||||||
|
new RegExp(searchText)
|
||||||
|
pattern = searchText
|
||||||
|
} catch {
|
||||||
|
pattern = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const escaped = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||||
|
pattern = searchState.matchWholeWord ? `\\b${escaped}\\b` : escaped
|
||||||
|
}
|
||||||
|
|
||||||
|
const flags = searchState.matchCase ? 'g' : 'gi'
|
||||||
|
const regex = buildRegex(pattern, flags)
|
||||||
|
highlightRegexCache = { state: searchState, regex }
|
||||||
|
return regex
|
||||||
|
}
|
||||||
|
|
||||||
const LogItem = ({ value, searchState }: Props) => {
|
const LogItem = ({ value, searchState }: Props) => {
|
||||||
const renderHighlightText = (text: string) => {
|
const renderHighlightText = (text: string) => {
|
||||||
if (!searchState?.text.trim()) return text
|
if (!searchState?.text.trim()) return text
|
||||||
|
|
||||||
try {
|
const regex = getHighlightRegex(searchState)
|
||||||
const searchText = searchState.text
|
if (!regex) return text
|
||||||
let pattern: string
|
|
||||||
|
|
||||||
if (searchState.useRegularExpression) {
|
const elements: ReactNode[] = []
|
||||||
try {
|
let lastIndex = 0
|
||||||
new RegExp(searchText)
|
let match: RegExpExecArray | null
|
||||||
pattern = searchText
|
|
||||||
} catch {
|
while ((match = regex.exec(text)) !== null) {
|
||||||
pattern = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
const start = match.index
|
||||||
}
|
const matchText = match[0]
|
||||||
} else {
|
|
||||||
const escaped = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
if (matchText === '') {
|
||||||
pattern = searchState.matchWholeWord ? `\\b${escaped}\\b` : escaped
|
regex.lastIndex += 1
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
const flags = searchState.matchCase ? 'g' : 'gi'
|
if (start > lastIndex) {
|
||||||
const regex = new RegExp(pattern, flags)
|
elements.push(text.slice(lastIndex, start))
|
||||||
const elements: ReactNode[] = []
|
|
||||||
let lastIndex = 0
|
|
||||||
let match: RegExpExecArray | null
|
|
||||||
|
|
||||||
while ((match = regex.exec(text)) !== null) {
|
|
||||||
const start = match.index
|
|
||||||
const matchText = match[0]
|
|
||||||
|
|
||||||
if (matchText === '') {
|
|
||||||
regex.lastIndex += 1
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if (start > lastIndex) {
|
|
||||||
elements.push(text.slice(lastIndex, start))
|
|
||||||
}
|
|
||||||
|
|
||||||
elements.push(
|
|
||||||
<span key={`highlight-${start}`} className="highlight">
|
|
||||||
{matchText}
|
|
||||||
</span>,
|
|
||||||
)
|
|
||||||
|
|
||||||
lastIndex = start + matchText.length
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (lastIndex < text.length) {
|
elements.push(
|
||||||
elements.push(text.slice(lastIndex))
|
<span key={`highlight-${start}`} className="highlight">
|
||||||
}
|
{matchText}
|
||||||
|
</span>,
|
||||||
|
)
|
||||||
|
|
||||||
return elements.length ? elements : text
|
lastIndex = start + matchText.length
|
||||||
} catch {
|
|
||||||
return text
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (lastIndex < text.length) {
|
||||||
|
elements.push(text.slice(lastIndex))
|
||||||
|
}
|
||||||
|
|
||||||
|
return elements.length ? elements : text
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -60,6 +60,23 @@ const ProxyGroupsChain = lazy(() =>
|
|||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const SCROLL_POSITIONS_KEY = 'proxy-scroll-positions'
|
||||||
|
type ScrollPositions = Record<string, number>
|
||||||
|
let scrollPositionsCache: ScrollPositions | undefined
|
||||||
|
|
||||||
|
// Scroll handling runs per frame and is throttled to 500ms writes; keep the
|
||||||
|
// parsed object so saves do not re-read and re-parse localStorage each time.
|
||||||
|
const readScrollPositions = (): ScrollPositions | undefined => {
|
||||||
|
if (scrollPositionsCache) return scrollPositionsCache
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(SCROLL_POSITIONS_KEY)
|
||||||
|
if (raw) scrollPositionsCache = JSON.parse(raw) as ScrollPositions
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error restoring scroll position:', e)
|
||||||
|
}
|
||||||
|
return scrollPositionsCache
|
||||||
|
}
|
||||||
|
|
||||||
function useStableCallback<T extends (...args: any[]) => any>(fn: T): T {
|
function useStableCallback<T extends (...args: any[]) => any>(fn: T): T {
|
||||||
const ref = useRef(fn)
|
const ref = useRef(fn)
|
||||||
ref.current = fn
|
ref.current = fn
|
||||||
@@ -150,13 +167,12 @@ function useProxyRenderState(
|
|||||||
|
|
||||||
const saveScrollPosition = useCallback(
|
const saveScrollPosition = useCallback(
|
||||||
(scrollTop: number) => {
|
(scrollTop: number) => {
|
||||||
const scrollPositions = localStorage.getItem('proxy-scroll-positions')
|
const scrollPositions = readScrollPositions() ?? {}
|
||||||
? JSON.parse(localStorage.getItem('proxy-scroll-positions') ?? '{}')
|
|
||||||
: {}
|
|
||||||
scrollPositions[scrollPositionKey] = scrollTop
|
scrollPositions[scrollPositionKey] = scrollTop
|
||||||
|
scrollPositionsCache = scrollPositions
|
||||||
try {
|
try {
|
||||||
localStorage.setItem(
|
localStorage.setItem(
|
||||||
'proxy-scroll-positions',
|
SCROLL_POSITIONS_KEY,
|
||||||
JSON.stringify(scrollPositions),
|
JSON.stringify(scrollPositions),
|
||||||
)
|
)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -167,15 +183,10 @@ function useProxyRenderState(
|
|||||||
)
|
)
|
||||||
|
|
||||||
const getScrollPosition = useCallback(() => {
|
const getScrollPosition = useCallback(() => {
|
||||||
try {
|
const savedPositions = readScrollPositions()
|
||||||
const savedPositions = localStorage.getItem('proxy-scroll-positions')
|
if (savedPositions) {
|
||||||
if (savedPositions) {
|
const savedPosition = savedPositions[scrollPositionKey]
|
||||||
const positions = JSON.parse(savedPositions)
|
return savedPosition ?? 0
|
||||||
const savedPosition = positions[scrollPositionKey]
|
|
||||||
return savedPosition ?? 0
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Error restoring scroll position:', e)
|
|
||||||
}
|
}
|
||||||
}, [scrollPositionKey])
|
}, [scrollPositionKey])
|
||||||
|
|
||||||
@@ -240,9 +251,13 @@ function ChainProxyGroups(props: {
|
|||||||
|
|
||||||
const rangeExtractor = useCallback(
|
const rangeExtractor = useCallback(
|
||||||
(range: Parameters<typeof defaultRangeExtractor>[0]) => {
|
(range: Parameters<typeof defaultRangeExtractor>[0]) => {
|
||||||
const activeStickyIndex = [...stickyGroupIndexes]
|
let activeStickyIndex: number | undefined
|
||||||
.reverse()
|
for (let i = stickyGroupIndexes.length - 1; i >= 0; i--) {
|
||||||
.find((index) => index <= range.startIndex)
|
if (stickyGroupIndexes[i] <= range.startIndex) {
|
||||||
|
activeStickyIndex = stickyGroupIndexes[i]
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
activeStickyIndexRef.current = activeStickyIndex ?? null
|
activeStickyIndexRef.current = activeStickyIndex ?? null
|
||||||
|
|
||||||
const indexes = defaultRangeExtractor(range)
|
const indexes = defaultRangeExtractor(range)
|
||||||
|
|||||||
@@ -158,9 +158,11 @@ const EMPTY_DATA: ITrafficDataPoint[] = []
|
|||||||
export const useTrafficMonitorEnhanced = (options?: {
|
export const useTrafficMonitorEnhanced = (options?: {
|
||||||
subscribe?: boolean
|
subscribe?: boolean
|
||||||
enabled?: boolean
|
enabled?: boolean
|
||||||
|
onSnapshot?: (message: ITrafficWorkerSnapshotMessage) => void
|
||||||
}) => {
|
}) => {
|
||||||
const subscribeToSnapshots = options?.subscribe ?? true
|
const subscribeToSnapshots = options?.subscribe ?? true
|
||||||
const enabled = options?.enabled ?? true
|
const enabled = options?.enabled ?? true
|
||||||
|
const onSnapshot = options?.onSnapshot
|
||||||
const isVisible = useVisibility()
|
const isVisible = useVisibility()
|
||||||
const [latestSnapshot, setLatestSnapshot] = useState<{
|
const [latestSnapshot, setLatestSnapshot] = useState<{
|
||||||
dataPoints: ITrafficDataPoint[]
|
dataPoints: ITrafficDataPoint[]
|
||||||
@@ -174,6 +176,8 @@ export const useTrafficMonitorEnhanced = (options?: {
|
|||||||
const currentRangeRef = useRef<number>(WORKER_CONFIG.defaultRangeMinutes)
|
const currentRangeRef = useRef<number>(WORKER_CONFIG.defaultRangeMinutes)
|
||||||
const isVisibleRef = useRef(isVisible)
|
const isVisibleRef = useRef(isVisible)
|
||||||
isVisibleRef.current = isVisible
|
isVisibleRef.current = isVisible
|
||||||
|
const onSnapshotRef = useRef(onSnapshot)
|
||||||
|
onSnapshotRef.current = onSnapshot
|
||||||
|
|
||||||
// 注册引用计数与Worker生命周期
|
// 注册引用计数与Worker生命周期
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -186,9 +190,12 @@ export const useTrafficMonitorEnhanced = (options?: {
|
|||||||
client.start(currentRangeRef.current)
|
client.start(currentRangeRef.current)
|
||||||
|
|
||||||
let unsubscribe: (() => void) | undefined
|
let unsubscribe: (() => void) | undefined
|
||||||
if (subscribeToSnapshots) {
|
if (subscribeToSnapshots || onSnapshot) {
|
||||||
unsubscribe = client.onSnapshot((message) => {
|
unsubscribe = client.onSnapshot((message) => {
|
||||||
if (!isVisibleRef.current) return
|
// onSnapshot is the always-live channel (ignores visibility); the
|
||||||
|
// state mirror below keeps its original always-latest contract.
|
||||||
|
onSnapshotRef.current?.(message)
|
||||||
|
if (!subscribeToSnapshots || !isVisibleRef.current) return
|
||||||
setLatestSnapshot({
|
setLatestSnapshot({
|
||||||
dataPoints: message.dataPoints,
|
dataPoints: message.dataPoints,
|
||||||
samplerStats: message.samplerStats,
|
samplerStats: message.samplerStats,
|
||||||
@@ -203,14 +210,14 @@ export const useTrafficMonitorEnhanced = (options?: {
|
|||||||
client.stop()
|
client.stop()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [enabled, subscribeToSnapshots])
|
}, [enabled, subscribeToSnapshots, onSnapshot])
|
||||||
|
|
||||||
// Re-prime snapshot ingestion after every visible transition
|
// Re-prime snapshot ingestion after every visible transition
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (enabled && subscribeToSnapshots && isVisible) {
|
if (enabled && isVisible && (subscribeToSnapshots || onSnapshot)) {
|
||||||
clientRef.current?.requestSnapshot()
|
clientRef.current?.requestSnapshot()
|
||||||
}
|
}
|
||||||
}, [enabled, subscribeToSnapshots, isVisible])
|
}, [enabled, subscribeToSnapshots, onSnapshot, isVisible])
|
||||||
|
|
||||||
// 添加流量数据
|
// 添加流量数据
|
||||||
const appendData = useCallback(
|
const appendData = useCallback(
|
||||||
@@ -244,8 +251,12 @@ export const useTrafficMonitorEnhanced = (options?: {
|
|||||||
/**
|
/**
|
||||||
* 图表数据Hook
|
* 图表数据Hook
|
||||||
*/
|
*/
|
||||||
export const useTrafficGraphDataEnhanced = () => {
|
export const useTrafficGraphDataEnhanced = (options?: {
|
||||||
const { graphData, samplerStats } = useTrafficMonitorEnhanced()
|
subscribe?: boolean
|
||||||
|
enabled?: boolean
|
||||||
|
onSnapshot?: (message: ITrafficWorkerSnapshotMessage) => void
|
||||||
|
}) => {
|
||||||
|
const { graphData, samplerStats } = useTrafficMonitorEnhanced(options)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...graphData,
|
...graphData,
|
||||||
|
|||||||
@@ -98,9 +98,6 @@
|
|||||||
"directMode": "الوضع المباشر",
|
"directMode": "الوضع المباشر",
|
||||||
"group": "Group",
|
"group": "Group",
|
||||||
"proxy": "Proxy",
|
"proxy": "Proxy",
|
||||||
"ruleTarget": "Rule Target",
|
|
||||||
"defaultRoute": "Default",
|
|
||||||
"ruleCount": "{{count}} rules",
|
|
||||||
"noActiveNode": "No active proxy node"
|
"noActiveNode": "No active proxy node"
|
||||||
},
|
},
|
||||||
"status": {
|
"status": {
|
||||||
|
|||||||
@@ -423,7 +423,7 @@
|
|||||||
},
|
},
|
||||||
"tooltips": {
|
"tooltips": {
|
||||||
"autoCloseConnections": "إنهاء الاتصالات القائمة عند تغيير اختيار مجموعة الوكيل أو وضع الوكيل",
|
"autoCloseConnections": "إنهاء الاتصالات القائمة عند تغيير اختيار مجموعة الوكيل أو وضع الوكيل",
|
||||||
"autoSwitchSelectorGroup": "في وضع القواعد، عند اختيار عقدة في مجموعة لا تمر بها حركة القواعد يتم أيضًا تحويل أول مجموعة select تحتوي عليها إلى تلك المجموعة",
|
"autoSwitchSelectorGroup": "في وضع القواعد، عند اختيار عقدة في مجموعة url-test أو fallback يتم أيضًا تحويل أول مجموعة select تحتوي عليها إلى تلك المجموعة",
|
||||||
"enableBuiltinEnhanced": "معالجة توافق ملف التكوين",
|
"enableBuiltinEnhanced": "معالجة توافق ملف التكوين",
|
||||||
"autoDelayDetection": "يختبر زمن استجابة العقدة الحالية على نحو دوري في الخلفية",
|
"autoDelayDetection": "يختبر زمن استجابة العقدة الحالية على نحو دوري في الخلفية",
|
||||||
"defaultLatencyTest": "يُستخدم فقط لاختبار طلب HTTP العميل. لن يؤثر على ملف التكوين"
|
"defaultLatencyTest": "يُستخدم فقط لاختبار طلب HTTP العميل. لن يؤثر على ملف التكوين"
|
||||||
|
|||||||
@@ -98,9 +98,6 @@
|
|||||||
"directMode": "Direktmodus",
|
"directMode": "Direktmodus",
|
||||||
"group": "Proxy-Gruppe",
|
"group": "Proxy-Gruppe",
|
||||||
"proxy": "Knoten",
|
"proxy": "Knoten",
|
||||||
"ruleTarget": "Regelziel",
|
|
||||||
"defaultRoute": "Standard",
|
|
||||||
"ruleCount": "{{count}} Regeln",
|
|
||||||
"noActiveNode": "Kein aktiver Proxy-Knoten"
|
"noActiveNode": "Kein aktiver Proxy-Knoten"
|
||||||
},
|
},
|
||||||
"status": {
|
"status": {
|
||||||
|
|||||||
@@ -423,7 +423,7 @@
|
|||||||
},
|
},
|
||||||
"tooltips": {
|
"tooltips": {
|
||||||
"autoCloseConnections": "Wenn der ausgewählte Knoten in der Proxy-Gruppe oder der Proxy-Modus geändert wird, werden die bestehenden Verbindungen geschlossen.",
|
"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 Gruppe gewählt, die kein Regelverkehr erreicht, wechselt auch die erste select-Gruppe, die diese Gruppe enthält, auf diese Gruppe.",
|
"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",
|
"enableBuiltinEnhanced": "Kompatibilitätsbehandlung der Konfigurationsdatei",
|
||||||
"autoDelayDetection": "Überprüft regelmäßig im Hintergrund die Latenz des aktuellen Knotens",
|
"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."
|
"defaultLatencyTest": "Dies wird nur für HTTP-Client-Anfragentests verwendet und hat keine Auswirkungen auf die Konfigurationsdatei."
|
||||||
|
|||||||
@@ -98,9 +98,6 @@
|
|||||||
"directMode": "Direct Mode",
|
"directMode": "Direct Mode",
|
||||||
"group": "Group",
|
"group": "Group",
|
||||||
"proxy": "Proxy",
|
"proxy": "Proxy",
|
||||||
"ruleTarget": "Rule Target",
|
|
||||||
"defaultRoute": "Default",
|
|
||||||
"ruleCount": "{{count}} rules",
|
|
||||||
"noActiveNode": "No active proxy node"
|
"noActiveNode": "No active proxy node"
|
||||||
},
|
},
|
||||||
"status": {
|
"status": {
|
||||||
|
|||||||
@@ -423,7 +423,7 @@
|
|||||||
},
|
},
|
||||||
"tooltips": {
|
"tooltips": {
|
||||||
"autoCloseConnections": "Terminate established connections when the proxy group selection or proxy mode changes",
|
"autoCloseConnections": "Terminate established connections when the proxy group selection or proxy mode changes",
|
||||||
"autoSwitchSelectorGroup": "In rule mode, selecting a node in a group that rule traffic does not reach also switches the first select group containing it to that group",
|
"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",
|
"enableBuiltinEnhanced": "Compatibility handling for the configuration file",
|
||||||
"autoDelayDetection": "Periodically test the current node latency in the background",
|
"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"
|
"defaultLatencyTest": "Used for HTTP client request testing only and won't make a difference to the configuration file"
|
||||||
|
|||||||
@@ -98,9 +98,6 @@
|
|||||||
"directMode": "Direct Mode",
|
"directMode": "Direct Mode",
|
||||||
"group": "Grupo de proxy",
|
"group": "Grupo de proxy",
|
||||||
"proxy": "Nodo",
|
"proxy": "Nodo",
|
||||||
"ruleTarget": "Destino de reglas",
|
|
||||||
"defaultRoute": "Predeterminado",
|
|
||||||
"ruleCount": "{{count}} reglas",
|
|
||||||
"noActiveNode": "No hay nodos de proxy activos"
|
"noActiveNode": "No hay nodos de proxy activos"
|
||||||
},
|
},
|
||||||
"status": {
|
"status": {
|
||||||
|
|||||||
@@ -423,7 +423,7 @@
|
|||||||
},
|
},
|
||||||
"tooltips": {
|
"tooltips": {
|
||||||
"autoCloseConnections": "Cierra las conexiones establecidas cuando se cambia el nodo seleccionado en el grupo de proxy o el modo de proxy.",
|
"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 al que no llega tráfico de reglas, el primer grupo select que lo contiene también cambia a ese grupo.",
|
"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",
|
"enableBuiltinEnhanced": "Procesamiento de compatibilidad de archivos de configuración",
|
||||||
"autoDelayDetection": "Prueba periódicamente la latencia del nodo actual en segundo plano",
|
"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."
|
"defaultLatencyTest": "Solo se utiliza para pruebas de solicitudes de clientes HTTP y no afectará al archivo de configuración."
|
||||||
|
|||||||
@@ -98,9 +98,6 @@
|
|||||||
"directMode": "حالت مستقیم",
|
"directMode": "حالت مستقیم",
|
||||||
"group": "Group",
|
"group": "Group",
|
||||||
"proxy": "Proxy",
|
"proxy": "Proxy",
|
||||||
"ruleTarget": "Rule Target",
|
|
||||||
"defaultRoute": "Default",
|
|
||||||
"ruleCount": "{{count}} rules",
|
|
||||||
"noActiveNode": "No active proxy node"
|
"noActiveNode": "No active proxy node"
|
||||||
},
|
},
|
||||||
"status": {
|
"status": {
|
||||||
|
|||||||
@@ -423,7 +423,7 @@
|
|||||||
},
|
},
|
||||||
"tooltips": {
|
"tooltips": {
|
||||||
"autoCloseConnections": "اتصالات برقرار شده را هنگام تغییر انتخاب گروه پروکسی یا حالت پروکسی خاتمه دهید",
|
"autoCloseConnections": "اتصالات برقرار شده را هنگام تغییر انتخاب گروه پروکسی یا حالت پروکسی خاتمه دهید",
|
||||||
"autoSwitchSelectorGroup": "در حالت قانون، با انتخاب یک گره در گروهی که ترافیک قوانین از آن عبور نمیکند، اولین گروه select شامل آن نیز به همان گروه تغییر میکند",
|
"autoSwitchSelectorGroup": "در حالت قانون، با انتخاب یک گره در گروه url-test یا fallback، اولین گروه select شامل آن نیز به همان گروه تغییر میکند",
|
||||||
"enableBuiltinEnhanced": "مدیریت سازگاری برای فایل پیکربندی",
|
"enableBuiltinEnhanced": "مدیریت سازگاری برای فایل پیکربندی",
|
||||||
"autoDelayDetection": "بهصورت دورهای تأخیر گره فعلی را در پسزمینه آزمایش میکند",
|
"autoDelayDetection": "بهصورت دورهای تأخیر گره فعلی را در پسزمینه آزمایش میکند",
|
||||||
"defaultLatencyTest": "فقط برای تست درخواستهای کلاینت HTTP استفاده میشود و بر فایل پیکربندی تأثیری نخواهد داشت"
|
"defaultLatencyTest": "فقط برای تست درخواستهای کلاینت HTTP استفاده میشود و بر فایل پیکربندی تأثیری نخواهد داشت"
|
||||||
|
|||||||
@@ -98,9 +98,6 @@
|
|||||||
"directMode": "Mode Langsung",
|
"directMode": "Mode Langsung",
|
||||||
"group": "Group",
|
"group": "Group",
|
||||||
"proxy": "Proxy",
|
"proxy": "Proxy",
|
||||||
"ruleTarget": "Rule Target",
|
|
||||||
"defaultRoute": "Default",
|
|
||||||
"ruleCount": "{{count}} rules",
|
|
||||||
"noActiveNode": "No active proxy node"
|
"noActiveNode": "No active proxy node"
|
||||||
},
|
},
|
||||||
"status": {
|
"status": {
|
||||||
|
|||||||
@@ -423,7 +423,7 @@
|
|||||||
},
|
},
|
||||||
"tooltips": {
|
"tooltips": {
|
||||||
"autoCloseConnections": "Hentikan koneksi yang sudah ada saat pemilihan grup proksi atau mode proksi berubah",
|
"autoCloseConnections": "Hentikan koneksi yang sudah ada saat pemilihan grup proksi atau mode proksi berubah",
|
||||||
"autoSwitchSelectorGroup": "Dalam mode aturan, memilih node di grup yang tidak dilalui lalu lintas aturan juga mengalihkan grup select pertama yang memuatnya ke grup tersebut",
|
"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",
|
"enableBuiltinEnhanced": "Penanganan kompatibilitas untuk file konfigurasi",
|
||||||
"autoDelayDetection": "Secara berkala menguji latensi node saat ini di latar belakang",
|
"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"
|
"defaultLatencyTest": "Digunakan hanya untuk pengujian permintaan klien HTTP dan tidak akan mempengaruhi file konfigurasi"
|
||||||
|
|||||||
@@ -98,9 +98,6 @@
|
|||||||
"directMode": "直接接続モード",
|
"directMode": "直接接続モード",
|
||||||
"group": "プロキシグループ",
|
"group": "プロキシグループ",
|
||||||
"proxy": "ノード",
|
"proxy": "ノード",
|
||||||
"ruleTarget": "ルールの宛先",
|
|
||||||
"defaultRoute": "デフォルト",
|
|
||||||
"ruleCount": "{{count}} 件のルール",
|
|
||||||
"noActiveNode": "アクティブなプロキシノードがありません。"
|
"noActiveNode": "アクティブなプロキシノードがありません。"
|
||||||
},
|
},
|
||||||
"status": {
|
"status": {
|
||||||
|
|||||||
@@ -423,7 +423,7 @@
|
|||||||
},
|
},
|
||||||
"tooltips": {
|
"tooltips": {
|
||||||
"autoCloseConnections": "プロキシグループで選択されたノードまたはプロキシモードが変更されたときに、既存の接続を閉じます。",
|
"autoCloseConnections": "プロキシグループで選択されたノードまたはプロキシモードが変更されたときに、既存の接続を閉じます。",
|
||||||
"autoSwitchSelectorGroup": "ルールモードで、ルールの通信が通らないグループのノードを選択すると、そのグループを含む最初の select グループも当該グループに切り替えます。",
|
"autoSwitchSelectorGroup": "ルールモードで url-test または fallback グループのノードを選択すると、そのグループを含む最初の select グループも当該グループに切り替えます。",
|
||||||
"enableBuiltinEnhanced": "設定ファイルの互換性処理",
|
"enableBuiltinEnhanced": "設定ファイルの互換性処理",
|
||||||
"autoDelayDetection": "バックグラウンドで現在のノードのレイテンシーを定期的にテストします",
|
"autoDelayDetection": "バックグラウンドで現在のノードのレイテンシーを定期的にテストします",
|
||||||
"defaultLatencyTest": "HTTPクライアントリクエストテストにのみ使用され、設定ファイルには影響しません。"
|
"defaultLatencyTest": "HTTPクライアントリクエストテストにのみ使用され、設定ファイルには影響しません。"
|
||||||
|
|||||||
@@ -98,9 +98,6 @@
|
|||||||
"directMode": "직접 모드",
|
"directMode": "직접 모드",
|
||||||
"group": "그룹",
|
"group": "그룹",
|
||||||
"proxy": "프록시",
|
"proxy": "프록시",
|
||||||
"ruleTarget": "규칙 대상",
|
|
||||||
"defaultRoute": "기본",
|
|
||||||
"ruleCount": "규칙 {{count}}개",
|
|
||||||
"noActiveNode": "활성 프록시 노드 없음"
|
"noActiveNode": "활성 프록시 노드 없음"
|
||||||
},
|
},
|
||||||
"status": {
|
"status": {
|
||||||
|
|||||||
@@ -423,7 +423,7 @@
|
|||||||
},
|
},
|
||||||
"tooltips": {
|
"tooltips": {
|
||||||
"autoCloseConnections": "프록시 그룹 선택 또는 프록시 모드 변경 시 기존 연결을 종료합니다",
|
"autoCloseConnections": "프록시 그룹 선택 또는 프록시 모드 변경 시 기존 연결을 종료합니다",
|
||||||
"autoSwitchSelectorGroup": "규칙 모드에서 규칙 트래픽이 지나지 않는 그룹의 노드를 선택하면 해당 그룹을 포함하는 첫 번째 select 그룹도 그 그룹으로 전환합니다",
|
"autoSwitchSelectorGroup": "규칙 모드에서 url-test 또는 fallback 그룹의 노드를 선택하면 해당 그룹을 포함하는 첫 번째 select 그룹도 그 그룹으로 전환합니다",
|
||||||
"enableBuiltinEnhanced": "구성 파일에 대한 호환성 처리를 수행합니다",
|
"enableBuiltinEnhanced": "구성 파일에 대한 호환성 처리를 수행합니다",
|
||||||
"autoDelayDetection": "백그라운드에서 현재 노드의 지연을 주기적으로 검사합니다",
|
"autoDelayDetection": "백그라운드에서 현재 노드의 지연을 주기적으로 검사합니다",
|
||||||
"defaultLatencyTest": "HTTP 클라이언트 요청 테스트에만 사용되며 구성 파일에는 영향을 주지 않습니다"
|
"defaultLatencyTest": "HTTP 클라이언트 요청 테스트에만 사용되며 구성 파일에는 영향을 주지 않습니다"
|
||||||
|
|||||||
@@ -98,9 +98,6 @@
|
|||||||
"directMode": "Modo direto",
|
"directMode": "Modo direto",
|
||||||
"group": "Grupo",
|
"group": "Grupo",
|
||||||
"proxy": "Proxy",
|
"proxy": "Proxy",
|
||||||
"ruleTarget": "Destino das regras",
|
|
||||||
"defaultRoute": "Padrão",
|
|
||||||
"ruleCount": "{{count}} regras",
|
|
||||||
"noActiveNode": "Nenhum nó de proxy ativo"
|
"noActiveNode": "Nenhum nó de proxy ativo"
|
||||||
},
|
},
|
||||||
"status": {
|
"status": {
|
||||||
|
|||||||
@@ -423,7 +423,7 @@
|
|||||||
},
|
},
|
||||||
"tooltips": {
|
"tooltips": {
|
||||||
"autoCloseConnections": "Encerra as conexões estabelecidas quando a seleção do grupo de proxy ou o modo de proxy muda",
|
"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 que o tráfego das regras não alcança, o primeiro grupo select que o contém também muda para esse grupo",
|
"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",
|
"enableBuiltinEnhanced": "Tratamento de compatibilidade para o arquivo de configuração",
|
||||||
"autoDelayDetection": "Testa periodicamente a latência do nó atual em segundo plano",
|
"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"
|
"defaultLatencyTest": "Usado apenas para testes de requisição do cliente HTTP e não afeta o arquivo de configuração"
|
||||||
|
|||||||
@@ -98,9 +98,6 @@
|
|||||||
"directMode": "Прямой режим",
|
"directMode": "Прямой режим",
|
||||||
"group": "Группа",
|
"group": "Группа",
|
||||||
"proxy": "Прокси",
|
"proxy": "Прокси",
|
||||||
"ruleTarget": "Цель правил",
|
|
||||||
"defaultRoute": "По умолчанию",
|
|
||||||
"ruleCount": "Правил: {{count}}",
|
|
||||||
"noActiveNode": "Нет активного прокси"
|
"noActiveNode": "Нет активного прокси"
|
||||||
},
|
},
|
||||||
"status": {
|
"status": {
|
||||||
|
|||||||
@@ -423,7 +423,7 @@
|
|||||||
},
|
},
|
||||||
"tooltips": {
|
"tooltips": {
|
||||||
"autoCloseConnections": "Закрывать установленные соединения при изменении выбора группы прокси или режима прокси",
|
"autoCloseConnections": "Закрывать установленные соединения при изменении выбора группы прокси или режима прокси",
|
||||||
"autoSwitchSelectorGroup": "В режиме правил при выборе узла в группе, через которую не идёт трафик правил, первая группа select, содержащая эту группу, также переключается на неё",
|
"autoSwitchSelectorGroup": "В режиме правил при выборе узла в группе url-test или fallback первая группа select, содержащая эту группу, также переключается на неё",
|
||||||
"enableBuiltinEnhanced": "Обработка совместимости для файла конфигурации",
|
"enableBuiltinEnhanced": "Обработка совместимости для файла конфигурации",
|
||||||
"autoDelayDetection": "Периодически проверяет задержку текущего узла в фоновом режиме",
|
"autoDelayDetection": "Периодически проверяет задержку текущего узла в фоновом режиме",
|
||||||
"defaultLatencyTest": "Используется только для тестирования HTTP-запросов клиента и не влияет на файл конфигурации"
|
"defaultLatencyTest": "Используется только для тестирования HTTP-запросов клиента и не влияет на файл конфигурации"
|
||||||
|
|||||||
@@ -98,9 +98,6 @@
|
|||||||
"directMode": "Doğrudan Mod",
|
"directMode": "Doğrudan Mod",
|
||||||
"group": "Grup",
|
"group": "Grup",
|
||||||
"proxy": "Vekil",
|
"proxy": "Vekil",
|
||||||
"ruleTarget": "Kural Hedefi",
|
|
||||||
"defaultRoute": "Varsayılan",
|
|
||||||
"ruleCount": "{{count}} kural",
|
|
||||||
"noActiveNode": "Aktif vekil düğümü yok"
|
"noActiveNode": "Aktif vekil düğümü yok"
|
||||||
},
|
},
|
||||||
"status": {
|
"status": {
|
||||||
|
|||||||
@@ -423,7 +423,7 @@
|
|||||||
},
|
},
|
||||||
"tooltips": {
|
"tooltips": {
|
||||||
"autoCloseConnections": "Vekil grup seçimi veya vekil modu değiştiğinde kurulan bağlantıları sonlandır",
|
"autoCloseConnections": "Vekil grup seçimi veya vekil modu değiştiğinde kurulan bağlantıları sonlandır",
|
||||||
"autoSwitchSelectorGroup": "Kural modunda, kural trafiğinin ulaşmadığı bir grupta düğüm seçildiğinde, bu grubu içeren ilk select grubu da o gruba geçer",
|
"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",
|
"enableBuiltinEnhanced": "Yapılandırma dosyası için uyumluluk işleme",
|
||||||
"autoDelayDetection": "Arka planda mevcut düğümün gecikmesini periyodik olarak test eder",
|
"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"
|
"defaultLatencyTest": "Yalnızca HTTP istemci isteği testi için kullanılır ve yapılandırma dosyasında bir fark yaratmaz"
|
||||||
|
|||||||
@@ -98,9 +98,6 @@
|
|||||||
"directMode": "Туры режим",
|
"directMode": "Туры режим",
|
||||||
"group": "Group",
|
"group": "Group",
|
||||||
"proxy": "Proxy",
|
"proxy": "Proxy",
|
||||||
"ruleTarget": "Rule Target",
|
|
||||||
"defaultRoute": "Default",
|
|
||||||
"ruleCount": "{{count}} rules",
|
|
||||||
"noActiveNode": "No active proxy node"
|
"noActiveNode": "No active proxy node"
|
||||||
},
|
},
|
||||||
"status": {
|
"status": {
|
||||||
|
|||||||
@@ -423,7 +423,7 @@
|
|||||||
},
|
},
|
||||||
"tooltips": {
|
"tooltips": {
|
||||||
"autoCloseConnections": "Прокси төркеме яисә режимын үзгәрткәндә актив тоташуларны өзү",
|
"autoCloseConnections": "Прокси төркеме яисә режимын үзгәрткәндә актив тоташуларны өзү",
|
||||||
"autoSwitchSelectorGroup": "Кагыйдәләр режимында кагыйдәләр трафигы үтми торган төркемдә төен сайлаганда, аны эченә алган беренче select төркеме дә шул төркемгә күчә",
|
"autoSwitchSelectorGroup": "Кагыйдәләр режимында url-test яки fallback төркемендә төен сайлаганда, аны эченә алган беренче select төркеме дә шул төркемгә күчә",
|
||||||
"enableBuiltinEnhanced": "Конфигурация файлы белән туры килә торган өстәмә оптимизация",
|
"enableBuiltinEnhanced": "Конфигурация файлы белән туры килә торган өстәмә оптимизация",
|
||||||
"autoDelayDetection": "Фон режимында хәзерге төен тоткарлыгын периодик тикшерә",
|
"autoDelayDetection": "Фон режимында хәзерге төен тоткарлыгын периодик тикшерә",
|
||||||
"defaultLatencyTest": "Бу фәкать клиентның HTTP сораулары тесты өчен кулланыла, конфигурация файлына йогынты ясамый"
|
"defaultLatencyTest": "Бу фәкать клиентның HTTP сораулары тесты өчен кулланыла, конфигурация файлына йогынты ясамый"
|
||||||
|
|||||||
@@ -98,9 +98,6 @@
|
|||||||
"directMode": "直连模式",
|
"directMode": "直连模式",
|
||||||
"group": "代理组",
|
"group": "代理组",
|
||||||
"proxy": "节点",
|
"proxy": "节点",
|
||||||
"ruleTarget": "规则入口",
|
|
||||||
"defaultRoute": "默认",
|
|
||||||
"ruleCount": "{{count}} 条规则",
|
|
||||||
"noActiveNode": "暂无激活的代理节点"
|
"noActiveNode": "暂无激活的代理节点"
|
||||||
},
|
},
|
||||||
"status": {
|
"status": {
|
||||||
|
|||||||
@@ -423,7 +423,7 @@
|
|||||||
},
|
},
|
||||||
"tooltips": {
|
"tooltips": {
|
||||||
"autoCloseConnections": "当代理组选中节点或代理模式变动时,关闭已建立的连接",
|
"autoCloseConnections": "当代理组选中节点或代理模式变动时,关闭已建立的连接",
|
||||||
"autoSwitchSelectorGroup": "规则模式下,在规则流量未经过的代理组中选择节点时,将首个包含该组的 select 代理组切换到该组",
|
"autoSwitchSelectorGroup": "规则模式下,在 url-test 或 fallback 代理组中选择节点时,将首个包含该组的 select 代理组切换到该组",
|
||||||
"enableBuiltinEnhanced": "配置文件的兼容性处理",
|
"enableBuiltinEnhanced": "配置文件的兼容性处理",
|
||||||
"autoDelayDetection": "后台定时检测当前节点延迟",
|
"autoDelayDetection": "后台定时检测当前节点延迟",
|
||||||
"defaultLatencyTest": "仅用于 HTTP 客户端请求测试,不会对配置文件产生影响"
|
"defaultLatencyTest": "仅用于 HTTP 客户端请求测试,不会对配置文件产生影响"
|
||||||
|
|||||||
@@ -98,9 +98,6 @@
|
|||||||
"directMode": "直連模式",
|
"directMode": "直連模式",
|
||||||
"group": "代理組",
|
"group": "代理組",
|
||||||
"proxy": "節點",
|
"proxy": "節點",
|
||||||
"ruleTarget": "規則入口",
|
|
||||||
"defaultRoute": "預設",
|
|
||||||
"ruleCount": "{{count}} 條規則",
|
|
||||||
"noActiveNode": "暫無作用中的代理節點"
|
"noActiveNode": "暫無作用中的代理節點"
|
||||||
},
|
},
|
||||||
"status": {
|
"status": {
|
||||||
|
|||||||
@@ -423,7 +423,7 @@
|
|||||||
},
|
},
|
||||||
"tooltips": {
|
"tooltips": {
|
||||||
"autoCloseConnections": "當代理組選中節點或代理模式變動時,關閉已建立的連線",
|
"autoCloseConnections": "當代理組選中節點或代理模式變動時,關閉已建立的連線",
|
||||||
"autoSwitchSelectorGroup": "規則模式下,在規則流量未經過的代理組中選擇節點時,將首個包含該組的 select 代理組切換到該組",
|
"autoSwitchSelectorGroup": "規則模式下,在 url-test 或 fallback 代理組中選擇節點時,將首個包含該組的 select 代理組切換到該組",
|
||||||
"enableBuiltinEnhanced": "配置檔案的相容性處理",
|
"enableBuiltinEnhanced": "配置檔案的相容性處理",
|
||||||
"autoDelayDetection": "在背景定時偵測目前節點延遲",
|
"autoDelayDetection": "在背景定時偵測目前節點延遲",
|
||||||
"defaultLatencyTest": "僅用於 HTTP 客戶端請求測試,不會對配置檔案產生影響"
|
"defaultLatencyTest": "僅用於 HTTP 客戶端請求測試,不會對配置檔案產生影響"
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import { asyncRetry } from 'foxts/async-retry'
|
|||||||
import { extractErrorMessage } from 'foxts/extract-error-message'
|
import { extractErrorMessage } from 'foxts/extract-error-message'
|
||||||
import { once } from 'foxts/once'
|
import { once } from 'foxts/once'
|
||||||
import i18n from 'i18next'
|
import i18n from 'i18next'
|
||||||
import { getBaseConfig } from 'tauri-plugin-mihomo-api'
|
|
||||||
|
|
||||||
import { debugLog } from '@/utils/debug'
|
import { debugLog } from '@/utils/debug'
|
||||||
|
|
||||||
@@ -138,29 +137,6 @@ const IP_CHECK_SERVICES: ServiceConfig[] = [
|
|||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
const getProxyHost = (allowLan: boolean, bindAddress: string) => {
|
|
||||||
const address = bindAddress.trim().replace(/^\[|\]$/g, '')
|
|
||||||
const normalizedAddress = address.toLowerCase()
|
|
||||||
const isIpv6 = normalizedAddress.includes(':')
|
|
||||||
const isIpv6Wildcard =
|
|
||||||
isIpv6 &&
|
|
||||||
normalizedAddress
|
|
||||||
.split(':')
|
|
||||||
.every((part) => part === '' || /^0+$/.test(part))
|
|
||||||
const isWildcard =
|
|
||||||
normalizedAddress === '*' ||
|
|
||||||
normalizedAddress === '0.0.0.0' ||
|
|
||||||
isIpv6Wildcard
|
|
||||||
|
|
||||||
if (!allowLan) return '127.0.0.1'
|
|
||||||
|
|
||||||
if (!address || isWildcard || normalizedAddress === 'localhost') {
|
|
||||||
return isIpv6Wildcard ? '[::1]' : '127.0.0.1'
|
|
||||||
}
|
|
||||||
|
|
||||||
return isIpv6 ? `[${address}]` : address
|
|
||||||
}
|
|
||||||
|
|
||||||
// 获取当前IP和地理位置信息
|
// 获取当前IP和地理位置信息
|
||||||
export const getIpInfo = async (): Promise<
|
export const getIpInfo = async (): Promise<
|
||||||
IpInfo & { lastFetchTs: number }
|
IpInfo & { lastFetchTs: number }
|
||||||
@@ -174,28 +150,6 @@ export const getIpInfo = async (): Promise<
|
|||||||
)
|
)
|
||||||
let lastError: unknown | null = null
|
let lastError: unknown | null = null
|
||||||
const userAgent = await getUserAgentPromise()
|
const userAgent = await getUserAgentPromise()
|
||||||
const { mixedPort, allowLan, bindAddress, authentication } =
|
|
||||||
await getBaseConfig()
|
|
||||||
const proxyUrl = `http://${getProxyHost(allowLan, bindAddress)}:${mixedPort}`
|
|
||||||
const proxyAuthentication = authentication?.[0]
|
|
||||||
const authSeparator = proxyAuthentication?.indexOf(':') ?? -1
|
|
||||||
|
|
||||||
if (proxyAuthentication !== undefined && authSeparator < 0) {
|
|
||||||
throw new Error('Invalid mixed proxy authentication configuration')
|
|
||||||
}
|
|
||||||
|
|
||||||
const proxy = {
|
|
||||||
all:
|
|
||||||
proxyAuthentication === undefined
|
|
||||||
? proxyUrl
|
|
||||||
: {
|
|
||||||
url: proxyUrl,
|
|
||||||
basicAuth: {
|
|
||||||
username: proxyAuthentication.slice(0, authSeparator),
|
|
||||||
password: proxyAuthentication.slice(authSeparator + 1),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
console.debug('User-Agent for IP detection:', userAgent)
|
console.debug('User-Agent for IP detection:', userAgent)
|
||||||
|
|
||||||
for (const service of shuffledServices) {
|
for (const service of shuffledServices) {
|
||||||
@@ -214,7 +168,6 @@ export const getIpInfo = async (): Promise<
|
|||||||
try {
|
try {
|
||||||
const response = await fetch(service.url, {
|
const response = await fetch(service.url, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
proxy,
|
|
||||||
signal: timeoutController.signal,
|
signal: timeoutController.signal,
|
||||||
connectTimeout: serviceTimeout,
|
connectTimeout: serviceTimeout,
|
||||||
headers: {
|
headers: {
|
||||||
|
|||||||
@@ -83,6 +83,8 @@ export const commands = {
|
|||||||
__TAURI_INVOKE<null>('record_selected_node', { groupName, node }),
|
__TAURI_INVOKE<null>('record_selected_node', { groupName, node }),
|
||||||
switchProxyNode: (groupName: string, proxyName: string, unfix: boolean) =>
|
switchProxyNode: (groupName: string, proxyName: string, unfix: boolean) =>
|
||||||
__TAURI_INVOKE<null>('switch_proxy_node', { groupName, proxyName, unfix }),
|
__TAURI_INVOKE<null>('switch_proxy_node', { groupName, proxyName, unfix }),
|
||||||
|
followProxyGroup: (groupName: string) =>
|
||||||
|
__TAURI_INVOKE<void>('follow_proxy_group', { groupName }),
|
||||||
saveDnsConfig: (dnsConfig: YamlMapping) =>
|
saveDnsConfig: (dnsConfig: YamlMapping) =>
|
||||||
__TAURI_INVOKE<null>('save_dns_config', { dnsConfig }),
|
__TAURI_INVOKE<null>('save_dns_config', { dnsConfig }),
|
||||||
applyDnsConfig: (apply: boolean) =>
|
applyDnsConfig: (apply: boolean) =>
|
||||||
|
|||||||
@@ -165,6 +165,10 @@ export async function switchProxyNode(
|
|||||||
return commands.switchProxyNode(groupName, proxyName, unfix)
|
return commands.switchProxyNode(groupName, proxyName, unfix)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function followProxyGroup(groupName: string) {
|
||||||
|
return commands.followProxyGroup(groupName)
|
||||||
|
}
|
||||||
|
|
||||||
export async function getProxyView(): Promise<ProxyViewV1> {
|
export async function getProxyView(): Promise<ProxyViewV1> {
|
||||||
const view = await commands.getProxyView()
|
const view = await commands.getProxyView()
|
||||||
if (view.schemaVersion !== 1) {
|
if (view.schemaVersion !== 1) {
|
||||||
|
|||||||
@@ -19,6 +19,13 @@ let currentRangeMinutes!: number
|
|||||||
let throttleTimer: ReturnType<typeof setTimeout> | null = null
|
let throttleTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
let lastTimestamp: number | undefined
|
let lastTimestamp: number | undefined
|
||||||
let lastBroadcast: ITrafficDataPoint[] = []
|
let lastBroadcast: ITrafficDataPoint[] = []
|
||||||
|
let lastSamplerVersion = 0
|
||||||
|
|
||||||
|
// The slice for `minutes` can only change without new samples when its oldest
|
||||||
|
// point ages past the range cutoff.
|
||||||
|
const agedPastRange = (reference: ITrafficDataPoint[], minutes: number) =>
|
||||||
|
reference.length > 0 &&
|
||||||
|
Date.now() - reference[0].timestamp >= minutes * 60 * 1000
|
||||||
|
|
||||||
const broadcastSnapshot = () => {
|
const broadcastSnapshot = () => {
|
||||||
const dataPoints = sampler.getDataForTimeRange(currentRangeMinutes)
|
const dataPoints = sampler.getDataForTimeRange(currentRangeMinutes)
|
||||||
@@ -33,6 +40,7 @@ const broadcastSnapshot = () => {
|
|||||||
|
|
||||||
ctx.postMessage(message)
|
ctx.postMessage(message)
|
||||||
lastBroadcast = dataPoints
|
lastBroadcast = dataPoints
|
||||||
|
lastSamplerVersion = sampler.getVersion()
|
||||||
}
|
}
|
||||||
|
|
||||||
const scheduleSnapshot = () => {
|
const scheduleSnapshot = () => {
|
||||||
@@ -55,9 +63,18 @@ ctx.onmessage = (event: MessageEvent<TrafficWorkerRequestMessage>) => {
|
|||||||
// no handle needed, worker teardown (terminate) drops pending timers
|
// no handle needed, worker teardown (terminate) drops pending timers
|
||||||
ctx.setInterval(() => {
|
ctx.setInterval(() => {
|
||||||
if (throttleTimer !== null) return
|
if (throttleTimer !== null) return
|
||||||
|
const version = sampler.getVersion()
|
||||||
|
if (
|
||||||
|
version === lastSamplerVersion &&
|
||||||
|
!agedPastRange(lastBroadcast, currentRangeMinutes)
|
||||||
|
) {
|
||||||
|
return
|
||||||
|
}
|
||||||
const slice = sampler.getDataForTimeRange(currentRangeMinutes)
|
const slice = sampler.getDataForTimeRange(currentRangeMinutes)
|
||||||
if (!isSameTrafficData(lastBroadcast, slice)) {
|
if (!isSameTrafficData(lastBroadcast, slice)) {
|
||||||
broadcastSnapshot()
|
broadcastSnapshot()
|
||||||
|
} else {
|
||||||
|
lastSamplerVersion = version
|
||||||
}
|
}
|
||||||
}, 1000)
|
}, 1000)
|
||||||
broadcastSnapshot()
|
broadcastSnapshot()
|
||||||
|
|||||||
@@ -82,9 +82,6 @@ export const translationKeys = [
|
|||||||
'home.components.currentProxy.labels.directMode',
|
'home.components.currentProxy.labels.directMode',
|
||||||
'home.components.currentProxy.labels.group',
|
'home.components.currentProxy.labels.group',
|
||||||
'home.components.currentProxy.labels.proxy',
|
'home.components.currentProxy.labels.proxy',
|
||||||
'home.components.currentProxy.labels.ruleTarget',
|
|
||||||
'home.components.currentProxy.labels.defaultRoute',
|
|
||||||
'home.components.currentProxy.labels.ruleCount',
|
|
||||||
'home.components.currentProxy.labels.noActiveNode',
|
'home.components.currentProxy.labels.noActiveNode',
|
||||||
'home.components.currentProxy.status.testing',
|
'home.components.currentProxy.status.testing',
|
||||||
'home.components.currentProxy.status.untested',
|
'home.components.currentProxy.status.untested',
|
||||||
|
|||||||
@@ -69,14 +69,11 @@ export interface TranslationResources {
|
|||||||
refreshDelay: string
|
refreshDelay: string
|
||||||
}
|
}
|
||||||
labels: {
|
labels: {
|
||||||
defaultRoute: string
|
|
||||||
directMode: string
|
directMode: string
|
||||||
globalMode: string
|
globalMode: string
|
||||||
group: string
|
group: string
|
||||||
noActiveNode: string
|
noActiveNode: string
|
||||||
proxy: string
|
proxy: string
|
||||||
ruleCount: string
|
|
||||||
ruleTarget: string
|
|
||||||
}
|
}
|
||||||
status: {
|
status: {
|
||||||
error: string
|
error: string
|
||||||
|
|||||||
@@ -7,14 +7,33 @@ interface ICompressedDataPoint {
|
|||||||
|
|
||||||
const pad2 = (value: number) => value.toString().padStart(2, '0')
|
const pad2 = (value: number) => value.toString().padStart(2, '0')
|
||||||
|
|
||||||
|
// Time labels are derived once per 1Hz timestamp and redrawn several times per
|
||||||
|
// second; the bounded cache keeps axis drawing allocation-free in steady state.
|
||||||
|
const TIME_LABEL_CACHE_LIMIT = 1024
|
||||||
|
const hourMinuteLabels = new Map<number, string>()
|
||||||
|
const minuteSecondLabels = new Map<number, string>()
|
||||||
|
|
||||||
export const formatTrafficHourMinute = (timestamp: number) => {
|
export const formatTrafficHourMinute = (timestamp: number) => {
|
||||||
|
const cached = hourMinuteLabels.get(timestamp)
|
||||||
|
if (cached !== undefined) return cached
|
||||||
|
|
||||||
const date = new Date(timestamp)
|
const date = new Date(timestamp)
|
||||||
return `${pad2(date.getHours())}:${pad2(date.getMinutes())}`
|
const label = `${pad2(date.getHours())}:${pad2(date.getMinutes())}`
|
||||||
|
if (hourMinuteLabels.size >= TIME_LABEL_CACHE_LIMIT) hourMinuteLabels.clear()
|
||||||
|
hourMinuteLabels.set(timestamp, label)
|
||||||
|
return label
|
||||||
}
|
}
|
||||||
|
|
||||||
export const formatTrafficMinuteSecond = (timestamp: number) => {
|
export const formatTrafficMinuteSecond = (timestamp: number) => {
|
||||||
|
const cached = minuteSecondLabels.get(timestamp)
|
||||||
|
if (cached !== undefined) return cached
|
||||||
|
|
||||||
const date = new Date(timestamp)
|
const date = new Date(timestamp)
|
||||||
return `${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`
|
const label = `${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`
|
||||||
|
if (minuteSecondLabels.size >= TIME_LABEL_CACHE_LIMIT)
|
||||||
|
minuteSecondLabels.clear()
|
||||||
|
minuteSecondLabels.set(timestamp, label)
|
||||||
|
return label
|
||||||
}
|
}
|
||||||
|
|
||||||
export const formatTrafficName = (timestamp: number) => {
|
export const formatTrafficName = (timestamp: number) => {
|
||||||
@@ -53,10 +72,12 @@ export class TrafficDataSampler {
|
|||||||
private compressedBuffer: ICompressedDataPoint[] = []
|
private compressedBuffer: ICompressedDataPoint[] = []
|
||||||
private compressedHead = 0
|
private compressedHead = 0
|
||||||
private compressionQueue: ITrafficDataPoint[] = []
|
private compressionQueue: ITrafficDataPoint[] = []
|
||||||
|
private version = 0
|
||||||
|
|
||||||
constructor(private config: ISamplingConfig) {}
|
constructor(private config: ISamplingConfig) {}
|
||||||
|
|
||||||
addDataPoint(point: ITrafficDataPoint) {
|
addDataPoint(point: ITrafficDataPoint) {
|
||||||
|
this.version++
|
||||||
this.rawBuffer.push(point)
|
this.rawBuffer.push(point)
|
||||||
|
|
||||||
const rawCutoff = Date.now() - this.config.rawDataMinutes * 60 * 1000
|
const rawCutoff = Date.now() - this.config.rawDataMinutes * 60 * 1000
|
||||||
@@ -167,7 +188,13 @@ export class TrafficDataSampler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Bumped by every mutation (added points, compression, aging trims, clear). */
|
||||||
|
getVersion(): number {
|
||||||
|
return this.version
|
||||||
|
}
|
||||||
|
|
||||||
clear() {
|
clear() {
|
||||||
|
this.version++
|
||||||
this.rawBuffer = []
|
this.rawBuffer = []
|
||||||
this.rawHead = 0
|
this.rawHead = 0
|
||||||
this.compressedBuffer = []
|
this.compressedBuffer = []
|
||||||
|
|||||||
Reference in New Issue
Block a user