mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-20 02:42:12 +08:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25bc4db8e9 | ||
|
|
5043b8706d | ||
|
|
2b812f5fa5 | ||
|
|
7074cc5c25 | ||
|
|
a85566a2cb |
@@ -67,7 +67,6 @@
|
|||||||
- 优化全局模式代理列表:仅显示 `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" | "proxy")
|
if !matches!(scenario.as_str(), "traffic" | "logs" | "connections")
|
||||||
|| !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,8 +2,6 @@ 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'
|
||||||
|
|||||||
@@ -1,137 +0,0 @@
|
|||||||
// 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
|
|
||||||
}
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
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>,
|
|
||||||
)
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
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'
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
// 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,11 +6,5 @@ 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,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -53,6 +53,15 @@ const StyledTextField = styled(TextField)(({ theme }) => ({
|
|||||||
},
|
},
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
const iconStyle = {
|
||||||
|
style: {
|
||||||
|
height: '24px',
|
||||||
|
width: '24px',
|
||||||
|
cursor: 'pointer',
|
||||||
|
} as React.CSSProperties,
|
||||||
|
inheritViewBox: true,
|
||||||
|
}
|
||||||
|
|
||||||
const useControllableState = <T,>(options: {
|
const useControllableState = <T,>(options: {
|
||||||
controlled: T | undefined
|
controlled: T | undefined
|
||||||
defaultValue: T
|
defaultValue: T
|
||||||
@@ -119,15 +128,6 @@ export const BaseSearchBox = ({
|
|||||||
defaultValue: defaultUseRegularExpression,
|
defaultValue: defaultUseRegularExpression,
|
||||||
})
|
})
|
||||||
|
|
||||||
const iconStyle = {
|
|
||||||
style: {
|
|
||||||
height: '24px',
|
|
||||||
width: '24px',
|
|
||||||
cursor: 'pointer',
|
|
||||||
} as React.CSSProperties,
|
|
||||||
inheritViewBox: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
onSearchRef.current = onSearch
|
onSearchRef.current = onSearch
|
||||||
}, [onSearch])
|
}, [onSearch])
|
||||||
|
|||||||
@@ -1,6 +1,13 @@
|
|||||||
import { styled } from '@mui/material/styles'
|
import { styled } from '@mui/material/styles'
|
||||||
import { default as MuiSwitch, SwitchProps } from '@mui/material/Switch'
|
import { default as MuiSwitch, SwitchProps } from '@mui/material/Switch'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MUI Switch delivers the boolean as the second onChange argument, so
|
||||||
|
* switch handlers use this adapter to stay boolean-only.
|
||||||
|
*/
|
||||||
|
export const switchChangeValue = (_event: unknown, value: boolean): boolean =>
|
||||||
|
value
|
||||||
|
|
||||||
export const Switch = styled((props: SwitchProps) => (
|
export const Switch = styled((props: SwitchProps) => (
|
||||||
<MuiSwitch
|
<MuiSwitch
|
||||||
focusVisibleClassName=".Mui-focusVisible"
|
focusVisibleClassName=".Mui-focusVisible"
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ export { BaseSplitChipEditor } from './base-split-chip-editor'
|
|||||||
export { BaseStyledSelect } from './base-styled-select'
|
export { BaseStyledSelect } from './base-styled-select'
|
||||||
export { BaseStyledTextField } from './base-styled-text-field'
|
export { BaseStyledTextField } from './base-styled-text-field'
|
||||||
export { MonacoEditor } from './monaco-editor'
|
export { MonacoEditor } from './monaco-editor'
|
||||||
export { Switch } from './base-switch'
|
export { Switch, switchChangeValue } from './base-switch'
|
||||||
export { TooltipIcon } from './base-tooltip-icon'
|
export { TooltipIcon } from './base-tooltip-icon'
|
||||||
export { VirtualList, type VirtualListHandle } from './virtual-list'
|
export { VirtualList, type VirtualListHandle } from './virtual-list'
|
||||||
export {
|
export {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
useEffectEvent,
|
useEffectEvent,
|
||||||
useImperativeHandle,
|
useImperativeHandle,
|
||||||
useMemo,
|
useMemo,
|
||||||
|
useReducer,
|
||||||
useRef,
|
useRef,
|
||||||
useState,
|
useState,
|
||||||
} from 'react'
|
} from 'react'
|
||||||
@@ -19,6 +20,7 @@ import {
|
|||||||
formatTrafficHourMinute,
|
formatTrafficHourMinute,
|
||||||
formatTrafficMinuteSecond,
|
formatTrafficMinuteSecond,
|
||||||
formatTrafficName,
|
formatTrafficName,
|
||||||
|
isSameTrafficData,
|
||||||
} from '@/utils/traffic-sampler'
|
} from '@/utils/traffic-sampler'
|
||||||
|
|
||||||
export interface EnhancedCanvasTrafficGraphRef {
|
export interface EnhancedCanvasTrafficGraphRef {
|
||||||
@@ -72,200 +74,16 @@ 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,
|
||||||
@@ -276,9 +94,11 @@ 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
|
||||||
@@ -309,49 +129,66 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
const lastDataTimestampRef = useRef<number>(0)
|
const lastDataTimestampRef = useRef<number>(0)
|
||||||
const dataStaleRef = useRef<boolean>(false)
|
const dataStaleRef = useRef<boolean>(false)
|
||||||
|
|
||||||
// Live snapshot data for the rAF draw path; React state only tracks the
|
const [displayData, dispatchDisplayData] = useReducer(
|
||||||
// diagnostics badge inputs so steady-state snapshots stop re-rendering.
|
displayDataReducer,
|
||||||
const displayDataRef = useRef<ITrafficDataPoint[]>([])
|
[],
|
||||||
const yScaleRef = useRef<{ topValue: number; bottomValue: number }>({
|
)
|
||||||
topValue: 1024,
|
const debounceTimeoutRef = useRef<number | null>(null)
|
||||||
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',
|
|
||||||
},
|
|
||||||
}),
|
}),
|
||||||
[colors],
|
[theme],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
@@ -433,9 +270,14 @@ 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 (displayDataRef.current.length === 0) return
|
if (displayData.length === 0) return
|
||||||
|
|
||||||
pendingMousePositionRef.current = {
|
pendingMousePositionRef.current = {
|
||||||
clientX: event.clientX,
|
clientX: event.clientX,
|
||||||
@@ -452,8 +294,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
if (!pendingMousePosition) return
|
if (!pendingMousePosition) return
|
||||||
|
|
||||||
const canvas = canvasRef.current
|
const canvas = canvasRef.current
|
||||||
const data = displayDataRef.current
|
if (!canvas || displayData.length === 0) return
|
||||||
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
|
||||||
@@ -468,11 +309,11 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
0,
|
0,
|
||||||
Math.min(1, relativeMouseX / effectiveWidth),
|
Math.min(1, relativeMouseX / effectiveWidth),
|
||||||
)
|
)
|
||||||
const dataIndex = Math.round(ratio * (data.length - 1))
|
const dataIndex = Math.round(ratio * (displayData.length - 1))
|
||||||
|
|
||||||
if (dataIndex < 0 || dataIndex >= data.length) return
|
if (dataIndex < 0 || dataIndex >= displayData.length) return
|
||||||
|
|
||||||
const dataPoint = data[dataIndex]
|
const dataPoint = displayData[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)
|
||||||
@@ -481,7 +322,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 } = yScaleRef.current
|
const { topValue: tvH, bottomValue: bvH } = yScale
|
||||||
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 =
|
||||||
@@ -518,7 +359,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
[calculateY, t],
|
[displayData, calculateY, yScale, t],
|
||||||
)
|
)
|
||||||
|
|
||||||
const handleMouseLeave = useCallback(() => {
|
const handleMouseLeave = useCallback(() => {
|
||||||
@@ -534,6 +375,45 @@ 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,
|
||||||
@@ -545,6 +425,8 @@ 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) => {
|
||||||
@@ -588,7 +470,37 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
|
|
||||||
ctx.restore()
|
ctx.restore()
|
||||||
},
|
},
|
||||||
[colors.grid, colors.text, colors.background],
|
[colors.grid, colors.text, colors.background, getYAxisTicks],
|
||||||
|
)
|
||||||
|
|
||||||
|
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(
|
||||||
@@ -604,7 +516,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 = TIME_DISPLAY_STRATEGIES[timeRange]
|
const strategy = getTimeDisplayStrategy(timeRange)
|
||||||
|
|
||||||
ctx.save()
|
ctx.save()
|
||||||
ctx.fillStyle = colors.text
|
ctx.fillStyle = colors.text
|
||||||
@@ -621,13 +533,15 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
Math.ceil((data.length * minPixelDistance) / effectiveWidth),
|
Math.ceil((data.length * minPixelDistance) / effectiveWidth),
|
||||||
)
|
)
|
||||||
|
|
||||||
resetTimeAxisPoints()
|
const timePoints: Array<{ index: number; x: number; label: string }> =
|
||||||
|
[]
|
||||||
|
|
||||||
if (data.length > 0 && data[0].timestamp) {
|
if (data.length > 0 && data[0].timestamp) {
|
||||||
pushTimeAxisPoint(
|
timePoints.push({
|
||||||
padding.left,
|
index: 0,
|
||||||
strategy.formatTime(data[0].timestamp),
|
x: padding.left,
|
||||||
)
|
label: strategy.formatTime(data[0].timestamp),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
for (
|
for (
|
||||||
@@ -639,37 +553,41 @@ 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
|
||||||
pushTimeAxisPoint(x, strategy.formatTime(point.timestamp))
|
timePoints.push({
|
||||||
|
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 = timeAxisPoints[timeAxisPoints.length - 1]
|
const lastPoint = timePoints[timePoints.length - 1]
|
||||||
|
|
||||||
if (!lastPoint || lastX - lastPoint.x >= minPixelDistance) {
|
if (!lastPoint || lastX - lastPoint.x >= minPixelDistance) {
|
||||||
pushTimeAxisPoint(
|
timePoints.push({
|
||||||
lastX,
|
index: data.length - 1,
|
||||||
strategy.formatTime(data[data.length - 1].timestamp),
|
x: lastX,
|
||||||
)
|
label: strategy.formatTime(data[data.length - 1].timestamp),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let i = 0; i < timeAxisPoints.length; i++) {
|
timePoints.forEach((point, index) => {
|
||||||
const point = timeAxisPoints[i]
|
if (index === 0) {
|
||||||
if (i === 0) {
|
|
||||||
ctx.textAlign = 'left'
|
ctx.textAlign = 'left'
|
||||||
} else if (i === timeAxisPoints.length - 1) {
|
} else if (index === timePoints.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],
|
[colors.text, timeRange, getTimeDisplayStrategy],
|
||||||
)
|
)
|
||||||
|
|
||||||
const drawGrid = useCallback(
|
const drawGrid = useCallback(
|
||||||
@@ -714,7 +632,6 @@ 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,
|
||||||
@@ -738,8 +655,13 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
0,
|
0,
|
||||||
height - padding.bottom,
|
height - padding.bottom,
|
||||||
)
|
)
|
||||||
gradient.addColorStop(0, gradientStops.start)
|
gradient.addColorStop(
|
||||||
gradient.addColorStop(1, gradientStops.end)
|
0,
|
||||||
|
`${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))
|
||||||
@@ -830,7 +752,6 @@ 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)
|
||||||
@@ -844,7 +765,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 } = yScaleRef.current
|
const { topValue, bottomValue } = yScale
|
||||||
|
|
||||||
drawYAxis(ctx, cssWidth, cssHeight, topValue, bottomValue)
|
drawYAxis(ctx, cssWidth, cssHeight, topValue, bottomValue)
|
||||||
|
|
||||||
@@ -859,7 +780,6 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
cssWidth,
|
cssWidth,
|
||||||
cssHeight,
|
cssHeight,
|
||||||
colors.down,
|
colors.down,
|
||||||
colors.gradient.down,
|
|
||||||
true,
|
true,
|
||||||
topValue,
|
topValue,
|
||||||
bottomValue,
|
bottomValue,
|
||||||
@@ -872,7 +792,6 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
cssWidth,
|
cssWidth,
|
||||||
cssHeight,
|
cssHeight,
|
||||||
colors.up,
|
colors.up,
|
||||||
colors.gradient.up,
|
|
||||||
true,
|
true,
|
||||||
topValue,
|
topValue,
|
||||||
bottomValue,
|
bottomValue,
|
||||||
@@ -885,7 +804,9 @@ 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,
|
||||||
@@ -896,7 +817,6 @@ 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
|
||||||
@@ -934,7 +854,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
|
|
||||||
ctx.restore()
|
ctx.restore()
|
||||||
}
|
}
|
||||||
}, [colors, syncCanvasSize, clearCanvas])
|
}, [displayData, colors, syncCanvasSize, clearCanvas])
|
||||||
|
|
||||||
const shouldSkipGraphDraw = useCallback(() => {
|
const shouldSkipGraphDraw = useCallback(() => {
|
||||||
if (!isDocumentVisibleRef.current) return true
|
if (!isDocumentVisibleRef.current) return true
|
||||||
@@ -977,55 +897,6 @@ 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()
|
||||||
@@ -1095,36 +966,119 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Box
|
<Box
|
||||||
sx={rootSx}
|
sx={{
|
||||||
|
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 ref={canvasRef} style={canvasStyle} onClick={toggleStyle} />
|
<canvas
|
||||||
|
ref={canvasRef}
|
||||||
|
style={{
|
||||||
|
width: '100%',
|
||||||
|
height: '100%',
|
||||||
|
display: 'block',
|
||||||
|
}}
|
||||||
|
onClick={toggleStyle}
|
||||||
|
/>
|
||||||
|
|
||||||
{tooltipData.visible && (
|
{tooltipData.visible && (
|
||||||
<canvas ref={hoverCanvasRef} style={hoverCanvasStyle} />
|
<canvas
|
||||||
|
ref={hoverCanvasRef}
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
inset: 0,
|
||||||
|
width: '100%',
|
||||||
|
height: '100%',
|
||||||
|
display: 'block',
|
||||||
|
pointerEvents: 'none',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Box sx={overlaySx}>
|
<Box
|
||||||
|
sx={{
|
||||||
|
position: 'absolute',
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
bottom: 0,
|
||||||
|
pointerEvents: 'none',
|
||||||
|
}}
|
||||||
|
>
|
||||||
<Box
|
<Box
|
||||||
component="div"
|
component="div"
|
||||||
onClick={handleTimeRangeClick}
|
onClick={handleTimeRangeClick}
|
||||||
sx={timeRangeBadgeSx}
|
sx={{
|
||||||
|
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 sx={legendsSx}>
|
<Box
|
||||||
<Box sx={legendSx.up}>
|
sx={{
|
||||||
|
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 sx={legendSx.down}>
|
<Box
|
||||||
|
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 sx={chartStyleHintSx}>
|
<Box
|
||||||
|
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'
|
||||||
@@ -1132,10 +1086,20 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
<Box sx={diagnosticsSx}>
|
<Box
|
||||||
|
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: badgeStats.points,
|
points: displayData.length,
|
||||||
compressed: badgeStats.compressed,
|
compressed: samplerStats.compressedBufferSize,
|
||||||
fps: GRAPH_CONFIG.targetFPS,
|
fps: GRAPH_CONFIG.targetFPS,
|
||||||
})}
|
})}
|
||||||
</Box>
|
</Box>
|
||||||
@@ -1163,9 +1127,15 @@ export const EnhancedCanvasTrafficGraph = memo(
|
|||||||
whiteSpace: 'nowrap',
|
whiteSpace: 'nowrap',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Box sx={tooltipTimeSx}>{tooltipData.timestamp}</Box>
|
<Box sx={{ color: 'text.secondary', mb: 0.2 }}>
|
||||||
<Box sx={tooltipUpSx}>↑ {tooltipData.upSpeed}</Box>
|
{tooltipData.timestamp}
|
||||||
<Box sx={tooltipDownSx}>↓ {tooltipData.downSpeed}</Box>
|
</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,15 +131,6 @@ 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,
|
||||||
@@ -261,35 +252,35 @@ export const EnhancedTrafficStats = () => {
|
|||||||
const statCards = useMemo(() => {
|
const statCards = useMemo(() => {
|
||||||
const cards: StatCardProps[] = [
|
const cards: StatCardProps[] = [
|
||||||
{
|
{
|
||||||
icon: uploadSpeedIcon,
|
icon: <ArrowUpwardRounded fontSize="small" />,
|
||||||
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: downloadSpeedIcon,
|
icon: <ArrowDownwardRounded fontSize="small" />,
|
||||||
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: activeConnectionsIcon,
|
icon: <LinkRounded fontSize="small" />,
|
||||||
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: uploadedIcon,
|
icon: <CloudUploadRounded fontSize="small" />,
|
||||||
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: downloadedIcon,
|
icon: <CloudDownloadRounded fontSize="small" />,
|
||||||
title: t('shared.labels.downloaded'),
|
title: t('shared.labels.downloaded'),
|
||||||
value: parsedData.downloadTotal,
|
value: parsedData.downloadTotal,
|
||||||
unit: parsedData.downloadTotalUnit,
|
unit: parsedData.downloadTotalUnit,
|
||||||
@@ -299,7 +290,7 @@ export const EnhancedTrafficStats = () => {
|
|||||||
|
|
||||||
if (displayMemory) {
|
if (displayMemory) {
|
||||||
cards.push({
|
cards.push({
|
||||||
icon: memoryUsageIcon,
|
icon: <MemoryRounded fontSize="small" />,
|
||||||
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,
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ import { emitTestAll } from '@/services/bus'
|
|||||||
|
|
||||||
import { EnhancedCard } from './enhanced-card'
|
import { EnhancedCard } from './enhanced-card'
|
||||||
|
|
||||||
|
const TEST_LIST_SENSORS = [PointerSensor]
|
||||||
|
|
||||||
// 自定义滚动条样式
|
// 自定义滚动条样式
|
||||||
const ScrollBox = styled(Box)(({ theme }) => ({
|
const ScrollBox = styled(Box)(({ theme }) => ({
|
||||||
maxHeight: '180px',
|
maxHeight: '180px',
|
||||||
@@ -205,7 +207,7 @@ export const TestCard = () => {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
<ScrollBox>
|
<ScrollBox>
|
||||||
<DragDropProvider sensors={[PointerSensor]} onDragEnd={onDragEnd}>
|
<DragDropProvider sensors={TEST_LIST_SENSORS} onDragEnd={onDragEnd}>
|
||||||
{renderTestItems}
|
{renderTestItems}
|
||||||
</DragDropProvider>
|
</DragDropProvider>
|
||||||
</ScrollBox>
|
</ScrollBox>
|
||||||
|
|||||||
@@ -42,39 +42,6 @@ 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()
|
||||||
@@ -107,6 +74,31 @@ 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}
|
||||||
@@ -128,6 +120,9 @@ 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}
|
||||||
@@ -142,6 +137,9 @@ 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}
|
||||||
@@ -156,7 +154,11 @@ export const LayoutTraffic = () => {
|
|||||||
{displayMemory && (
|
{displayMemory && (
|
||||||
<Box
|
<Box
|
||||||
title={`${t('home.components.traffic.metrics.memoryUsage')} `}
|
title={`${t('home.components.traffic.metrics.memoryUsage')} `}
|
||||||
{...memoryBoxStyle}
|
{...boxStyle}
|
||||||
|
sx={{
|
||||||
|
...boxStyle.sx,
|
||||||
|
cursor: 'auto',
|
||||||
|
}}
|
||||||
color={'disabled'}
|
color={'disabled'}
|
||||||
>
|
>
|
||||||
<MemoryRounded {...iconStyle} />
|
<MemoryRounded {...iconStyle} />
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import { type PointerEvent, useCallback } from 'react'
|
|||||||
import { useWindowControls } from '@/hooks/use-window'
|
import { useWindowControls } from '@/hooks/use-window'
|
||||||
import getSystem from '@/utils/get-system'
|
import getSystem from '@/utils/get-system'
|
||||||
|
|
||||||
|
const OS = getSystem()
|
||||||
|
|
||||||
const RESIZE_HANDLES = [
|
const RESIZE_HANDLES = [
|
||||||
{ direction: 'North', position: 'north' },
|
{ direction: 'North', position: 'north' },
|
||||||
{ direction: 'NorthEast', position: 'north-east' },
|
{ direction: 'NorthEast', position: 'north-east' },
|
||||||
@@ -38,7 +40,7 @@ export const WindowResizeHandles = () => {
|
|||||||
[currentWindow],
|
[currentWindow],
|
||||||
)
|
)
|
||||||
|
|
||||||
if (getSystem() !== 'linux' || maximized) return null
|
if (OS !== 'linux' || maximized) return null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
@@ -59,7 +61,6 @@ export const WindowResizeHandles = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const WindowControls = () => {
|
export const WindowControls = () => {
|
||||||
const OS = getSystem()
|
|
||||||
const { maximized, minimize, close, toggleMaximize } = useWindowControls()
|
const { maximized, minimize, close, toggleMaximize } = useWindowControls()
|
||||||
|
|
||||||
// 通过前端对 tauri 窗口进行翻转全屏时会短暂地与系统图标重叠渲染。
|
// 通过前端对 tauri 窗口进行翻转全屏时会短暂地与系统图标重叠渲染。
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ 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',
|
||||||
@@ -48,74 +47,62 @@ 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
|
||||||
|
|
||||||
const regex = getHighlightRegex(searchState)
|
try {
|
||||||
if (!regex) return text
|
const searchText = searchState.text
|
||||||
|
let pattern: string
|
||||||
|
|
||||||
const elements: ReactNode[] = []
|
if (searchState.useRegularExpression) {
|
||||||
let lastIndex = 0
|
try {
|
||||||
let match: RegExpExecArray | null
|
new RegExp(searchText)
|
||||||
|
pattern = searchText
|
||||||
while ((match = regex.exec(text)) !== null) {
|
} catch {
|
||||||
const start = match.index
|
pattern = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||||
const matchText = match[0]
|
}
|
||||||
|
} else {
|
||||||
if (matchText === '') {
|
const escaped = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||||
regex.lastIndex += 1
|
pattern = searchState.matchWholeWord ? `\\b${escaped}\\b` : escaped
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (start > lastIndex) {
|
const flags = searchState.matchCase ? 'g' : 'gi'
|
||||||
elements.push(text.slice(lastIndex, start))
|
const regex = new RegExp(pattern, flags)
|
||||||
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
elements.push(
|
if (lastIndex < text.length) {
|
||||||
<span key={`highlight-${start}`} className="highlight">
|
elements.push(text.slice(lastIndex))
|
||||||
{matchText}
|
}
|
||||||
</span>,
|
|
||||||
)
|
|
||||||
|
|
||||||
lastIndex = start + matchText.length
|
return elements.length ? elements : text
|
||||||
|
} catch {
|
||||||
|
return text
|
||||||
}
|
}
|
||||||
|
|
||||||
if (lastIndex < text.length) {
|
|
||||||
elements.push(text.slice(lastIndex))
|
|
||||||
}
|
|
||||||
|
|
||||||
return elements.length ? elements : text
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Alert, Box, Typography } from '@mui/material'
|
import { Alert, Box, Typography } from '@mui/material'
|
||||||
|
import { useMemo } from 'react'
|
||||||
import { Trans, useTranslation } from 'react-i18next'
|
import { Trans, useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
const stageHints = {
|
const stageHints = {
|
||||||
@@ -14,26 +15,31 @@ interface Props {
|
|||||||
|
|
||||||
export const EnhanceHint = ({ stage }: Props) => {
|
export const EnhanceHint = ({ stage }: Props) => {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const orderComponents = Object.fromEntries(
|
// The component map identity changes only when the active stage changes.
|
||||||
Object.keys(stageHints).map((key) => [
|
const orderComponents = useMemo(
|
||||||
key,
|
() =>
|
||||||
<Box
|
Object.fromEntries(
|
||||||
key={key}
|
Object.keys(stageHints).map((key) => [
|
||||||
component={key === stage ? 'strong' : 'span'}
|
key,
|
||||||
sx={
|
<Box
|
||||||
key === stage
|
key={key}
|
||||||
? {
|
component={key === stage ? 'strong' : 'span'}
|
||||||
fontWeight: 'bold',
|
sx={
|
||||||
color: 'primary.contrastText',
|
key === stage
|
||||||
bgcolor: 'primary.main',
|
? {
|
||||||
borderRadius: 0.5,
|
fontWeight: 'bold',
|
||||||
px: 0.5,
|
color: 'primary.contrastText',
|
||||||
boxDecorationBreak: 'clone',
|
bgcolor: 'primary.main',
|
||||||
}
|
borderRadius: 0.5,
|
||||||
: undefined
|
px: 0.5,
|
||||||
}
|
boxDecorationBreak: 'clone',
|
||||||
/>,
|
}
|
||||||
]),
|
: undefined
|
||||||
|
}
|
||||||
|
/>,
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
[stage],
|
||||||
)
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -56,6 +56,8 @@ interface GroupedVirtualListProps<T> {
|
|||||||
style?: CSSProperties
|
style?: CSSProperties
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const GROUPED_LIST_SENSORS = [PointerSensor, KeyboardSensor]
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 用于编辑规则/节点/代理组功能的 prepend/original/append 分组虚拟化列表
|
* 用于编辑规则/节点/代理组功能的 prepend/original/append 分组虚拟化列表
|
||||||
*/
|
*/
|
||||||
@@ -141,7 +143,7 @@ export function GroupedVirtualList<T>(props: GroupedVirtualListProps<T>) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<DragDropProvider
|
<DragDropProvider
|
||||||
sensors={[PointerSensor, KeyboardSensor]}
|
sensors={GROUPED_LIST_SENSORS}
|
||||||
onDragStart={onDragStart}
|
onDragStart={onDragStart}
|
||||||
onDragOver={onDragOver}
|
onDragOver={onDragOver}
|
||||||
onDragEnd={onDragEnd}
|
onDragEnd={onDragEnd}
|
||||||
|
|||||||
@@ -112,9 +112,12 @@ export const ProfileMore = (props: Props) => {
|
|||||||
document.markSaved(currentValue)
|
document.markSaved(currentValue)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// document gets a fresh identity every render; setValue is the stable
|
||||||
|
// useState setter, so the callback keys on it instead.
|
||||||
|
const { setValue } = document
|
||||||
const handleResetToDefault = useCallback(() => {
|
const handleResetToDefault = useCallback(() => {
|
||||||
document.setValue(DEFAULT_SCRIPT)
|
setValue(DEFAULT_SCRIPT)
|
||||||
}, [document])
|
}, [setValue])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -61,21 +61,26 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
useImperativeHandle(ref, () => ({
|
// The handle only closes over stable form/state setters.
|
||||||
create: () => {
|
useImperativeHandle(
|
||||||
setOpenType('new')
|
ref,
|
||||||
setOpen(true)
|
() => ({
|
||||||
},
|
create: () => {
|
||||||
edit: (item: IProfileItem) => {
|
setOpenType('new')
|
||||||
if (item) {
|
setOpen(true)
|
||||||
Object.entries(item).forEach(([key, value]) => {
|
},
|
||||||
setValue(key as any, value)
|
edit: (item: IProfileItem) => {
|
||||||
})
|
if (item) {
|
||||||
}
|
Object.entries(item).forEach(([key, value]) => {
|
||||||
setOpenType('edit')
|
setValue(key as any, value)
|
||||||
setOpen(true)
|
})
|
||||||
},
|
}
|
||||||
}))
|
setOpenType('edit')
|
||||||
|
setOpen(true)
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
[setValue],
|
||||||
|
)
|
||||||
|
|
||||||
const handleOk = useLockFn(
|
const handleOk = useLockFn(
|
||||||
handleSubmit(async (form) => {
|
handleSubmit(async (form) => {
|
||||||
|
|||||||
@@ -57,6 +57,8 @@ const chainPointerSensor = PointerSensor.configure({
|
|||||||
activationConstraints: () => undefined,
|
activationConstraints: () => undefined,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const CHAIN_SENSORS = [chainPointerSensor, KeyboardSensor]
|
||||||
|
|
||||||
type RuntimeConfigWithProxySequence = IConfigData & { proxies?: unknown }
|
type RuntimeConfigWithProxySequence = IConfigData & { proxies?: unknown }
|
||||||
|
|
||||||
interface ProxyChainProps {
|
interface ProxyChainProps {
|
||||||
@@ -665,10 +667,7 @@ export const ProxyChain = ({
|
|||||||
</Button>
|
</Button>
|
||||||
</Box>
|
</Box>
|
||||||
) : (
|
) : (
|
||||||
<DragDropProvider
|
<DragDropProvider sensors={CHAIN_SENSORS} onDragEnd={handleDragEnd}>
|
||||||
sensors={[chainPointerSensor, KeyboardSensor]}
|
|
||||||
onDragEnd={handleDragEnd}
|
|
||||||
>
|
|
||||||
<Box sx={{ borderRadius: 1, minHeight: 60, p: 1 }}>
|
<Box sx={{ borderRadius: 1, minHeight: 60, p: 1 }}>
|
||||||
{currentProxyChain.map((proxy, index) => (
|
{currentProxyChain.map((proxy, index) => (
|
||||||
<SortableProxyChainItem
|
<SortableProxyChainItem
|
||||||
|
|||||||
@@ -60,23 +60,6 @@ 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
|
||||||
@@ -167,12 +150,13 @@ function useProxyRenderState(
|
|||||||
|
|
||||||
const saveScrollPosition = useCallback(
|
const saveScrollPosition = useCallback(
|
||||||
(scrollTop: number) => {
|
(scrollTop: number) => {
|
||||||
const scrollPositions = readScrollPositions() ?? {}
|
const scrollPositions = localStorage.getItem('proxy-scroll-positions')
|
||||||
|
? JSON.parse(localStorage.getItem('proxy-scroll-positions') ?? '{}')
|
||||||
|
: {}
|
||||||
scrollPositions[scrollPositionKey] = scrollTop
|
scrollPositions[scrollPositionKey] = scrollTop
|
||||||
scrollPositionsCache = scrollPositions
|
|
||||||
try {
|
try {
|
||||||
localStorage.setItem(
|
localStorage.setItem(
|
||||||
SCROLL_POSITIONS_KEY,
|
'proxy-scroll-positions',
|
||||||
JSON.stringify(scrollPositions),
|
JSON.stringify(scrollPositions),
|
||||||
)
|
)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -183,10 +167,15 @@ function useProxyRenderState(
|
|||||||
)
|
)
|
||||||
|
|
||||||
const getScrollPosition = useCallback(() => {
|
const getScrollPosition = useCallback(() => {
|
||||||
const savedPositions = readScrollPositions()
|
try {
|
||||||
if (savedPositions) {
|
const savedPositions = localStorage.getItem('proxy-scroll-positions')
|
||||||
const savedPosition = savedPositions[scrollPositionKey]
|
if (savedPositions) {
|
||||||
return savedPosition ?? 0
|
const positions = JSON.parse(savedPositions)
|
||||||
|
const savedPosition = positions[scrollPositionKey]
|
||||||
|
return savedPosition ?? 0
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error restoring scroll position:', e)
|
||||||
}
|
}
|
||||||
}, [scrollPositionKey])
|
}, [scrollPositionKey])
|
||||||
|
|
||||||
@@ -251,13 +240,9 @@ function ChainProxyGroups(props: {
|
|||||||
|
|
||||||
const rangeExtractor = useCallback(
|
const rangeExtractor = useCallback(
|
||||||
(range: Parameters<typeof defaultRangeExtractor>[0]) => {
|
(range: Parameters<typeof defaultRangeExtractor>[0]) => {
|
||||||
let activeStickyIndex: number | undefined
|
const activeStickyIndex = [...stickyGroupIndexes]
|
||||||
for (let i = stickyGroupIndexes.length - 1; i >= 0; i--) {
|
.reverse()
|
||||||
if (stickyGroupIndexes[i] <= range.startIndex) {
|
.find((index) => index <= range.startIndex)
|
||||||
activeStickyIndex = stickyGroupIndexes[i]
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
activeStickyIndexRef.current = activeStickyIndex ?? null
|
activeStickyIndexRef.current = activeStickyIndex ?? null
|
||||||
|
|
||||||
const indexes = defaultRangeExtractor(range)
|
const indexes = defaultRangeExtractor(range)
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import {
|
|||||||
} from '@mui/material'
|
} from '@mui/material'
|
||||||
import { useLockFn } from 'ahooks'
|
import { useLockFn } from 'ahooks'
|
||||||
import dayjs from 'dayjs'
|
import dayjs from 'dayjs'
|
||||||
import { useState } from 'react'
|
import { useMemo, useState } from 'react'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { updateRuleProvider } from 'tauri-plugin-mihomo-api'
|
import { updateRuleProvider } from 'tauri-plugin-mihomo-api'
|
||||||
|
|
||||||
@@ -42,6 +42,11 @@ export const ProviderButton = () => {
|
|||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
const { ruleProviders } = useRulesData()
|
const { ruleProviders } = useRulesData()
|
||||||
|
|
||||||
|
const sortedProviderEntries = useMemo(
|
||||||
|
() => Object.entries(ruleProviders || {}).sort(),
|
||||||
|
[ruleProviders],
|
||||||
|
)
|
||||||
const { refreshRules, refreshRuleProviders } = useAppRefreshers()
|
const { refreshRules, refreshRuleProviders } = useAppRefreshers()
|
||||||
const [updating, setUpdating] = useState<Record<string, boolean>>({})
|
const [updating, setUpdating] = useState<Record<string, boolean>>({})
|
||||||
|
|
||||||
@@ -166,121 +171,119 @@ export const ProviderButton = () => {
|
|||||||
|
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
<List sx={{ py: 0, minHeight: 250 }}>
|
<List sx={{ py: 0, minHeight: 250 }}>
|
||||||
{Object.entries(ruleProviders || {})
|
{sortedProviderEntries.map(([key, item]) => {
|
||||||
.sort()
|
const provider = item
|
||||||
.map(([key, item]) => {
|
const time = dayjs(provider.updatedAt)
|
||||||
const provider = item
|
const isUpdating = updating[key]
|
||||||
const time = dayjs(provider.updatedAt)
|
|
||||||
const isUpdating = updating[key]
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ListItem
|
<ListItem
|
||||||
key={key}
|
key={key}
|
||||||
sx={[
|
sx={[
|
||||||
{
|
{
|
||||||
p: 0,
|
p: 0,
|
||||||
mb: '8px',
|
mb: '8px',
|
||||||
borderRadius: 2,
|
borderRadius: 2,
|
||||||
overflow: 'hidden',
|
overflow: 'hidden',
|
||||||
transition: 'all 0.2s',
|
transition: 'all 0.2s',
|
||||||
},
|
},
|
||||||
({ palette: { mode, primary } }) => {
|
({ palette: { mode, primary } }) => {
|
||||||
const bgcolor = mode === 'light' ? '#ffffff' : '#24252f'
|
const bgcolor = mode === 'light' ? '#ffffff' : '#24252f'
|
||||||
const hoverColor =
|
const hoverColor =
|
||||||
mode === 'light'
|
mode === 'light'
|
||||||
? alpha(primary.main, 0.1)
|
? alpha(primary.main, 0.1)
|
||||||
: alpha(primary.main, 0.2)
|
: alpha(primary.main, 0.2)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
backgroundColor: bgcolor,
|
backgroundColor: bgcolor,
|
||||||
'&:hover': {
|
'&:hover': {
|
||||||
backgroundColor: hoverColor,
|
backgroundColor: hoverColor,
|
||||||
borderColor: alpha(primary.main, 0.3),
|
borderColor: alpha(primary.main, 0.3),
|
||||||
},
|
},
|
||||||
}
|
|
||||||
},
|
|
||||||
]}
|
|
||||||
>
|
|
||||||
<ListItemText
|
|
||||||
sx={{ px: 2, py: 1 }}
|
|
||||||
primary={
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
display: 'flex',
|
|
||||||
justifyContent: 'space-between',
|
|
||||||
alignItems: 'center',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Typography
|
|
||||||
variant="subtitle1"
|
|
||||||
component="div"
|
|
||||||
noWrap
|
|
||||||
title={key}
|
|
||||||
sx={{ display: 'flex', alignItems: 'center' }}
|
|
||||||
>
|
|
||||||
<span style={{ marginRight: '8px' }}>{key}</span>
|
|
||||||
<TypeBox component="span">
|
|
||||||
{provider.ruleCount}
|
|
||||||
</TypeBox>
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Typography
|
|
||||||
variant="body2"
|
|
||||||
color="text.secondary"
|
|
||||||
noWrap
|
|
||||||
>
|
|
||||||
<small>{t('shared.labels.updateAt')}: </small>
|
|
||||||
{time.fromNow()}
|
|
||||||
</Typography>
|
|
||||||
</Box>
|
|
||||||
}
|
}
|
||||||
secondary={
|
},
|
||||||
<Box sx={{ display: 'flex' }}>
|
]}
|
||||||
<TypeBox component="span">
|
>
|
||||||
{typeof provider.vehicleType === 'string'
|
<ListItemText
|
||||||
? provider.vehicleType
|
sx={{ px: 2, py: 1 }}
|
||||||
: provider.vehicleType.Unknown}
|
primary={
|
||||||
</TypeBox>
|
<Box
|
||||||
<TypeBox component="span">
|
|
||||||
{typeof provider.behavior === 'string'
|
|
||||||
? provider.behavior
|
|
||||||
: provider.behavior.Unknown}
|
|
||||||
</TypeBox>
|
|
||||||
</Box>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<Divider orientation="vertical" flexItem />
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
width: 40,
|
|
||||||
display: 'flex',
|
|
||||||
justifyContent: 'center',
|
|
||||||
alignItems: 'center',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<IconButton
|
|
||||||
size="small"
|
|
||||||
color="primary"
|
|
||||||
onClick={() => updateProvider(key)}
|
|
||||||
disabled={isUpdating}
|
|
||||||
aria-label={t('rules.page.provider.actions.update')}
|
|
||||||
sx={{
|
sx={{
|
||||||
animation: isUpdating
|
display: 'flex',
|
||||||
? 'spin 1s linear infinite'
|
justifyContent: 'space-between',
|
||||||
: 'none',
|
alignItems: 'center',
|
||||||
'@keyframes spin': {
|
|
||||||
'0%': { transform: 'rotate(0deg)' },
|
|
||||||
'100%': { transform: 'rotate(360deg)' },
|
|
||||||
},
|
|
||||||
}}
|
}}
|
||||||
title={t('rules.page.provider.actions.update')}
|
|
||||||
>
|
>
|
||||||
<RefreshRounded />
|
<Typography
|
||||||
</IconButton>
|
variant="subtitle1"
|
||||||
</Box>
|
component="div"
|
||||||
</ListItem>
|
noWrap
|
||||||
)
|
title={key}
|
||||||
})}
|
sx={{ display: 'flex', alignItems: 'center' }}
|
||||||
|
>
|
||||||
|
<span style={{ marginRight: '8px' }}>{key}</span>
|
||||||
|
<TypeBox component="span">
|
||||||
|
{provider.ruleCount}
|
||||||
|
</TypeBox>
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<Typography
|
||||||
|
variant="body2"
|
||||||
|
color="text.secondary"
|
||||||
|
noWrap
|
||||||
|
>
|
||||||
|
<small>{t('shared.labels.updateAt')}: </small>
|
||||||
|
{time.fromNow()}
|
||||||
|
</Typography>
|
||||||
|
</Box>
|
||||||
|
}
|
||||||
|
secondary={
|
||||||
|
<Box sx={{ display: 'flex' }}>
|
||||||
|
<TypeBox component="span">
|
||||||
|
{typeof provider.vehicleType === 'string'
|
||||||
|
? provider.vehicleType
|
||||||
|
: provider.vehicleType.Unknown}
|
||||||
|
</TypeBox>
|
||||||
|
<TypeBox component="span">
|
||||||
|
{typeof provider.behavior === 'string'
|
||||||
|
? provider.behavior
|
||||||
|
: provider.behavior.Unknown}
|
||||||
|
</TypeBox>
|
||||||
|
</Box>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Divider orientation="vertical" flexItem />
|
||||||
|
<Box
|
||||||
|
sx={{
|
||||||
|
width: 40,
|
||||||
|
display: 'flex',
|
||||||
|
justifyContent: 'center',
|
||||||
|
alignItems: 'center',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<IconButton
|
||||||
|
size="small"
|
||||||
|
color="primary"
|
||||||
|
onClick={() => updateProvider(key)}
|
||||||
|
disabled={isUpdating}
|
||||||
|
aria-label={t('rules.page.provider.actions.update')}
|
||||||
|
sx={{
|
||||||
|
animation: isUpdating
|
||||||
|
? 'spin 1s linear infinite'
|
||||||
|
: 'none',
|
||||||
|
'@keyframes spin': {
|
||||||
|
'0%': { transform: 'rotate(0deg)' },
|
||||||
|
'100%': { transform: 'rotate(360deg)' },
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
title={t('rules.page.provider.actions.update')}
|
||||||
|
>
|
||||||
|
<RefreshRounded />
|
||||||
|
</IconButton>
|
||||||
|
</Box>
|
||||||
|
</ListItem>
|
||||||
|
)
|
||||||
|
})}
|
||||||
</List>
|
</List>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
|
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ const HOTKEY_FUNC_LABELS: Record<(typeof HOTKEY_FUNC)[number], string> = {
|
|||||||
reactivate_profiles: 'settings.modals.hotkey.functions.reactivateProfiles',
|
reactivate_profiles: 'settings.modals.hotkey.functions.reactivateProfiles',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const EMPTY_KEYS: string[] = []
|
||||||
|
|
||||||
export const HotkeyViewer = forwardRef<DialogRef>((props, ref) => {
|
export const HotkeyViewer = forwardRef<DialogRef>((props, ref) => {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
@@ -132,7 +134,7 @@ export const HotkeyViewer = forwardRef<DialogRef>((props, ref) => {
|
|||||||
<ItemWrapper key={func} data-setting-target={HOTKEY_FUNC_LABELS[func]}>
|
<ItemWrapper key={func} data-setting-target={HOTKEY_FUNC_LABELS[func]}>
|
||||||
<Typography>{t(HOTKEY_FUNC_LABELS[func])}</Typography>
|
<Typography>{t(HOTKEY_FUNC_LABELS[func])}</Typography>
|
||||||
<HotkeyInput
|
<HotkeyInput
|
||||||
value={hotkeyMap[func] ?? []}
|
value={hotkeyMap[func] ?? EMPTY_KEYS}
|
||||||
onChange={(v) => setHotkeyMap((m) => ({ ...m, [func]: v }))}
|
onChange={(v) => setHotkeyMap((m) => ({ ...m, [func]: v }))}
|
||||||
/>
|
/>
|
||||||
</ItemWrapper>
|
</ItemWrapper>
|
||||||
|
|||||||
@@ -17,7 +17,13 @@ import { exists } from '@tauri-apps/plugin-fs'
|
|||||||
import { forwardRef, useEffect, 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,
|
||||||
|
switchChangeValue,
|
||||||
|
} from '@/components/base'
|
||||||
import { DEFAULT_HOVER_DELAY } from '@/components/proxy/proxy-group-navigator'
|
import { DEFAULT_HOVER_DELAY } from '@/components/proxy/proxy-group-navigator'
|
||||||
import { useVerge } from '@/hooks/use-verge'
|
import { useVerge } from '@/hooks/use-verge'
|
||||||
import { useWindowDecorations } from '@/hooks/use-window'
|
import { useWindowDecorations } from '@/hooks/use-window'
|
||||||
@@ -104,7 +110,6 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
|||||||
close: () => setOpen(false),
|
close: () => setOpen(false),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const onSwitchFormat = (_e: any, value: boolean) => value
|
|
||||||
const onError = (err: any) => {
|
const onError = (err: any) => {
|
||||||
showNotice.error(err)
|
showNotice.error(err)
|
||||||
}
|
}
|
||||||
@@ -134,7 +139,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
|||||||
value={decorated}
|
value={decorated}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={switchChangeValue}
|
||||||
onChange={async () => {
|
onChange={async () => {
|
||||||
await toggleDecorations()
|
await toggleDecorations()
|
||||||
}}
|
}}
|
||||||
@@ -151,7 +156,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
|||||||
value={verge?.traffic_graph ?? true}
|
value={verge?.traffic_graph ?? true}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={switchChangeValue}
|
||||||
onChange={(e) => onChangeData({ traffic_graph: e })}
|
onChange={(e) => onChangeData({ traffic_graph: e })}
|
||||||
onGuard={(e) => patchVerge({ traffic_graph: e })}
|
onGuard={(e) => patchVerge({ traffic_graph: e })}
|
||||||
>
|
>
|
||||||
@@ -167,7 +172,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
|||||||
value={verge?.enable_memory_usage ?? true}
|
value={verge?.enable_memory_usage ?? true}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={switchChangeValue}
|
||||||
onChange={(e) => onChangeData({ enable_memory_usage: e })}
|
onChange={(e) => onChangeData({ enable_memory_usage: e })}
|
||||||
onGuard={(e) => patchVerge({ enable_memory_usage: e })}
|
onGuard={(e) => patchVerge({ enable_memory_usage: e })}
|
||||||
>
|
>
|
||||||
@@ -185,7 +190,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
|||||||
value={verge?.enable_group_icon ?? true}
|
value={verge?.enable_group_icon ?? true}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={switchChangeValue}
|
||||||
onChange={(e) => onChangeData({ enable_group_icon: e })}
|
onChange={(e) => onChangeData({ enable_group_icon: e })}
|
||||||
onGuard={(e) => patchVerge({ enable_group_icon: e })}
|
onGuard={(e) => patchVerge({ enable_group_icon: e })}
|
||||||
>
|
>
|
||||||
@@ -203,7 +208,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
|||||||
value={verge?.pause_render_traffic_stats_on_blur ?? true}
|
value={verge?.pause_render_traffic_stats_on_blur ?? true}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={switchChangeValue}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
onChangeData({ pause_render_traffic_stats_on_blur: e })
|
onChangeData({ pause_render_traffic_stats_on_blur: e })
|
||||||
}
|
}
|
||||||
@@ -271,7 +276,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
|||||||
value={verge?.enable_hover_jump_navigator ?? true}
|
value={verge?.enable_hover_jump_navigator ?? true}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={switchChangeValue}
|
||||||
onChange={(e) => onChangeData({ enable_hover_jump_navigator: e })}
|
onChange={(e) => onChangeData({ enable_hover_jump_navigator: e })}
|
||||||
onGuard={(e) => patchVerge({ enable_hover_jump_navigator: e })}
|
onGuard={(e) => patchVerge({ enable_hover_jump_navigator: e })}
|
||||||
>
|
>
|
||||||
@@ -373,7 +378,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
|||||||
value={verge?.collapse_navbar ?? false}
|
value={verge?.collapse_navbar ?? false}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={switchChangeValue}
|
||||||
onChange={(e) => onChangeData({ collapse_navbar: e })}
|
onChange={(e) => onChangeData({ collapse_navbar: e })}
|
||||||
onGuard={(e) => patchVerge({ collapse_navbar: e })}
|
onGuard={(e) => patchVerge({ collapse_navbar: e })}
|
||||||
>
|
>
|
||||||
@@ -420,7 +425,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
|||||||
value={verge?.enable_tray_speed ?? false}
|
value={verge?.enable_tray_speed ?? false}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={switchChangeValue}
|
||||||
onChange={(e) => onChangeData({ enable_tray_speed: e })}
|
onChange={(e) => onChangeData({ enable_tray_speed: e })}
|
||||||
onGuard={(e) => patchVerge({ enable_tray_speed: e })}
|
onGuard={(e) => patchVerge({ enable_tray_speed: e })}
|
||||||
>
|
>
|
||||||
@@ -440,7 +445,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
|||||||
}
|
}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={switchChangeValue}
|
||||||
onChange={(e) => onChangeData({ enable_tray_icon: e })}
|
onChange={(e) => onChangeData({ enable_tray_icon: e })}
|
||||||
onGuard={(e) => patchVerge({ enable_tray_icon: e })}
|
onGuard={(e) => patchVerge({ enable_tray_icon: e })}
|
||||||
>
|
>
|
||||||
@@ -494,7 +499,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
|||||||
value={verge?.tray_inline_outbound_modes ?? false}
|
value={verge?.tray_inline_outbound_modes ?? false}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={switchChangeValue}
|
||||||
onChange={(e) => onChangeData({ tray_inline_outbound_modes: e })}
|
onChange={(e) => onChangeData({ tray_inline_outbound_modes: e })}
|
||||||
onGuard={(e) => patchVerge({ tray_inline_outbound_modes: e })}
|
onGuard={(e) => patchVerge({ tray_inline_outbound_modes: e })}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
TextField,
|
TextField,
|
||||||
} from '@mui/material'
|
} from '@mui/material'
|
||||||
import { useLockFn } from 'ahooks'
|
import { useLockFn } from 'ahooks'
|
||||||
import { forwardRef, useState } from 'react'
|
import { forwardRef, useMemo, 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'
|
||||||
@@ -17,6 +17,20 @@ import { showNotice } from '@/services/notice-service'
|
|||||||
|
|
||||||
import { useSettingDialog } from '../settings-search-context'
|
import { useSettingDialog } from '../settings-search-context'
|
||||||
|
|
||||||
|
const APP_LOG_LEVEL_OPTIONS = [
|
||||||
|
'trace',
|
||||||
|
'debug',
|
||||||
|
'info',
|
||||||
|
'warn',
|
||||||
|
'error',
|
||||||
|
'silent',
|
||||||
|
].map((level) => ({
|
||||||
|
value: level,
|
||||||
|
label: level[0].toUpperCase() + level.slice(1).toLowerCase(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
const PROXY_LAYOUT_COLUMN_VALUES = [1, 2, 3, 4, 5]
|
||||||
|
|
||||||
const buildInitialValues = (verge?: IVergeConfig | null) => ({
|
const buildInitialValues = (verge?: IVergeConfig | null) => ({
|
||||||
appLogLevel: verge?.app_log_level ?? 'warn',
|
appLogLevel: verge?.app_log_level ?? 'warn',
|
||||||
appLogMaxSize: verge?.app_log_max_size ?? 128,
|
appLogMaxSize: verge?.app_log_max_size ?? 128,
|
||||||
@@ -38,6 +52,40 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
|
|||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const { verge, patchVerge } = useVerge()
|
const { verge, patchVerge } = useVerge()
|
||||||
|
|
||||||
|
const autoLogCleanOptions = useMemo(
|
||||||
|
() => [
|
||||||
|
{
|
||||||
|
key: t('settings.modals.misc.options.autoLogClean.never'),
|
||||||
|
value: 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
||||||
|
n: 1,
|
||||||
|
}),
|
||||||
|
value: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
||||||
|
n: 7,
|
||||||
|
}),
|
||||||
|
value: 2,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
||||||
|
n: 30,
|
||||||
|
}),
|
||||||
|
value: 3,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
||||||
|
n: 90,
|
||||||
|
}),
|
||||||
|
value: 4,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[t],
|
||||||
|
)
|
||||||
|
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
const [values, setValues] = useState(() => buildInitialValues(null))
|
const [values, setValues] = useState(() => buildInitialValues(null))
|
||||||
|
|
||||||
@@ -104,9 +152,9 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
{['trace', 'debug', 'info', 'warn', 'error', 'silent'].map((i) => (
|
{APP_LOG_LEVEL_OPTIONS.map(({ value, label }) => (
|
||||||
<MenuItem value={i} key={i}>
|
<MenuItem value={value} key={value}>
|
||||||
{i[0].toUpperCase() + i.slice(1).toLowerCase()}
|
{label}
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
))}
|
))}
|
||||||
</Select>
|
</Select>
|
||||||
@@ -285,7 +333,7 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
|
|||||||
<MenuItem value={6} key={6}>
|
<MenuItem value={6} key={6}>
|
||||||
{t('settings.modals.misc.options.proxyLayoutColumns.auto')}
|
{t('settings.modals.misc.options.proxyLayoutColumns.auto')}
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
{[1, 2, 3, 4, 5].map((i) => (
|
{PROXY_LAYOUT_COLUMN_VALUES.map((i) => (
|
||||||
<MenuItem value={i} key={i}>
|
<MenuItem value={i} key={i}>
|
||||||
{i}
|
{i}
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
@@ -312,36 +360,7 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
{/* 1: 1天, 2: 7天, 3: 30天, 4: 90天*/}
|
{/* 1: 1天, 2: 7天, 3: 30天, 4: 90天*/}
|
||||||
{[
|
{autoLogCleanOptions.map((i) => (
|
||||||
{
|
|
||||||
key: t('settings.modals.misc.options.autoLogClean.never'),
|
|
||||||
value: 0,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
|
||||||
n: 1,
|
|
||||||
}),
|
|
||||||
value: 1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
|
||||||
n: 7,
|
|
||||||
}),
|
|
||||||
value: 2,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
|
||||||
n: 30,
|
|
||||||
}),
|
|
||||||
value: 3,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
|
|
||||||
n: 90,
|
|
||||||
}),
|
|
||||||
value: 4,
|
|
||||||
},
|
|
||||||
].map((i) => (
|
|
||||||
<MenuItem key={i.value} value={i.value}>
|
<MenuItem key={i.value} value={i.value}>
|
||||||
{i.key}
|
{i.key}
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
|
|||||||
@@ -84,6 +84,19 @@ const splitBypass = (value?: string) =>
|
|||||||
.map((item) => item.trim())
|
.map((item) => item.trim())
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
|
|
||||||
|
const OS = getSystem()
|
||||||
|
|
||||||
|
const DEFAULT_BYPASS =
|
||||||
|
OS === 'windows'
|
||||||
|
? 'localhost;127.*;192.168.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;*.local;<local>'
|
||||||
|
: OS === 'linux'
|
||||||
|
? 'localhost,127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,::1'
|
||||||
|
: '127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,localhost,*.local,*.crashlytics.com,<local>'
|
||||||
|
|
||||||
|
const DEFAULT_BYPASS_CHIPS = splitBypass(DEFAULT_BYPASS)
|
||||||
|
|
||||||
|
const BYPASS_SEPARATOR = OS === 'windows' ? ';' : ','
|
||||||
|
|
||||||
const buildInitialValues = (verge?: IVergeConfig | null) => ({
|
const buildInitialValues = (verge?: IVergeConfig | null) => ({
|
||||||
guard: verge?.enable_proxy_guard,
|
guard: verge?.enable_proxy_guard,
|
||||||
enable_bypass_check: verge?.enable_bypass_check ?? true,
|
enable_bypass_check: verge?.enable_bypass_check ?? true,
|
||||||
@@ -97,8 +110,7 @@ const buildInitialValues = (verge?: IVergeConfig | null) => ({
|
|||||||
|
|
||||||
export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
|
export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const systemName = getSystem()
|
const isWindows = OS === 'windows'
|
||||||
const isWindows = systemName === 'windows'
|
|
||||||
const validReg = useMemo(() => getValidReg(isWindows), [isWindows])
|
const validReg = useMemo(() => getValidReg(isWindows), [isWindows])
|
||||||
|
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false)
|
||||||
@@ -130,17 +142,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
|
|||||||
queryFn: getEmbeddedServerPort,
|
queryFn: getEmbeddedServerPort,
|
||||||
})
|
})
|
||||||
|
|
||||||
const separator = useMemo(() => (isWindows ? ';' : ','), [isWindows])
|
const separator = BYPASS_SEPARATOR
|
||||||
|
|
||||||
const defaultBypass = () => {
|
|
||||||
if (isWindows) {
|
|
||||||
return 'localhost;127.*;192.168.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;*.local;<local>'
|
|
||||||
}
|
|
||||||
if (systemName === 'linux') {
|
|
||||||
return 'localhost,127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,::1'
|
|
||||||
}
|
|
||||||
return '127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,localhost,*.local,*.crashlytics.com,<local>'
|
|
||||||
}
|
|
||||||
|
|
||||||
const { systemProxyAddress } = useSystemData()
|
const { systemProxyAddress } = useSystemData()
|
||||||
const displayedMixedPort = useDisplayedMixedPort()
|
const displayedMixedPort = useDisplayedMixedPort()
|
||||||
@@ -503,7 +505,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
|
|||||||
checked={value.use_default}
|
checked={value.use_default}
|
||||||
onChange={(_, e) => {
|
onChange={(_, e) => {
|
||||||
if (!e && !value.bypass) {
|
if (!e && !value.bypass) {
|
||||||
const nextBypass = defaultBypass()
|
const nextBypass = DEFAULT_BYPASS
|
||||||
setValue((v) => ({
|
setValue((v) => ({
|
||||||
...v,
|
...v,
|
||||||
use_default: e,
|
use_default: e,
|
||||||
@@ -575,7 +577,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
|
|||||||
/>
|
/>
|
||||||
<Box sx={{ padding: '0 2px 5px' }}>
|
<Box sx={{ padding: '0 2px 5px' }}>
|
||||||
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
|
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
|
||||||
{splitBypass(defaultBypass()).map((item) => (
|
{DEFAULT_BYPASS_CHIPS.map((item) => (
|
||||||
<Chip key={item} label={item} size="small" />
|
<Chip key={item} label={item} size="small" />
|
||||||
))}
|
))}
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@@ -20,6 +20,12 @@ import { showNotice } from '@/services/notice-service'
|
|||||||
|
|
||||||
import { useSettingDialog } from '../settings-search-context'
|
import { useSettingDialog } from '../settings-search-context'
|
||||||
|
|
||||||
|
const textProps = {
|
||||||
|
size: 'small',
|
||||||
|
autoComplete: 'off',
|
||||||
|
sx: { width: 135 },
|
||||||
|
} as const
|
||||||
|
|
||||||
export function ThemeViewer(props: { ref?: React.Ref<DialogRef> }) {
|
export function ThemeViewer(props: { ref?: React.Ref<DialogRef> }) {
|
||||||
const { ref } = props
|
const { ref } = props
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
@@ -45,12 +51,6 @@ export function ThemeViewer(props: { ref?: React.Ref<DialogRef> }) {
|
|||||||
close: () => setOpen(false),
|
close: () => setOpen(false),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const textProps = {
|
|
||||||
size: 'small',
|
|
||||||
autoComplete: 'off',
|
|
||||||
sx: { width: 135 },
|
|
||||||
} as const
|
|
||||||
|
|
||||||
const handleChange = (field: keyof typeof theme) => (e: any) => {
|
const handleChange = (field: keyof typeof theme) => (e: any) => {
|
||||||
setTheme((t) => ({ ...t, [field]: e.target.value }))
|
setTheme((t) => ({ ...t, [field]: e.target.value }))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
} from '@mui/material'
|
} from '@mui/material'
|
||||||
import { useLockFn } from 'ahooks'
|
import { useLockFn } from 'ahooks'
|
||||||
import type { Ref } from 'react'
|
import type { Ref } from 'react'
|
||||||
import { useState } from 'react'
|
import { useMemo, useState } from 'react'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -58,8 +58,9 @@ export function TunViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
|||||||
dnsMode: '',
|
dnsMode: '',
|
||||||
})
|
})
|
||||||
|
|
||||||
const routeExcludeAddressItems = splitRouteExcludeAddress(
|
const routeExcludeAddressItems = useMemo(
|
||||||
values.routeExcludeAddress,
|
() => splitRouteExcludeAddress(values.routeExcludeAddress),
|
||||||
|
[values.routeExcludeAddress],
|
||||||
)
|
)
|
||||||
const routeExcludeAddressError =
|
const routeExcludeAddressError =
|
||||||
values.autoRoute &&
|
values.autoRoute &&
|
||||||
|
|||||||
@@ -189,10 +189,7 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
|||||||
void openExternalUrl(url).catch(showNotice.error)
|
void openExternalUrl(url).catch(showNotice.error)
|
||||||
}
|
}
|
||||||
|
|
||||||
const progress = useMemo(() => {
|
const progress = total <= 0 ? 0 : Math.min((downloaded / total) * 100, 100)
|
||||||
if (total <= 0) return 0
|
|
||||||
return Math.min((downloaded / total) * 100, 100)
|
|
||||||
}, [downloaded, total])
|
|
||||||
|
|
||||||
useImperativeHandle(ref, () => ({
|
useImperativeHandle(ref, () => ({
|
||||||
open: () => {
|
open: () => {
|
||||||
|
|||||||
@@ -5,7 +5,13 @@ import { useRef, useState } from 'react'
|
|||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { updateGeo, type LogLevel } from 'tauri-plugin-mihomo-api'
|
import { updateGeo, type LogLevel } from 'tauri-plugin-mihomo-api'
|
||||||
|
|
||||||
import { BaseDialog, DialogRef, Switch, TooltipIcon } from '@/components/base'
|
import {
|
||||||
|
BaseDialog,
|
||||||
|
DialogRef,
|
||||||
|
Switch,
|
||||||
|
TooltipIcon,
|
||||||
|
switchChangeValue,
|
||||||
|
} from '@/components/base'
|
||||||
import { useClash } from '@/hooks/use-clash'
|
import { useClash } from '@/hooks/use-clash'
|
||||||
import { useClashLog } from '@/hooks/use-clash-log'
|
import { useClashLog } from '@/hooks/use-clash-log'
|
||||||
import { useDisplayedMixedPort } from '@/hooks/use-displayed-mixed-port'
|
import { useDisplayedMixedPort } from '@/hooks/use-displayed-mixed-port'
|
||||||
@@ -69,7 +75,6 @@ const SettingClash = ({ onError }: Props) => {
|
|||||||
const corsRef = useRef<DialogRef>(null)
|
const corsRef = useRef<DialogRef>(null)
|
||||||
const tunnelRef = useRef<DialogRef>(null)
|
const tunnelRef = useRef<DialogRef>(null)
|
||||||
|
|
||||||
const onSwitchFormat = (_e: any, value: boolean) => value
|
|
||||||
const onChangeData = (patch: Partial<IConfigData>) => {
|
const onChangeData = (patch: Partial<IConfigData>) => {
|
||||||
mutateClash((old) => ({ ...old!, ...patch }), false)
|
mutateClash((old) => ({ ...old!, ...patch }), false)
|
||||||
}
|
}
|
||||||
@@ -173,7 +178,7 @@ const SettingClash = ({ onError }: Props) => {
|
|||||||
value={allowLan ?? false}
|
value={allowLan ?? false}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={switchChangeValue}
|
||||||
onChange={(e) => onChangeData({ 'allow-lan': e })}
|
onChange={(e) => onChangeData({ 'allow-lan': e })}
|
||||||
onGuard={(e) => patchClash({ 'allow-lan': e })}
|
onGuard={(e) => patchClash({ 'allow-lan': e })}
|
||||||
>
|
>
|
||||||
@@ -213,7 +218,7 @@ const SettingClash = ({ onError }: Props) => {
|
|||||||
value={ipv6 ?? false}
|
value={ipv6 ?? false}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={switchChangeValue}
|
||||||
onChange={(e) => onChangeData({ ipv6: e })}
|
onChange={(e) => onChangeData({ ipv6: e })}
|
||||||
onGuard={(e) => patchClash({ ipv6: e })}
|
onGuard={(e) => patchClash({ ipv6: e })}
|
||||||
>
|
>
|
||||||
@@ -235,7 +240,7 @@ const SettingClash = ({ onError }: Props) => {
|
|||||||
value={unifiedDelay ?? false}
|
value={unifiedDelay ?? false}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={switchChangeValue}
|
||||||
onChange={(e) => onChangeData({ 'unified-delay': e })}
|
onChange={(e) => onChangeData({ 'unified-delay': e })}
|
||||||
onGuard={(e) => patchClash({ 'unified-delay': e })}
|
onGuard={(e) => patchClash({ 'unified-delay': e })}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
import { Box } from '@mui/material'
|
import { Box } from '@mui/material'
|
||||||
import React from 'react'
|
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
import { Switch, TooltipIcon } from '@/components/base'
|
import { Switch, TooltipIcon, switchChangeValue } from '@/components/base'
|
||||||
import ProxyControlSwitches from '@/components/shared/proxy-control-switches'
|
import ProxyControlSwitches from '@/components/shared/proxy-control-switches'
|
||||||
import { useVerge } from '@/hooks/use-verge'
|
import { useVerge } from '@/hooks/use-verge'
|
||||||
|
|
||||||
@@ -20,10 +19,6 @@ const SettingSystem = ({ onError }: Props) => {
|
|||||||
|
|
||||||
const { enable_auto_launch, enable_silent_start } = verge ?? {}
|
const { enable_auto_launch, enable_silent_start } = verge ?? {}
|
||||||
|
|
||||||
const onSwitchFormat = (
|
|
||||||
_e: React.ChangeEvent<HTMLInputElement>,
|
|
||||||
value: boolean,
|
|
||||||
) => value
|
|
||||||
const onChangeData = (patch: Partial<IVergeConfig>) => {
|
const onChangeData = (patch: Partial<IVergeConfig>) => {
|
||||||
mutateVerge({ ...verge, ...patch })
|
mutateVerge({ ...verge, ...patch })
|
||||||
}
|
}
|
||||||
@@ -52,7 +47,7 @@ const SettingSystem = ({ onError }: Props) => {
|
|||||||
value={enable_auto_launch ?? false}
|
value={enable_auto_launch ?? false}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={switchChangeValue}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
onChangeData({ enable_auto_launch: e })
|
onChangeData({ enable_auto_launch: e })
|
||||||
}}
|
}}
|
||||||
@@ -85,7 +80,7 @@ const SettingSystem = ({ onError }: Props) => {
|
|||||||
value={enable_silent_start ?? false}
|
value={enable_silent_start ?? false}
|
||||||
valueProps="checked"
|
valueProps="checked"
|
||||||
onCatch={onError}
|
onCatch={onError}
|
||||||
onFormat={onSwitchFormat}
|
onFormat={switchChangeValue}
|
||||||
onChange={(e) => onChangeData({ enable_silent_start: e })}
|
onChange={(e) => onChangeData({ enable_silent_start: e })}
|
||||||
onGuard={(e) => patchVerge({ enable_silent_start: e })}
|
onGuard={(e) => patchVerge({ enable_silent_start: e })}
|
||||||
>
|
>
|
||||||
|
|||||||
+22
-12
@@ -1,5 +1,6 @@
|
|||||||
import { useLockFn } from 'ahooks'
|
import { useLockFn } from 'ahooks'
|
||||||
import i18n from 'i18next'
|
import i18n from 'i18next'
|
||||||
|
import { useCallback } from 'react'
|
||||||
import { getVersion } from 'tauri-plugin-mihomo-api'
|
import { getVersion } from 'tauri-plugin-mihomo-api'
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -86,23 +87,29 @@ export const useClashMode = (shouldFetch: boolean = true) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const useClash = () => {
|
export const useClash = () => {
|
||||||
const { data: clash, refetch } = useRuntimeConfig()
|
const { data: clash } = useRuntimeConfig()
|
||||||
|
|
||||||
const { data: versionData, refetch: mutateVersion } = useQuery({
|
const { data: versionData, refetch: mutateVersion } = useQuery({
|
||||||
queryKey: ['getVersion'],
|
queryKey: ['getVersion'],
|
||||||
queryFn: getVersion,
|
queryFn: getVersion,
|
||||||
})
|
})
|
||||||
|
|
||||||
const mutateClash = (updater?: MutateClashUpdater, revalidate?: boolean) => {
|
// Stable identity: consumers pass mutateClash into their own callbacks.
|
||||||
if (updater === undefined) {
|
// revalidateQuery hits the same cache key refetch would, without capturing
|
||||||
return refetch()
|
// the per-render refetch closure.
|
||||||
}
|
const mutateClash = useCallback(
|
||||||
void setCacheData<IConfigData>(['getRuntimeConfig'], updater)
|
(updater?: MutateClashUpdater, revalidate?: boolean) => {
|
||||||
if (revalidate !== false) {
|
if (updater === undefined) {
|
||||||
return refetch()
|
return revalidateQuery(['getRuntimeConfig'])
|
||||||
}
|
}
|
||||||
return Promise.resolve()
|
void setCacheData<IConfigData>(['getRuntimeConfig'], updater)
|
||||||
}
|
if (revalidate !== false) {
|
||||||
|
return revalidateQuery(['getRuntimeConfig'])
|
||||||
|
}
|
||||||
|
return Promise.resolve()
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
const patchClash = useLockFn(async (patch: Partial<IConfigData>) => {
|
const patchClash = useLockFn(async (patch: Partial<IConfigData>) => {
|
||||||
await mutate(() => patchClashConfig(patch), {
|
await mutate(() => patchClashConfig(patch), {
|
||||||
@@ -143,7 +150,10 @@ export const useClashInfo = () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
const invalidateClashConfig = () => revalidateQuery(['getClashConfig'])
|
const invalidateClashConfig = useCallback(
|
||||||
|
() => revalidateQuery(['getClashConfig']),
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
clashInfo,
|
clashInfo,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useCallback, useSyncExternalStore } from 'react'
|
import { useCallback, useMemo, useSyncExternalStore } from 'react'
|
||||||
|
|
||||||
import delayManager, { type DelaySnapshot } from '@/services/delay'
|
import delayManager, { type DelaySnapshot } from '@/services/delay'
|
||||||
import type { ResolvedProxyMember } from '@/types/proxy-view'
|
import type { ResolvedProxyMember } from '@/types/proxy-view'
|
||||||
@@ -32,7 +32,7 @@ export const useGroupsDelays = (
|
|||||||
groups: readonly string[],
|
groups: readonly string[],
|
||||||
): ReadonlyMap<string, DelaySnapshot> => {
|
): ReadonlyMap<string, DelaySnapshot> => {
|
||||||
// Group membership must remain unambiguous when names contain spaces.
|
// Group membership must remain unambiguous when names contain spaces.
|
||||||
const groupKey = JSON.stringify(groups)
|
const groupKey = useMemo(() => JSON.stringify(groups), [groups])
|
||||||
|
|
||||||
const subscribe = useCallback(
|
const subscribe = useCallback(
|
||||||
(onSettle: () => void) => {
|
(onSettle: () => void) => {
|
||||||
|
|||||||
@@ -158,11 +158,9 @@ 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[]
|
||||||
@@ -176,8 +174,6 @@ 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(() => {
|
||||||
@@ -190,12 +186,9 @@ export const useTrafficMonitorEnhanced = (options?: {
|
|||||||
client.start(currentRangeRef.current)
|
client.start(currentRangeRef.current)
|
||||||
|
|
||||||
let unsubscribe: (() => void) | undefined
|
let unsubscribe: (() => void) | undefined
|
||||||
if (subscribeToSnapshots || onSnapshot) {
|
if (subscribeToSnapshots) {
|
||||||
unsubscribe = client.onSnapshot((message) => {
|
unsubscribe = client.onSnapshot((message) => {
|
||||||
// onSnapshot is the always-live channel (ignores visibility); the
|
if (!isVisibleRef.current) return
|
||||||
// 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,
|
||||||
@@ -210,14 +203,14 @@ export const useTrafficMonitorEnhanced = (options?: {
|
|||||||
client.stop()
|
client.stop()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [enabled, subscribeToSnapshots, onSnapshot])
|
}, [enabled, subscribeToSnapshots])
|
||||||
|
|
||||||
// Re-prime snapshot ingestion after every visible transition
|
// Re-prime snapshot ingestion after every visible transition
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (enabled && isVisible && (subscribeToSnapshots || onSnapshot)) {
|
if (enabled && subscribeToSnapshots && isVisible) {
|
||||||
clientRef.current?.requestSnapshot()
|
clientRef.current?.requestSnapshot()
|
||||||
}
|
}
|
||||||
}, [enabled, subscribeToSnapshots, onSnapshot, isVisible])
|
}, [enabled, subscribeToSnapshots, isVisible])
|
||||||
|
|
||||||
// 添加流量数据
|
// 添加流量数据
|
||||||
const appendData = useCallback(
|
const appendData = useCallback(
|
||||||
@@ -251,12 +244,8 @@ export const useTrafficMonitorEnhanced = (options?: {
|
|||||||
/**
|
/**
|
||||||
* 图表数据Hook
|
* 图表数据Hook
|
||||||
*/
|
*/
|
||||||
export const useTrafficGraphDataEnhanced = (options?: {
|
export const useTrafficGraphDataEnhanced = () => {
|
||||||
subscribe?: boolean
|
const { graphData, samplerStats } = useTrafficMonitorEnhanced()
|
||||||
enabled?: boolean
|
|
||||||
onSnapshot?: (message: ITrafficWorkerSnapshotMessage) => void
|
|
||||||
}) => {
|
|
||||||
const { graphData, samplerStats } = useTrafficMonitorEnhanced(options)
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...graphData,
|
...graphData,
|
||||||
|
|||||||
@@ -177,13 +177,15 @@ export async function getProxyView(): Promise<ProxyViewV1> {
|
|||||||
return view
|
return view
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getClashLogs matches both patterns against every log line.
|
||||||
|
const CLASH_LOG_REGEX = /time="(.+?)"\s+level=(.+?)\s+msg="(.+?)"/
|
||||||
|
const CLASH_LOG_NEW_REGEX = /(.+?)\s+(.+?)\s+(.+)/
|
||||||
|
|
||||||
export async function getClashLogs() {
|
export async function getClashLogs() {
|
||||||
const regex = /time="(.+?)"\s+level=(.+?)\s+msg="(.+?)"/
|
|
||||||
const newRegex = /(.+?)\s+(.+?)\s+(.+)/
|
|
||||||
const logs = await commands.getClashLogs()
|
const logs = await commands.getClashLogs()
|
||||||
|
|
||||||
return logs.reduce<ILogItem[]>((acc, log) => {
|
return logs.reduce<ILogItem[]>((acc, log) => {
|
||||||
const result = log.match(regex)
|
const result = log.match(CLASH_LOG_REGEX)
|
||||||
if (result) {
|
if (result) {
|
||||||
const [_, _time, type, payload] = result
|
const [_, _time, type, payload] = result
|
||||||
const time = dayjs(_time).format('MM-DD HH:mm:ss')
|
const time = dayjs(_time).format('MM-DD HH:mm:ss')
|
||||||
@@ -191,7 +193,7 @@ export async function getClashLogs() {
|
|||||||
return acc
|
return acc
|
||||||
}
|
}
|
||||||
|
|
||||||
const result2 = log.match(newRegex)
|
const result2 = log.match(CLASH_LOG_NEW_REGEX)
|
||||||
if (result2) {
|
if (result2) {
|
||||||
const [_, time, type, payload] = result2
|
const [_, time, type, payload] = result2
|
||||||
acc.push({ time, type, payload })
|
acc.push({ time, type, payload })
|
||||||
|
|||||||
@@ -514,9 +514,21 @@ export function hideNotice(id: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function hideNoticesByCode(code: string) {
|
function hideNoticesByCode(code: string) {
|
||||||
notices
|
// One subscriber notification for the whole batch; per-notice removal
|
||||||
.filter((notice) => notice.code === code)
|
// would notify once per item.
|
||||||
.forEach(({ id }) => hideNotice(id))
|
const remaining: NoticeItem[] = []
|
||||||
|
let removed = false
|
||||||
|
for (const notice of notices) {
|
||||||
|
if (notice.code === code) {
|
||||||
|
removed = true
|
||||||
|
if (notice.timerId) clearTimeout(notice.timerId)
|
||||||
|
} else {
|
||||||
|
remaining.push(notice)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!removed) return
|
||||||
|
notices = remaining
|
||||||
|
notifySubscribers()
|
||||||
}
|
}
|
||||||
|
|
||||||
export function syncSidecarFailure(snapshot: SidecarFailureSnapshot) {
|
export function syncSidecarFailure(snapshot: SidecarFailureSnapshot) {
|
||||||
|
|||||||
@@ -19,13 +19,6 @@ 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)
|
||||||
@@ -40,7 +33,6 @@ const broadcastSnapshot = () => {
|
|||||||
|
|
||||||
ctx.postMessage(message)
|
ctx.postMessage(message)
|
||||||
lastBroadcast = dataPoints
|
lastBroadcast = dataPoints
|
||||||
lastSamplerVersion = sampler.getVersion()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const scheduleSnapshot = () => {
|
const scheduleSnapshot = () => {
|
||||||
@@ -63,18 +55,9 @@ 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,33 +7,14 @@ 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)
|
||||||
const label = `${pad2(date.getHours())}:${pad2(date.getMinutes())}`
|
return `${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)
|
||||||
const label = `${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`
|
return `${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) => {
|
||||||
@@ -72,12 +53,10 @@ 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
|
||||||
@@ -188,13 +167,7 @@ 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 = []
|
||||||
|
|||||||
@@ -241,17 +241,17 @@ export function parseUrlLike(
|
|||||||
: result
|
: result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Both predicates run per parsed proxy URI.
|
||||||
|
const IPV4_REGEX = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/
|
||||||
|
const IPV6_REGEX =
|
||||||
|
/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::$|^::1$|^([0-9a-fA-F]{1,4}:)*::([0-9a-fA-F]{1,4}:)*[0-9a-fA-F]{1,4}$/
|
||||||
|
|
||||||
export function isIPv4(address: string): boolean {
|
export function isIPv4(address: string): boolean {
|
||||||
// Check if the address is IPv4
|
return IPV4_REGEX.test(address)
|
||||||
const ipv4Regex = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/
|
|
||||||
return ipv4Regex.test(address)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isIPv6(address: string): boolean {
|
export function isIPv6(address: string): boolean {
|
||||||
// Check if the address is IPv6 - simplified regex to avoid backreference issues
|
return IPV6_REGEX.test(address)
|
||||||
const ipv6Regex =
|
|
||||||
/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::$|^::1$|^([0-9a-fA-F]{1,4}:)*::([0-9a-fA-F]{1,4}:)*[0-9a-fA-F]{1,4}$/
|
|
||||||
return ipv6Regex.test(address)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function decodeBase64OrOriginal(str: string): string {
|
export function decodeBase64OrOriginal(str: string): string {
|
||||||
|
|||||||
Reference in New Issue
Block a user