mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-19 02:12:10 +08:00
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:
@@ -7,6 +7,7 @@ import {
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getSortedRowModel,
|
||||
Row,
|
||||
SortingState,
|
||||
Updater,
|
||||
useReactTable,
|
||||
@@ -16,11 +17,13 @@ import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import dayjs from 'dayjs'
|
||||
import { useLocalStorage } from 'foxact/use-local-storage'
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
useSyncExternalStore,
|
||||
type ReactNode,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
@@ -32,9 +35,156 @@ import { ConnectionColumnManager } from './connection-column-manager'
|
||||
|
||||
const ROW_HEIGHT = 40
|
||||
|
||||
/**
|
||||
* Reconcile stored column order with base columns to handle added/removed fields
|
||||
*/
|
||||
type TickListener = () => void
|
||||
let _tickNow = Date.now()
|
||||
const _tickListeners = new Set<TickListener>()
|
||||
let _tickTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
const _startTick = () => {
|
||||
if (_tickTimer !== null) return
|
||||
_tickTimer = setInterval(() => {
|
||||
_tickNow = Date.now()
|
||||
_tickListeners.forEach((fn) => fn())
|
||||
}, 5000)
|
||||
}
|
||||
|
||||
const _stopTick = () => {
|
||||
if (_tickListeners.size === 0 && _tickTimer !== null) {
|
||||
clearInterval(_tickTimer)
|
||||
_tickTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
const tickStore = {
|
||||
subscribe: (listener: TickListener) => {
|
||||
_tickListeners.add(listener)
|
||||
_startTick()
|
||||
return () => {
|
||||
_tickListeners.delete(listener)
|
||||
_stopTick()
|
||||
}
|
||||
},
|
||||
getSnapshot: () => _tickNow,
|
||||
}
|
||||
|
||||
interface RelativeTimeCellProps {
|
||||
start: string
|
||||
}
|
||||
|
||||
const RelativeTimeCell = memo(function RelativeTimeCell({
|
||||
start,
|
||||
}: RelativeTimeCellProps) {
|
||||
const now = useSyncExternalStore(tickStore.subscribe, tickStore.getSnapshot)
|
||||
return <>{dayjs(start).from(now)}</>
|
||||
})
|
||||
|
||||
const SX_OUTER: React.ComponentProps<typeof Box>['sx'] = {
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
position: 'relative',
|
||||
fontFamily: (theme) => theme.typography.fontFamily,
|
||||
}
|
||||
|
||||
const SX_SCROLL_CONTAINER: React.ComponentProps<typeof Box>['sx'] = {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
overflow: 'auto',
|
||||
WebkitOverflowScrolling: 'touch',
|
||||
overscrollBehavior: 'contain',
|
||||
borderRadius: 1,
|
||||
border: 'none',
|
||||
'&::-webkit-scrollbar': {
|
||||
height: 8,
|
||||
},
|
||||
}
|
||||
|
||||
const SX_HEADER_STICKY: React.ComponentProps<typeof Box>['sx'] = {
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 2,
|
||||
}
|
||||
|
||||
const SX_CELL_CONTENT: React.ComponentProps<typeof Box>['sx'] = {
|
||||
flex: 1,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 0.5,
|
||||
px: 1,
|
||||
py: 1,
|
||||
}
|
||||
|
||||
const SX_RESIZE_HANDLE: React.ComponentProps<typeof Box>['sx'] = {
|
||||
cursor: 'col-resize',
|
||||
position: 'absolute',
|
||||
right: 0,
|
||||
top: 0,
|
||||
width: 4,
|
||||
height: '100%',
|
||||
transform: 'translateX(50%)',
|
||||
'&:hover': {
|
||||
backgroundColor: (theme) => theme.palette.action.active,
|
||||
},
|
||||
}
|
||||
|
||||
const SX_ICON_BTN: React.ComponentProps<typeof IconButton>['sx'] = {
|
||||
position: 'absolute',
|
||||
top: 4,
|
||||
right: 4,
|
||||
zIndex: 3,
|
||||
backgroundColor: (theme) =>
|
||||
theme.palette.mode === 'dark'
|
||||
? theme.palette.background.default
|
||||
: theme.palette.background.paper,
|
||||
'&:hover': {
|
||||
backgroundColor: (theme) => theme.palette.action.hover,
|
||||
},
|
||||
}
|
||||
|
||||
const SX_HEADER_ROW: React.ComponentProps<typeof Box>['sx'] = {
|
||||
display: 'flex',
|
||||
borderBottom: (theme) => `1px solid ${theme.palette.divider}`,
|
||||
backgroundColor: (theme) => theme.palette.background.paper,
|
||||
}
|
||||
|
||||
const SX_HEADER_CELL_BASE: React.ComponentProps<typeof Box>['sx'] = {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
position: 'relative',
|
||||
boxSizing: 'border-box',
|
||||
fontSize: 13,
|
||||
fontWeight: 600,
|
||||
color: 'text.secondary',
|
||||
userSelect: 'none',
|
||||
'&:hover': {
|
||||
backgroundColor: (theme) => theme.palette.action.hover,
|
||||
},
|
||||
}
|
||||
|
||||
const SX_DATA_CELL_BASE: React.ComponentProps<typeof Box>['sx'] = {
|
||||
boxSizing: 'border-box',
|
||||
px: 1,
|
||||
fontSize: 13,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
whiteSpace: 'nowrap',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
}
|
||||
|
||||
const SX_ROW_BASE: React.ComponentProps<typeof Box>['sx'] = {
|
||||
display: 'flex',
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
right: 0,
|
||||
cursor: 'pointer',
|
||||
borderBottom: (theme) => `1px solid ${theme.palette.divider}`,
|
||||
'&:hover': {
|
||||
backgroundColor: (theme) => theme.palette.action.hover,
|
||||
},
|
||||
}
|
||||
|
||||
const reconcileColumnOrder = (
|
||||
storedOrder: string[],
|
||||
baseFields: string[],
|
||||
@@ -95,6 +245,68 @@ const getConnectionCellValue = (field: ColumnField, each: IConnectionsItem) => {
|
||||
}
|
||||
}
|
||||
|
||||
interface RowComponentProps {
|
||||
row: Row<IConnectionsItem>
|
||||
virtualStart: number
|
||||
virtualSize: number
|
||||
onShowDetail: (data: IConnectionsItem) => void
|
||||
}
|
||||
|
||||
const RowComponent = memo(
|
||||
function RowComponent({
|
||||
row,
|
||||
virtualStart,
|
||||
virtualSize,
|
||||
onShowDetail,
|
||||
}: RowComponentProps) {
|
||||
const handleClick = useCallback(
|
||||
() => onShowDetail(row.original),
|
||||
[onShowDetail, row.original],
|
||||
)
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={[
|
||||
SX_ROW_BASE,
|
||||
{
|
||||
height: virtualSize,
|
||||
transform: `translateY(${virtualStart}px)`,
|
||||
},
|
||||
]}
|
||||
onClick={handleClick}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => {
|
||||
const meta = cell.column.columnDef.meta as {
|
||||
align?: 'left' | 'right'
|
||||
}
|
||||
return (
|
||||
<Box
|
||||
key={cell.id}
|
||||
sx={[
|
||||
SX_DATA_CELL_BASE,
|
||||
{
|
||||
flex: `0 0 ${cell.column.getSize()}px`,
|
||||
minWidth: cell.column.columnDef.minSize ?? 80,
|
||||
maxWidth: cell.column.columnDef.maxSize,
|
||||
justifyContent:
|
||||
meta?.align === 'right' ? 'flex-end' : 'flex-start',
|
||||
},
|
||||
]}
|
||||
>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</Box>
|
||||
)
|
||||
})}
|
||||
</Box>
|
||||
)
|
||||
},
|
||||
(prev, next) =>
|
||||
prev.row === next.row &&
|
||||
prev.virtualStart === next.virtualStart &&
|
||||
prev.virtualSize === next.virtualSize &&
|
||||
prev.onShowDetail === next.onShowDetail,
|
||||
)
|
||||
|
||||
interface Props {
|
||||
connections: IConnectionsItem[]
|
||||
onShowDetail: (data: IConnectionsItem) => void
|
||||
@@ -106,16 +318,20 @@ interface Props {
|
||||
export const ConnectionTable = (props: Props) => {
|
||||
const {
|
||||
connections,
|
||||
onShowDetail,
|
||||
onShowDetail: rawOnShowDetail,
|
||||
columnManagerOpen,
|
||||
onOpenColumnManager,
|
||||
onCloseColumnManager,
|
||||
} = props
|
||||
const onShowDetailRef = useRef(rawOnShowDetail)
|
||||
onShowDetailRef.current = rawOnShowDetail
|
||||
const onShowDetail = useCallback(
|
||||
(data: IConnectionsItem) => onShowDetailRef.current(data),
|
||||
[],
|
||||
)
|
||||
const { t } = useTranslation()
|
||||
const [columnWidths, setColumnWidths] = useLocalStorage<ColumnSizingState>(
|
||||
'connection-table-widths',
|
||||
// server-side value, this is the default value used by server-side rendering (if any)
|
||||
// Do not omit (otherwise a Suspense boundary will be triggered)
|
||||
{},
|
||||
)
|
||||
|
||||
@@ -227,7 +443,6 @@ export const ConnectionTable = (props: Props) => {
|
||||
width: 100,
|
||||
minWidth: 80,
|
||||
align: 'right',
|
||||
// cell filled later with shared relativeNow ticker
|
||||
},
|
||||
{
|
||||
field: 'source',
|
||||
@@ -307,18 +522,25 @@ export const ConnectionTable = (props: Props) => {
|
||||
)
|
||||
|
||||
const [sorting, setSorting] = useState<SortingState>([])
|
||||
const [relativeNow, setRelativeNow] = useState(() => Date.now())
|
||||
|
||||
// columnDefs no longer depends on relativeNow — time column delegates to RelativeTimeCell
|
||||
const columnDefs = useMemo<ColumnDef<IConnectionsItem>[]>(() => {
|
||||
return baseColumns.map((column) => {
|
||||
const baseCell: ColumnDef<IConnectionsItem>['cell'] = column.cell
|
||||
? (ctx) => column.cell?.(ctx.row.original)
|
||||
: (ctx) => ctx.getValue() as ReactNode
|
||||
|
||||
const cell: ColumnDef<IConnectionsItem>['cell'] =
|
||||
column.field === 'time'
|
||||
? (ctx) => dayjs(ctx.getValue() as string).from(relativeNow)
|
||||
: baseCell
|
||||
let cell: ColumnDef<IConnectionsItem>['cell']
|
||||
if (column.field === 'time') {
|
||||
cell = (ctx) => <RelativeTimeCell start={ctx.row.original.start} />
|
||||
} else if (column.cell) {
|
||||
const renderCell = column.cell
|
||||
cell = (ctx) => renderCell(ctx.row.original)
|
||||
} else {
|
||||
cell = (ctx) =>
|
||||
ctx.row.original
|
||||
? (getConnectionCellValue(
|
||||
column.field,
|
||||
ctx.row.original,
|
||||
) as ReactNode)
|
||||
: null
|
||||
}
|
||||
|
||||
return {
|
||||
id: column.field,
|
||||
@@ -334,17 +556,7 @@ export const ConnectionTable = (props: Props) => {
|
||||
cell,
|
||||
} satisfies ColumnDef<IConnectionsItem>
|
||||
})
|
||||
}, [baseColumns, relativeNow])
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return undefined
|
||||
|
||||
const timer = window.setInterval(() => {
|
||||
setRelativeNow(Date.now())
|
||||
}, 5000)
|
||||
|
||||
return () => window.clearInterval(timer)
|
||||
}, [])
|
||||
}, [baseColumns])
|
||||
|
||||
const handleColumnSizingChange = useCallback(
|
||||
(updater: Updater<ColumnSizingState>) => {
|
||||
@@ -420,75 +632,26 @@ export const ConnectionTable = (props: Props) => {
|
||||
|
||||
return (
|
||||
<>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
position: 'relative',
|
||||
fontFamily: (theme) => theme.typography.fontFamily,
|
||||
}}
|
||||
>
|
||||
<Box sx={SX_OUTER}>
|
||||
<Tooltip title={t('connections.components.columnManager.title')}>
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={onOpenColumnManager}
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
top: 4,
|
||||
right: 4,
|
||||
zIndex: 3,
|
||||
backgroundColor: (theme) =>
|
||||
theme.palette.mode === 'dark'
|
||||
? theme.palette.background.default
|
||||
: theme.palette.background.paper,
|
||||
'&:hover': {
|
||||
backgroundColor: (theme) => theme.palette.action.hover,
|
||||
},
|
||||
}}
|
||||
sx={SX_ICON_BTN}
|
||||
>
|
||||
<ViewColumnRounded fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<Box
|
||||
ref={tableContainerRef}
|
||||
sx={{
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
overflow: 'auto',
|
||||
WebkitOverflowScrolling: 'touch',
|
||||
overscrollBehavior: 'contain',
|
||||
borderRadius: 1,
|
||||
border: 'none',
|
||||
'&::-webkit-scrollbar': {
|
||||
height: 8,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Box ref={tableContainerRef} sx={SX_SCROLL_CONTAINER}>
|
||||
<Box
|
||||
sx={{
|
||||
minWidth: '100%',
|
||||
width: tableWidth,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 2,
|
||||
}}
|
||||
>
|
||||
<Box sx={SX_HEADER_STICKY}>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<Box
|
||||
key={headerGroup.id}
|
||||
sx={{
|
||||
display: 'flex',
|
||||
borderBottom: (theme) =>
|
||||
`1px solid ${theme.palette.divider}`,
|
||||
backgroundColor: (theme) => theme.palette.background.paper,
|
||||
}}
|
||||
>
|
||||
<Box key={headerGroup.id} sx={SX_HEADER_ROW}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
if (header.isPlaceholder) {
|
||||
return null
|
||||
@@ -500,23 +663,14 @@ export const ConnectionTable = (props: Props) => {
|
||||
return (
|
||||
<Box
|
||||
key={header.id}
|
||||
sx={{
|
||||
flex: `0 0 ${header.getSize()}px`,
|
||||
minWidth: header.column.columnDef.minSize || 80,
|
||||
maxWidth: header.column.columnDef.maxSize,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
position: 'relative',
|
||||
boxSizing: 'border-box',
|
||||
fontSize: 13,
|
||||
fontWeight: 600,
|
||||
color: 'text.secondary',
|
||||
userSelect: 'none',
|
||||
'&:hover': {
|
||||
backgroundColor: (theme) =>
|
||||
theme.palette.action.hover,
|
||||
sx={[
|
||||
SX_HEADER_CELL_BASE,
|
||||
{
|
||||
flex: `0 0 ${header.getSize()}px`,
|
||||
minWidth: header.column.columnDef.minSize ?? 80,
|
||||
maxWidth: header.column.columnDef.maxSize,
|
||||
},
|
||||
}}
|
||||
]}
|
||||
>
|
||||
<Box
|
||||
component="span"
|
||||
@@ -525,21 +679,18 @@ export const ConnectionTable = (props: Props) => {
|
||||
? header.column.getToggleSortingHandler()
|
||||
: undefined
|
||||
}
|
||||
sx={{
|
||||
flex: 1,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent:
|
||||
meta?.align === 'right'
|
||||
? 'flex-end'
|
||||
: 'flex-start',
|
||||
gap: 0.5,
|
||||
px: 1,
|
||||
py: 1,
|
||||
cursor: header.column.getCanSort()
|
||||
? 'pointer'
|
||||
: 'default',
|
||||
}}
|
||||
sx={[
|
||||
SX_CELL_CONTENT,
|
||||
{
|
||||
justifyContent:
|
||||
meta?.align === 'right'
|
||||
? 'flex-end'
|
||||
: 'flex-start',
|
||||
cursor: header.column.getCanSort()
|
||||
? 'pointer'
|
||||
: 'default',
|
||||
},
|
||||
]}
|
||||
>
|
||||
{flexRender(
|
||||
header.column.columnDef.header,
|
||||
@@ -561,19 +712,7 @@ export const ConnectionTable = (props: Props) => {
|
||||
event.stopPropagation()
|
||||
header.getResizeHandler()(event)
|
||||
}}
|
||||
sx={{
|
||||
cursor: 'col-resize',
|
||||
position: 'absolute',
|
||||
right: 0,
|
||||
top: 0,
|
||||
width: 4,
|
||||
height: '100%',
|
||||
transform: 'translateX(50%)',
|
||||
'&:hover': {
|
||||
backgroundColor: (theme) =>
|
||||
theme.palette.action.active,
|
||||
},
|
||||
}}
|
||||
sx={SX_RESIZE_HANDLE}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
@@ -593,57 +732,13 @@ export const ConnectionTable = (props: Props) => {
|
||||
if (!row) return null
|
||||
|
||||
return (
|
||||
<Box
|
||||
<RowComponent
|
||||
key={row.id}
|
||||
onClick={() => onShowDetail(row.original)}
|
||||
sx={{
|
||||
display: 'flex',
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
right: 0,
|
||||
height: virtualRow.size,
|
||||
transform: `translateY(${virtualRow.start}px)`,
|
||||
borderBottom: (theme) =>
|
||||
`1px solid ${theme.palette.divider}`,
|
||||
cursor: 'pointer',
|
||||
'&:hover': {
|
||||
backgroundColor: (theme) => theme.palette.action.hover,
|
||||
},
|
||||
}}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => {
|
||||
const meta = cell.column.columnDef.meta as {
|
||||
align?: 'left' | 'right'
|
||||
}
|
||||
return (
|
||||
<Box
|
||||
key={cell.id}
|
||||
sx={{
|
||||
flex: `0 0 ${cell.column.getSize()}px`,
|
||||
minWidth: cell.column.columnDef.minSize || 80,
|
||||
maxWidth: cell.column.columnDef.maxSize,
|
||||
boxSizing: 'border-box',
|
||||
px: 1,
|
||||
fontSize: 13,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent:
|
||||
meta?.align === 'right'
|
||||
? 'flex-end'
|
||||
: 'flex-start',
|
||||
whiteSpace: 'nowrap',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
}}
|
||||
>
|
||||
{flexRender(
|
||||
cell.column.columnDef.cell,
|
||||
cell.getContext(),
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
})}
|
||||
</Box>
|
||||
row={row}
|
||||
virtualStart={virtualRow.start}
|
||||
virtualSize={virtualRow.size}
|
||||
onShowDetail={onShowDetail}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</Box>
|
||||
|
||||
@@ -121,6 +121,9 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
const initialFocusState =
|
||||
typeof document !== 'undefined' ? !document.hidden : true
|
||||
const [isWindowFocused, setIsWindowFocused] = useState(initialFocusState)
|
||||
const [isDocumentVisible, setIsDocumentVisible] =
|
||||
useState(initialFocusState)
|
||||
const isDocumentVisibleRef = useRef(initialFocusState)
|
||||
|
||||
// 悬浮提示状态
|
||||
const [tooltipData, setTooltipData] = useState<TooltipData>({
|
||||
@@ -246,7 +249,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
resumeCooldownRef.current = 0
|
||||
}
|
||||
},
|
||||
[setIsWindowFocused, setCurrentFPS, pause_render_traffic_stats_on_blur],
|
||||
[pause_render_traffic_stats_on_blur],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -256,8 +259,12 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
|
||||
const handleFocus = () => handleFocusStateChange(true)
|
||||
const handleBlur = () => handleFocusStateChange(false)
|
||||
const handleVisibilityChange = () =>
|
||||
handleFocusStateChange(!document.hidden)
|
||||
const handleVisibilityChange = () => {
|
||||
const visible = !document.hidden
|
||||
isDocumentVisibleRef.current = visible
|
||||
setIsDocumentVisible(visible)
|
||||
handleFocusStateChange(visible)
|
||||
}
|
||||
|
||||
window.addEventListener('focus', handleFocus)
|
||||
window.addEventListener('blur', handleBlur)
|
||||
@@ -270,39 +277,18 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
}
|
||||
}, [handleFocusStateChange])
|
||||
|
||||
// Y轴坐标计算 - 基于刻度范围的线性映射
|
||||
// Y轴坐标计算 - 线性映射
|
||||
const calculateY = useCallback(
|
||||
(value: number, height: number, data: ITrafficDataPoint[]): number => {
|
||||
(
|
||||
value: number,
|
||||
height: number,
|
||||
topValue: number,
|
||||
bottomValue: number,
|
||||
): number => {
|
||||
const padding = GRAPH_CONFIG.padding
|
||||
const topY = padding.top + 10 // 与刻度系统保持一致
|
||||
const topY = padding.top + 10
|
||||
const bottomY = height - padding.bottom - 5
|
||||
|
||||
if (data.length === 0) return bottomY
|
||||
|
||||
// 获取当前的刻度范围
|
||||
const allValues = [...data.map((d) => d.up), ...data.map((d) => d.down)]
|
||||
const maxValue = Math.max(...allValues)
|
||||
const minValue = Math.min(...allValues)
|
||||
|
||||
let topValue, bottomValue
|
||||
|
||||
if (maxValue === 0) {
|
||||
topValue = 1024
|
||||
bottomValue = 0
|
||||
} else {
|
||||
const range = maxValue - minValue
|
||||
const padding_percent = range > 0 ? 0.1 : 0.5
|
||||
|
||||
if (range === 0) {
|
||||
bottomValue = 0
|
||||
topValue = maxValue * 1.2
|
||||
} else {
|
||||
bottomValue = Math.max(0, minValue - range * padding_percent)
|
||||
topValue = maxValue + range * padding_percent
|
||||
}
|
||||
}
|
||||
|
||||
// 线性映射到Y坐标
|
||||
if (topValue === bottomValue) return bottomY
|
||||
|
||||
const ratio = (value - bottomValue) / (topValue - bottomValue)
|
||||
@@ -311,6 +297,38 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
[],
|
||||
)
|
||||
|
||||
const computeYScale = useCallback(
|
||||
(
|
||||
data: ITrafficDataPoint[],
|
||||
): { topValue: number; bottomValue: number } => {
|
||||
if (data.length === 0) return { topValue: 1024, bottomValue: 0 }
|
||||
|
||||
let maxValue = 0
|
||||
let minValue = Infinity
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
const up = data[i].up
|
||||
const down = data[i].down
|
||||
if (up > maxValue) maxValue = up
|
||||
if (down > maxValue) maxValue = down
|
||||
if (up < minValue) minValue = up
|
||||
if (down < minValue) minValue = down
|
||||
}
|
||||
if (!isFinite(minValue)) minValue = 0
|
||||
|
||||
if (maxValue === 0) return { topValue: 1024, bottomValue: 0 }
|
||||
|
||||
const range = maxValue - minValue
|
||||
if (range === 0) return { topValue: maxValue * 1.2, bottomValue: 0 }
|
||||
|
||||
const pct = 0.1
|
||||
return {
|
||||
topValue: maxValue + range * pct,
|
||||
bottomValue: Math.max(0, minValue - range * pct),
|
||||
}
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
// 鼠标悬浮处理 - 计算最近的数据点
|
||||
const handleMouseMove = useCallback(
|
||||
(event: React.MouseEvent<HTMLCanvasElement>) => {
|
||||
@@ -346,8 +364,9 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
: '未知时间'
|
||||
|
||||
// 计算数据点对应的Y坐标位置(用于高亮)
|
||||
const upY = calculateY(dataPoint.up, rect.height, displayData)
|
||||
const downY = calculateY(dataPoint.down, rect.height, displayData)
|
||||
const { topValue: tvH, bottomValue: bvH } = computeYScale(displayData)
|
||||
const upY = calculateY(dataPoint.up, rect.height, tvH, bvH)
|
||||
const downY = calculateY(dataPoint.down, rect.height, tvH, bvH)
|
||||
const highlightY =
|
||||
Math.max(dataPoint.up, dataPoint.down) === dataPoint.up
|
||||
? upY
|
||||
@@ -365,7 +384,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
})
|
||||
}
|
||||
},
|
||||
[displayData, calculateY],
|
||||
[displayData, calculateY, computeYScale],
|
||||
)
|
||||
|
||||
// 鼠标离开处理
|
||||
@@ -375,14 +394,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
|
||||
// 获取智能Y轴刻度(三刻度系统:最小值、中间值、最大值)
|
||||
const getYAxisTicks = useCallback(
|
||||
(data: ITrafficDataPoint[], height: number) => {
|
||||
if (data.length === 0) return []
|
||||
|
||||
// 找到数据的最大值和最小值
|
||||
const allValues = [...data.map((d) => d.up), ...data.map((d) => d.down)]
|
||||
const maxValue = Math.max(...allValues)
|
||||
const minValue = Math.min(...allValues)
|
||||
|
||||
(topValue: number, bottomValue: number, height: number) => {
|
||||
// 格式化流量数值
|
||||
const formatTrafficValue = (bytes: number): string => {
|
||||
if (bytes === 0) return '0'
|
||||
@@ -397,32 +409,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
const topY = padding.top + 10 // 避免与顶部时间范围按钮重叠
|
||||
const bottomY = height - padding.bottom - 5 // 避免与底部时间轴重叠
|
||||
const middleY = (topY + bottomY) / 2
|
||||
|
||||
// 计算对应的值
|
||||
let topValue, middleValue, bottomValue
|
||||
|
||||
if (maxValue === 0) {
|
||||
// 如果没有流量,显示0到一个小值的范围
|
||||
topValue = 1024 // 1KB
|
||||
middleValue = 512 // 512B
|
||||
bottomValue = 0
|
||||
} else {
|
||||
// 根据数据范围计算合适的刻度值
|
||||
const range = maxValue - minValue
|
||||
const padding_percent = range > 0 ? 0.1 : 0.5 // 如果范围为0,使用更大的边距
|
||||
|
||||
if (range === 0) {
|
||||
// 所有值相同的情况
|
||||
bottomValue = 0
|
||||
middleValue = maxValue * 0.5
|
||||
topValue = maxValue * 1.2
|
||||
} else {
|
||||
// 正常情况
|
||||
bottomValue = Math.max(0, minValue - range * padding_percent)
|
||||
topValue = maxValue + range * padding_percent
|
||||
middleValue = (bottomValue + topValue) / 2
|
||||
}
|
||||
}
|
||||
const middleValue = (bottomValue + topValue) / 2
|
||||
|
||||
// 创建三个固定位置的刻度
|
||||
const ticks = [
|
||||
@@ -454,10 +441,11 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
width: number,
|
||||
height: number,
|
||||
data: ITrafficDataPoint[],
|
||||
topValue: number,
|
||||
bottomValue: number,
|
||||
) => {
|
||||
const padding = GRAPH_CONFIG.padding
|
||||
const ticks = getYAxisTicks(data, height)
|
||||
const ticks = getYAxisTicks(topValue, bottomValue, height)
|
||||
|
||||
if (ticks.length === 0) return
|
||||
|
||||
@@ -706,7 +694,8 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
height: number,
|
||||
color: string,
|
||||
withGradient = false,
|
||||
data: ITrafficDataPoint[],
|
||||
topValue: number,
|
||||
bottomValue: number,
|
||||
) => {
|
||||
if (values.length < 2) return
|
||||
|
||||
@@ -715,7 +704,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
|
||||
const points = values.map((value, index) => [
|
||||
padding.left + (index / (values.length - 1)) * effectiveWidth,
|
||||
calculateY(value, height, data),
|
||||
calculateY(value, height, topValue, bottomValue),
|
||||
])
|
||||
|
||||
ctx.save()
|
||||
@@ -827,8 +816,10 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
// Clear using CSS dimensions; context is already scaled by DPR.
|
||||
ctx.clearRect(0, 0, cssWidth, cssHeight)
|
||||
|
||||
const { topValue, bottomValue } = computeYScale(displayData)
|
||||
|
||||
// 绘制Y轴刻度线(背景层)
|
||||
drawYAxis(ctx, cssWidth, cssHeight, displayData)
|
||||
drawYAxis(ctx, cssWidth, cssHeight, topValue, bottomValue)
|
||||
|
||||
// 绘制网格
|
||||
drawGrid(ctx, cssWidth, cssHeight)
|
||||
@@ -848,7 +839,8 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
cssHeight,
|
||||
colors.down,
|
||||
true,
|
||||
displayData,
|
||||
topValue,
|
||||
bottomValue,
|
||||
)
|
||||
|
||||
// 绘制上传线(前景层)
|
||||
@@ -859,7 +851,8 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
cssHeight,
|
||||
colors.up,
|
||||
true,
|
||||
displayData,
|
||||
topValue,
|
||||
bottomValue,
|
||||
)
|
||||
|
||||
// 绘制悬浮高亮线
|
||||
@@ -895,6 +888,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
}, [
|
||||
displayData,
|
||||
colors,
|
||||
computeYScale,
|
||||
drawYAxis,
|
||||
drawGrid,
|
||||
drawTimeAxis,
|
||||
@@ -989,6 +983,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
// 受控的动画循环
|
||||
useEffect(() => {
|
||||
if (
|
||||
!isDocumentVisible ||
|
||||
(!isWindowFocused && pause_render_traffic_stats_on_blur) ||
|
||||
displayData.length === 0 ||
|
||||
dataStaleRef.current
|
||||
@@ -1002,6 +997,14 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
}
|
||||
|
||||
const animate = (currentTime: number) => {
|
||||
if (!isDocumentVisibleRef.current) {
|
||||
if (animationFrameRef.current) {
|
||||
cancelAnimationFrame(animationFrameRef.current)
|
||||
animationFrameRef.current = undefined
|
||||
}
|
||||
lastRenderTimeRef.current = getNow()
|
||||
return
|
||||
}
|
||||
if (!isWindowFocusedRef.current && pause_render_traffic_stats_on_blur) {
|
||||
lastRenderTimeRef.current = getNow()
|
||||
animationFrameRef.current = undefined
|
||||
@@ -1053,6 +1056,7 @@ export const EnhancedCanvasTrafficGraph = memo(
|
||||
}, [
|
||||
drawGraph,
|
||||
displayData.length,
|
||||
isDocumentVisible,
|
||||
isWindowFocused,
|
||||
pause_render_traffic_stats_on_blur,
|
||||
collectFrameSample,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -19,52 +19,65 @@ export interface ConnectionMonitorData {
|
||||
closedConnections: IConnectionsItem[]
|
||||
}
|
||||
|
||||
const trimClosedConnections = (
|
||||
closedConnections: IConnectionsItem[],
|
||||
): IConnectionsItem[] =>
|
||||
closedConnections.length > MAX_CLOSED_CONNS_NUM
|
||||
? closedConnections.slice(-MAX_CLOSED_CONNS_NUM)
|
||||
: closedConnections
|
||||
|
||||
const mergeConnectionSnapshot = (
|
||||
payload: IConnections,
|
||||
previous: ConnectionMonitorData = initConnData,
|
||||
): ConnectionMonitorData => {
|
||||
const nextConnections = payload.connections ?? []
|
||||
const previousActive = previous.activeConnections ?? []
|
||||
const nextById = new Map(nextConnections.map((conn) => [conn.id, conn]))
|
||||
const previousClosed = previous.closedConnections ?? []
|
||||
|
||||
// Keep surviving connections in their previous relative order to reduce row reshuffle,
|
||||
// but constrain the array to the incoming snapshot length.
|
||||
const carried = previousActive
|
||||
.map((prev) => {
|
||||
const next = nextById.get(prev.id)
|
||||
if (!next) return null
|
||||
const nextById = new Map<string, IConnectionsItem>()
|
||||
for (let i = 0; i < nextConnections.length; i++) {
|
||||
nextById.set(nextConnections[i].id, nextConnections[i])
|
||||
}
|
||||
|
||||
const carried: IConnectionsItem[] = []
|
||||
const dropped: IConnectionsItem[] = []
|
||||
|
||||
for (let i = 0; i < previousActive.length; i++) {
|
||||
const prev = previousActive[i]
|
||||
const next = nextById.get(prev.id)
|
||||
if (next !== undefined) {
|
||||
nextById.delete(prev.id)
|
||||
return {
|
||||
...next,
|
||||
curUpload: next.upload - prev.upload,
|
||||
curDownload: next.download - prev.download,
|
||||
} as IConnectionsItem
|
||||
})
|
||||
.filter(Boolean) as IConnectionsItem[]
|
||||
if (prev.upload === next.upload && prev.download === next.download) {
|
||||
// Reuse prev reference: row identity stability is the contract Stage 2 memo relies on.
|
||||
carried.push(prev)
|
||||
} else {
|
||||
carried.push({
|
||||
...next,
|
||||
curUpload: next.upload - prev.upload,
|
||||
curDownload: next.download - prev.download,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
dropped.push(prev)
|
||||
}
|
||||
}
|
||||
|
||||
const newcomers = nextConnections
|
||||
.filter((conn) => nextById.has(conn.id))
|
||||
.map((conn) => ({
|
||||
...conn,
|
||||
curUpload: 0,
|
||||
curDownload: 0,
|
||||
}))
|
||||
const activeConnections: IConnectionsItem[] = carried
|
||||
for (let i = 0; i < nextConnections.length; i++) {
|
||||
const conn = nextConnections[i]
|
||||
if (nextById.has(conn.id)) {
|
||||
activeConnections.push({
|
||||
...conn,
|
||||
curUpload: 0,
|
||||
curDownload: 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const activeConnections = [...carried, ...newcomers]
|
||||
const activeIds = new Set(activeConnections.map((conn) => conn.id))
|
||||
|
||||
const closedConnections = trimClosedConnections([
|
||||
...(previous.closedConnections ?? []),
|
||||
...previousActive.filter((conn) => !activeIds.has(conn.id)),
|
||||
])
|
||||
const rawClosedLen = previousClosed.length + dropped.length
|
||||
let closedConnections: IConnectionsItem[]
|
||||
if (rawClosedLen <= MAX_CLOSED_CONNS_NUM) {
|
||||
closedConnections = previousClosed.concat(dropped)
|
||||
} else {
|
||||
const skipPrev = rawClosedLen - MAX_CLOSED_CONNS_NUM
|
||||
closedConnections =
|
||||
skipPrev >= previousClosed.length
|
||||
? dropped.slice(skipPrev - previousClosed.length)
|
||||
: previousClosed.slice(skipPrev).concat(dropped)
|
||||
}
|
||||
|
||||
return {
|
||||
uploadTotal: payload.uploadTotal ?? 0,
|
||||
|
||||
@@ -36,7 +36,16 @@ const filterLogsByLevel = (
|
||||
const appendLogs = (
|
||||
current: ILogItem[] | undefined,
|
||||
incoming: ILogItem[],
|
||||
): ILogItem[] => clampLogs([...(current ?? []), ...incoming])
|
||||
): ILogItem[] => {
|
||||
const base = current ?? []
|
||||
const total = base.length + incoming.length
|
||||
if (total <= MAX_LOG_NUM) return base.concat(incoming)
|
||||
const dropFromBase = total - MAX_LOG_NUM
|
||||
if (dropFromBase >= base.length) {
|
||||
return incoming.slice(incoming.length - MAX_LOG_NUM)
|
||||
}
|
||||
return base.slice(dropFromBase).concat(incoming)
|
||||
}
|
||||
|
||||
export const useLogData = () => {
|
||||
const queryClient = useQueryClient()
|
||||
@@ -55,6 +64,7 @@ export const useLogData = () => {
|
||||
setupHandlers: ({ next, scheduleReconnect, isMounted }) => {
|
||||
let flushTimer: ReturnType<typeof setTimeout> | null = null
|
||||
const buffer: ILogItem[] = []
|
||||
let flushTimeStr: string | null = null
|
||||
|
||||
const clearFlushTimer = () => {
|
||||
if (flushTimer) {
|
||||
@@ -69,6 +79,7 @@ export const useLogData = () => {
|
||||
return
|
||||
}
|
||||
const pendingLogs = buffer.splice(0, buffer.length)
|
||||
flushTimeStr = null
|
||||
next(null, (current) => appendLogs(current, pendingLogs))
|
||||
flushTimer = null
|
||||
}
|
||||
@@ -89,7 +100,10 @@ export const useLogData = () => {
|
||||
) {
|
||||
return
|
||||
}
|
||||
parsed.time = dayjs().format('MM-DD HH:mm:ss')
|
||||
if (flushTimeStr === null) {
|
||||
flushTimeStr = dayjs().format('MM-DD HH:mm:ss')
|
||||
}
|
||||
parsed.time = flushTimeStr
|
||||
buffer.push(parsed)
|
||||
if (buffer.length > MAX_LOG_NUM) {
|
||||
buffer.splice(0, buffer.length - MAX_LOG_NUM)
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from 'react'
|
||||
import { Traffic } from 'tauri-plugin-mihomo-api'
|
||||
|
||||
import { useVisibility } from '@/hooks/use-visibility'
|
||||
import { debugLog } from '@/utils/debug'
|
||||
import { TrafficDataSampler, formatTrafficName } from '@/utils/traffic-sampler'
|
||||
|
||||
@@ -17,7 +18,9 @@ class ReferenceCounter {
|
||||
private callbacks = new Set<() => void>()
|
||||
|
||||
private notify() {
|
||||
this.callbacks.forEach((cb) => cb())
|
||||
this.callbacks.forEach((cb) => {
|
||||
cb()
|
||||
})
|
||||
}
|
||||
|
||||
increment(): () => void {
|
||||
@@ -199,7 +202,9 @@ class TrafficWorkerClient {
|
||||
) => {
|
||||
const message = event.data
|
||||
if (message.type === 'snapshot') {
|
||||
this.listeners.forEach((listener) => listener(message))
|
||||
this.listeners.forEach((listener) => {
|
||||
listener(message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,9 +233,11 @@ class TrafficWorkerClient {
|
||||
}
|
||||
|
||||
private startInline(initMessage: TrafficWorkerRequestMessage) {
|
||||
this.inlineMonitor = new InlineTrafficMonitor((snapshot) =>
|
||||
this.listeners.forEach((listener) => listener(snapshot)),
|
||||
)
|
||||
this.inlineMonitor = new InlineTrafficMonitor((snapshot) => {
|
||||
this.listeners.forEach((listener) => {
|
||||
listener(snapshot)
|
||||
})
|
||||
})
|
||||
this.mode = 'inline'
|
||||
this.ready = true
|
||||
this.post(initMessage)
|
||||
@@ -347,6 +354,7 @@ export const useTrafficMonitorEnhanced = (options?: {
|
||||
}) => {
|
||||
const subscribeToSnapshots = options?.subscribe ?? true
|
||||
const enabled = options?.enabled ?? true
|
||||
const isVisible = useVisibility()
|
||||
const [latestSnapshot, setLatestSnapshot] = useState<{
|
||||
availableDataPoints: ITrafficDataPoint[]
|
||||
samplerStats: ISamplerStats
|
||||
@@ -404,14 +412,14 @@ export const useTrafficMonitorEnhanced = (options?: {
|
||||
|
||||
// Periodically refresh "now" so idle streams age out of the selected window when subscribed
|
||||
useEffect(() => {
|
||||
if (!enabled || !subscribeToSnapshots) return
|
||||
if (!enabled || !subscribeToSnapshots || !isVisible) return
|
||||
|
||||
const timer = window.setInterval(() => {
|
||||
setNow(Date.now())
|
||||
}, 1000)
|
||||
|
||||
return () => window.clearInterval(timer)
|
||||
}, [enabled, subscribeToSnapshots])
|
||||
}, [enabled, subscribeToSnapshots, isVisible])
|
||||
|
||||
// 添加流量数据
|
||||
const appendData = useCallback(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createContext, use } from 'react'
|
||||
import { Context, createContext, use } from 'react'
|
||||
import {
|
||||
BaseConfig,
|
||||
ProxyProvider,
|
||||
@@ -39,14 +39,78 @@ export interface ConnectionSpeedData {
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
export const AppDataContext = createContext<AppDataContextType | null>(null)
|
||||
export interface ProxiesContextType {
|
||||
proxies: any
|
||||
proxyProviders: Record<string, ProxyProvider | undefined>
|
||||
isProxiesPending: boolean
|
||||
}
|
||||
|
||||
export const useAppData = () => {
|
||||
const context = use(AppDataContext)
|
||||
export interface RulesContextType {
|
||||
rules: Rule[]
|
||||
ruleProviders: Record<string, RuleProvider | undefined>
|
||||
}
|
||||
|
||||
if (!context) {
|
||||
throw new Error('useAppData must be used within AppDataProvider')
|
||||
export interface ClashConfigContextType {
|
||||
clashConfig: BaseConfig | undefined
|
||||
isClashConfigPending: boolean
|
||||
}
|
||||
|
||||
export interface SystemContextType {
|
||||
sysproxy: any
|
||||
runningMode?: string
|
||||
systemProxyAddress: string
|
||||
}
|
||||
|
||||
export interface UptimeContextType {
|
||||
uptime: number
|
||||
}
|
||||
|
||||
export interface RefreshersContextType {
|
||||
refreshProxy: () => Promise<any>
|
||||
refreshClashConfig: () => Promise<any>
|
||||
refreshRules: () => Promise<any>
|
||||
refreshSysproxy: () => Promise<any>
|
||||
refreshProxyProviders: () => Promise<any>
|
||||
refreshRuleProviders: () => Promise<any>
|
||||
refreshAll: () => Promise<any>
|
||||
}
|
||||
|
||||
export const ProxiesContext = createContext<ProxiesContextType | null>(null)
|
||||
export const RulesContext = createContext<RulesContextType | null>(null)
|
||||
export const ClashConfigContext = createContext<ClashConfigContextType | null>(
|
||||
null,
|
||||
)
|
||||
export const SystemContext = createContext<SystemContextType | null>(null)
|
||||
export const UptimeContext = createContext<UptimeContextType | null>(null)
|
||||
export const RefreshersContext = createContext<RefreshersContextType | null>(
|
||||
null,
|
||||
)
|
||||
|
||||
const useCtx = <T>(ctx: Context<T | null>): T => {
|
||||
const v = use(ctx)
|
||||
if (!v) throw new Error('useAppData must be used within AppDataProvider')
|
||||
return v
|
||||
}
|
||||
|
||||
export const useAppData = (): AppDataContextType => {
|
||||
const { proxies, proxyProviders, isProxiesPending } = useCtx(ProxiesContext)
|
||||
const { rules, ruleProviders } = useCtx(RulesContext)
|
||||
const { clashConfig, isClashConfigPending } = useCtx(ClashConfigContext)
|
||||
const { sysproxy, runningMode, systemProxyAddress } = useCtx(SystemContext)
|
||||
const { uptime } = useCtx(UptimeContext)
|
||||
const refreshers = useCtx(RefreshersContext)
|
||||
|
||||
return {
|
||||
proxies,
|
||||
clashConfig: clashConfig as BaseConfig,
|
||||
rules,
|
||||
sysproxy,
|
||||
runningMode,
|
||||
uptime,
|
||||
proxyProviders: proxyProviders as Record<string, ProxyProvider>,
|
||||
ruleProviders: ruleProviders as Record<string, RuleProvider>,
|
||||
systemProxyAddress,
|
||||
isCoreDataPending: isProxiesPending || isClashConfigPending,
|
||||
...refreshers,
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
@@ -16,7 +16,14 @@ import {
|
||||
getSystemProxy,
|
||||
} from '@/services/cmds'
|
||||
|
||||
import { AppDataContext, AppDataContextType } from './app-data-context'
|
||||
import {
|
||||
ClashConfigContext,
|
||||
ProxiesContext,
|
||||
RefreshersContext,
|
||||
RulesContext,
|
||||
SystemContext,
|
||||
UptimeContext,
|
||||
} from './app-data-context'
|
||||
|
||||
const TQ_MIHOMO = {
|
||||
refetchOnWindowFocus: false,
|
||||
@@ -33,6 +40,12 @@ const TQ_DEFAULTS = {
|
||||
retry: 2,
|
||||
} as const
|
||||
|
||||
function useStableFn<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
|
||||
}
|
||||
|
||||
// 全局数据提供者组件
|
||||
export const AppDataProvider = ({
|
||||
children,
|
||||
@@ -44,7 +57,7 @@ export const AppDataProvider = ({
|
||||
const {
|
||||
data: proxiesData,
|
||||
isPending: isProxiesPending,
|
||||
refetch: refreshProxy,
|
||||
refetch: _refetchProxy,
|
||||
} = useQuery({
|
||||
queryKey: ['getProxies'],
|
||||
queryFn: calcuProxies,
|
||||
@@ -54,43 +67,57 @@ export const AppDataProvider = ({
|
||||
const {
|
||||
data: clashConfig,
|
||||
isPending: isClashConfigPending,
|
||||
refetch: refreshClashConfig,
|
||||
refetch: _refetchClashConfig,
|
||||
} = useQuery({
|
||||
queryKey: ['getClashConfig'],
|
||||
queryFn: getBaseConfig,
|
||||
...TQ_MIHOMO,
|
||||
})
|
||||
|
||||
const { data: proxyProviders, refetch: refreshProxyProviders } = useQuery({
|
||||
const { data: proxyProviders, refetch: _refetchProxyProviders } = useQuery({
|
||||
queryKey: ['getProxyProviders'],
|
||||
queryFn: calcuProxyProviders,
|
||||
...TQ_MIHOMO,
|
||||
})
|
||||
|
||||
const { data: ruleProviders, refetch: refreshRuleProviders } = useQuery({
|
||||
const { data: ruleProviders, refetch: _refetchRuleProviders } = useQuery({
|
||||
queryKey: ['getRuleProviders'],
|
||||
queryFn: getRuleProviders,
|
||||
...TQ_MIHOMO,
|
||||
})
|
||||
|
||||
const { data: rulesData, refetch: refreshRules } = useQuery({
|
||||
const { data: rulesData, refetch: _refetchRules } = useQuery({
|
||||
queryKey: ['getRules'],
|
||||
queryFn: getRules,
|
||||
...TQ_MIHOMO,
|
||||
})
|
||||
|
||||
const refreshProxyRef = useRef(refreshProxy)
|
||||
const refreshRulesRef = useRef(refreshRules)
|
||||
const refreshRuleProvidersRef = useRef(refreshRuleProviders)
|
||||
useEffect(() => {
|
||||
refreshProxyRef.current = refreshProxy
|
||||
}, [refreshProxy])
|
||||
useEffect(() => {
|
||||
refreshRulesRef.current = refreshRules
|
||||
}, [refreshRules])
|
||||
useEffect(() => {
|
||||
refreshRuleProvidersRef.current = refreshRuleProviders
|
||||
}, [refreshRuleProviders])
|
||||
const { data: sysproxy, refetch: _refetchSysproxy } = useQuery({
|
||||
queryKey: ['getSystemProxy'],
|
||||
queryFn: getSystemProxy,
|
||||
...TQ_DEFAULTS,
|
||||
})
|
||||
|
||||
const { data: runningMode } = useQuery({
|
||||
queryKey: ['getRunningMode'],
|
||||
queryFn: getRunningMode,
|
||||
...TQ_DEFAULTS,
|
||||
})
|
||||
|
||||
const { data: uptimeData } = useQuery({
|
||||
queryKey: ['appUptime'],
|
||||
queryFn: getAppUptime,
|
||||
...TQ_DEFAULTS,
|
||||
refetchInterval: 3000,
|
||||
retry: 1,
|
||||
})
|
||||
|
||||
const refreshProxy = useStableFn(_refetchProxy)
|
||||
const refreshClashConfig = useStableFn(_refetchClashConfig)
|
||||
const refreshRules = useStableFn(_refetchRules)
|
||||
const refreshSysproxy = useStableFn(_refetchSysproxy)
|
||||
const refreshProxyProviders = useStableFn(_refetchProxyProviders)
|
||||
const refreshRuleProviders = useStableFn(_refetchRuleProviders)
|
||||
|
||||
useEffect(() => {
|
||||
let lastProfileId: string | null = null
|
||||
@@ -109,15 +136,15 @@ export const AppDataProvider = ({
|
||||
}
|
||||
lastProfileId = newProfileId
|
||||
lastUpdateTime = now
|
||||
refreshRulesRef.current().catch(() => {})
|
||||
refreshRuleProvidersRef.current().catch(() => {})
|
||||
refreshRules().catch(() => {})
|
||||
refreshRuleProviders().catch(() => {})
|
||||
}
|
||||
|
||||
const handleRefreshProxy = () => {
|
||||
const now = Date.now()
|
||||
if (now - lastUpdateTime <= refreshThrottle) return
|
||||
lastUpdateTime = now
|
||||
refreshProxyRef.current().catch(() => {})
|
||||
refreshProxy().catch(() => {})
|
||||
}
|
||||
|
||||
const initializeListeners = async () => {
|
||||
@@ -153,29 +180,8 @@ export const AppDataProvider = ({
|
||||
}
|
||||
})
|
||||
}
|
||||
}, [])
|
||||
}, [refreshProxy, refreshRules, refreshRuleProviders])
|
||||
|
||||
const { data: sysproxy, refetch: refreshSysproxy } = useQuery({
|
||||
queryKey: ['getSystemProxy'],
|
||||
queryFn: getSystemProxy,
|
||||
...TQ_DEFAULTS,
|
||||
})
|
||||
|
||||
const { data: runningMode } = useQuery({
|
||||
queryKey: ['getRunningMode'],
|
||||
queryFn: getRunningMode,
|
||||
...TQ_DEFAULTS,
|
||||
})
|
||||
|
||||
const { data: uptimeData } = useQuery({
|
||||
queryKey: ['appUptime'],
|
||||
queryFn: getAppUptime,
|
||||
...TQ_DEFAULTS,
|
||||
refetchInterval: 3000,
|
||||
retry: 1,
|
||||
})
|
||||
|
||||
// 提供统一的刷新方法
|
||||
const refreshAll = useCallback(async () => {
|
||||
await Promise.all([
|
||||
refreshProxy(),
|
||||
@@ -194,9 +200,32 @@ export const AppDataProvider = ({
|
||||
refreshRuleProviders,
|
||||
])
|
||||
|
||||
// 聚合所有数据
|
||||
const value = useMemo(() => {
|
||||
// 计算系统代理地址
|
||||
const proxiesValue = useMemo(
|
||||
() => ({
|
||||
proxies: proxiesData,
|
||||
proxyProviders: proxyProviders || {},
|
||||
isProxiesPending,
|
||||
}),
|
||||
[proxiesData, proxyProviders, isProxiesPending],
|
||||
)
|
||||
|
||||
const rulesValue = useMemo(
|
||||
() => ({
|
||||
rules: rulesData?.rules ?? [],
|
||||
ruleProviders: ruleProviders?.providers || {},
|
||||
}),
|
||||
[rulesData, ruleProviders],
|
||||
)
|
||||
|
||||
const clashConfigValue = useMemo(
|
||||
() => ({
|
||||
clashConfig,
|
||||
isClashConfigPending,
|
||||
}),
|
||||
[clashConfig, isClashConfigPending],
|
||||
)
|
||||
|
||||
const systemValue = useMemo(() => {
|
||||
const calculateSystemProxyAddress = () => {
|
||||
if (!verge || !clashConfig) return '-'
|
||||
|
||||
@@ -228,24 +257,16 @@ export const AppDataProvider = ({
|
||||
}
|
||||
|
||||
return {
|
||||
// 数据
|
||||
proxies: proxiesData,
|
||||
clashConfig,
|
||||
rules: rulesData?.rules ?? [],
|
||||
sysproxy,
|
||||
runningMode,
|
||||
uptime: uptimeData || 0,
|
||||
|
||||
// 提供者数据
|
||||
proxyProviders: proxyProviders || {},
|
||||
ruleProviders: ruleProviders?.providers || {},
|
||||
|
||||
systemProxyAddress: calculateSystemProxyAddress(),
|
||||
}
|
||||
}, [sysproxy, runningMode, verge, clashConfig])
|
||||
|
||||
// core 数据加载状态
|
||||
isCoreDataPending: isProxiesPending || isClashConfigPending,
|
||||
const uptimeValue = useMemo(() => ({ uptime: uptimeData || 0 }), [uptimeData])
|
||||
|
||||
// 刷新方法
|
||||
const refreshersValue = useMemo(
|
||||
() => ({
|
||||
refreshProxy,
|
||||
refreshClashConfig,
|
||||
refreshRules,
|
||||
@@ -253,27 +274,31 @@ export const AppDataProvider = ({
|
||||
refreshProxyProviders,
|
||||
refreshRuleProviders,
|
||||
refreshAll,
|
||||
} as AppDataContextType
|
||||
}, [
|
||||
proxiesData,
|
||||
clashConfig,
|
||||
isProxiesPending,
|
||||
isClashConfigPending,
|
||||
rulesData,
|
||||
sysproxy,
|
||||
runningMode,
|
||||
uptimeData,
|
||||
proxyProviders,
|
||||
ruleProviders,
|
||||
verge,
|
||||
refreshProxy,
|
||||
refreshClashConfig,
|
||||
refreshRules,
|
||||
refreshSysproxy,
|
||||
refreshProxyProviders,
|
||||
refreshRuleProviders,
|
||||
refreshAll,
|
||||
])
|
||||
}),
|
||||
[
|
||||
refreshProxy,
|
||||
refreshClashConfig,
|
||||
refreshRules,
|
||||
refreshSysproxy,
|
||||
refreshProxyProviders,
|
||||
refreshRuleProviders,
|
||||
refreshAll,
|
||||
],
|
||||
)
|
||||
|
||||
return <AppDataContext value={value}>{children}</AppDataContext>
|
||||
return (
|
||||
<ProxiesContext value={proxiesValue}>
|
||||
<RulesContext value={rulesValue}>
|
||||
<ClashConfigContext value={clashConfigValue}>
|
||||
<SystemContext value={systemValue}>
|
||||
<UptimeContext value={uptimeValue}>
|
||||
<RefreshersContext value={refreshersValue}>
|
||||
{children}
|
||||
</RefreshersContext>
|
||||
</UptimeContext>
|
||||
</SystemContext>
|
||||
</ClashConfigContext>
|
||||
</RulesContext>
|
||||
</ProxiesContext>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user