Compare commits

..
Author SHA1 Message Date
Tunglies f0e1460a04 perf(home): build traffic range snapshots in one pass
The 200ms graph snapshot built three to four intermediate arrays on the
compressed path before posting to the worker. It now fills one
preallocated result in a single pass and only sorts when the compressed
and raw ranges actually interleave.
2026-11-19 21:46:06 +08:00
Tunglies e90f8c500f perf(log): reuse the empty logs fallback identity
A fresh [] fallback gave the subscription hook's refresh callback and
snapshot effect a new identity on every render while logs streamed; the
empty list is now a shared module constant.
2026-11-19 21:46:04 +08:00
Tunglies 36f79c6033 perf(proxy): stable group location and chain list identities
The sticky-header scroll callback depended on the render list identity,
re-creating the item renderer on every list rebuild; it now reads the
list through a stable ref callback. Rebinding no longer allocates new
chain items and arrays when values are unchanged, so the 15s proxy-view
refresh stops re-serializing identical chains to localStorage, and the
chain delay key join is memoized.
2026-11-19 21:45:54 +08:00
Tunglies d535c1b7d1 perf(proxy): stable tool callbacks and shared delay entries
Group headers and heads passed freshly-created closures into the
memoized tools, defeating it on every render; the tool callbacks are now
groupName-parameterized and forwarded directly. Cached delay entries are
write-once, so the defensive copy on read and the second copy in the
delay-state reducer were dropped.
2026-11-19 21:45:45 +08:00
Tunglies d162478100 perf(ui): hoist static dialog identities and memoize settings search
The DNS viewer rebuilt Monaco's options object per keystroke, the update
dialog rebuilt its markdown component map and plugin array per progress
chunk (remounting link and blockquote subtrees), and the settings search
rescanned the ~180-entry catalog on unrelated renders such as arrow-key
selection. These identities are now module constants or single memos;
the width-dependent minimap option is applied at editor mount.
2026-11-19 21:45:34 +08:00
Tunglies f4761e763a perf(ui): keep mutateVerge identity stable across renders
mutateVerge was a per-render closure that dozens of consumer callbacks
depended on, and its updater fell back to a render-time config snapshot.
It now keeps a stable identity, revalidates through the module-level
query helper, and passes the live cache value (preload snapshot when the
cache is still empty) to function updaters; object-form callers were
migrated to updater functions.
2026-11-19 21:45:27 +08:00
Tunglies 01e28608ef perf(profile): derive editor policy names and dedupe pasted proxies
The groups editor re-read both profile files and re-parsed three YAML
documents on every prepend/append/delete edit. The origin names are now
read once per open and folded into a memoized policy list, and batch
pasted proxy names dedupe through a Set instead of a linear scan.
2026-11-19 21:45:19 +08:00
Tunglies 0013fb3680 perf(profile): stabilize profile grid callbacks and context menus
ProfileItem is memoized, but the grid passed five freshly-created closure
props per render, so URL keystrokes and switch spinners re-rendered every
card. The callbacks are now uid/item-parameterized stable handlers, and
the context-menu label map and item literals are hoisted or gated on the
menu being open.
2026-11-19 21:45:05 +08:00
40 changed files with 1010 additions and 1272 deletions
+1 -1
View File
@@ -63,11 +63,11 @@
<details> <details>
<summary><strong> 🚀 优化改进 </strong></summary> <summary><strong> 🚀 优化改进 </strong></summary>
- 优化首页流量图与代理、订阅、日志、设置页面的渲染效率,长列表滚动与实时刷新更流畅
- 优化连接、规则和日志筛选:切换页面后保留过滤条件 - 优化连接、规则和日志筛选:切换页面后保留过滤条件
- 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组 - 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组
- 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件 - 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件
- 优化首页「当前节点」卡片:代理组列表加入 `fallback` 代理组,切换到 `url-test` 或 `fallback` 代理组时同样联动 `select` 代理组 - 优化首页「当前节点」卡片:代理组列表加入 `fallback` 代理组,切换到 `url-test` 或 `fallback` 代理组时同样联动 `select` 代理组
- 优化主页流量图表与日志、代理列表的实时刷新和滚动占用,降低高频更新时的 CPU 负载
**🍎 macOS** **🍎 macOS**
+1 -1
View File
@@ -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
View File
@@ -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'
-137
View File
@@ -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
}
-93
View File
@@ -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>,
)
-17
View File
@@ -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'
-30
View File
@@ -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
View File
@@ -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,
},
},
}), }),
) )
@@ -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>
+6 -15
View File
@@ -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,
+6 -6
View File
@@ -87,18 +87,18 @@ export const TestCard = () => {
x.uid === uid ? { ...x, ...patch } : x, x.uid === uid ? { ...x, ...patch } : x,
) )
mutateVerge({ ...verge, test_list: newList }) mutateVerge((prev) => ({ ...prev, test_list: newList }))
}, },
[testList, verge, mutateVerge], [testList, mutateVerge],
) )
const onDeleteTestListItem = useCallback( const onDeleteTestListItem = useCallback(
(uid: string) => { (uid: string) => {
const newList = testList.filter((x) => x.uid !== uid) const newList = testList.filter((x) => x.uid !== uid)
patchVerge({ test_list: newList }) patchVerge({ test_list: newList })
mutateVerge({ ...verge, test_list: newList }) mutateVerge((prev) => ({ ...prev, test_list: newList }))
}, },
[testList, verge, patchVerge, mutateVerge], [testList, patchVerge, mutateVerge],
) )
const onDragEnd = useCallback( const onDragEnd = useCallback(
@@ -129,7 +129,7 @@ export const TestCard = () => {
newList.splice(newIndex, 0, removed) newList.splice(newIndex, 0, removed)
// 优化:先本地更新,再异步 patch,避免UI卡死 // 优化:先本地更新,再异步 patch,避免UI卡死
mutateVerge({ ...verge, test_list: newList }) mutateVerge((prev) => ({ ...prev, test_list: newList }))
const patchFn = () => { const patchFn = () => {
try { try {
patchVerge({ test_list: newList }) patchVerge({ test_list: newList })
@@ -141,7 +141,7 @@ export const TestCard = () => {
setTimeout(patchFn, 0) setTimeout(patchFn, 0)
} }
}, },
[testList, verge, mutateVerge, patchVerge], [testList, mutateVerge, patchVerge],
) )
// 仅在verge首次加载时初始化测试列表 // 仅在verge首次加载时初始化测试列表
+36 -34
View File
@@ -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} />
+8 -21
View File
@@ -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,15 +47,11 @@ interface Props {
searchState?: SearchState searchState?: SearchState
} }
// Compiling per row multiplied by high-frequency log appends; searchState is const LogItem = ({ value, searchState }: Props) => {
// React state, so identity reuse is safe until the search inputs change. const renderHighlightText = (text: string) => {
let highlightRegexCache: { state: SearchState; regex: RegExp | null } | null = if (!searchState?.text.trim()) return text
null
const getHighlightRegex = (searchState: SearchState): RegExp | null => {
if (highlightRegexCache?.state === searchState)
return highlightRegexCache.regex
try {
const searchText = searchState.text const searchText = searchState.text
let pattern: string let pattern: string
@@ -73,18 +68,7 @@ const getHighlightRegex = (searchState: SearchState): RegExp | null => {
} }
const flags = searchState.matchCase ? 'g' : 'gi' const flags = searchState.matchCase ? 'g' : 'gi'
const regex = buildRegex(pattern, flags) const regex = new RegExp(pattern, flags)
highlightRegexCache = { state: searchState, regex }
return regex
}
const LogItem = ({ value, searchState }: Props) => {
const renderHighlightText = (text: string) => {
if (!searchState?.text.trim()) return text
const regex = getHighlightRegex(searchState)
if (!regex) return text
const elements: ReactNode[] = [] const elements: ReactNode[] = []
let lastIndex = 0 let lastIndex = 0
let match: RegExpExecArray | null let match: RegExpExecArray | null
@@ -116,6 +100,9 @@ const LogItem = ({ value, searchState }: Props) => {
} }
return elements.length ? elements : text return elements.length ? elements : text
} catch {
return text
}
} }
return ( return (
+23 -11
View File
@@ -176,7 +176,10 @@ export const GroupsEditorViewer = (props: Props) => {
}, },
}) })
const [groupList, setGroupList] = useState<IProxyGroupConfig[]>([]) const [groupList, setGroupList] = useState<IProxyGroupConfig[]>([])
const [proxyPolicyList, setProxyPolicyList] = useState<string[]>([]) const [originPolicy, setOriginPolicy] = useState<{
proxyNames: string[]
groupNames: string[]
}>({ proxyNames: [], groupNames: [] })
const [proxyProviderList, setProxyProviderList] = useState<string[]>([]) const [proxyProviderList, setProxyProviderList] = useState<string[]>([])
const [prependSeq, setPrependSeq] = useState<IProxyGroupConfig[]>([]) const [prependSeq, setPrependSeq] = useState<IProxyGroupConfig[]>([])
const [appendSeq, setAppendSeq] = useState<IProxyGroupConfig[]>([]) const [appendSeq, setAppendSeq] = useState<IProxyGroupConfig[]>([])
@@ -353,6 +356,9 @@ export const GroupsEditorViewer = (props: Props) => {
} }
}, [prependSeq, appendSeq, deleteSeq]) }, [prependSeq, appendSeq, deleteSeq])
// Origin policy names come from profile files that this dialog never
// rewrites while open, so they are read once per open; the live seq states
// are folded in by the derived proxyPolicyList below.
const fetchProxyPolicy = useCallback(async () => { const fetchProxyPolicy = useCallback(async () => {
const data = await readProfileFile(profileUid) const data = await readProfileFile(profileUid)
const proxiesData = await readProfileFile(proxiesUid) const proxiesData = await readProfileFile(proxiesUid)
@@ -388,17 +394,13 @@ export const GroupsEditorViewer = (props: Props) => {
(name): name is string => typeof name === 'string' && name.length > 0, (name): name is string => typeof name === 'string' && name.length > 0,
) )
const computedPolicyList = builtinProxyPolicies.concat( setOriginPolicy({
prependSeq.map((group: IProxyGroupConfig) => group.name),
(originGroupsObj?.['proxy-groups'] || [])
.map((group: IProxyGroupConfig) => group.name)
.filter((name) => !deleteSeq.includes(name)),
appendSeq.map((group: IProxyGroupConfig) => group.name),
proxyNames, proxyNames,
) groupNames: (originGroupsObj?.['proxy-groups'] || []).map(
(group) => group.name,
setProxyPolicyList(Array.from(new Set(computedPolicyList))) ),
}, [appendSeq, deleteSeq, prependSeq, profileUid, proxiesUid]) })
}, [profileUid, proxiesUid])
const fetchProfile = useCallback(async () => { const fetchProfile = useCallback(async () => {
const data = await readProfileFile(profileUid) const data = await readProfileFile(profileUid)
const mergeData = await readProfileFile(mergeUid) const mergeData = await readProfileFile(mergeUid)
@@ -442,6 +444,16 @@ export const GroupsEditorViewer = (props: Props) => {
fetchProxyPolicy() fetchProxyPolicy()
}, [fetchProxyPolicy, open]) }, [fetchProxyPolicy, open])
const proxyPolicyList = useMemo(() => {
const computedPolicyList = builtinProxyPolicies.concat(
prependSeq.map((group) => group.name),
originPolicy.groupNames.filter((name) => !deleteSeq.includes(name)),
appendSeq.map((group) => group.name),
originPolicy.proxyNames,
)
return Array.from(new Set(computedPolicyList))
}, [appendSeq, deleteSeq, originPolicy, prependSeq])
useEffect(() => { useEffect(() => {
if (!open) return if (!open) return
fetchContent() fetchContent()
+52 -44
View File
@@ -61,6 +61,31 @@ const round = keyframes`
to { transform: rotate(360deg); } to { transform: rotate(360deg); }
` `
type ContextMenuItem = {
label: string
handler: () => void
disabled: boolean
}
const menuLabels: Record<string, TranslationKey> = {
home: 'profiles.components.menu.home',
select: 'profiles.components.menu.select',
shareQrCode: 'profiles.components.menu.shareQrCode',
editInfo: 'profiles.components.menu.editInfo',
editFile: 'profiles.components.menu.editFile',
editRules: 'profiles.components.menu.editRules',
editProxies: 'profiles.components.menu.editProxies',
editGroups: 'profiles.components.menu.editGroups',
extendConfig: 'profiles.components.menu.extendConfig',
extendScript: 'profiles.components.menu.extendScript',
openFile: 'profiles.components.menu.openFile',
update: 'profiles.components.menu.update',
updateViaProxy: 'profiles.components.menu.updateViaProxy',
delete: 'shared.actions.delete',
} as const
const EMPTY_CONTEXT_MENU: ContextMenuItem[] = []
export interface ProfileItemProps { export interface ProfileItemProps {
id: string id: string
index: number index: number
@@ -68,13 +93,13 @@ export interface ProfileItemProps {
activating: boolean activating: boolean
itemData: IProfileItem itemData: IProfileItem
mutateProfiles: () => Promise<void> mutateProfiles: () => Promise<void>
onSelect: (force: boolean) => void onSelect: (uid: string, force: boolean) => void
onEdit: () => void onEdit: (item: IProfileItem) => void
onSave?: (prev?: string, curr?: string) => void onSave?: (uid: string, prev?: string, curr?: string) => void
onDelete: () => void onDelete: (uid: string) => void
batchMode?: boolean batchMode?: boolean
isSelected?: boolean isSelected?: boolean
onSelectionChange?: () => void onSelectionChange?: (uid: string) => void
timerUpdateRevision: number timerUpdateRevision: number
completedUpdateRevision: number completedUpdateRevision: number
} }
@@ -322,7 +347,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const onEditInfo = () => { const onEditInfo = () => {
setAnchorEl(null) setAnchorEl(null)
onEdit() onEdit(itemData)
} }
const onShareQrCode = () => { const onShareQrCode = () => {
@@ -362,7 +387,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const onForceSelect = () => { const onForceSelect = () => {
setAnchorEl(null) setAnchorEl(null)
onSelect(true) onSelect(id, true)
} }
const onOpenFile = useLockFn(async () => { const onOpenFile = useLockFn(async () => {
@@ -412,30 +437,13 @@ const ProfileItemBase = (props: ProfileItemProps) => {
} }
}) })
type ContextMenuItem = { // The context menu is closed on almost every render; building its items
label: string // only while open keeps the idle path allocation-free.
handler: () => void const menuItems: ContextMenuItem[] =
disabled: boolean anchorEl === null
} ? EMPTY_CONTEXT_MENU
: hasUrl
const menuLabels: Record<string, TranslationKey> = { ? [
home: 'profiles.components.menu.home',
select: 'profiles.components.menu.select',
shareQrCode: 'profiles.components.menu.shareQrCode',
editInfo: 'profiles.components.menu.editInfo',
editFile: 'profiles.components.menu.editFile',
editRules: 'profiles.components.menu.editRules',
editProxies: 'profiles.components.menu.editProxies',
editGroups: 'profiles.components.menu.editGroups',
extendConfig: 'profiles.components.menu.extendConfig',
extendScript: 'profiles.components.menu.extendScript',
openFile: 'profiles.components.menu.openFile',
update: 'profiles.components.menu.update',
updateViaProxy: 'profiles.components.menu.updateViaProxy',
delete: 'shared.actions.delete',
} as const
const urlModeMenu: ContextMenuItem[] = [
...(hasHome ...(hasHome
? [ ? [
{ {
@@ -511,7 +519,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
setAnchorEl(null) setAnchorEl(null)
if (batchMode) { if (batchMode) {
if (onSelectionChange) { if (onSelectionChange) {
onSelectionChange() onSelectionChange(id)
} }
} else { } else {
setConfirmOpen(true) setConfirmOpen(true)
@@ -520,7 +528,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
disabled: false, disabled: false,
}, },
] ]
const fileModeMenu: ContextMenuItem[] = [ : [
{ {
label: menuLabels.select, label: menuLabels.select,
handler: onForceSelect, handler: onForceSelect,
@@ -572,7 +580,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
setAnchorEl(null) setAnchorEl(null)
if (batchMode) { if (batchMode) {
if (onSelectionChange) { if (onSelectionChange) {
onSelectionChange() onSelectionChange(id)
} }
} else { } else {
setConfirmOpen(true) setConfirmOpen(true)
@@ -599,7 +607,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
await profileDocument.reload() await profileDocument.reload()
return return
} }
onSave?.(profileDocument.savedValue, currentValue) onSave?.(id, profileDocument.savedValue, currentValue)
profileDocument.markSaved(currentValue) profileDocument.markSaved(currentValue)
}) })
@@ -614,7 +622,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
await mergeDocument.reload() await mergeDocument.reload()
return return
} }
onSave?.(mergeDocument.savedValue, currentValue) onSave?.(id, mergeDocument.savedValue, currentValue)
mergeDocument.markSaved(currentValue) mergeDocument.markSaved(currentValue)
}) })
@@ -632,7 +640,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
await scriptDocument.reload() await scriptDocument.reload()
return return
} }
onSave?.(scriptDocument.savedValue, currentValue) onSave?.(id, scriptDocument.savedValue, currentValue)
scriptDocument.markSaved(currentValue) scriptDocument.markSaved(currentValue)
}) })
@@ -646,7 +654,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
e.stopPropagation() e.stopPropagation()
return return
} }
onSelect(false) onSelect(id, false)
}} }}
onContextMenu={(event) => { onContextMenu={(event) => {
const { clientX, clientY } = event const { clientX, clientY } = event
@@ -687,7 +695,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
onClick={(e) => { onClick={(e) => {
e.stopPropagation() e.stopPropagation()
if (onSelectionChange) { if (onSelectionChange) {
onSelectionChange() onSelectionChange(id)
} }
}} }}
> >
@@ -853,7 +861,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
e.preventDefault() e.preventDefault()
}} }}
> >
{(hasUrl ? urlModeMenu : fileModeMenu).map((item) => ( {menuItems.map((item) => (
<MenuItem <MenuItem
key={item.label} key={item.label}
onClick={item.handler} onClick={item.handler}
@@ -897,7 +905,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
profileUid={uid!} profileUid={uid!}
property={option?.rules ?? ''} property={option?.rules ?? ''}
open={true} open={true}
onSave={onSave} onSave={(prev, curr) => onSave?.(id, prev, curr)}
onClose={() => setRulesOpen(false)} onClose={() => setRulesOpen(false)}
/> />
)} )}
@@ -906,7 +914,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
profileUid={uid!} profileUid={uid!}
property={option?.proxies ?? ''} property={option?.proxies ?? ''}
open={true} open={true}
onSave={onSave} onSave={(prev, curr) => onSave?.(id, prev, curr)}
onClose={() => setProxiesOpen(false)} onClose={() => setProxiesOpen(false)}
/> />
)} )}
@@ -917,7 +925,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
profileUid={uid!} profileUid={uid!}
property={option?.groups ?? ''} property={option?.groups ?? ''}
open={true} open={true}
onSave={onSave} onSave={(prev, curr) => onSave?.(id, prev, curr)}
onClose={() => { onClose={() => {
setGroupsOpen(false) setGroupsOpen(false)
}} }}
@@ -963,7 +971,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
onCancel={() => setConfirmOpen(false)} onCancel={() => setConfirmOpen(false)}
onClose={() => setConfirmOpen(false)} onClose={() => setConfirmOpen(false)}
onOk={() => { onOk={() => {
onDelete() onDelete(id)
setConfirmOpen(false) setConfirmOpen(false)
}} }}
> >
@@ -180,7 +180,7 @@ export const ProxiesEditorViewer = (props: Props) => {
// 优化:异步分片解析,避免主线程阻塞,解析完成后批量setState // 优化:异步分片解析,避免主线程阻塞,解析完成后批量setState
const handleParseAsync = (cb: (proxies: IProxyConfig[]) => void) => { const handleParseAsync = (cb: (proxies: IProxyConfig[]) => void) => {
const proxies: IProxyConfig[] = [] const proxies: IProxyConfig[] = []
const names: string[] = [] const names = new Set<string>()
let uris: string let uris: string
try { try {
uris = atob(proxyUri) uris = atob(proxyUri)
@@ -198,9 +198,9 @@ export const ProxiesEditorViewer = (props: Props) => {
const uri = lines[idx] const uri = lines[idx]
try { try {
const proxy = parseUri(uri.trim()) const proxy = parseUri(uri.trim())
if (!names.includes(proxy.name)) { if (!names.has(proxy.name)) {
proxies.push(proxy) proxies.push(proxy)
names.push(proxy.name) names.add(proxy.name)
} }
} catch (err) { } catch (err) {
console.warn( console.warn(
+32 -6
View File
@@ -3,6 +3,7 @@ import * as yaml from 'js-yaml'
import { import {
getRecord, getRecord,
rebindNode, rebindNode,
sameSource,
type ProxyNodeView, type ProxyNodeView,
type ProxyViewV1, type ProxyViewV1,
} from '@/types/proxy-view' } from '@/types/proxy-view'
@@ -20,22 +21,47 @@ export const rebindProxyChainItems = (
items: readonly ProxyChainItem[], items: readonly ProxyChainItem[],
candidates: readonly ProxyNodeView[], candidates: readonly ProxyNodeView[],
proxyView: ProxyViewV1, proxyView: ProxyViewV1,
): ProxyChainItem[] => ): ProxyChainItem[] => {
items.map((item) => { // The proxy view refreshes on a fixed cadence; reusing item and array
// identities while the rebound values are equal keeps persistence effects
// and memoized chain rows from reprocessing identical content.
let reboundItems: ProxyChainItem[] | undefined
items.forEach((item, index) => {
const rebound = rebindNode(candidates, { const rebound = rebindNode(candidates, {
name: item.name, name: item.name,
source: item.source, source: item.source,
}) })
const record = const record =
rebound === undefined ? undefined : getRecord(proxyView, rebound.recordId) rebound === undefined ? undefined : getRecord(proxyView, rebound.recordId)
return { const source = rebound?.source ?? item.source
const type = rebound?.type ?? item.type
const delay = record?.history.at(-1)?.delay
const sourceReused =
item.source === source ||
(item.source !== undefined &&
source !== undefined &&
sameSource(item.source, source))
if (
item.recordId === rebound?.recordId &&
sourceReused &&
item.type === type &&
item.delay === delay
) {
return
}
reboundItems ??= [...items]
reboundItems[index] = {
...item, ...item,
recordId: rebound?.recordId, recordId: rebound?.recordId,
source: rebound?.source ?? item.source, source,
type: rebound?.type ?? item.type, type,
delay: record?.history.at(-1)?.delay, delay,
} }
}) })
return reboundItems ?? (items as ProxyChainItem[])
}
interface ParsedChainConfig { interface ParsedChainConfig {
proxies?: Array<{ proxies?: Array<{
+19 -17
View File
@@ -31,9 +31,9 @@ interface Props {
url?: string url?: string
groupName: string groupName: string
headState: HeadState headState: HeadState
onLocation: () => void onLocation: (groupName: string) => void
onCheckDelay: () => void onCheckDelay: (groupName: string) => void
onHeadState: (val: Partial<HeadState>) => void onHeadState: (groupName: string, val: Partial<HeadState>) => void
} }
export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) { export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
@@ -76,7 +76,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
// 因此对写入 headState 的动作做防抖,避免每输入一个字符就过滤一次。 // 因此对写入 headState 的动作做防抖,避免每输入一个字符就过滤一次。
const { run: applyFilter, flush: flushFilter } = useDebounceFn( const { run: applyFilter, flush: flushFilter } = useDebounceFn(
(state: SearchState) => { (state: SearchState) => {
onHeadState({ onHeadState(groupName, {
filterText: state.text, filterText: state.text,
filterMatchCase: state.matchCase, filterMatchCase: state.matchCase,
filterMatchWholeWord: state.matchWholeWord, filterMatchWholeWord: state.matchWholeWord,
@@ -125,7 +125,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.preventDefault() e.preventDefault()
e.stopPropagation() e.stopPropagation()
}} }}
onChange={(e) => onHeadState({ testUrl: e.target.value })} onChange={(e) => onHeadState(groupName, { testUrl: e.target.value })}
sx={{ flex: '1 1 auto', input: { py: 0.65, px: 1 } }} sx={{ flex: '1 1 auto', input: { py: 0.65, px: 1 } }}
/> />
)} )}
@@ -155,8 +155,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation() e.stopPropagation()
if (!headState.open) if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync // eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true })) flushSync(() => onHeadState(groupName, { open: true }))
onLocation() onLocation(groupName)
}} }}
> >
<MyLocationRounded fontSize="inherit" /> <MyLocationRounded fontSize="inherit" />
@@ -171,16 +171,16 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation() e.stopPropagation()
if (!headState.open) if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync // eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true })) flushSync(() => onHeadState(groupName, { open: true }))
// Remind the user that it is custom test url // Remind the user that it is custom test url
if (testUrl?.trim() && textState !== 'filter') { if (testUrl?.trim() && textState !== 'filter') {
onHeadState({ textState: 'url' }) onHeadState(groupName, { textState: 'url' })
} }
if (testUrl?.trim() && !isValidUrl(testUrl)) { if (testUrl?.trim() && !isValidUrl(testUrl)) {
showNotice.warning('proxies.feedback.warnings.invalidTestUrl') showNotice.warning('proxies.feedback.warnings.invalidTestUrl')
return return
} }
onCheckDelay() onCheckDelay(groupName)
}} }}
> >
<NetworkCheckRounded fontSize="inherit" /> <NetworkCheckRounded fontSize="inherit" />
@@ -201,8 +201,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation() e.stopPropagation()
if (!headState.open) if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync // eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true })) flushSync(() => onHeadState(groupName, { open: true }))
onHeadState({ onHeadState(groupName, {
sortType: ((sortType + 1) % 3) as ProxySortType, sortType: ((sortType + 1) % 3) as ProxySortType,
}) })
}} }}
@@ -219,7 +219,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
onClick={(e) => { onClick={(e) => {
e.preventDefault() e.preventDefault()
e.stopPropagation() e.stopPropagation()
onHeadState({ onHeadState(groupName, {
textState: textState === 'url' ? null : 'url', textState: textState === 'url' ? null : 'url',
}) })
setTimeout(() => inputRef.current?.focus()) setTimeout(() => inputRef.current?.focus())
@@ -245,8 +245,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation() e.stopPropagation()
if (!headState.open) if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync // eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true })) flushSync(() => onHeadState(groupName, { open: true }))
onHeadState({ showType: !showType }) onHeadState(groupName, { showType: !showType })
}} }}
> >
{showType ? ( {showType ? (
@@ -265,8 +265,10 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation() e.stopPropagation()
if (!headState.open && textState !== 'filter') if (!headState.open && textState !== 'filter')
// eslint-disable-next-line @eslint-react/dom-no-flush-sync // eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true })) flushSync(() => onHeadState(groupName, { open: true }))
onHeadState({ textState: textState === 'filter' ? null : 'filter' }) onHeadState(groupName, {
textState: textState === 'filter' ? null : 'filter',
})
setTimeout(() => inputRef.current?.focus()) setTimeout(() => inputRef.current?.focus())
}} }}
> >
+2 -2
View File
@@ -93,7 +93,7 @@ interface ProxyGroupsChainProps {
// Shared callbacks // Shared callbacks
onCheckAll: (groupName: string) => void onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onLocation: (group: any) => void onLocation: (groupName: string) => void
onGroupSelect: (groupName: string) => void onGroupSelect: (groupName: string) => void
onScrollToTop: () => void onScrollToTop: () => void
} }
@@ -245,7 +245,7 @@ function ProxyVirtualList({
activeStickyIndex: number | null activeStickyIndex: number | null
isChainMode?: boolean isChainMode?: boolean
measureElement: (node: Element | null) => void measureElement: (node: Element | null) => void
onLocation: (group: any) => void onLocation: (groupName: string) => void
onCheckAll: (groupName: string) => void onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onChangeProxy: (group: ProxyGroupView, member: ResolvedProxyMember) => void onChangeProxy: (group: ProxyGroupView, member: ResolvedProxyMember) => void
+38 -46
View File
@@ -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,11 +167,16 @@ function useProxyRenderState(
) )
const getScrollPosition = useCallback(() => { const getScrollPosition = useCallback(() => {
const savedPositions = readScrollPositions() try {
const savedPositions = localStorage.getItem('proxy-scroll-positions')
if (savedPositions) { if (savedPositions) {
const savedPosition = savedPositions[scrollPositionKey] const positions = JSON.parse(savedPositions)
const savedPosition = positions[scrollPositionKey]
return savedPosition ?? 0 return savedPosition ?? 0
} }
} catch (e) {
console.error('Error restoring scroll position:', e)
}
}, [scrollPositionKey]) }, [scrollPositionKey])
return { return {
@@ -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)
@@ -339,16 +324,20 @@ function ChainProxyGroups(props: {
scrollTopRef.current = 0 scrollTopRef.current = 0
}, []) }, [])
const handleLocation = useStableCallback((group: ProxyGroupView) => { const handleLocation = useStableCallback((groupName: string) => {
if (!group) return // Flat (type 1) headers such as GLOBAL carry the same live group.
const { name, now } = group const headerIndex = renderList.findIndex(
(e) => (e.type === 0 || e.type === 1) && e.group?.name === groupName,
)
const now = renderList[headerIndex]?.group?.now
if (!now) return
const index = renderList.findIndex( const index = renderList.findIndex(
(item) => (e) =>
item.group?.name === name && e.group?.name === groupName &&
((item.type === 2 && item.member?.member.ref.name === now) || ((e.type === 2 && e.member?.member.ref.name === now) ||
(item.type === 4 && (e.type === 4 &&
item.memberCol?.some(({ member }) => member.ref.name === now))), e.memberCol?.some(({ member }) => member.ref.name === now))),
) )
if (index >= 0) { if (index >= 0) {
@@ -511,13 +500,17 @@ function NormalProxyGroups(props: { mode: string }) {
[globalGroupName, select, setHeadState], [globalGroupName, select, setHeadState],
) )
const handleLocation = useStableCallback((group: ProxyGroupView) => { const handleLocation = useStableCallback((groupName: string) => {
if (!group) return // Flat (type 1) headers such as GLOBAL carry the same live group.
const { name, now } = group const headerIndex = renderList.findIndex(
(e) => (e.type === 0 || e.type === 1) && e.group?.name === groupName,
)
const now = renderList[headerIndex]?.group?.now
if (!now) return
const index = renderList.findIndex( const index = renderList.findIndex(
(e) => (e) =>
e.group?.name === name && e.group?.name === groupName &&
((e.type === 2 && e.member?.member.ref.name === now) || ((e.type === 2 && e.member?.member.ref.name === now) ||
(e.type === 4 && (e.type === 4 &&
e.memberCol?.some(({ member }) => member.ref.name === now))), e.memberCol?.some(({ member }) => member.ref.name === now))),
@@ -531,8 +524,9 @@ function NormalProxyGroups(props: { mode: string }) {
} }
}) })
const handleGroupLocationByName = useCallback( // Stable identity: this feeds the sticky-header render callback; a
(groupName: string) => { // [renderList] dep would re-create it on every list rebuild.
const handleGroupLocationByName = useStableCallback((groupName: string) => {
const index = renderList.findIndex( const index = renderList.findIndex(
(item) => item.type === 0 && item.group?.name === groupName, (item) => item.type === 0 && item.group?.name === groupName,
) )
@@ -543,9 +537,7 @@ function NormalProxyGroups(props: { mode: string }) {
behavior: 'smooth', behavior: 'smooth',
}) })
} }
}, })
[renderList],
)
const proxyGroupNames = useMemo(() => { const proxyGroupNames = useMemo(() => {
const names = renderList const names = renderList
+18 -12
View File
@@ -30,9 +30,9 @@ interface Props {
url?: string url?: string
groupName: string groupName: string
headState: HeadState headState: HeadState
onLocation: () => void onLocation: (groupName: string) => void
onCheckDelay: () => void onCheckDelay: (groupName: string) => void
onHeadState: (val: Partial<HeadState>) => void onHeadState: (groupName: string, val: Partial<HeadState>) => void
} }
const defaultSx: SxProps = {} const defaultSx: SxProps = {}
@@ -81,7 +81,7 @@ export const ProxyHead = ({
size="small" size="small"
color="inherit" color="inherit"
title={t('proxies.page.tooltips.locate')} title={t('proxies.page.tooltips.locate')}
onClick={onLocation} onClick={() => onLocation(groupName)}
> >
<MyLocationRounded /> <MyLocationRounded />
</IconButton> </IconButton>
@@ -95,13 +95,13 @@ export const ProxyHead = ({
// Remind the user that it is custom test url // Remind the user that it is custom test url
if (testUrl?.trim() && textState !== 'filter') { if (testUrl?.trim() && textState !== 'filter') {
debugLog(`[ProxyHead] 使用自定义测试URL: ${testUrl}`) debugLog(`[ProxyHead] 使用自定义测试URL: ${testUrl}`)
onHeadState({ textState: 'url' }) onHeadState(groupName, { textState: 'url' })
} }
if (testUrl?.trim() && !isValidUrl(testUrl)) { if (testUrl?.trim() && !isValidUrl(testUrl)) {
showNotice.warning('proxies.feedback.warnings.invalidTestUrl') showNotice.warning('proxies.feedback.warnings.invalidTestUrl')
return return
} }
onCheckDelay() onCheckDelay(groupName)
}} }}
> >
<NetworkCheckRounded /> <NetworkCheckRounded />
@@ -118,7 +118,9 @@ export const ProxyHead = ({
][sortType] ][sortType]
} }
onClick={() => onClick={() =>
onHeadState({ sortType: ((sortType + 1) % 3) as ProxySortType }) onHeadState(groupName, {
sortType: ((sortType + 1) % 3) as ProxySortType,
})
} }
> >
{sortType !== 1 && sortType !== 2 && <SortRounded />} {sortType !== 1 && sortType !== 2 && <SortRounded />}
@@ -131,7 +133,9 @@ export const ProxyHead = ({
color="inherit" color="inherit"
title={t('proxies.page.tooltips.delayCheckUrl')} title={t('proxies.page.tooltips.delayCheckUrl')}
onClick={() => onClick={() =>
onHeadState({ textState: textState === 'url' ? null : 'url' }) onHeadState(groupName, {
textState: textState === 'url' ? null : 'url',
})
} }
> >
{textState === 'url' ? ( {textState === 'url' ? (
@@ -149,7 +153,7 @@ export const ProxyHead = ({
? t('proxies.page.tooltips.showBasic') ? t('proxies.page.tooltips.showBasic')
: t('proxies.page.tooltips.showDetail') : t('proxies.page.tooltips.showDetail')
} }
onClick={() => onHeadState({ showType: !showType })} onClick={() => onHeadState(groupName, { showType: !showType })}
> >
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />} {showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton> </IconButton>
@@ -159,7 +163,9 @@ export const ProxyHead = ({
color="inherit" color="inherit"
title={t('proxies.page.tooltips.filter')} title={t('proxies.page.tooltips.filter')}
onClick={() => onClick={() =>
onHeadState({ textState: textState === 'filter' ? null : 'filter' }) onHeadState(groupName, {
textState: textState === 'filter' ? null : 'filter',
})
} }
> >
{textState === 'filter' ? <SearchOffRounded /> : <SearchRounded />} {textState === 'filter' ? <SearchOffRounded /> : <SearchRounded />}
@@ -176,7 +182,7 @@ export const ProxyHead = ({
useRegularExpression: filterUseRegularExpression, useRegularExpression: filterUseRegularExpression,
}} }}
onSearch={(_, state) => onSearch={(_, state) =>
onHeadState({ onHeadState(groupName, {
filterText: state.text, filterText: state.text,
filterMatchCase: state.matchCase, filterMatchCase: state.matchCase,
filterMatchWholeWord: state.matchWholeWord, filterMatchWholeWord: state.matchWholeWord,
@@ -197,7 +203,7 @@ export const ProxyHead = ({
size="small" size="small"
variant="outlined" variant="outlined"
placeholder={t('proxies.page.placeholders.delayCheckUrl')} placeholder={t('proxies.page.placeholders.delayCheckUrl')}
onChange={(e) => onHeadState({ testUrl: e.target.value })} onChange={(e) => onHeadState(groupName, { testUrl: e.target.value })}
sx={{ ml: 0.5, flex: '1 1 auto', input: { py: 0.65, px: 1 } }} sx={{ ml: 0.5, flex: '1 1 auto', input: { py: 0.65, px: 1 } }}
/> />
)} )}
+7 -7
View File
@@ -33,7 +33,7 @@ interface RenderProps {
item: IRenderItem item: IRenderItem
stickyed?: boolean stickyed?: boolean
isChainMode?: boolean isChainMode?: boolean
onLocation: (group: IRenderItem['group']) => void onLocation: (groupName: string) => void
onCheckAll: (groupName: string) => void onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onChangeProxy: ( onChangeProxy: (
@@ -179,9 +179,9 @@ const ProxyGroupHeader = (props: RenderProps) => {
url={group.testUrl!} url={group.testUrl!}
groupName={group.name} groupName={group.name}
headState={headState!} headState={headState!}
onLocation={() => onLocation(group)} onLocation={onLocation}
onCheckDelay={() => onCheckAll(group.name)} onCheckDelay={onCheckAll}
onHeadState={(p) => onHeadState(group.name, p)} onHeadState={onHeadState}
/> />
{!toolsOnLeft && proxyCount} {!toolsOnLeft && proxyCount}
</ProxyGroupHeaderBlock> </ProxyGroupHeaderBlock>
@@ -270,9 +270,9 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
url={group.testUrl!} url={group.testUrl!}
groupName={group.name} groupName={group.name}
headState={headState!} headState={headState!}
onLocation={() => onLocation(group)} onLocation={onLocation}
onCheckDelay={() => onCheckAll(group.name)} onCheckDelay={onCheckAll}
onHeadState={(p) => onHeadState(group.name, p)} onHeadState={onHeadState}
/> />
) )
} }
+6 -2
View File
@@ -175,7 +175,9 @@ export const useRenderList = (
chainOccurrencesRef.current = chainOccurrences chainOccurrencesRef.current = chainOccurrences
const chainDelayGroup = const chainDelayGroup =
mode === 'rule' && selectedGroup ? selectedGroup : CHAIN_DELAY_GROUP mode === 'rule' && selectedGroup ? selectedGroup : CHAIN_DELAY_GROUP
const chainDelayKey = chainOccurrences const chainDelayKey = useMemo(
() =>
chainOccurrences
.map(({ member }) => { .map(({ member }) => {
if (member.kind !== 'node') return `${member.kind}:${member.ref.name}` if (member.kind !== 'node') return `${member.kind}:${member.ref.name}`
const source = member.node.source const source = member.node.source
@@ -183,7 +185,9 @@ export const useRenderList = (
? `provider:${source.providerName}:${source.proxyName}` ? `provider:${source.providerName}:${source.proxyName}`
: `core:${source.proxyName}` : `core:${source.proxyName}`
}) })
.join('\u0000') .join('\u0000'),
[chainOccurrences],
)
useEffect(() => { useEffect(() => {
if (!isChainMode || !chainDelayKey) return if (!isChainMode || !chainDelayKey) return
+35 -23
View File
@@ -51,6 +51,25 @@ const Item = styled(ListItem)(() => ({
}, },
})) }))
// Static editor settings; a per-render object would re-trigger Monaco's
// updateOptions and listener resubscription on every keystroke. The minimap
// depends on the live window width and is applied at editor mount instead.
const MONACO_OPTIONS = {
tabSize: 2,
mouseWheelZoom: true,
quickSuggestions: {
strings: true,
comments: true,
other: true,
},
padding: {
top: 33,
},
fontFamily: MONACO_FONT_FAMILY,
fontLigatures: false,
smoothScrolling: true,
} as const
type NameserverPolicy = Record<string, any> type NameserverPolicy = Record<string, any>
function parseNameserverPolicy(str: string): NameserverPolicy { function parseNameserverPolicy(str: string): NameserverPolicy {
@@ -520,9 +539,21 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
} }
}) })
const handleYamlChange = (value?: string) => { const handleYamlChange = useCallback((value?: string) => {
setYamlContent(value || '') setYamlContent(value || '')
} }, [])
const handleEditorMount = useCallback(
(editorInstance: MonacoEditorInstance) => {
editorRef.current = editorInstance
editorInstance.updateOptions({
minimap: {
enabled: document.documentElement.clientWidth >= 1500,
},
})
},
[],
)
const handleChange = (field: string) => (event: any) => { const handleChange = (field: string) => (event: any) => {
const value = const value =
@@ -1052,27 +1083,8 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
value={yamlContent} value={yamlContent}
theme={themeMode === 'light' ? 'light' : 'vs-dark'} theme={themeMode === 'light' ? 'light' : 'vs-dark'}
className="flex-grow" className="flex-grow"
onMount={(editorInstance) => { onMount={handleEditorMount}
editorRef.current = editorInstance options={MONACO_OPTIONS}
}}
options={{
tabSize: 2,
minimap: {
enabled: document.documentElement.clientWidth >= 1500,
},
mouseWheelZoom: true,
quickSuggestions: {
strings: true,
comments: true,
other: true,
},
padding: {
top: 33,
},
fontFamily: MONACO_FONT_FAMILY,
fontLigatures: false,
smoothScrolling: true,
}}
onChange={handleYamlChange} onChange={handleYamlChange}
/> />
)} )}
@@ -109,7 +109,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
showNotice.error(err) showNotice.error(err)
} }
const onChangeData = (patch: Partial<IVergeConfig>) => { const onChangeData = (patch: Partial<IVergeConfig>) => {
mutateVerge({ ...verge, ...patch }) mutateVerge((prev) => ({ ...prev, ...patch }))
} }
return ( return (
@@ -326,7 +326,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
Promise.resolve().then(async () => { Promise.resolve().then(async () => {
try { try {
if (Object.keys(patch).length > 0) { if (Object.keys(patch).length > 0) {
mutateVerge({ ...verge, ...patch }) mutateVerge((prev) => ({ ...prev, ...patch }))
} }
if (Object.keys(patch).length > 0) { if (Object.keys(patch).length > 0) {
await patchVerge(patch) await patchVerge(patch)
+82 -83
View File
@@ -114,6 +114,84 @@ const getAlertTypeFromClassName = (
return match?.[1] as GitHubAlertType | null return match?.[1] as GitHubAlertType | null
} }
const openUrlWithNotice = (url: string) => {
void openExternalUrl(url).catch(showNotice.error)
}
// Renderer map is static; a per-render identity would remount every link and
// blockquote subtree while download progress re-renders the dialog.
const MARKDOWN_COMPONENTS: ReactMarkdownOptions['components'] = {
a: ({ href, children, ...props }) => {
const isFragment = href?.startsWith('#') ?? false
const renderedHref = isFragment
? `#${UPDATE_MARKDOWN_ID_PREFIX}${href?.slice(1)}`
: href
? '#'
: undefined
return (
<a
{...props}
href={renderedHref}
target={undefined}
rel={undefined}
onClick={(event) => {
if (isFragment) return
event.preventDefault()
if (!href) return
openUrlWithNotice(href)
}}
onAuxClick={(event) => {
if (isFragment) return
event.preventDefault()
if (event.button === 1 && href) {
openUrlWithNotice(href)
}
}}
>
{children}
</a>
)
},
blockquote: ({ className, children }) => {
const alertType = getAlertTypeFromClassName(className)
if (!alertType) {
return <blockquote className={className}>{children}</blockquote>
}
return (
<Box
component="blockquote"
className={className}
sx={(theme) => {
const color = GITHUB_ALERTS[alertType].color
return {
m: '12px 0 18px',
px: 2,
py: 1,
borderLeft: `4px solid ${color}`,
borderRadius: 1,
bgcolor: alpha(color, theme.palette.mode === 'dark' ? 0.16 : 0.08),
'& p': {
my: 0.75,
},
'& .markdown-alert-title': {
display: 'flex',
alignItems: 'center',
gap: 0.75,
fontWeight: 700,
lineHeight: 1.4,
},
}
}}
>
{children}
</Box>
)
},
}
const findFirstTextNode = (node: MarkdownNode): MarkdownNode | null => { const findFirstTextNode = (node: MarkdownNode): MarkdownNode | null => {
if (node.type === 'text') return node if (node.type === 'text') return node
for (const child of node.children ?? []) { for (const child of node.children ?? []) {
@@ -185,10 +263,6 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
}) })
const { downloaded, total } = download const { downloaded, total } = download
const openUrlWithNotice = (url: string) => {
void openExternalUrl(url).catch(showNotice.error)
}
const progress = useMemo(() => { const progress = useMemo(() => {
if (total <= 0) return 0 if (total <= 0) return 0
return Math.min((downloaded / total) * 100, 100) return Math.min((downloaded / total) * 100, 100)
@@ -212,8 +286,8 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
) as Record<GitHubAlertType, string>, ) as Record<GitHubAlertType, string>,
[t], [t],
) )
const remarkGitHubAlertsPlugin = useMemo( const remarkPlugins = useMemo(
() => () => remarkGitHubAlerts(githubAlertLabels), () => [() => remarkGitHubAlerts(githubAlertLabels)],
[githubAlertLabels], [githubAlertLabels],
) )
@@ -475,83 +549,8 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
{open && ( {open && (
<Suspense fallback={<LinearProgress />}> <Suspense fallback={<LinearProgress />}>
<LazyReactMarkdown <LazyReactMarkdown
remarkPlugins={[remarkGitHubAlertsPlugin]} remarkPlugins={remarkPlugins}
components={{ components={MARKDOWN_COMPONENTS}
a: ({ href, children, ...props }) => {
const isFragment = href?.startsWith('#') ?? false
const renderedHref = isFragment
? `#${UPDATE_MARKDOWN_ID_PREFIX}${href?.slice(1)}`
: href
? '#'
: undefined
return (
<a
{...props}
href={renderedHref}
target={undefined}
rel={undefined}
onClick={(event) => {
if (isFragment) return
event.preventDefault()
if (!href) return
openUrlWithNotice(href)
}}
onAuxClick={(event) => {
if (isFragment) return
event.preventDefault()
if (event.button === 1 && href) {
openUrlWithNotice(href)
}
}}
>
{children}
</a>
)
},
blockquote: ({ className, children }) => {
const alertType = getAlertTypeFromClassName(className)
if (!alertType) {
return (
<blockquote className={className}>{children}</blockquote>
)
}
return (
<Box
component="blockquote"
className={className}
sx={(theme) => {
const color = GITHUB_ALERTS[alertType].color
return {
m: '12px 0 18px',
px: 2,
py: 1,
borderLeft: `4px solid ${color}`,
borderRadius: 1,
bgcolor: alpha(
color,
theme.palette.mode === 'dark' ? 0.16 : 0.08,
),
'& p': {
my: 0.75,
},
'& .markdown-alert-title': {
display: 'flex',
alignItems: 'center',
gap: 0.75,
fontWeight: 700,
lineHeight: 1.4,
},
}
}}
>
{children}
</Box>
)
},
}}
> >
{markdownContent} {markdownContent}
</LazyReactMarkdown> </LazyReactMarkdown>
+1 -1
View File
@@ -25,7 +25,7 @@ const SettingSystem = ({ onError }: Props) => {
value: boolean, value: boolean,
) => value ) => value
const onChangeData = (patch: Partial<IVergeConfig>) => { const onChangeData = (patch: Partial<IVergeConfig>) => {
mutateVerge({ ...verge, ...patch }) mutateVerge((prev) => ({ ...prev, ...patch }))
} }
return ( return (
@@ -72,7 +72,7 @@ const SettingVergeBasic = ({ onError }: Props) => {
const backupRef = useRef<DialogRef>(null) const backupRef = useRef<DialogRef>(null)
const onChangeData = (patch: any) => { const onChangeData = (patch: any) => {
mutateVerge({ ...verge, ...patch }) mutateVerge((prev) => ({ ...prev, ...patch }))
} }
const onCopyClashEnv = useCallback(async () => { const onCopyClashEnv = useCallback(async () => {
+12 -3
View File
@@ -10,7 +10,7 @@ import {
TextField, TextField,
Typography, Typography,
} from '@mui/material' } from '@mui/material'
import { useEffect, useRef, useState, type ReactNode } from 'react' import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import getSystem from '@/utils/get-system' import getSystem from '@/utils/get-system'
@@ -21,6 +21,9 @@ import {
type SearchDialog, type SearchDialog,
} from './settings-search-context' } from './settings-search-context'
// Constant for the runtime; module-level like the other getSystem() callers.
const OS = getSystem()
export function SettingsSearch({ export function SettingsSearch({
children, children,
}: { }: {
@@ -40,11 +43,17 @@ export function SettingsSearch({
const originalScrollRef = useRef(0) const originalScrollRef = useRef(0)
const resultScrollRef = useRef(0) const resultScrollRef = useRef(0)
const cancelLocateRef = useRef<() => void>(() => {}) const cancelLocateRef = useRef<() => void>(() => {})
const results = searchSettings( // The catalog scan touches every entry with translations; memoizing keeps
// unrelated state (arrow-key selection) from re-running it.
const results = useMemo(
() =>
searchSettings(
query, query,
getSystem(), OS,
(key) => t(key), (key) => t(key),
(key) => t(key, { lng: 'en' }), (key) => t(key, { lng: 'en' }),
),
[query, t],
) )
const searching = !!query.trim() const searching = !!query.trim()
const scroller = () => const scroller = () =>
@@ -163,7 +163,7 @@ const ProxyControlSwitches = ({
}) })
return false return false
} }
mutateVerge({ ...verge, enable_tun_mode: value }) mutateVerge((prev) => ({ ...prev, enable_tun_mode: value }))
await patchVerge({ enable_tun_mode: value }) await patchVerge({ enable_tun_mode: value })
} }
+4 -1
View File
@@ -12,6 +12,9 @@ const FLUSH_DELAY_MS = 50
type LogType = ILogItem['type'] type LogType = ILogItem['type']
const DEFAULT_LOG_TYPES: LogType[] = ['debug', 'info', 'warning', 'error'] const DEFAULT_LOG_TYPES: LogType[] = ['debug', 'info', 'warning', 'error']
// Shared empty fallback: a fresh [] would give `refresh` a new identity on
// every render and re-run the snapshot effect while logs stream.
const EMPTY_LOGS: ILogItem[] = []
const LOG_LEVEL_FILTERS: Record<LogLevel, LogType[]> = { const LOG_LEVEL_FILTERS: Record<LogLevel, LogType[]> = {
DEBUG: DEFAULT_LOG_TYPES, DEBUG: DEFAULT_LOG_TYPES,
INFO: ['info', 'warning', 'error'], INFO: ['info', 'warning', 'error'],
@@ -55,7 +58,7 @@ export const useLogData = () => {
const { response, refresh, setData } = useMihomoWsSubscription<ILogItem[]>({ const { response, refresh, setData } = useMihomoWsSubscription<ILogItem[]>({
subscriptionKey: enableLog ? 'getClashLog' : null, subscriptionKey: enableLog ? 'getClashLog' : null,
fallbackData: [], fallbackData: EMPTY_LOGS,
connect: () => MihomoWebSocket.connect_logs(logLevel), connect: () => MihomoWebSocket.connect_logs(logLevel),
setupHandlers: ({ next, scheduleReconnect, isMounted }) => { setupHandlers: ({ next, scheduleReconnect, isMounted }) => {
let flushTimer: ReturnType<typeof setTimeout> | null = null let flushTimer: ReturnType<typeof setTimeout> | null = null
+1 -1
View File
@@ -61,7 +61,7 @@ export function useProxyDelayState(
} }
const cachedUpdate = delayManager.getDelayUpdate(name, groupName) const cachedUpdate = delayManager.getDelayUpdate(name, groupName)
if (cachedUpdate) { if (cachedUpdate) {
setDelayState({ ...cachedUpdate }) setDelayState(cachedUpdate)
return return
} }
+7 -18
View File
@@ -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,
+21 -15
View File
@@ -3,12 +3,16 @@ import { useCallback } from 'react'
import { getVergeConfig, patchVergeConfig } from '@/services/cmds' import { getVergeConfig, patchVergeConfig } from '@/services/cmds'
import { mutate } from '@/services/mutate' import { mutate } from '@/services/mutate'
import { getPreloadConfig, setPreloadConfig } from '@/services/preload' import { getPreloadConfig, setPreloadConfig } from '@/services/preload'
import { setCacheData, useQuery } from '@/services/query-client' import {
revalidateQuery,
setCacheData,
useQuery,
} from '@/services/query-client'
export const useVerge = () => { export const useVerge = () => {
const initialVergeConfig = getPreloadConfig() const initialVergeConfig = getPreloadConfig()
const { data: verge, refetch } = useQuery({ const { data: verge } = useQuery({
queryKey: ['getVergeConfig'], queryKey: ['getVergeConfig'],
queryFn: async () => { queryFn: async () => {
const config = await getVergeConfig() const config = await getVergeConfig()
@@ -20,23 +24,25 @@ export const useVerge = () => {
staleTime: 5000, staleTime: 5000,
}) })
const mutateVerge = ( // Stable identity: many consumers list mutateVerge in their own callback
updaterOrData?: // deps, so a per-render closure here would churn their memoization too.
| IVergeConfig // The updater receives the live cache value (preload snapshot when the
| ((prev: IVergeConfig | undefined) => IVergeConfig | undefined) // cache is still empty) instead of a render-time snapshot, so an older
| undefined, // render cannot clobber a newer cache write.
const mutateVerge = useCallback(
(
updater?: (prev: IVergeConfig | undefined) => IVergeConfig | undefined,
) => { ) => {
if (updaterOrData === undefined) { if (updater === undefined) {
void refetch() void revalidateQuery(['getVergeConfig'])
return return
} }
void setCacheData<IVergeConfig>( void setCacheData<IVergeConfig>(['getVergeConfig'], (current) =>
['getVergeConfig'], updater(current ?? getPreloadConfig() ?? undefined),
typeof updaterOrData === 'function' )
? (current) => updaterOrData(current ?? verge) },
: updaterOrData, [],
) )
}
// Callers own the error toast (GuardState onCatch / page onError), so the // Callers own the error toast (GuardState onCatch / page onError), so the
// funnel must not add a second one. // funnel must not add a second one.
+44 -18
View File
@@ -462,9 +462,12 @@ const ProfilePage = () => {
[runProfileSwitchQueue], [runProfileSwitchQueue],
) )
const onSelect = async (profile: string, force: boolean) => { const onSelect = useCallback(
async (profile: string, force: boolean) => {
await activateProfile(profile, true, force) await activateProfile(profile, true, force)
} },
[activateProfile],
)
useEffect(() => { useEffect(() => {
let cancelled = false let cancelled = false
@@ -594,7 +597,7 @@ const ProfilePage = () => {
} }
} }
const toggleProfileSelection = (uid: string) => { const toggleProfileSelection = useCallback((uid: string) => {
setSelectedProfiles((prev) => { setSelectedProfiles((prev) => {
const newSet = new Set(prev) const newSet = new Set(prev)
if (newSet.has(uid)) { if (newSet.has(uid)) {
@@ -604,7 +607,40 @@ const ProfilePage = () => {
} }
return newSet return newSet
}) })
}, [])
// Item-grid callbacks stay identity-stable so ProfileItem's memo holds
// across unrelated page state (URL input keystrokes, switch spinners).
// onEnhance/onDelete are useLockFn wrappers whose identity changes every
// render, so they are read through refs here.
const onEnhanceRef = useRef(onEnhance)
onEnhanceRef.current = onEnhance
const onDeleteRef = useRef(onDelete)
onDeleteRef.current = onDelete
const handleItemEdit = useCallback((item: IProfileItem) => {
viewerRef.current?.edit(item)
}, [])
const handleItemSave = useCallback(
async (uid: string, prev?: string, curr?: string) => {
if (prev !== curr && profiles.current === uid) {
await onEnhanceRef.current(false)
} }
},
[profiles],
)
const handleItemDelete = useCallback(
(uid: string) => {
if (batchMode) {
toggleProfileSelection(uid)
} else {
onDeleteRef.current(uid)
}
},
[batchMode, toggleProfileSelection],
)
const selectAllProfiles = () => { const selectAllProfiles = () => {
setSelectedProfiles(new Set(profileItems.map((item) => item.uid!))) setSelectedProfiles(new Set(profileItems.map((item) => item.uid!)))
@@ -908,23 +944,13 @@ const ProfilePage = () => {
completedUpdateRevisions.get(item.uid!) ?? 0 completedUpdateRevisions.get(item.uid!) ?? 0
} }
mutateProfiles={mutateProfiles} mutateProfiles={mutateProfiles}
onSelect={(f) => onSelect(item.uid!, f)} onSelect={onSelect}
onEdit={() => viewerRef.current?.edit(item)} onEdit={handleItemEdit}
onSave={async (prev, curr) => { onSave={handleItemSave}
if (prev !== curr && profiles.current === item.uid) { onDelete={handleItemDelete}
await onEnhance(false)
}
}}
onDelete={() => {
if (batchMode) {
toggleProfileSelection(item.uid!)
} else {
onDelete(item.uid!)
}
}}
batchMode={batchMode} batchMode={batchMode}
isSelected={selectedProfiles.has(item.uid!)} isSelected={selectedProfiles.has(item.uid!)}
onSelectionChange={() => toggleProfileSelection(item.uid!)} onSelectionChange={toggleProfileSelection}
/> />
))} ))}
</Box> </Box>
+3 -1
View File
@@ -237,7 +237,9 @@ class DelayManager {
return undefined return undefined
} }
return { ...entry } // Entries are replaced, never mutated, so the cached object is shared
// directly; readers treat it as immutable.
return entry
} }
getDelay(name: string, group: string) { getDelay(name: string, group: string) {
-17
View File
@@ -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()
+1 -1
View File
@@ -156,7 +156,7 @@ export const selectRuleChainMembers = (
}) })
} }
const sameSource = ( export const sameSource = (
left: ProxyNodeView['source'], left: ProxyNodeView['source'],
right: ProxyNodeView['source'], right: ProxyNodeView['source'],
) => ) =>
+36 -42
View File
@@ -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
@@ -145,10 +124,10 @@ export class TrafficDataSampler {
) { ) {
rawStart++ rawStart++
} }
const rawData = this.rawBuffer.slice(rawStart) const rawCount = this.rawBuffer.length - rawStart
if (minutes <= this.config.rawDataMinutes) { if (minutes <= this.config.rawDataMinutes) {
return rawData return this.rawBuffer.slice(rawStart)
} }
const compressedCutoffUpper = const compressedCutoffUpper =
@@ -161,19 +140,40 @@ export class TrafficDataSampler {
) { ) {
compressedStart++ compressedStart++
} }
let compressedEnd = compressedStart
while (
compressedEnd < this.compressedBuffer.length &&
this.compressedBuffer[compressedEnd].timestamp <= compressedCutoffUpper
) {
compressedEnd++
}
const compressedData = this.compressedBuffer // Single preallocated result; raw entries keep their stored identity.
.slice(compressedStart) const compressedCount = compressedEnd - compressedStart
.filter((p) => p.timestamp <= compressedCutoffUpper) const result: ITrafficDataPoint[] = new Array(compressedCount + rawCount)
.map((p) => ({ for (let i = 0; i < compressedCount; i++) {
up: p.up, const point = this.compressedBuffer[compressedStart + i]
down: p.down, result[i] = {
timestamp: p.timestamp, up: point.up,
})) down: point.down,
timestamp: point.timestamp,
}
}
for (let i = 0; i < rawCount; i++) {
result[compressedCount + i] = this.rawBuffer[rawStart + i]
}
return [...compressedData, ...rawData].sort( // Compressed points precede raw ones except across the trim boundary;
(a, b) => a.timestamp - b.timestamp, // sort only when the two ranges actually interleave.
) if (
compressedCount > 0 &&
rawCount > 0 &&
this.compressedBuffer[compressedEnd - 1].timestamp >
this.rawBuffer[rawStart].timestamp
) {
result.sort((a, b) => a.timestamp - b.timestamp)
}
return result
} }
getStats(): ISamplerStats { getStats(): ISamplerStats {
@@ -188,13 +188,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 = []