mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-19 10:22:07 +08:00
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.
This commit is contained in:
@@ -7,7 +7,6 @@ import {
|
||||
useEffectEvent,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
useReducer,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react'
|
||||
@@ -20,7 +19,6 @@ import {
|
||||
formatTrafficHourMinute,
|
||||
formatTrafficMinuteSecond,
|
||||
formatTrafficName,
|
||||
isSameTrafficData,
|
||||
} from '@/utils/traffic-sampler'
|
||||
|
||||
export interface EnhancedCanvasTrafficGraphRef {
|
||||
@@ -74,16 +72,200 @@ const GRAPH_CONFIG = {
|
||||
|
||||
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 {
|
||||
ref?: Ref<EnhancedCanvasTrafficGraphRef>
|
||||
}
|
||||
|
||||
const displayDataReducer = (
|
||||
current: ITrafficDataPoint[],
|
||||
payload: ITrafficDataPoint[],
|
||||
): ITrafficDataPoint[] =>
|
||||
isSameTrafficData(current, payload) ? current : payload
|
||||
|
||||
export const EnhancedCanvasTrafficGraph = memo(
|
||||
function EnhancedCanvasTrafficGraph({
|
||||
ref,
|
||||
@@ -94,11 +276,9 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
const pause_render_traffic_stats_on_blur =
|
||||
verge.verge?.pause_render_traffic_stats_on_blur ?? true
|
||||
|
||||
const { dataPoints, requestRange, samplerStats } =
|
||||
useTrafficGraphDataEnhanced()
|
||||
|
||||
const [timeRange, setTimeRange] = useState<TimeRange>(10)
|
||||
const [chartStyle, setChartStyle] = useState<'bezier' | 'line'>('bezier')
|
||||
const [badgeStats, setBadgeStats] = useState({ points: 0, compressed: 0 })
|
||||
|
||||
const initialFocusState =
|
||||
typeof document !== 'undefined' ? !document.hidden : true
|
||||
@@ -129,66 +309,49 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
const lastDataTimestampRef = useRef<number>(0)
|
||||
const dataStaleRef = useRef<boolean>(false)
|
||||
|
||||
const [displayData, dispatchDisplayData] = useReducer(
|
||||
displayDataReducer,
|
||||
[],
|
||||
)
|
||||
const debounceTimeoutRef = useRef<number | null>(null)
|
||||
// Live snapshot data for the rAF draw path; React state only tracks the
|
||||
// diagnostics badge inputs so steady-state snapshots stop re-rendering.
|
||||
const displayDataRef = useRef<ITrafficDataPoint[]>([])
|
||||
const yScaleRef = useRef<{ topValue: number; bottomValue: number }>({
|
||||
topValue: 1024,
|
||||
bottomValue: 0,
|
||||
})
|
||||
|
||||
const colors = useMemo(
|
||||
() => ({
|
||||
const colors = useMemo(() => {
|
||||
const base = {
|
||||
up: theme.palette.secondary.main,
|
||||
down: theme.palette.primary.main,
|
||||
grid: theme.palette.divider,
|
||||
text: theme.palette.text.secondary,
|
||||
background: theme.palette.background.paper,
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
gradient: {
|
||||
up: makeGradientStops(base.up),
|
||||
down: makeGradientStops(base.down),
|
||||
},
|
||||
}
|
||||
}, [theme])
|
||||
|
||||
const legendSx = useMemo(
|
||||
() => ({
|
||||
up: {
|
||||
fontSize: '11px',
|
||||
fontWeight: 'bold',
|
||||
color: colors.up,
|
||||
textAlign: 'right',
|
||||
},
|
||||
down: {
|
||||
fontSize: '11px',
|
||||
fontWeight: 'bold',
|
||||
color: colors.down,
|
||||
textAlign: 'right',
|
||||
},
|
||||
}),
|
||||
[theme],
|
||||
[colors],
|
||||
)
|
||||
|
||||
const updateDisplayData = useCallback((newData: ITrafficDataPoint[]) => {
|
||||
if (debounceTimeoutRef.current !== null) {
|
||||
window.clearTimeout(debounceTimeoutRef.current)
|
||||
}
|
||||
debounceTimeoutRef.current = window.setTimeout(() => {
|
||||
dispatchDisplayData(newData)
|
||||
}, 50)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
updateDisplayData(dataPoints)
|
||||
|
||||
return () => {
|
||||
if (debounceTimeoutRef.current !== null) {
|
||||
window.clearTimeout(debounceTimeoutRef.current)
|
||||
debounceTimeoutRef.current = null
|
||||
}
|
||||
}
|
||||
}, [dataPoints, updateDisplayData])
|
||||
|
||||
useEffect(() => {
|
||||
requestRange(timeRange)
|
||||
}, [requestRange, timeRange])
|
||||
|
||||
useEffect(() => {
|
||||
if (displayData.length === 0) {
|
||||
lastDataTimestampRef.current = 0
|
||||
dataStaleRef.current = false
|
||||
return
|
||||
}
|
||||
|
||||
const latestTimestamp =
|
||||
displayData[displayData.length - 1]?.timestamp ?? null
|
||||
if (latestTimestamp) {
|
||||
lastDataTimestampRef.current = latestTimestamp
|
||||
const age = Date.now() - latestTimestamp
|
||||
const stale = age > STALE_DATA_THRESHOLD
|
||||
dataStaleRef.current = stale
|
||||
} else {
|
||||
dataStaleRef.current = false
|
||||
}
|
||||
}, [displayData])
|
||||
|
||||
const handleFocusStateChange = useEffectEvent((focused: boolean) => {
|
||||
isWindowFocusedRef.current = focused
|
||||
|
||||
@@ -270,14 +433,9 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
[],
|
||||
)
|
||||
|
||||
const yScale = useMemo(
|
||||
() => computeYScale(displayData),
|
||||
[computeYScale, displayData],
|
||||
)
|
||||
|
||||
const handleMouseMove = useCallback(
|
||||
(event: React.MouseEvent<HTMLElement>) => {
|
||||
if (displayData.length === 0) return
|
||||
if (displayDataRef.current.length === 0) return
|
||||
|
||||
pendingMousePositionRef.current = {
|
||||
clientX: event.clientX,
|
||||
@@ -294,7 +452,8 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
if (!pendingMousePosition) return
|
||||
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas || displayData.length === 0) return
|
||||
const data = displayDataRef.current
|
||||
if (!canvas || data.length === 0) return
|
||||
|
||||
const rect = canvas.getBoundingClientRect()
|
||||
const mouseX = pendingMousePosition.clientX - rect.left
|
||||
@@ -309,11 +468,11 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
0,
|
||||
Math.min(1, relativeMouseX / effectiveWidth),
|
||||
)
|
||||
const dataIndex = Math.round(ratio * (displayData.length - 1))
|
||||
const dataIndex = Math.round(ratio * (data.length - 1))
|
||||
|
||||
if (dataIndex < 0 || dataIndex >= displayData.length) return
|
||||
if (dataIndex < 0 || dataIndex >= data.length) return
|
||||
|
||||
const dataPoint = displayData[dataIndex]
|
||||
const dataPoint = data[dataIndex]
|
||||
|
||||
const [upValue, upUnit] = parseTraffic(dataPoint.up)
|
||||
const [downValue, downUnit] = parseTraffic(dataPoint.down)
|
||||
@@ -322,7 +481,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
? formatTrafficName(dataPoint.timestamp)
|
||||
: t('home.components.traffic.unknownTime')
|
||||
|
||||
const { topValue: tvH, bottomValue: bvH } = yScale
|
||||
const { topValue: tvH, bottomValue: bvH } = yScaleRef.current
|
||||
const upY = calculateY(dataPoint.up, rect.height, tvH, bvH)
|
||||
const downY = calculateY(dataPoint.down, rect.height, tvH, bvH)
|
||||
const highlightY =
|
||||
@@ -359,7 +518,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
})
|
||||
})
|
||||
},
|
||||
[displayData, calculateY, yScale, t],
|
||||
[calculateY, t],
|
||||
)
|
||||
|
||||
const handleMouseLeave = useCallback(() => {
|
||||
@@ -375,45 +534,6 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
)
|
||||
}, [])
|
||||
|
||||
const getYAxisTicks = useCallback(
|
||||
(topValue: number, bottomValue: number, height: number) => {
|
||||
const formatTrafficValue = (bytes: number): string => {
|
||||
if (bytes === 0) return '0'
|
||||
if (bytes < 1024) return `${Math.round(bytes)}B`
|
||||
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)}KB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`
|
||||
}
|
||||
|
||||
const padding = GRAPH_CONFIG.padding
|
||||
|
||||
const topY = padding.top + 10
|
||||
const bottomY = height - padding.bottom - 5
|
||||
const middleY = (topY + bottomY) / 2
|
||||
const middleValue = (bottomValue + topValue) / 2
|
||||
|
||||
const ticks = [
|
||||
{
|
||||
value: bottomValue,
|
||||
label: formatTrafficValue(bottomValue),
|
||||
y: bottomY,
|
||||
},
|
||||
{
|
||||
value: middleValue,
|
||||
label: formatTrafficValue(middleValue),
|
||||
y: middleY,
|
||||
},
|
||||
{
|
||||
value: topValue,
|
||||
label: formatTrafficValue(topValue),
|
||||
y: topY,
|
||||
},
|
||||
]
|
||||
|
||||
return ticks
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
const drawYAxis = useCallback(
|
||||
(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
@@ -425,8 +545,6 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
const padding = GRAPH_CONFIG.padding
|
||||
const ticks = getYAxisTicks(topValue, bottomValue, height)
|
||||
|
||||
if (ticks.length === 0) return
|
||||
|
||||
ctx.save()
|
||||
|
||||
ticks.forEach((tick, index) => {
|
||||
@@ -470,37 +588,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
|
||||
ctx.restore()
|
||||
},
|
||||
[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,
|
||||
}
|
||||
}
|
||||
},
|
||||
[],
|
||||
[colors.grid, colors.text, colors.background],
|
||||
)
|
||||
|
||||
const drawTimeAxis = useCallback(
|
||||
@@ -516,7 +604,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
const effectiveWidth = width - padding.left - padding.right
|
||||
const timeAxisY = height - padding.bottom + 14
|
||||
|
||||
const strategy = getTimeDisplayStrategy(timeRange)
|
||||
const strategy = TIME_DISPLAY_STRATEGIES[timeRange]
|
||||
|
||||
ctx.save()
|
||||
ctx.fillStyle = colors.text
|
||||
@@ -533,15 +621,13 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
Math.ceil((data.length * minPixelDistance) / effectiveWidth),
|
||||
)
|
||||
|
||||
const timePoints: Array<{ index: number; x: number; label: string }> =
|
||||
[]
|
||||
resetTimeAxisPoints()
|
||||
|
||||
if (data.length > 0 && data[0].timestamp) {
|
||||
timePoints.push({
|
||||
index: 0,
|
||||
x: padding.left,
|
||||
label: strategy.formatTime(data[0].timestamp),
|
||||
})
|
||||
pushTimeAxisPoint(
|
||||
padding.left,
|
||||
strategy.formatTime(data[0].timestamp),
|
||||
)
|
||||
}
|
||||
|
||||
for (
|
||||
@@ -553,41 +639,37 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
if (!point.timestamp) continue
|
||||
|
||||
const x = padding.left + (i / (data.length - 1)) * effectiveWidth
|
||||
timePoints.push({
|
||||
index: i,
|
||||
x,
|
||||
label: strategy.formatTime(point.timestamp),
|
||||
})
|
||||
pushTimeAxisPoint(x, strategy.formatTime(point.timestamp))
|
||||
}
|
||||
|
||||
if (data.length > 1 && data[data.length - 1].timestamp) {
|
||||
const lastX = width - padding.right
|
||||
const lastPoint = timePoints[timePoints.length - 1]
|
||||
const lastPoint = timeAxisPoints[timeAxisPoints.length - 1]
|
||||
|
||||
if (!lastPoint || lastX - lastPoint.x >= minPixelDistance) {
|
||||
timePoints.push({
|
||||
index: data.length - 1,
|
||||
x: lastX,
|
||||
label: strategy.formatTime(data[data.length - 1].timestamp),
|
||||
})
|
||||
pushTimeAxisPoint(
|
||||
lastX,
|
||||
strategy.formatTime(data[data.length - 1].timestamp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
timePoints.forEach((point, index) => {
|
||||
if (index === 0) {
|
||||
for (let i = 0; i < timeAxisPoints.length; i++) {
|
||||
const point = timeAxisPoints[i]
|
||||
if (i === 0) {
|
||||
ctx.textAlign = 'left'
|
||||
} else if (index === timePoints.length - 1) {
|
||||
} else if (i === timeAxisPoints.length - 1) {
|
||||
ctx.textAlign = 'right'
|
||||
} else {
|
||||
ctx.textAlign = 'center'
|
||||
}
|
||||
|
||||
ctx.fillText(point.label, point.x, timeAxisY)
|
||||
})
|
||||
}
|
||||
|
||||
ctx.restore()
|
||||
},
|
||||
[colors.text, timeRange, getTimeDisplayStrategy],
|
||||
[colors.text, timeRange],
|
||||
)
|
||||
|
||||
const drawGrid = useCallback(
|
||||
@@ -632,6 +714,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
width: number,
|
||||
height: number,
|
||||
color: string,
|
||||
gradientStops: { start: string; end: string },
|
||||
withGradient = false,
|
||||
topValue: number,
|
||||
bottomValue: number,
|
||||
@@ -655,13 +738,8 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
0,
|
||||
height - padding.bottom,
|
||||
)
|
||||
gradient.addColorStop(
|
||||
0,
|
||||
`${color}${Math.round(GRAPH_CONFIG.alpha.gradient * 255)
|
||||
.toString(16)
|
||||
.padStart(2, '0')}`,
|
||||
)
|
||||
gradient.addColorStop(1, `${color}00`)
|
||||
gradient.addColorStop(0, gradientStops.start)
|
||||
gradient.addColorStop(1, gradientStops.end)
|
||||
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(getX(0), getY(0))
|
||||
@@ -752,6 +830,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
|
||||
const drawGraph = useCallback(() => {
|
||||
const canvas = canvasRef.current
|
||||
const displayData = displayDataRef.current
|
||||
if (!canvas || displayData.length === 0) {
|
||||
clearCanvas(canvasRef.current)
|
||||
clearCanvas(hoverCanvasRef.current)
|
||||
@@ -765,7 +844,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
// Clear using CSS dimensions; context is already scaled by DPR.
|
||||
ctx.clearRect(0, 0, cssWidth, cssHeight)
|
||||
|
||||
const { topValue, bottomValue } = yScale
|
||||
const { topValue, bottomValue } = yScaleRef.current
|
||||
|
||||
drawYAxis(ctx, cssWidth, cssHeight, topValue, bottomValue)
|
||||
|
||||
@@ -780,6 +859,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
cssWidth,
|
||||
cssHeight,
|
||||
colors.down,
|
||||
colors.gradient.down,
|
||||
true,
|
||||
topValue,
|
||||
bottomValue,
|
||||
@@ -792,6 +872,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
cssWidth,
|
||||
cssHeight,
|
||||
colors.up,
|
||||
colors.gradient.up,
|
||||
true,
|
||||
topValue,
|
||||
bottomValue,
|
||||
@@ -804,9 +885,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
)
|
||||
canvas.dataset.perfDraw = String(displayData.at(-1)?.timestamp ?? 0)
|
||||
}, [
|
||||
displayData,
|
||||
colors,
|
||||
yScale,
|
||||
drawYAxis,
|
||||
drawGrid,
|
||||
drawTimeAxis,
|
||||
@@ -817,6 +896,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
|
||||
const drawHoverOverlay = useCallback(() => {
|
||||
const canvas = hoverCanvasRef.current
|
||||
const displayData = displayDataRef.current
|
||||
if (!canvas || displayData.length < 2) {
|
||||
clearCanvas(canvas)
|
||||
return
|
||||
@@ -854,7 +934,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
|
||||
ctx.restore()
|
||||
}
|
||||
}, [displayData, colors, syncCanvasSize, clearCanvas])
|
||||
}, [colors, syncCanvasSize, clearCanvas])
|
||||
|
||||
const shouldSkipGraphDraw = useCallback(() => {
|
||||
if (!isDocumentVisibleRef.current) return true
|
||||
@@ -897,6 +977,55 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
})
|
||||
}, [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(() => {
|
||||
tooltipDataRef.current = tooltipData
|
||||
scheduleHoverDraw()
|
||||
@@ -966,119 +1095,36 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
position: 'relative',
|
||||
bgcolor: 'action.hover',
|
||||
borderRadius: 1,
|
||||
cursor: 'pointer',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
sx={rootSx}
|
||||
onClick={toggleStyle}
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
display: 'block',
|
||||
}}
|
||||
onClick={toggleStyle}
|
||||
/>
|
||||
<canvas ref={canvasRef} style={canvasStyle} onClick={toggleStyle} />
|
||||
|
||||
{tooltipData.visible && (
|
||||
<canvas
|
||||
ref={hoverCanvasRef}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
inset: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
display: 'block',
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
/>
|
||||
<canvas ref={hoverCanvasRef} style={hoverCanvasStyle} />
|
||||
)}
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
<Box sx={overlaySx}>
|
||||
<Box
|
||||
component="div"
|
||||
onClick={handleTimeRangeClick}
|
||||
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)',
|
||||
},
|
||||
}}
|
||||
sx={timeRangeBadgeSx}
|
||||
>
|
||||
{getTimeRangeText()}
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
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',
|
||||
}}
|
||||
>
|
||||
<Box sx={legendsSx}>
|
||||
<Box sx={legendSx.up}>
|
||||
{t('home.components.traffic.legends.upload')}
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
fontSize: '11px',
|
||||
fontWeight: 'bold',
|
||||
color: colors.down,
|
||||
textAlign: 'right',
|
||||
}}
|
||||
>
|
||||
<Box sx={legendSx.down}>
|
||||
{t('home.components.traffic.legends.download')}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
bottom: 6,
|
||||
right: 8,
|
||||
fontSize: '10px',
|
||||
color: 'text.disabled',
|
||||
opacity: 0.7,
|
||||
}}
|
||||
>
|
||||
<Box sx={chartStyleHintSx}>
|
||||
{t(
|
||||
chartStyle === 'bezier'
|
||||
? 'home.components.traffic.chartStyles.smooth'
|
||||
@@ -1086,20 +1132,10 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
bottom: 6,
|
||||
left: 8,
|
||||
fontSize: '9px',
|
||||
color: 'text.disabled',
|
||||
opacity: 0.6,
|
||||
lineHeight: 1.2,
|
||||
}}
|
||||
>
|
||||
<Box sx={diagnosticsSx}>
|
||||
{t('home.components.traffic.diagnostics', {
|
||||
points: displayData.length,
|
||||
compressed: samplerStats.compressedBufferSize,
|
||||
points: badgeStats.points,
|
||||
compressed: badgeStats.compressed,
|
||||
fps: GRAPH_CONFIG.targetFPS,
|
||||
})}
|
||||
</Box>
|
||||
@@ -1127,15 +1163,9 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
whiteSpace: 'nowrap',
|
||||
}}
|
||||
>
|
||||
<Box sx={{ color: 'text.secondary', mb: 0.2 }}>
|
||||
{tooltipData.timestamp}
|
||||
</Box>
|
||||
<Box sx={{ color: 'secondary.main', fontWeight: 500 }}>
|
||||
↑ {tooltipData.upSpeed}
|
||||
</Box>
|
||||
<Box sx={{ color: 'primary.main', fontWeight: 500 }}>
|
||||
↓ {tooltipData.downSpeed}
|
||||
</Box>
|
||||
<Box sx={tooltipTimeSx}>{tooltipData.timestamp}</Box>
|
||||
<Box sx={tooltipUpSx}>↑ {tooltipData.upSpeed}</Box>
|
||||
<Box sx={tooltipDownSx}>↓ {tooltipData.downSpeed}</Box>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
@@ -158,9 +158,11 @@ const EMPTY_DATA: ITrafficDataPoint[] = []
|
||||
export const useTrafficMonitorEnhanced = (options?: {
|
||||
subscribe?: boolean
|
||||
enabled?: boolean
|
||||
onSnapshot?: (message: ITrafficWorkerSnapshotMessage) => void
|
||||
}) => {
|
||||
const subscribeToSnapshots = options?.subscribe ?? true
|
||||
const enabled = options?.enabled ?? true
|
||||
const onSnapshot = options?.onSnapshot
|
||||
const isVisible = useVisibility()
|
||||
const [latestSnapshot, setLatestSnapshot] = useState<{
|
||||
dataPoints: ITrafficDataPoint[]
|
||||
@@ -174,6 +176,8 @@ export const useTrafficMonitorEnhanced = (options?: {
|
||||
const currentRangeRef = useRef<number>(WORKER_CONFIG.defaultRangeMinutes)
|
||||
const isVisibleRef = useRef(isVisible)
|
||||
isVisibleRef.current = isVisible
|
||||
const onSnapshotRef = useRef(onSnapshot)
|
||||
onSnapshotRef.current = onSnapshot
|
||||
|
||||
// 注册引用计数与Worker生命周期
|
||||
useEffect(() => {
|
||||
@@ -186,9 +190,12 @@ export const useTrafficMonitorEnhanced = (options?: {
|
||||
client.start(currentRangeRef.current)
|
||||
|
||||
let unsubscribe: (() => void) | undefined
|
||||
if (subscribeToSnapshots) {
|
||||
if (subscribeToSnapshots || onSnapshot) {
|
||||
unsubscribe = client.onSnapshot((message) => {
|
||||
if (!isVisibleRef.current) return
|
||||
// onSnapshot is the always-live channel (ignores visibility); the
|
||||
// state mirror below keeps its original always-latest contract.
|
||||
onSnapshotRef.current?.(message)
|
||||
if (!subscribeToSnapshots || !isVisibleRef.current) return
|
||||
setLatestSnapshot({
|
||||
dataPoints: message.dataPoints,
|
||||
samplerStats: message.samplerStats,
|
||||
@@ -203,14 +210,14 @@ export const useTrafficMonitorEnhanced = (options?: {
|
||||
client.stop()
|
||||
}
|
||||
}
|
||||
}, [enabled, subscribeToSnapshots])
|
||||
}, [enabled, subscribeToSnapshots, onSnapshot])
|
||||
|
||||
// Re-prime snapshot ingestion after every visible transition
|
||||
useEffect(() => {
|
||||
if (enabled && subscribeToSnapshots && isVisible) {
|
||||
if (enabled && isVisible && (subscribeToSnapshots || onSnapshot)) {
|
||||
clientRef.current?.requestSnapshot()
|
||||
}
|
||||
}, [enabled, subscribeToSnapshots, isVisible])
|
||||
}, [enabled, subscribeToSnapshots, onSnapshot, isVisible])
|
||||
|
||||
// 添加流量数据
|
||||
const appendData = useCallback(
|
||||
@@ -244,8 +251,12 @@ export const useTrafficMonitorEnhanced = (options?: {
|
||||
/**
|
||||
* 图表数据Hook
|
||||
*/
|
||||
export const useTrafficGraphDataEnhanced = () => {
|
||||
const { graphData, samplerStats } = useTrafficMonitorEnhanced()
|
||||
export const useTrafficGraphDataEnhanced = (options?: {
|
||||
subscribe?: boolean
|
||||
enabled?: boolean
|
||||
onSnapshot?: (message: ITrafficWorkerSnapshotMessage) => void
|
||||
}) => {
|
||||
const { graphData, samplerStats } = useTrafficMonitorEnhanced(options)
|
||||
|
||||
return {
|
||||
...graphData,
|
||||
|
||||
@@ -19,6 +19,13 @@ let currentRangeMinutes!: number
|
||||
let throttleTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let lastTimestamp: number | undefined
|
||||
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 dataPoints = sampler.getDataForTimeRange(currentRangeMinutes)
|
||||
@@ -33,6 +40,7 @@ const broadcastSnapshot = () => {
|
||||
|
||||
ctx.postMessage(message)
|
||||
lastBroadcast = dataPoints
|
||||
lastSamplerVersion = sampler.getVersion()
|
||||
}
|
||||
|
||||
const scheduleSnapshot = () => {
|
||||
@@ -55,9 +63,18 @@ ctx.onmessage = (event: MessageEvent<TrafficWorkerRequestMessage>) => {
|
||||
// no handle needed, worker teardown (terminate) drops pending timers
|
||||
ctx.setInterval(() => {
|
||||
if (throttleTimer !== null) return
|
||||
const version = sampler.getVersion()
|
||||
if (
|
||||
version === lastSamplerVersion &&
|
||||
!agedPastRange(lastBroadcast, currentRangeMinutes)
|
||||
) {
|
||||
return
|
||||
}
|
||||
const slice = sampler.getDataForTimeRange(currentRangeMinutes)
|
||||
if (!isSameTrafficData(lastBroadcast, slice)) {
|
||||
broadcastSnapshot()
|
||||
} else {
|
||||
lastSamplerVersion = version
|
||||
}
|
||||
}, 1000)
|
||||
broadcastSnapshot()
|
||||
|
||||
@@ -7,14 +7,33 @@ interface ICompressedDataPoint {
|
||||
|
||||
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) => {
|
||||
const cached = hourMinuteLabels.get(timestamp)
|
||||
if (cached !== undefined) return cached
|
||||
|
||||
const date = new Date(timestamp)
|
||||
return `${pad2(date.getHours())}:${pad2(date.getMinutes())}`
|
||||
const label = `${pad2(date.getHours())}:${pad2(date.getMinutes())}`
|
||||
if (hourMinuteLabels.size >= TIME_LABEL_CACHE_LIMIT) hourMinuteLabels.clear()
|
||||
hourMinuteLabels.set(timestamp, label)
|
||||
return label
|
||||
}
|
||||
|
||||
export const formatTrafficMinuteSecond = (timestamp: number) => {
|
||||
const cached = minuteSecondLabels.get(timestamp)
|
||||
if (cached !== undefined) return cached
|
||||
|
||||
const date = new Date(timestamp)
|
||||
return `${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`
|
||||
const label = `${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`
|
||||
if (minuteSecondLabels.size >= TIME_LABEL_CACHE_LIMIT)
|
||||
minuteSecondLabels.clear()
|
||||
minuteSecondLabels.set(timestamp, label)
|
||||
return label
|
||||
}
|
||||
|
||||
export const formatTrafficName = (timestamp: number) => {
|
||||
@@ -53,10 +72,12 @@ export class TrafficDataSampler {
|
||||
private compressedBuffer: ICompressedDataPoint[] = []
|
||||
private compressedHead = 0
|
||||
private compressionQueue: ITrafficDataPoint[] = []
|
||||
private version = 0
|
||||
|
||||
constructor(private config: ISamplingConfig) {}
|
||||
|
||||
addDataPoint(point: ITrafficDataPoint) {
|
||||
this.version++
|
||||
this.rawBuffer.push(point)
|
||||
|
||||
const rawCutoff = Date.now() - this.config.rawDataMinutes * 60 * 1000
|
||||
@@ -167,7 +188,13 @@ export class TrafficDataSampler {
|
||||
}
|
||||
}
|
||||
|
||||
/** Bumped by every mutation (added points, compression, aging trims, clear). */
|
||||
getVersion(): number {
|
||||
return this.version
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.version++
|
||||
this.rawBuffer = []
|
||||
this.rawHead = 0
|
||||
this.compressedBuffer = []
|
||||
|
||||
Reference in New Issue
Block a user