Files
clash-verge-rev/src/components/layout/layout-traffic.tsx
T
Tunglies e4abdb8c0d perf(ui): remove per-second allocations in traffic, log and proxy render paths (#8689)
* perf(home): draw the traffic graph from refs instead of per-snapshot state

Worker snapshots re-rendered the whole graph tree per update and the
sampler sliced its full buffer every second just to compare for
equality. Snapshots now feed display data and the y-scale through refs
(React state only tracks the diagnostics badge inputs, skipped while
hidden), the draw callback chain is identity-stable, per-draw axis
ticks/labels and gradient strings go through pooled buffers and bounded
caches, and the sampler version counter plus an oldest-point age check
let the idle poll skip unchanged slices.

* perf(ui): hoist static icons and style identities in traffic widgets

Stat-card icons were rebuilt per parsed-data update, defeating the
memoized card comparison, and the layout traffic widget reallocated its
style objects (with a redundant double sx spread) on every tick.

* perf(log): compile the highlight regex once per search state

Each visible row recompiled (and re-escaped) the same regex three times
per render while logs stream in; the compiled regex is now cached per
search state identity.

* perf(proxy): reuse the parsed scroll-position snapshot and drop per-frame copies

The sticky-index lookup copied and reversed its array per range
extraction and every throttled save re-read and re-parsed the same
localStorage payload; the reverse scan is now allocation-free and the
parse goes through one read-through snapshot.

* test(perf): add proxy scroll scene to the perf adapter

Adds a proxy page scenario to the measurement adapter: a core-module
shim serves synthetic proxy/clash/run-state data at the invoke seam
(active only for the proxy scenario; other scenarios stay
byte-identical), and a sawtooth scroll driver keeps the virtualizer
measuring and the throttled scroll-position save running. Running the
scene additionally requires the harness-side scenario contract and
schema v10 from the clash-verge-rev-harness repository.

* chore(changelog): drop the hot-path refresh entries

* test(perf): move the proxy adapter scene to a separate change
2026-11-23 07:45:22 +00:00

172 lines
4.8 KiB
TypeScript

import {
ArrowDownwardRounded,
ArrowUpwardRounded,
ErrorOutlineRounded,
MemoryRounded,
} from '@mui/icons-material'
import type { BoxProps, SvgIconProps, TypographyProps } from '@mui/material'
import { Box, Typography } from '@mui/material'
import { useEffect, useRef } from 'react'
import { ErrorBoundary } from 'react-error-boundary'
import { useTranslation } from 'react-i18next'
import { useMemoryData } from '@/hooks/use-memory-data'
import { useTrafficData } from '@/hooks/use-traffic-data'
import { useVerge } from '@/hooks/use-verge'
import { useVisibility } from '@/hooks/use-visibility'
import parseTraffic from '@/utils/parse-traffic'
import { TrafficGraph, type TrafficRef } from './traffic-graph'
const unavailableSx = {
p: 1,
minHeight: 60,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
bgcolor: 'error.light',
borderRadius: 1,
color: 'error.contrastText',
}
const TrafficUnavailableFallback = () => {
const { t } = useTranslation()
return (
<Box sx={unavailableSx}>
<ErrorOutlineRounded sx={{ mr: 1, fontSize: 20 }} />
<Typography variant="caption">
{t('shared.feedback.errors.trafficUnavailable')}
</Typography>
</Box>
)
}
// 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 = () => {
const { t } = useTranslation()
const { verge } = useVerge()
const trafficGraph = verge?.traffic_graph ?? true
const displayMemory = verge?.enable_memory_usage ?? true
const trafficRef = useRef<TrafficRef>(null)
const pageVisible = useVisibility()
const {
response: { data: traffic },
} = useTrafficData({ enabled: pageVisible })
const {
response: { data: memory },
} = useMemoryData({ enabled: displayMemory && pageVisible })
useEffect(() => {
if (trafficRef.current) {
trafficRef.current.appendData({
up: traffic?.up || 0,
down: traffic?.down || 0,
upTotal: traffic?.upTotal || 0,
downTotal: traffic?.downTotal || 0,
})
}
}, [traffic])
const [up, upUnit] = parseTraffic(traffic?.up || 0)
const [down, downUnit] = parseTraffic(traffic?.down || 0)
const [inuse, inuseUnit] = parseTraffic(memory?.inuse || 0)
return (
<ErrorBoundary
FallbackComponent={TrafficUnavailableFallback}
onError={(error, errorInfo) =>
console.error('[LayoutTraffic]', error, errorInfo)
}
>
<Box sx={{ position: 'relative' }}>
{trafficGraph && pageVisible && (
<div
style={{ width: '100%', height: 60, marginBottom: 6 }}
onClick={trafficRef.current?.toggleStyle}
>
<TrafficGraph ref={trafficRef} />
</div>
)}
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.75 }}>
<Box
title={`${t('home.components.traffic.metrics.uploadSpeed')}`}
{...boxStyle}
>
<ArrowUpwardRounded
{...iconStyle}
color={(traffic?.up || 0) > 0 ? 'secondary' : 'disabled'}
/>
<Typography {...valStyle} color="secondary">
{up}
</Typography>
<Typography {...unitStyle}>{upUnit}/s</Typography>
</Box>
<Box
title={`${t('home.components.traffic.metrics.downloadSpeed')}`}
{...boxStyle}
>
<ArrowDownwardRounded
{...iconStyle}
color={(traffic?.down || 0) > 0 ? 'primary' : 'disabled'}
/>
<Typography {...valStyle} color="primary">
{down}
</Typography>
<Typography {...unitStyle}>{downUnit}/s</Typography>
</Box>
{displayMemory && (
<Box
title={`${t('home.components.traffic.metrics.memoryUsage')} `}
{...memoryBoxStyle}
color={'disabled'}
>
<MemoryRounded {...iconStyle} />
<Typography {...valStyle}>{inuse}</Typography>
<Typography {...unitStyle}>{inuseUnit}</Typography>
</Box>
)}
</Box>
</Box>
</ErrorBoundary>
)
}