perf(ui): reduce CPU and memory pressure on hot frontend paths

WebSocket hooks (use-connection-data, use-log-data)
- Single-pass merge for connection snapshots; reuse previous row reference
  when upload/download are unchanged so downstream memos can bail out
- Single-allocation cap on closedConnections (no double concat+slice)
- Single-allocation clamp in appendLogs
- Cache dayjs().format result within each 50ms log flush window

Connection table (connection-table.tsx)
- Decouple 5s relative-time tick from columnDefs via shared module-level
  tickStore + memoised RelativeTimeCell so the tick no longer rebuilds
  the table
- RowComponent memo with custom comparator (relies on stable row reference)
- Lift sx objects to module scope
- Stable onShowDetail via ref

App data provider (app-data-provider, app-data-context)
- Split monolithic context into six sub-contexts (Proxies/Rules/ClashConfig/
  System/Uptime/Refreshers); 3s uptime ticks no longer invalidate unrelated
  consumers
- useAppData adapter aggregates sub-contexts; consumer files unchanged
- useStableFn helper stabilises all refresh* callback identities
- Extract useCtx helper to remove repeated null-check boilerplate

Canvas traffic graph (enhanced-canvas-traffic-graph, use-traffic-monitor)
- Lift Y-axis scale (max/min) to drawGraph layer; calculateY allocations
  per frame: ~600 -> 1
- Document visibility gate stops RAF and the setNow interval when the
  window is hidden; appendData unaffected
- Reuse the existing visibilitychange listener instead of adding a second
  one; isDocumentVisibleRef guards animate() inside the frame
- Convert forEach arrow shorthands to block bodies
- Drop unnecessary state-setter deps from a useCallback

Proxy groups (proxy-groups, proxy-render, use-render-list)
- Narrow proxyColItemsMemo dep: headState -> headState.showType
- Per-group fingerprint cache + prevListRef in use-render-list; steady-state
  refetch ticks become O(0) and the list reference stays stable when nothing
  changed
- useStableCallback wraps handleCheckAll / handleLocation
This commit is contained in:
Tunglies
2026-04-19 19:33:23 +08:00
parent b1eb011050
commit d203121abe
10 changed files with 724 additions and 444 deletions
+60 -49
View File
@@ -34,6 +34,12 @@ import {
import { ProxyRender } from './proxy-render'
import { useRenderList } from './use-render-list'
function useStableCallback<T extends (...args: any[]) => any>(fn: T): T {
const ref = useRef(fn)
ref.current = fn
return useCallback((...args: Parameters<T>) => ref.current(...args), []) as T
}
interface Props {
mode: string
isChainMode?: boolean
@@ -51,6 +57,7 @@ export const ProxyGroups = (props: Props) => {
const { t } = useTranslation()
const { mode, isChainMode = false, chainConfigData } = props
// Drive 3s polling on the shared TQ cache; data is read via useAppData() below
useQuery({
queryKey: ['getProxies'],
queryFn: calcuProxies,
@@ -313,60 +320,64 @@ export const ProxyGroups = (props: Props) => {
)
// 测全部延迟
const handleCheckAll = useLockFn(async (groupName: string) => {
debugLog(`[ProxyGroups] 开始测试所有延迟,组: ${groupName}`)
const handleCheckAll = useStableCallback(
useLockFn(async (groupName: string) => {
debugLog(`[ProxyGroups] 开始测试所有延迟,组: ${groupName}`)
const proxies = renderList
.filter(
(e) => e.group?.name === groupName && (e.type === 2 || e.type === 4),
const proxies = renderList
.filter(
(e) => e.group?.name === groupName && (e.type === 2 || e.type === 4),
)
.flatMap((e) => e.proxyCol || e.proxy!)
.filter(Boolean)
debugLog(`[ProxyGroups] 找到代理数量: ${proxies.length}`)
const providers = new Set(
proxies.map((p) => p!.provider!).filter(Boolean),
)
.flatMap((e) => e.proxyCol || e.proxy!)
.filter(Boolean)
debugLog(`[ProxyGroups] 找到代理数量: ${proxies.length}`)
const providers = new Set(proxies.map((p) => p!.provider!).filter(Boolean))
if (providers.size) {
debugLog(`[ProxyGroups] 发现提供者,数量: ${providers.size}`)
Promise.allSettled(
[...providers].map((p) => healthcheckProxyProvider(p)),
).then(() => {
debugLog(`[ProxyGroups] 提供者健康检查完成`)
onProxies()
})
}
const names = proxies.filter((p) => !p!.provider).map((p) => p!.name)
debugLog(`[ProxyGroups] 过滤后需要测试的代理数量: ${names.length}`)
const url = delayManager.getUrl(groupName)
debugLog(`[ProxyGroups] 测试URL: ${url}, 超时: ${timeout}ms`)
try {
await Promise.race([
delayManager.checkListDelay(names, groupName, timeout),
delayGroup(groupName, url, timeout).then((result) => {
debugLog(
`[ProxyGroups] getGroupProxyDelays返回结果数量:`,
Object.keys(result || {}).length,
)
}), // 查询group delays 将清除fixed(不关注调用结果)
])
debugLog(`[ProxyGroups] 延迟测试完成,组: ${groupName}`)
} catch (error) {
console.error(`[ProxyGroups] 延迟测试出错,组: ${groupName}`, error)
} finally {
const headState = getGroupHeadState(groupName)
if (headState?.sortType === 1) {
onHeadState(groupName, { sortType: headState.sortType })
if (providers.size) {
debugLog(`[ProxyGroups] 发现提供者,数量: ${providers.size}`)
Promise.allSettled(
[...providers].map((p) => healthcheckProxyProvider(p)),
).then(() => {
debugLog(`[ProxyGroups] 提供者健康检查完成`)
onProxies()
})
}
onProxies()
}
})
const names = proxies.filter((p) => !p!.provider).map((p) => p!.name)
debugLog(`[ProxyGroups] 过滤后需要测试的代理数量: ${names.length}`)
const url = delayManager.getUrl(groupName)
debugLog(`[ProxyGroups] 测试URL: ${url}, 超时: ${timeout}ms`)
try {
await Promise.race([
delayManager.checkListDelay(names, groupName, timeout),
delayGroup(groupName, url, timeout).then((result) => {
debugLog(
`[ProxyGroups] getGroupProxyDelays返回结果数量:`,
Object.keys(result || {}).length,
)
}), // 查询group delays 将清除fixed(不关注调用结果)
])
debugLog(`[ProxyGroups] 延迟测试完成,组: ${groupName}`)
} catch (error) {
console.error(`[ProxyGroups] 延迟测试出错,组: ${groupName}`, error)
} finally {
const headState = getGroupHeadState(groupName)
if (headState?.sortType === 1) {
onHeadState(groupName, { sortType: headState.sortType })
}
onProxies()
}
}),
)
// 滚到对应的节点
const handleLocation = (group: IProxyGroupItem) => {
const handleLocation = useStableCallback((group: IProxyGroupItem) => {
if (!group) return
const { name, now } = group
@@ -380,7 +391,7 @@ export const ProxyGroups = (props: Props) => {
if (index >= 0) {
virtualizer.scrollToIndex(index, { align: 'center', behavior: 'smooth' })
}
}
})
// 定位到指定的代理组
const handleGroupLocationByName = useCallback(
+3 -2
View File
@@ -62,6 +62,7 @@ export const ProxyRender = (props: RenderProps) => {
enabled: enable_group_icon,
})
const showType = headState?.showType
const proxyColItemsMemo = useMemo(() => {
if (type !== 4 || !proxyCol) {
return null
@@ -73,11 +74,11 @@ export const ProxyRender = (props: RenderProps) => {
group={group}
proxy={proxyItem!}
selected={group.now === proxyItem?.name}
showType={headState?.showType}
showType={showType}
onClick={() => onChangeProxy(group, proxyItem!)}
/>
))
}, [type, proxyCol, item.key, group, headState, onChangeProxy])
}, [type, proxyCol, item.key, group, showType, onChangeProxy])
if (type === 0) {
return (
+54 -9
View File
@@ -1,4 +1,4 @@
import { useEffect, useMemo } from 'react'
import { useEffect, useMemo, useRef } from 'react'
import { useRuntimeConfig } from '@/hooks/use-clash'
import { useVerge } from '@/hooks/use-verge'
@@ -68,6 +68,15 @@ export interface IRenderItem {
testUrl?: string
}
type GroupCache = {
now: string
all: IProxyItem[]
headState: HeadState
col: number
latencyTimeout: number | undefined
items: IRenderItem[]
}
// 优化列布局计算
const calculateColumns = (width: number, configCol: number): number => {
if (configCol > 0 && configCol < 6) return configCol
@@ -169,6 +178,9 @@ export const useRenderList = (
}
}, [isChainMode, runtimeConfig, verge?.default_latency_timeout, refreshProxy])
const groupCacheRef = useRef<Map<string, GroupCache>>(new Map())
const prevListRef = useRef<IRenderItem[]>([])
// 处理渲染列表
const renderList: IRenderItem[] = useMemo(() => {
if (!proxiesData) return []
@@ -371,8 +383,25 @@ export const useRenderList = (
? proxiesData.groups
: [proxiesData.global!]
const cache = groupCacheRef.current
let anyChanged = false
const retList = renderGroups.flatMap((group: ProxyGroup) => {
const headState = headStates[group.name] || DEFAULT_STATE
const cached = cache.get(group.name)
if (
cached &&
cached.now === group.now &&
cached.all === group.all &&
cached.headState === headState &&
cached.col === col &&
cached.latencyTimeout === latencyTimeout
) {
return cached.items
}
anyChanged = true
const ret: IRenderItem[] = [
{
type: 0,
@@ -413,9 +442,9 @@ export const useRenderList = (
headState,
})
} else if (col > 1) {
return ret.concat(
groupProxies(proxies, col).map((proxyCol, colIndex) => ({
type: 4,
ret.push(
...groupProxies(proxies, col).map((proxyCol, colIndex) => ({
type: 4 as const,
key: `col-${group.name}-${proxyCol[0].name}-${colIndex}`,
group,
headState,
@@ -425,9 +454,9 @@ export const useRenderList = (
})),
)
} else {
return ret.concat(
proxies.map((proxy) => ({
type: 2,
ret.push(
...proxies.map((proxy) => ({
type: 2 as const,
key: `${group.name}-${proxy!.name}`,
group,
proxy,
@@ -437,11 +466,27 @@ export const useRenderList = (
)
}
}
cache.set(group.name, {
now: group.now,
all: group.all,
headState,
col,
latencyTimeout,
items: ret,
})
return ret
})
if (!useRule) return retList.slice(1)
return retList.filter((item: IRenderItem) => !item.group.hidden)
const filtered = !useRule
? retList.slice(1)
: retList.filter((item: IRenderItem) => !item.group.hidden)
if (!anyChanged && prevListRef.current.length === filtered.length) {
return prevListRef.current
}
prevListRef.current = filtered
return filtered
}, [
headStates,
proxiesData,