mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-20 02:42:12 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4969630f57 | ||
|
|
50fd66925a | ||
|
|
5d2e69ba6c | ||
|
|
71444c9815 | ||
|
|
02a1998b8d |
+1
-3
@@ -28,8 +28,6 @@
|
|||||||
<details>
|
<details>
|
||||||
<summary><strong> 🐞 修复问题 </strong></summary>
|
<summary><strong> 🐞 修复问题 </strong></summary>
|
||||||
|
|
||||||
- 修复「外部控制器」复制成功的提示一闪而过
|
|
||||||
- 修复订阅的规则、代理组、节点编辑器快速连续操作时条目可能重复或错位
|
|
||||||
- 修复检测更新后又发布新版时,应用内更新失败
|
- 修复检测更新后又发布新版时,应用内更新失败
|
||||||
- 修复订阅响应过大导致内存占用过高,限制单次下载为 4 MiB
|
- 修复订阅响应过大导致内存占用过高,限制单次下载为 4 MiB
|
||||||
- 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组
|
- 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组
|
||||||
@@ -65,11 +63,11 @@
|
|||||||
<details>
|
<details>
|
||||||
<summary><strong> 🚀 优化改进 </strong></summary>
|
<summary><strong> 🚀 优化改进 </strong></summary>
|
||||||
|
|
||||||
- 优化设置页打开时的开销:布局设置弹窗首次打开时才加载图标
|
|
||||||
- 优化连接、规则和日志筛选:切换页面后保留过滤条件
|
- 优化连接、规则和日志筛选:切换页面后保留过滤条件
|
||||||
- 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组
|
- 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组
|
||||||
- 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件
|
- 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件
|
||||||
- 优化首页「当前节点」卡片:代理组列表加入 `fallback` 代理组,切换到 `url-test` 或 `fallback` 代理组时同样联动 `select` 代理组
|
- 优化首页「当前节点」卡片:代理组列表加入 `fallback` 代理组,切换到 `url-test` 或 `fallback` 代理组时同样联动 `select` 代理组
|
||||||
|
- 优化主页流量图表与日志、代理列表的实时刷新和滚动占用,降低高频更新时的 CPU 负载
|
||||||
|
|
||||||
**🍎 macOS**
|
**🍎 macOS**
|
||||||
|
|
||||||
|
|||||||
+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,
|
||||||
|
},
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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 (
|
||||||
|
|||||||
@@ -218,7 +218,7 @@ export const GroupsEditorViewer = (props: Props) => {
|
|||||||
group={item}
|
group={item}
|
||||||
onDelete={() => {
|
onDelete={() => {
|
||||||
if (isDeleted) {
|
if (isDeleted) {
|
||||||
setDeleteSeq((prev) => prev.filter((v) => v !== item.name))
|
setDeleteSeq(deleteSeq.filter((v) => v !== item.name))
|
||||||
} else {
|
} else {
|
||||||
setDeleteSeq((prev) => [...prev, item.name])
|
setDeleteSeq((prev) => [...prev, item.name])
|
||||||
}
|
}
|
||||||
@@ -233,7 +233,7 @@ export const GroupsEditorViewer = (props: Props) => {
|
|||||||
type="prepend"
|
type="prepend"
|
||||||
group={item}
|
group={item}
|
||||||
onDelete={() => {
|
onDelete={() => {
|
||||||
setPrependSeq((prev) => prev.filter((v) => v.name !== item.name))
|
setPrependSeq(prependSeq.filter((v) => v.name !== item.name))
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
@@ -244,7 +244,7 @@ export const GroupsEditorViewer = (props: Props) => {
|
|||||||
type="append"
|
type="append"
|
||||||
group={item}
|
group={item}
|
||||||
onDelete={() => {
|
onDelete={() => {
|
||||||
setAppendSeq((prev) => prev.filter((v) => v.name !== item.name))
|
setAppendSeq(appendSeq.filter((v) => v.name !== item.name))
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
@@ -255,22 +255,21 @@ export const GroupsEditorViewer = (props: Props) => {
|
|||||||
activeIndex: number,
|
activeIndex: number,
|
||||||
overIndex: number,
|
overIndex: number,
|
||||||
) => {
|
) => {
|
||||||
|
const list = category === 'prepend' ? prependSeq : appendSeq
|
||||||
|
const filtered =
|
||||||
|
category === 'prepend' ? filteredPrependSeq : filteredAppendSeq
|
||||||
const setList = category === 'prepend' ? setPrependSeq : setAppendSeq
|
const setList = category === 'prepend' ? setPrependSeq : setAppendSeq
|
||||||
// Recompute inside the updater: two writes in one batch must not read the same pre-batch array.
|
const activeRealIndex = findRealIndex(list, filtered, activeIndex)
|
||||||
setList((prev) => {
|
const overRealIndex = findRealIndex(list, filtered, overIndex)
|
||||||
const filtered = prev.filter((v) => match(v.name))
|
if (
|
||||||
const activeRealIndex = findRealIndex(prev, filtered, activeIndex)
|
activeRealIndex < 0 ||
|
||||||
const overRealIndex = findRealIndex(prev, filtered, overIndex)
|
overRealIndex < 0 ||
|
||||||
if (
|
activeRealIndex === overRealIndex
|
||||||
activeRealIndex < 0 ||
|
) {
|
||||||
overRealIndex < 0 ||
|
return
|
||||||
activeRealIndex === overRealIndex
|
}
|
||||||
) {
|
|
||||||
return prev
|
|
||||||
}
|
|
||||||
|
|
||||||
return arrayMove(prev, activeRealIndex, overRealIndex)
|
setList(arrayMove(list, activeRealIndex, overRealIndex))
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const fetchContent = useCallback(async () => {
|
const fetchContent = useCallback(async () => {
|
||||||
@@ -1020,20 +1019,14 @@ export const GroupsEditorViewer = (props: Props) => {
|
|||||||
onClick={() => {
|
onClick={() => {
|
||||||
try {
|
try {
|
||||||
validateGroup()
|
validateGroup()
|
||||||
const values = formIns.getValues()
|
|
||||||
for (const item of [...prependSeq, ...groupList]) {
|
for (const item of [...prependSeq, ...groupList]) {
|
||||||
if (item.name === values.name) {
|
if (item.name === formIns.getValues().name) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
t('profiles.modals.groupsEditor.errors.nameExists'),
|
t('profiles.modals.groupsEditor.errors.nameExists'),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Recheck inside the updater so a same-batch second click cannot duplicate the entry.
|
setPrependSeq([formIns.getValues(), ...prependSeq])
|
||||||
setPrependSeq((prev) =>
|
|
||||||
prev.some((v) => v.name === values.name)
|
|
||||||
? prev
|
|
||||||
: [values, ...prev],
|
|
||||||
)
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
showNotice.error(err)
|
showNotice.error(err)
|
||||||
}
|
}
|
||||||
@@ -1050,20 +1043,14 @@ export const GroupsEditorViewer = (props: Props) => {
|
|||||||
onClick={() => {
|
onClick={() => {
|
||||||
try {
|
try {
|
||||||
validateGroup()
|
validateGroup()
|
||||||
const values = formIns.getValues()
|
|
||||||
for (const item of [...appendSeq, ...groupList]) {
|
for (const item of [...appendSeq, ...groupList]) {
|
||||||
if (item.name === values.name) {
|
if (item.name === formIns.getValues().name) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
t('profiles.modals.groupsEditor.errors.nameExists'),
|
t('profiles.modals.groupsEditor.errors.nameExists'),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Recheck inside the updater so a same-batch second click cannot duplicate the entry.
|
setAppendSeq([...appendSeq, formIns.getValues()])
|
||||||
setAppendSeq((prev) =>
|
|
||||||
prev.some((v) => v.name === values.name)
|
|
||||||
? prev
|
|
||||||
: [...prev, values],
|
|
||||||
)
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
showNotice.error(err)
|
showNotice.error(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -123,7 +123,7 @@ export const ProxiesEditorViewer = (props: Props) => {
|
|||||||
proxy={item}
|
proxy={item}
|
||||||
onDelete={() => {
|
onDelete={() => {
|
||||||
if (isDeleted) {
|
if (isDeleted) {
|
||||||
setDeleteSeq((prev) => prev.filter((v) => v !== item.name))
|
setDeleteSeq(deleteSeq.filter((v) => v !== item.name))
|
||||||
} else {
|
} else {
|
||||||
setDeleteSeq((prev) => [...prev, item.name])
|
setDeleteSeq((prev) => [...prev, item.name])
|
||||||
}
|
}
|
||||||
@@ -138,7 +138,7 @@ export const ProxiesEditorViewer = (props: Props) => {
|
|||||||
type="prepend"
|
type="prepend"
|
||||||
proxy={item}
|
proxy={item}
|
||||||
onDelete={() => {
|
onDelete={() => {
|
||||||
setPrependSeq((prev) => prev.filter((v) => v.name !== item.name))
|
setPrependSeq(prependSeq.filter((v) => v.name !== item.name))
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
@@ -149,7 +149,7 @@ export const ProxiesEditorViewer = (props: Props) => {
|
|||||||
type="append"
|
type="append"
|
||||||
proxy={item}
|
proxy={item}
|
||||||
onDelete={() => {
|
onDelete={() => {
|
||||||
setAppendSeq((prev) => prev.filter((v) => v.name !== item.name))
|
setAppendSeq(appendSeq.filter((v) => v.name !== item.name))
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
@@ -160,22 +160,21 @@ export const ProxiesEditorViewer = (props: Props) => {
|
|||||||
activeIndex: number,
|
activeIndex: number,
|
||||||
overIndex: number,
|
overIndex: number,
|
||||||
) => {
|
) => {
|
||||||
|
const list = category === 'prepend' ? prependSeq : appendSeq
|
||||||
|
const filtered =
|
||||||
|
category === 'prepend' ? filteredPrependSeq : filteredAppendSeq
|
||||||
const setList = category === 'prepend' ? setPrependSeq : setAppendSeq
|
const setList = category === 'prepend' ? setPrependSeq : setAppendSeq
|
||||||
// Recompute inside the updater: two writes in one batch must not read the same pre-batch array.
|
const activeRealIndex = findRealIndex(list, filtered, activeIndex)
|
||||||
setList((prev) => {
|
const overRealIndex = findRealIndex(list, filtered, overIndex)
|
||||||
const filtered = prev.filter((v) => hasValidName(v) && match(v.name))
|
if (
|
||||||
const activeRealIndex = findRealIndex(prev, filtered, activeIndex)
|
activeRealIndex < 0 ||
|
||||||
const overRealIndex = findRealIndex(prev, filtered, overIndex)
|
overRealIndex < 0 ||
|
||||||
if (
|
activeRealIndex === overRealIndex
|
||||||
activeRealIndex < 0 ||
|
) {
|
||||||
overRealIndex < 0 ||
|
return
|
||||||
activeRealIndex === overRealIndex
|
}
|
||||||
) {
|
|
||||||
return prev
|
|
||||||
}
|
|
||||||
|
|
||||||
return arrayMove(prev, activeRealIndex, overRealIndex)
|
setList(arrayMove(list, activeRealIndex, overRealIndex))
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 优化:异步分片解析,避免主线程阻塞,解析完成后批量setState
|
// 优化:异步分片解析,避免主线程阻塞,解析完成后批量setState
|
||||||
|
|||||||
@@ -318,7 +318,7 @@ export const RulesEditorViewer = (props: Props) => {
|
|||||||
ruleRaw={item}
|
ruleRaw={item}
|
||||||
onDelete={() => {
|
onDelete={() => {
|
||||||
if (isDeleted) {
|
if (isDeleted) {
|
||||||
setDeleteSeq((prev) => prev.filter((v) => v !== item))
|
setDeleteSeq(deleteSeq.filter((v) => v !== item))
|
||||||
} else {
|
} else {
|
||||||
setDeleteSeq((prev) => [...prev, item])
|
setDeleteSeq((prev) => [...prev, item])
|
||||||
}
|
}
|
||||||
@@ -333,13 +333,13 @@ export const RulesEditorViewer = (props: Props) => {
|
|||||||
type="prepend"
|
type="prepend"
|
||||||
ruleRaw={item}
|
ruleRaw={item}
|
||||||
onDelete={() => {
|
onDelete={() => {
|
||||||
setPrependSeq((prev) => prev.filter((v) => v !== item))
|
setPrependSeq(prependSeq.filter((v) => v !== item))
|
||||||
}}
|
}}
|
||||||
onAppend={() => {
|
onAppend={() => {
|
||||||
setAppendSeq((prev) =>
|
setAppendSeq((prev) =>
|
||||||
prev.includes(item) ? prev : [...prev, item],
|
prev.includes(item) ? prev : [...prev, item],
|
||||||
)
|
)
|
||||||
setPrependSeq((prev) => prev.filter((v) => v !== item))
|
setPrependSeq(prependSeq.filter((v) => v !== item))
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
@@ -350,13 +350,13 @@ export const RulesEditorViewer = (props: Props) => {
|
|||||||
type="append"
|
type="append"
|
||||||
ruleRaw={item}
|
ruleRaw={item}
|
||||||
onDelete={() => {
|
onDelete={() => {
|
||||||
setAppendSeq((prev) => prev.filter((v) => v !== item))
|
setAppendSeq(appendSeq.filter((v) => v !== item))
|
||||||
}}
|
}}
|
||||||
onPrepend={() => {
|
onPrepend={() => {
|
||||||
setPrependSeq((prev) =>
|
setPrependSeq((prev) =>
|
||||||
prev.includes(item) ? prev : [...prev, item],
|
prev.includes(item) ? prev : [...prev, item],
|
||||||
)
|
)
|
||||||
setAppendSeq((prev) => prev.filter((v) => v !== item))
|
setAppendSeq(appendSeq.filter((v) => v !== item))
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
@@ -367,22 +367,21 @@ export const RulesEditorViewer = (props: Props) => {
|
|||||||
activeIndex: number,
|
activeIndex: number,
|
||||||
overIndex: number,
|
overIndex: number,
|
||||||
) => {
|
) => {
|
||||||
|
const list = category === 'prepend' ? prependSeq : appendSeq
|
||||||
|
const filtered =
|
||||||
|
category === 'prepend' ? filteredPrependSeq : filteredAppendSeq
|
||||||
const setList = category === 'prepend' ? setPrependSeq : setAppendSeq
|
const setList = category === 'prepend' ? setPrependSeq : setAppendSeq
|
||||||
// Recompute inside the updater: two writes in one batch must not read the same pre-batch array.
|
const activeRealIndex = findRealIndex(list, filtered, activeIndex)
|
||||||
setList((prev) => {
|
const overRealIndex = findRealIndex(list, filtered, overIndex)
|
||||||
const filtered = prev.filter(match)
|
if (
|
||||||
const activeRealIndex = findRealIndex(prev, filtered, activeIndex)
|
activeRealIndex < 0 ||
|
||||||
const overRealIndex = findRealIndex(prev, filtered, overIndex)
|
overRealIndex < 0 ||
|
||||||
if (
|
activeRealIndex === overRealIndex
|
||||||
activeRealIndex < 0 ||
|
) {
|
||||||
overRealIndex < 0 ||
|
return
|
||||||
activeRealIndex === overRealIndex
|
}
|
||||||
) {
|
|
||||||
return prev
|
|
||||||
}
|
|
||||||
|
|
||||||
return arrayMove(prev, activeRealIndex, overRealIndex)
|
setList(arrayMove(list, activeRealIndex, overRealIndex))
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const fetchContent = useCallback(async () => {
|
const fetchContent = useCallback(async () => {
|
||||||
@@ -749,9 +748,8 @@ export const RulesEditorViewer = (props: Props) => {
|
|||||||
onClick={() => {
|
onClick={() => {
|
||||||
try {
|
try {
|
||||||
const raw = validateRule()
|
const raw = validateRule()
|
||||||
setPrependSeq((prev) =>
|
if (prependSeq.includes(raw)) return
|
||||||
prev.includes(raw) ? prev : [raw, ...prev],
|
setPrependSeq([raw, ...prependSeq])
|
||||||
)
|
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
showNotice.error(err)
|
showNotice.error(err)
|
||||||
}
|
}
|
||||||
@@ -768,9 +766,8 @@ export const RulesEditorViewer = (props: Props) => {
|
|||||||
onClick={() => {
|
onClick={() => {
|
||||||
try {
|
try {
|
||||||
const raw = validateRule()
|
const raw = validateRule()
|
||||||
setAppendSeq((prev) =>
|
if (appendSeq.includes(raw)) return
|
||||||
prev.includes(raw) ? prev : [...prev, raw],
|
setAppendSeq([...appendSeq, raw])
|
||||||
)
|
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
showNotice.error(err)
|
showNotice.error(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import {
|
|||||||
Tooltip,
|
Tooltip,
|
||||||
} from '@mui/material'
|
} from '@mui/material'
|
||||||
import { useLockFn } from 'ahooks'
|
import { useLockFn } from 'ahooks'
|
||||||
import { useRef, useState, type Ref } from 'react'
|
import { useState, type Ref } from 'react'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
import { BaseDialog, DialogRef, Switch } from '@/components/base'
|
import { BaseDialog, DialogRef, Switch } from '@/components/base'
|
||||||
@@ -26,10 +26,6 @@ export function ControllerViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
|||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
const [copySuccess, setCopySuccess] = useState<null | string>(null)
|
const [copySuccess, setCopySuccess] = useState<null | string>(null)
|
||||||
// A second copy within the window must not be hidden by the first timer.
|
|
||||||
const copySuccessTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(
|
|
||||||
undefined,
|
|
||||||
)
|
|
||||||
const [isSaving, setIsSaving] = useState(false)
|
const [isSaving, setIsSaving] = useState(false)
|
||||||
|
|
||||||
const { clashInfo, patchInfo } = useClashInfo()
|
const { clashInfo, patchInfo } = useClashInfo()
|
||||||
@@ -100,11 +96,7 @@ export function ControllerViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
|||||||
try {
|
try {
|
||||||
await navigator.clipboard.writeText(text)
|
await navigator.clipboard.writeText(text)
|
||||||
setCopySuccess(type)
|
setCopySuccess(type)
|
||||||
clearTimeout(copySuccessTimerRef.current)
|
setTimeout(() => setCopySuccess(null))
|
||||||
copySuccessTimerRef.current = setTimeout(
|
|
||||||
() => setCopySuccess(null),
|
|
||||||
2000,
|
|
||||||
)
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.warn('[ControllerViewer] copy to clipboard failed:', err)
|
console.warn('[ControllerViewer] copy to clipboard failed:', err)
|
||||||
showNotice.error(
|
showNotice.error(
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import { convertFileSrc } from '@tauri-apps/api/core'
|
|||||||
import { join } from '@tauri-apps/api/path'
|
import { join } from '@tauri-apps/api/path'
|
||||||
import { open as openDialog } from '@tauri-apps/plugin-dialog'
|
import { open as openDialog } from '@tauri-apps/plugin-dialog'
|
||||||
import { exists } from '@tauri-apps/plugin-fs'
|
import { exists } from '@tauri-apps/plugin-fs'
|
||||||
import { forwardRef, useEffect, useRef, useState } from 'react'
|
import { forwardRef, useEffect, useState } from 'react'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
import { BaseDialog, DialogRef, Switch, TooltipIcon } from '@/components/base'
|
import { BaseDialog, DialogRef, Switch, TooltipIcon } from '@/components/base'
|
||||||
@@ -62,16 +62,9 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
|||||||
|
|
||||||
const { decorated, toggleDecorations } = useWindowDecorations()
|
const { decorated, toggleDecorations } = useWindowDecorations()
|
||||||
|
|
||||||
// Icon paths are only reachable from the open dialog; both settings sections
|
|
||||||
// mount this viewer, so an eager read would double ~11 IPC calls per visit.
|
|
||||||
// Loaded once per mount, deferred to the first open.
|
|
||||||
const iconsLoadedRef = useRef(false)
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open || iconsLoadedRef.current) return
|
|
||||||
iconsLoadedRef.current = true
|
|
||||||
initIconPath()
|
initIconPath()
|
||||||
}, [open])
|
}, [])
|
||||||
|
|
||||||
async function initIconPath() {
|
async function initIconPath() {
|
||||||
const appDir = await getAppDir()
|
const appDir = await getAppDir()
|
||||||
|
|||||||
@@ -48,14 +48,10 @@ export const useSystemProxyState = () => {
|
|||||||
// Coalesce rapid clicks so only the latest requested state is applied.
|
// Coalesce rapid clicks so only the latest requested state is applied.
|
||||||
const pendingRef = useRef<boolean | null>(null)
|
const pendingRef = useRef<boolean | null>(null)
|
||||||
const busyRef = useRef(false)
|
const busyRef = useRef(false)
|
||||||
// The drain loop outlives the render it started in; reading the config
|
|
||||||
// through a ref keeps mid-loop revalidations visible to later iterations.
|
|
||||||
const vergeRef = useRef(verge)
|
|
||||||
vergeRef.current = verge
|
|
||||||
|
|
||||||
const toggleSystemProxy = async (enabled: boolean) => {
|
const toggleSystemProxy = async (enabled: boolean) => {
|
||||||
// Roll failed optimistic writes back to the latest confirmed state.
|
// Roll failed optimistic writes back to the latest confirmed state.
|
||||||
let confirmed = vergeRef.current?.enable_system_proxy ?? false
|
let confirmed = verge?.enable_system_proxy ?? false
|
||||||
mutateVerge((prev) =>
|
mutateVerge((prev) =>
|
||||||
prev ? { ...prev, enable_system_proxy: enabled } : prev,
|
prev ? { ...prev, enable_system_proxy: enabled } : prev,
|
||||||
)
|
)
|
||||||
@@ -73,7 +69,7 @@ export const useSystemProxyState = () => {
|
|||||||
errorNotice: false,
|
errorNotice: false,
|
||||||
})
|
})
|
||||||
confirmed = target
|
confirmed = target
|
||||||
if (!target && vergeRef.current?.auto_close_connection) {
|
if (!target && verge?.auto_close_connection) {
|
||||||
await mutate(() => closeAllConnections(), {
|
await mutate(() => closeAllConnections(), {
|
||||||
id: 'close-all-connections',
|
id: 'close-all-connections',
|
||||||
errorNotice: false,
|
errorNotice: false,
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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()
|
||||||
|
|||||||
@@ -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