chore: trim excessive comments

This commit is contained in:
wonfen
2026-08-19 07:27:43 +08:00
parent 42b91b6294
commit 807f9a206d
103 changed files with 293 additions and 2517 deletions
+2 -18
View File
@@ -63,12 +63,9 @@ export const ClashModeCard = () => {
const { isCoreDataPending } = useCoreDataStatus()
const { refreshClashConfig } = useAppRefreshers()
// 点击后到后端确认前的乐观模式,使按钮立即响应
const [optimisticMode, setOptimisticMode] = useState<ClashMode | null>(null)
// 主源:mihomo /configs 的实时 mode(最准,但依赖严格反序列化,可能整体失败)
const controllerMode = toClashMode(clashConfig?.mode)
// 主源不可用时,启用两个容错兜底来源
const needFallback = !controllerMode
const { data: runtimeConfig, isPending: isRuntimeConfigPending } =
useRuntimeConfig(needFallback)
@@ -78,9 +75,7 @@ export const ClashModeCard = () => {
isPending: isBackendModePending,
refetch: refetchBackendMode,
} = useClashMode(needFallback)
// backendMode(已保存 clash 配置)在每次切换时都会被 change_clash_mode 同步更新,
// 而 runtimeMode(生成的运行时配置)在 API 切换后不会刷新、可能陈旧,
// 因此优先用 backendMode,避免陈旧 runtime mode 遮住新值。
// Saved config is refreshed on mode changes; runtime config may be stale.
const fallbackMode = toClashMode(backendMode) ?? runtimeMode
const resolvedMode = controllerMode ?? fallbackMode
@@ -92,37 +87,29 @@ export const ClashModeCard = () => {
? '\u00A0'
: t('home.components.clashMode.errors.communication')
// 切换模式的处理函数:乐观更新 + 真实失败回滚并提示
const onChangeMode = useLockFn(async (mode: ClashMode) => {
if (mode === currentMode) return
if (verge?.auto_close_connection) {
closeAllConnections()
}
// 乐观置为目标模式,按钮立即反映点击
setOptimisticMode(mode)
try {
// patchClashMode 现在会在后端 PATCH 失败时 reject
await patchClashMode(mode)
} catch (error) {
// 真实失败:回滚乐观状态并提示用户
setOptimisticMode(null)
showNotice.error(error)
return
}
// 成功:写穿主源缓存,使实时 mode 立即反映新值——即使随后的 /configs refetch
// 失败(TanStack 会保留旧 data),controllerMode 也不会再压过新值导致闪回。
// 若主源从未成功过(old 为 undefined)则保持不动,改由兜底来源反映。
// Write through the live cache to avoid flashing the old mode during refetch.
setCacheData<BaseConfig>(['getClashConfig'], (old) =>
old ? { ...old, mode } : old,
)
// 刷新主源与兜底源以与后端对齐,待数据落地后再清除乐观状态
await Promise.allSettled([refreshClashConfig(), refetchBackendMode()])
setOptimisticMode(null)
})
// 按钮样式
const buttonStyles = (mode: ClashMode) => ({
cursor: 'pointer',
px: 2,
@@ -159,7 +146,6 @@ export const ClashModeCard = () => {
: {},
})
// 描述样式
const descriptionStyles = {
width: '95%',
textAlign: 'center',
@@ -176,7 +162,6 @@ export const ClashModeCard = () => {
return (
<Box sx={{ display: 'flex', flexDirection: 'column', width: '100%' }}>
{/* 模式选择按钮组 */}
<Stack
direction="row"
spacing={1}
@@ -209,7 +194,6 @@ export const ClashModeCard = () => {
))}
</Stack>
{/* 说明文本区域 */}
<Box
sx={{
width: '100%',
+1 -22
View File
@@ -62,7 +62,6 @@ import {
import { debugLog } from '@/utils/debug'
import { compareByDelay, DEFAULT_DELAY_TIMEOUT } from '@/utils/delay'
// 本地存储的键名
const STORAGE_KEY_GROUP = 'clash-verge-selected-proxy-group'
const STORAGE_KEY_SORT_TYPE = 'clash-verge-proxy-sort-type'
@@ -70,7 +69,6 @@ const AUTO_CHECK_DEFAULT_INTERVAL_MINUTES = 5
const AUTO_CHECK_INITIAL_DELAY_MS = 100
const PROXY_MENU_MAX_HEIGHT = 500
// 代理节点信息接口
interface ProxyOption {
memberIndex: number
member: ResolvedProxyMember
@@ -81,8 +79,6 @@ interface ProxyOption {
type OpenSelect = 'group' | 'proxy' | null
// 排序类型: 默认 | 按延迟 | 按字母
function convertDelayColor(
delayValue: number,
): 'success' | 'warning' | 'error' | 'primary' | 'default' {
@@ -449,7 +445,6 @@ export const CurrentProxyCard = () => {
[getProfileStorageKey],
)
// 统一代理选择器
const { handleSelectChange } = useProxySelection({
onSuccess: () => {
refreshProxy()
@@ -460,12 +455,10 @@ export const CurrentProxyCard = () => {
},
})
// 判断模式
const mode = clashConfig?.mode?.toLowerCase() || 'rule'
const isGlobalMode = mode === 'global'
const isDirectMode = mode === 'direct'
// Sorting type state
const [sortType, setSortType] = useState<ProxySortType>(() => {
const savedSortType = localStorage.getItem(STORAGE_KEY_SORT_TYPE)
return savedSortType ? (Number(savedSortType) as ProxySortType) : 0
@@ -474,7 +467,6 @@ export const CurrentProxyCard = () => {
const [selectedGroupName, setSelectedGroupName] = useState('')
const [openSelect, setOpenSelect] = useState<OpenSelect>(null)
const delayButtonRef = useRef<HTMLButtonElement>(null)
// Sorting reads delays from a store outside React; this hands them over as a value.
const delays = useGroupDelays(selectedGroupName || null)
const autoCheckInProgressRef = useRef(false)
@@ -618,8 +610,7 @@ export const CurrentProxyCard = () => {
}
const previousProxy = selectedGroup.now
const nextName = option.member.ref.name
// Recorded like any other selection, global mode included: what the profile holds is
// what gets re-applied when a core starts, so a choice it never learns about is undone.
// The profile selection is the durable source across core restarts and run modes.
handleSelectChange(
selectedGroup.name,
previousProxy,
@@ -631,7 +622,6 @@ export const CurrentProxyCard = () => {
[handleSelectChange, isDirectMode, selectedGroup, unsortedProxyOptions],
)
// 导航到代理页面
const goToProxies = useCallback(() => {
navigate('/proxies')
}, [navigate])
@@ -645,7 +635,6 @@ export const CurrentProxyCard = () => {
? delayManager.getDelayFix(currentMember, selectedGroupName)
: -1
// 信号图标(增加非空校验)
const signalInfo =
currentProxy && selectedGroupName
? getSignalIcon(currentDelay, t)
@@ -728,14 +717,12 @@ export const CurrentProxyCard = () => {
autoDelayEnabled,
])
// 排序类型变更
const handleSortTypeChange = useCallback(() => {
const newSortType = ((sortType + 1) % 3) as ProxySortType
setSortType(newSortType)
localStorage.setItem(STORAGE_KEY_SORT_TYPE, newSortType.toString())
}, [sortType])
// 延迟测试
const handleCheckDelay = useLockFn(async () => {
const groupName = selectedGroupName
if (!groupName || isDirectMode) return
@@ -782,7 +769,6 @@ export const CurrentProxyCard = () => {
[handleCheckDelay],
)
// 计算要显示的代理选项(增加非空校验)
const proxyOptions = useMemo(
() =>
isDirectMode
@@ -802,7 +788,6 @@ export const CurrentProxyCard = () => {
],
)
// 获取排序图标
const getSortIcon = (): React.ReactElement => {
switch (sortType) {
case 1:
@@ -814,7 +799,6 @@ export const CurrentProxyCard = () => {
}
}
// 获取排序提示文本
const getSortTooltip = (): string => {
switch (sortType) {
case 0:
@@ -890,7 +874,6 @@ export const CurrentProxyCard = () => {
<Box sx={{ py: 4, height: 24 }} />
) : currentProxy || (!isDirectMode && selectedGroup) ? (
<Box>
{/* 代理节点信息显示 */}
<Box
sx={{
display: 'flex',
@@ -935,7 +918,6 @@ export const CurrentProxyCard = () => {
sx={{ mr: 0.5 }}
/>
)}
{/* 节点特性 */}
{currentProxy?.udp && (
<Chip size="small" label="UDP" variant="outlined" />
)}
@@ -954,7 +936,6 @@ export const CurrentProxyCard = () => {
</Box>
</Box>
{/* 显示延迟 */}
{currentProxy && !isDirectMode && (
<Chip
size="small"
@@ -963,7 +944,6 @@ export const CurrentProxyCard = () => {
/>
)}
</Box>
{/* 代理组选择器 */}
<FormControl
fullWidth
variant="outlined"
@@ -991,7 +971,6 @@ export const CurrentProxyCard = () => {
</Select>
</FormControl>
{/* 代理节点选择器 */}
<PersistentProxySelect
label={t('home.components.currentProxy.labels.proxy')}
groupName={selectedGroupName}
@@ -22,22 +22,19 @@ import {
formatTrafficName,
} from '@/utils/traffic-sampler'
// 流量数据项接口
interface ITrafficItem {
up: number
down: number
timestamp?: number
}
// 对外暴露的接口
export interface EnhancedCanvasTrafficGraphRef {
appendData: (data: ITrafficItem) => void
toggleStyle: () => void
}
type TimeRange = 1 | 5 | 10 // 分钟
type TimeRange = 1 | 5 | 10
// 悬浮提示数据接口
interface TooltipData {
x: number
y: number
@@ -45,21 +42,21 @@ interface TooltipData {
downSpeed: string
timestamp: string
visible: boolean
dataIndex: number // 添加数据索引用于高亮
highlightY: number // 高亮Y轴位置
dataIndex: number
highlightY: number
}
const MAX_POINTS = 300
const TARGET_FPS = 15 // 降低帧率减少闪烁
const TARGET_FPS = 15
const LINE_WIDTH_UP = 2.5
const LINE_WIDTH_DOWN = 2.5
const LINE_WIDTH_GRID = 0.5
const ALPHA_GRADIENT = 0.15 // 降低渐变透明度
const ALPHA_GRADIENT = 0.15
const ALPHA_LINE = 0.9
const PADDING_TOP = 16
const PADDING_RIGHT = 16 // 增加右边距确保时间戳完整显示
const PADDING_BOTTOM = 32 // 进一步增加底部空间给时间轴和统计信息
const PADDING_LEFT = 35 // 增加左边距为Y轴标签留出空间
const PADDING_RIGHT = 16
const PADDING_BOTTOM = 32
const PADDING_LEFT = 35
const GRAPH_CONFIG = {
maxPoints: MAX_POINTS,
@@ -116,10 +113,6 @@ const displayDataReducer = (
): ITrafficDataPoint[] =>
isSameTrafficData(current, payload) ? current : payload
/**
* 稳定版Canvas流量图表组件
* 修复闪烁问题,添加时间轴显示
*/
export const EnhancedCanvasTrafficGraph = memo(
function EnhancedCanvasTrafficGraph({
ref,
@@ -130,11 +123,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')
@@ -142,7 +133,6 @@ export const EnhancedCanvasTrafficGraph = memo(
typeof document !== 'undefined' ? !document.hidden : true
const isDocumentVisibleRef = useRef(initialFocusState)
// 悬浮提示状态
const [tooltipData, setTooltipData] = useState<TooltipData>({
x: 0,
y: 0,
@@ -155,7 +145,6 @@ export const EnhancedCanvasTrafficGraph = memo(
})
const tooltipDataRef = useRef<TooltipData>(tooltipData)
// Canvas引用和渲染状态
const canvasRef = useRef<HTMLCanvasElement>(null)
const hoverCanvasRef = useRef<HTMLCanvasElement>(null)
const drawFrameRef = useRef<number | undefined>(undefined)
@@ -170,7 +159,6 @@ export const EnhancedCanvasTrafficGraph = memo(
const lastDataTimestampRef = useRef<number>(0)
const dataStaleRef = useRef<boolean>(false)
// 当前显示的数据缓存
const [displayData, dispatchDisplayData] = useReducer(
displayDataReducer,
[],
@@ -178,7 +166,6 @@ export const EnhancedCanvasTrafficGraph = memo(
const debounceTimeoutRef = useRef<number | null>(null)
const [currentFPS, setCurrentFPS] = useState(GRAPH_CONFIG.targetFPS)
// 主题颜色配置
const colors = useMemo(
() => ({
up: theme.palette.secondary.main,
@@ -190,17 +177,15 @@ export const EnhancedCanvasTrafficGraph = memo(
[theme],
)
// 更新显示数据(防抖处理)
const updateDisplayData = useCallback((newData: ITrafficDataPoint[]) => {
if (debounceTimeoutRef.current !== null) {
window.clearTimeout(debounceTimeoutRef.current)
}
debounceTimeoutRef.current = window.setTimeout(() => {
dispatchDisplayData(newData)
}, 50) // 50ms防抖
}, 50)
}, [])
// 监听数据变化
useEffect(() => {
updateDisplayData(dataPoints)
@@ -274,7 +259,6 @@ export const EnhancedCanvasTrafficGraph = memo(
}
}, [handleFocusStateChange])
// Y轴坐标计算 - 线性映射
const calculateY = useCallback(
(
value: number,
@@ -331,7 +315,6 @@ export const EnhancedCanvasTrafficGraph = memo(
[computeYScale, displayData],
)
// 鼠标悬浮处理 - 计算最近的数据点
const handleMouseMove = useCallback(
(event: React.MouseEvent<HTMLElement>) => {
if (displayData.length === 0) return
@@ -361,7 +344,6 @@ export const EnhancedCanvasTrafficGraph = memo(
const effectiveWidth = rect.width - padding.left - padding.right
if (effectiveWidth <= 0) return
// 计算最接近的数据点索引
const relativeMouseX = mouseX - padding.left
const ratio = Math.max(
0,
@@ -373,16 +355,13 @@ export const EnhancedCanvasTrafficGraph = memo(
const dataPoint = displayData[dataIndex]
// 格式化流量数据
const [upValue, upUnit] = parseTraffic(dataPoint.up)
const [downValue, downUnit] = parseTraffic(dataPoint.down)
// 格式化时间戳
const timeStr = dataPoint.timestamp
? formatTrafficName(dataPoint.timestamp)
: t('home.components.traffic.unknownTime')
// 计算数据点对应的Y坐标位置(用于高亮)
const { topValue: tvH, bottomValue: bvH } = yScale
const upY = calculateY(dataPoint.up, rect.height, tvH, bvH)
const downY = calculateY(dataPoint.down, rect.height, tvH, bvH)
@@ -423,7 +402,6 @@ export const EnhancedCanvasTrafficGraph = memo(
[displayData, calculateY, yScale, t],
)
// 鼠标离开处理
const handleMouseLeave = useCallback(() => {
pendingMousePositionRef.current = null
@@ -437,10 +415,8 @@ export const EnhancedCanvasTrafficGraph = memo(
)
}, [])
// 获取智能Y轴刻度(三刻度系统:最小值、中间值、最大值)
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`
@@ -450,13 +426,11 @@ export const EnhancedCanvasTrafficGraph = memo(
const padding = GRAPH_CONFIG.padding
// 强制显示三个刻度:底部、中间、顶部
const topY = padding.top + 10 // 避免与顶部时间范围按钮重叠
const bottomY = height - padding.bottom - 5 // 避免与底部时间轴重叠
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,
@@ -480,7 +454,6 @@ export const EnhancedCanvasTrafficGraph = memo(
[],
)
// 绘制Y轴刻度线和标签
const drawYAxis = useCallback(
(
ctx: CanvasRenderingContext2D,
@@ -497,13 +470,12 @@ export const EnhancedCanvasTrafficGraph = memo(
ctx.save()
ticks.forEach((tick, index) => {
const isBottomTick = index === 0 // 最底部的刻度
const isTopTick = index === ticks.length - 1 // 最顶部的刻度
const isBottomTick = index === 0
const isTopTick = index === ticks.length - 1
// 绘制水平刻度线,只绘制关键刻度线
if (isBottomTick || isTopTick) {
ctx.strokeStyle = colors.grid
ctx.lineWidth = isBottomTick ? 0.8 : 0.4 // 底部刻度线稍粗
ctx.lineWidth = isBottomTick ? 0.8 : 0.4
ctx.globalAlpha = isBottomTick ? 0.25 : 0.15
ctx.beginPath()
@@ -512,7 +484,6 @@ export const EnhancedCanvasTrafficGraph = memo(
ctx.stroke()
}
// 绘制Y轴标签
ctx.fillStyle = colors.text
ctx.font =
"8px -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif"
@@ -520,7 +491,6 @@ export const EnhancedCanvasTrafficGraph = memo(
ctx.textAlign = 'right'
ctx.textBaseline = 'middle'
// 为标签添加更清晰的背景(仅在必要时)
if (tick.label !== '0') {
const labelWidth = ctx.measureText(tick.label).width
ctx.globalAlpha = 0.15
@@ -533,7 +503,6 @@ export const EnhancedCanvasTrafficGraph = memo(
)
}
// 绘制标签文字
ctx.globalAlpha = 0.9
ctx.fillStyle = colors.text
ctx.fillText(tick.label, padding.left - 4, tick.y)
@@ -544,38 +513,36 @@ export const EnhancedCanvasTrafficGraph = memo(
[colors.grid, colors.text, colors.background, getYAxisTicks],
)
// 获取时间范围对应的最佳时间显示策略
const getTimeDisplayStrategy = useCallback(
(timeRangeMinutes: TimeRange) => {
switch (timeRangeMinutes) {
case 1: // 1分钟:更密集的时间标签,显示 MM:SS
case 1:
return {
maxLabels: 6, // 减少到6个,更适合短时间
maxLabels: 6,
formatTime: formatTrafficMinuteSecond,
intervalSeconds: 10, // 每10秒一个标签,更合理
minPixelDistance: 35, // 减少间距,允许更多标签
intervalSeconds: 10,
minPixelDistance: 35,
}
case 5: // 5分钟:中等密度,显示 HH:MM
case 5:
return {
maxLabels: 6, // 6个标签比较合适
maxLabels: 6,
formatTime: formatTrafficHourMinute,
intervalSeconds: 30, // 约30秒间隔
minPixelDistance: 38, // 减少间距,允许更多标签
intervalSeconds: 30,
minPixelDistance: 38,
}
case 10: // 10分钟:标准密度,显示 HH:MM
case 10:
default:
return {
maxLabels: 8, // 保持8个
maxLabels: 8,
formatTime: formatTrafficHourMinute,
intervalSeconds: 60, // 1分钟间隔
minPixelDistance: 40, // 减少间距,允许更多标签
intervalSeconds: 60,
minPixelDistance: 40,
}
}
},
[],
)
// 绘制时间轴
const drawTimeAxis = useCallback(
(
ctx: CanvasRenderingContext2D,
@@ -597,22 +564,18 @@ export const EnhancedCanvasTrafficGraph = memo(
"10px -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif"
ctx.globalAlpha = 0.7
// 根据数据长度和时间范围智能选择显示间隔
const targetLabels = Math.min(strategy.maxLabels, data.length)
const step = Math.max(1, Math.floor(data.length / (targetLabels - 1)))
// 使用策略中定义的最小像素间距
const minPixelDistance = strategy.minPixelDistance || 45
const actualStep = Math.max(
step,
Math.ceil((data.length * minPixelDistance) / effectiveWidth),
)
// 收集要显示的时间点
const timePoints: Array<{ index: number; x: number; label: string }> =
[]
// 添加第一个时间点
if (data.length > 0 && data[0].timestamp) {
timePoints.push({
index: 0,
@@ -621,7 +584,6 @@ export const EnhancedCanvasTrafficGraph = memo(
})
}
// 添加中间的时间点
for (
let i = actualStep;
i < data.length - actualStep;
@@ -638,12 +600,10 @@ export const EnhancedCanvasTrafficGraph = memo(
})
}
// 添加最后一个时间点(如果不会与前面的重叠)
if (data.length > 1 && data[data.length - 1].timestamp) {
const lastX = width - padding.right
const lastPoint = timePoints[timePoints.length - 1]
// 确保最后一个标签与前一个标签有足够间距
if (!lastPoint || lastX - lastPoint.x >= minPixelDistance) {
timePoints.push({
index: data.length - 1,
@@ -653,16 +613,12 @@ export const EnhancedCanvasTrafficGraph = memo(
}
}
// 绘制时间标签
timePoints.forEach((point, index) => {
if (index === 0) {
// 第一个标签左对齐
ctx.textAlign = 'left'
} else if (index === timePoints.length - 1) {
// 最后一个标签右对齐
ctx.textAlign = 'right'
} else {
// 中间标签居中对齐
ctx.textAlign = 'center'
}
@@ -674,7 +630,6 @@ export const EnhancedCanvasTrafficGraph = memo(
[colors.text, timeRange, getTimeDisplayStrategy],
)
// 绘制网格线
const drawGrid = useCallback(
(ctx: CanvasRenderingContext2D, width: number, height: number) => {
const padding = GRAPH_CONFIG.padding
@@ -686,7 +641,6 @@ export const EnhancedCanvasTrafficGraph = memo(
ctx.lineWidth = GRAPH_CONFIG.lineWidth.grid
ctx.globalAlpha = 0.7
// 水平网格线
const horizontalLines = 4
for (let i = 1; i <= horizontalLines; i++) {
const y = padding.top + (effectiveHeight / (horizontalLines + 1)) * i
@@ -696,7 +650,6 @@ export const EnhancedCanvasTrafficGraph = memo(
ctx.stroke()
}
// 垂直网格线
const verticalLines = 6
for (let i = 1; i <= verticalLines; i++) {
const x = padding.left + (effectiveWidth / (verticalLines + 1)) * i
@@ -711,7 +664,6 @@ export const EnhancedCanvasTrafficGraph = memo(
[colors.grid],
)
// 绘制流量线条
const drawTrafficLine = useCallback(
(
ctx: CanvasRenderingContext2D,
@@ -736,7 +688,6 @@ export const EnhancedCanvasTrafficGraph = memo(
ctx.save()
// 绘制渐变填充
if (withGradient && chartStyle === 'bezier') {
const gradient = ctx.createLinearGradient(
0,
@@ -777,7 +728,6 @@ export const EnhancedCanvasTrafficGraph = memo(
ctx.fill()
}
// 绘制主线条
ctx.beginPath()
ctx.strokeStyle = color
ctx.lineWidth = GRAPH_CONFIG.lineWidth.up
@@ -846,7 +796,6 @@ export const EnhancedCanvasTrafficGraph = memo(
[syncCanvasSize],
)
// 主绘制函数
const drawGraph = useCallback(() => {
const canvas = canvasRef.current
if (!canvas || displayData.length === 0) {
@@ -864,16 +813,12 @@ export const EnhancedCanvasTrafficGraph = memo(
const { topValue, bottomValue } = yScale
// 绘制Y轴刻度线(背景层)
drawYAxis(ctx, cssWidth, cssHeight, topValue, bottomValue)
// 绘制网格
drawGrid(ctx, cssWidth, cssHeight)
// 绘制时间轴
drawTimeAxis(ctx, cssWidth, cssHeight, displayData)
// 绘制下载线(背景层)
drawTrafficLine(
ctx,
displayData,
@@ -886,7 +831,6 @@ export const EnhancedCanvasTrafficGraph = memo(
bottomValue,
)
// 绘制上传线(前景层)
drawTrafficLine(
ctx,
displayData,
@@ -937,15 +881,13 @@ export const EnhancedCanvasTrafficGraph = memo(
ctx.strokeStyle = colors.text
ctx.lineWidth = 1
ctx.globalAlpha = 0.6
ctx.setLineDash([4, 4]) // 虚线效果
ctx.setLineDash([4, 4])
// 绘制垂直指示线
ctx.beginPath()
ctx.moveTo(dataX, padding.top)
ctx.lineTo(dataX, cssHeight - padding.bottom)
ctx.stroke()
// 绘制水平指示线(高亮Y轴位置)
ctx.beginPath()
ctx.moveTo(padding.left, currentTooltip.highlightY)
ctx.lineTo(cssWidth - padding.right, currentTooltip.highlightY)
@@ -1048,7 +990,6 @@ export const EnhancedCanvasTrafficGraph = memo(
}
}, [])
// 切换时间范围
const handleTimeRangeClick = useCallback((event: React.MouseEvent) => {
event.stopPropagation()
setTimeRange((prev) => {
@@ -1056,12 +997,10 @@ export const EnhancedCanvasTrafficGraph = memo(
})
}, [])
// 切换图表样式
const toggleStyle = useCallback(() => {
setChartStyle((prev) => (prev === 'bezier' ? 'line' : 'bezier'))
}, [])
// 兼容性方法
const appendData = useCallback((data: ITrafficItem) => {
debugLog(
'[EnhancedCanvasTrafficGraphV2] appendData called (using global data):',
@@ -1069,7 +1008,6 @@ export const EnhancedCanvasTrafficGraph = memo(
)
}, [])
// 暴露方法给父组件
useImperativeHandle(
ref,
() => ({
@@ -1079,7 +1017,6 @@ export const EnhancedCanvasTrafficGraph = memo(
[appendData, toggleStyle],
)
// 获取时间范围文本
const getTimeRangeText = useCallback(() => {
return t('home.components.traffic.patterns.minutes', {
time: timeRange,
@@ -1125,7 +1062,6 @@ export const EnhancedCanvasTrafficGraph = memo(
/>
)}
{/* 控制层覆盖 */}
<Box
sx={{
position: 'absolute',
@@ -1136,14 +1072,13 @@ export const EnhancedCanvasTrafficGraph = memo(
pointerEvents: 'none',
}}
>
{/* 时间范围按钮 */}
<Box
component="div"
onClick={handleTimeRangeClick}
sx={{
position: 'absolute',
top: 6,
left: 40, // 向右移动,避免与Y轴最大值标签重叠
left: 40,
fontSize: '11px',
fontWeight: 'bold',
color: 'text.secondary',
@@ -1161,7 +1096,6 @@ export const EnhancedCanvasTrafficGraph = memo(
{getTimeRangeText()}
</Box>
{/* 图例 */}
<Box
sx={{
position: 'absolute',
@@ -1194,7 +1128,6 @@ export const EnhancedCanvasTrafficGraph = memo(
</Box>
</Box>
{/* 样式指示器 */}
<Box
sx={{
position: 'absolute',
@@ -1212,7 +1145,6 @@ export const EnhancedCanvasTrafficGraph = memo(
)}
</Box>
{/* 数据统计指示器(左下角) */}
<Box
sx={{
position: 'absolute',
@@ -1231,7 +1163,6 @@ export const EnhancedCanvasTrafficGraph = memo(
})}
</Box>
{/* 悬浮提示框 */}
{tooltipData.visible && (
<Box
sx={{
+4 -38
View File
@@ -24,7 +24,6 @@ import { useQuery } from '@/services/query-client'
import { EnhancedCard } from './enhanced-card'
// 定义刷新时间(秒)
const IP_REFRESH_SECONDS = 300
const COUNTDOWN_TICK_INTERVAL = 5_000
const IP_INFO_CACHE_KEY = 'cv_ip_info_cache'
@@ -54,7 +53,6 @@ const InfoItem = memo(({ label, value }: { label: string; value?: string }) => (
</Box>
))
// 获取国旗表情
const getCountryFlag = (countryCode: string | undefined) => {
if (!countryCode) return ''
const codePoints = countryCode
@@ -97,16 +95,12 @@ const IPInfoCardContainer = forwardRef<HTMLElement, React.PropsWithChildren>(
},
)
// IP信息卡片组件
export const IpInfoCard = () => {
const { t } = useTranslation()
const [showIp, setShowIp] = useState(false)
const appWindow = useMemo(() => getCurrentWebviewWindow(), [])
// track ip info card has been in viewport or not
// hasIntersected default to false, and will be true once the card is in viewport
// and will never be false again afterwards (unless resetIntersected is called or
// the component is unmounted)
// Once intersected, refreshes stay enabled until unmount.
const [containerRef, hasIntersected, _resetIntersected] = useIntersection({
rootMargin: '0px',
})
@@ -118,7 +112,6 @@ export const IpInfoCard = () => {
const { data: ipInfo, error, isLoading, refetch: mutate } = useIPInfo()
// function useEffectEvent
const onCountdownTick = useEffectEvent(async () => {
const now = Date.now()
const ts = ipInfo?.lastFetchTs
@@ -131,35 +124,22 @@ export const IpInfoCard = () => {
if (remaining <= 0) {
if (
// has intersected at least once
// this avoids unncessary revalidation if user never scrolls down,
// then we will only load initially once.
hasIntersected &&
// is online
navigator.onLine &&
// there is no ongoing revalidation already scheduled
countdown.type !== 'revalidating' &&
// window is visible
(await appWindow.isVisible())
) {
setCountdown({ type: 'revalidating' })
// we do not care about the result of mutate here. after mutate is done,
// simply wait for next interval tick with `setCountdown({ type: "countdown", ... })`
try {
await mutate()
} finally {
// in case mutate throws error, we still need to reset the countdown state
setCountdown({
type: 'countdown',
remainingSeconds: IP_REFRESH_SECONDS,
})
}
} else {
// do nothing. we even skip "setCountdown" to reduce re-renders
//
// but the remaining time still <= 0, and setInterval is not stopped, this
// callback will still be regularly triggered, as soon as the window is visible
// or network online again, we mutate() immediately in the following tick.
// Keep the expired state so the next eligible tick refreshes immediately.
}
} else {
setCountdown({
@@ -169,14 +149,10 @@ export const IpInfoCard = () => {
}
})
// Countdown / refresh scheduler — updates UI every 1s and triggers immediate revalidation when expired
useEffect(() => {
let timer: number | null = null
// Do not add document.hidden check here as it is not reliable in Tauri.
//
// Thank god IntersectionObserver is a DOM API that relies on DOM/webview
// instead of Tauri, which is reliable enough.
// Prefer DOM intersection state; Tauri visibility is unreliable on some platforms.
if (hasIntersected) {
console.debug(
'IP info card has entered the viewport, starting the countdown interval.',
@@ -188,25 +164,17 @@ export const IpInfoCard = () => {
)
}
// This will fire when the window is minimized or restored
document.addEventListener('visibilitychange', onVisibilityChange)
// Tauri's visibility change detection is actually broken on some platforms:
// https://github.com/tauri-apps/tauri/issues/10592
//
// It is working on macOS though (tested).
// So at least we should try to pause countdown on supported platforms to
// reduce power consumption.
// Best-effort power saving; see https://github.com/tauri-apps/tauri/issues/10592.
function onVisibilityChange() {
if (document.hidden) {
console.debug('Document hidden, pause the interval')
// Pause the timer
if (timer != null) {
clearInterval(timer)
timer = null
}
} else if (hasIntersected) {
console.debug('Document visible, resume the interval')
// Resume the timer only when previous one is cleared
if (timer == null) {
timer = window.setInterval(onCountdownTick, COUNTDOWN_TICK_INTERVAL)
}
@@ -274,7 +242,6 @@ export const IpInfoCard = () => {
overflow: 'hidden',
}}
>
{/* 左侧:国家和IP地址 */}
<Box sx={{ width: '40%', overflow: 'hidden' }}>
<Box
sx={{
@@ -358,7 +325,6 @@ export const IpInfoCard = () => {
/>
</Box>
{/* 右侧:组织、ISP和位置信息 */}
<Box sx={{ width: '60%', overflow: 'auto' }}>
<InfoItem
label={t('home.components.ipInfo.labels.isp')}
-15
View File
@@ -32,7 +32,6 @@ export const SystemInfoCard = () => {
const { isAdminMode, isSidecarMode, mutateSystemState } = useSystemState()
const { installServiceAndRestartCore } = useServiceInstaller()
// 自动检查更新逻辑(lastCheckUpdate 由 useUpdate 统一管理)
const { checkUpdate: triggerCheckUpdate, lastCheckUpdate } = useUpdate(true)
const [osInfo, setOsInfo] = useState('')
@@ -42,7 +41,6 @@ export const SystemInfoCard = () => {
[lastCheckUpdate],
)
// 初始化系统信息
useEffect(() => {
getSystemInfo()
.then((info) => {
@@ -61,7 +59,6 @@ export const SystemInfoCard = () => {
.catch(console.error)
}, [])
// 如果启用了自动检查更新但没有记录,设置当前时间并延迟检查
useEffect(() => {
if (!verge?.auto_check_update) return
if (readLastCheckTime() !== null) return
@@ -73,12 +70,10 @@ export const SystemInfoCard = () => {
return () => window.clearTimeout(timeoutId)
}, [verge?.auto_check_update, triggerCheckUpdate])
// 导航到设置页面
const goToSettings = useCallback(() => {
navigate('/settings')
}, [navigate])
// 切换自启动状态
const toggleAutoLaunch = useCallback(async () => {
if (!verge) return
try {
@@ -88,7 +83,6 @@ export const SystemInfoCard = () => {
}
}, [verge, patchVerge])
// 点击运行模式处理,Sidecar或纯管理员模式允许安装服务
const handleRunningModeClick = useCallback(async () => {
if (isSidecarMode || (isAdminMode && isSidecarMode)) {
await installServiceAndRestartCore()
@@ -101,7 +95,6 @@ export const SystemInfoCard = () => {
mutateSystemState,
])
// 检查更新
const onCheckUpdate = useLockFn(async () => {
try {
const result = await triggerCheckUpdate()
@@ -119,16 +112,13 @@ export const SystemInfoCard = () => {
}
})
// 是否启用自启动
const autoLaunchEnabled = useMemo(
() => verge?.enable_auto_launch || false,
[verge],
)
// 运行模式样式
const runningModeStyle = useMemo(
() => ({
// Sidecar或纯管理员模式允许安装服务
cursor:
isSidecarMode || (isAdminMode && isSidecarMode) ? 'pointer' : 'default',
textDecoration:
@@ -143,10 +133,8 @@ export const SystemInfoCard = () => {
[isSidecarMode, isAdminMode],
)
// 获取模式图标和文本
const getModeIcon = () => {
if (isAdminMode) {
// 判断是否为组合模式(管理员+服务)
if (!isSidecarMode) {
return (
<>
@@ -184,10 +172,8 @@ export const SystemInfoCard = () => {
}
}
// 获取模式文本
const getModeText = () => {
if (isAdminMode) {
// 判断是否同时处于服务模式
if (!isSidecarMode) {
return t('home.components.systemInfo.badges.adminServiceMode')
}
@@ -199,7 +185,6 @@ export const SystemInfoCard = () => {
}
}
// 只有当verge存在时才渲染内容
if (!verge) return null
return (
+1 -10
View File
@@ -17,12 +17,10 @@ import parseTraffic from '@/utils/parse-traffic'
import { TrafficGraph, type TrafficRef } from './traffic-graph'
// setup the traffic
export const LayoutTraffic = () => {
const { t } = useTranslation()
const { verge } = useVerge()
// whether hide traffic graph
const trafficGraph = verge?.traffic_graph ?? true
const displayMemory = verge?.enable_memory_usage ?? true
@@ -36,7 +34,6 @@ export const LayoutTraffic = () => {
response: { data: memory },
} = useMemoryData({ enabled: displayMemory && pageVisible })
// 监听数据变化,为图表添加数据点
useEffect(() => {
if (trafficRef.current) {
trafficRef.current.appendData({
@@ -48,7 +45,6 @@ export const LayoutTraffic = () => {
}
}, [traffic])
// 使用parseTraffic统一处理转换,保持与首页一致的显示格式
const [up, upUnit] = parseTraffic(traffic?.up || 0)
const [down, downUnit] = parseTraffic(traffic?.down || 0)
const [inuse, inuseUnit] = parseTraffic(memory?.inuse || 0)
@@ -96,7 +92,6 @@ export const LayoutTraffic = () => {
{...boxStyle}
sx={{
...boxStyle.sx,
// opacity: traffic?.is_fresh ? 1 : 0.6,
}}
>
<ArrowUpwardRounded
@@ -114,7 +109,6 @@ export const LayoutTraffic = () => {
{...boxStyle}
sx={{
...boxStyle.sx,
// opacity: traffic?.is_fresh ? 1 : 0.6,
}}
>
<ArrowDownwardRounded
@@ -134,12 +128,9 @@ export const LayoutTraffic = () => {
sx={{
...boxStyle.sx,
cursor: 'auto',
// opacity: memory?.is_fresh ? 1 : 0.6,
}}
color={'disabled'}
onClick={async () => {
// isDebug && (await gc());
}}
onClick={async () => {}}
>
<MemoryRounded {...iconStyle} />
<Typography {...valStyle}>{inuse}</Typography>
-26
View File
@@ -102,7 +102,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const loadingCache = useLoadingCache()
const setLoadingCache = useSetLoadingCache()
// 新增状态:是否显示下次更新时间
const [showNextUpdate, setShowNextUpdate] = useState(false)
const showNextUpdateRef = useRef(false)
const [nextUpdateTime, setNextUpdateTime] = useState('')
@@ -126,7 +125,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const { uid, name = 'Profile', extra, updated = 0, option } = itemData
// 获取下次更新时间的函数
const fetchNextUpdateTimeCallback = useCallback(
async (forceRefresh = false) => {
if (
@@ -136,9 +134,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
try {
debugLog(`尝试获取配置 ${itemData.uid} 的下次更新时间`)
// 如果需要强制刷新,先触发Timer.refresh()
if (forceRefresh) {
// 这里可以通过一个新的API来触发刷新,但目前我们依赖patch_profile中的刷新
debugLog(`强制刷新定时器任务`)
}
@@ -149,13 +145,11 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const nextUpdateDate = dayjs(nextUpdate * 1000)
const now = dayjs()
// 如果已经过期,显示"更新失败"
if (nextUpdateDate.isBefore(now)) {
setNextUpdateTime(
t('profiles.components.profileItem.status.lastUpdateFailed'),
)
} else {
// 否则显示剩余时间
const diffMinutes = nextUpdateDate.diff(now, 'minute')
if (diffMinutes < 60) {
@@ -197,7 +191,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
)
const fetchNextUpdateTime = useLockFn(fetchNextUpdateTimeCallback)
// 切换显示模式的函数
const toggleUpdateTimeDisplay = (e: React.MouseEvent) => {
e.stopPropagation()
@@ -212,7 +205,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
showNextUpdateRef.current = showNextUpdate
}, [showNextUpdate])
// 当组件加载或更新间隔变化时更新下次更新时间
useEffect(() => {
if (showNextUpdate) {
fetchNextUpdateTime()
@@ -224,7 +216,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
updated,
])
// 页面统一订阅定时器事件,这里只响应当前配置的更新信号
useEffect(() => {
if (timerUpdateRevision === 0 || !showNextUpdateRef.current) return
@@ -247,9 +238,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
fetchNextUpdateTime()
}, [completedUpdateRevision, fetchNextUpdateTime])
// local file mode
// remote file mode
// remote file mode
const hasUrl = !!itemData.url
const hasExtra = !!extra // only subscription url has extra info
const hasHome = !!itemData.home // only subscription url has home page
@@ -265,7 +253,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const loading = loadingCache.has(itemData.uid)
// interval update fromNow field
const [, forceRefresh] = useReducer((value: number) => value + 1, 0)
useEffect(() => {
if (!hasUrl) return
@@ -275,7 +262,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const handler = () => {
const now = Date.now()
const lastUpdate = updated * 1000
// 大于一天的不管
if (now - lastUpdate >= 24 * 36e5) return
const wait = now - lastUpdate >= 36e5 ? 30e5 : 5e4
@@ -394,7 +380,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
setAnchorEl(null)
setLoading(true)
// 根据类型设置初始更新选项
const option: Partial<IProfileOption> = {}
if (type === 0) {
option.with_proxy = false
@@ -410,15 +395,11 @@ const ProfileItemBase = (props: ProfileItemProps) => {
}
try {
// 调用后端更新(后端会自动处理回退逻辑)
const payload = Object.keys(option).length > 0 ? option : undefined
await updateProfile(itemData.uid, payload)
// 更新成功,刷新列表
void mutateProfiles()
} catch {
// 更新完全失败(包括后端的回退尝试)
// 不需要做处理,后端会通过事件通知系统发送错误
} finally {
setLoading(false)
}
@@ -522,7 +503,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
handler: () => {
setAnchorEl(null)
if (batchMode) {
// If in batch mode, just toggle selection instead of showing delete confirmation
if (onSelectionChange) {
onSelectionChange()
}
@@ -584,7 +564,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
handler: () => {
setAnchorEl(null)
if (batchMode) {
// If in batch mode, just toggle selection instead of showing delete confirmation
if (onSelectionChange) {
onSelectionChange()
}
@@ -640,7 +619,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
<ProfileBox
aria-selected={selected}
onClick={(e) => {
// 如果正在激活中,阻止重复点击
if (activating) {
e.preventDefault()
e.stopPropagation()
@@ -734,7 +712,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
</Typography>
</Box>
{/* only if has url can it be updated */}
{hasUrl && (
<IconButton
title={t('shared.actions.refresh')}
@@ -750,7 +727,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
disabled={loading}
onClick={(e) => {
e.stopPropagation()
// 如果正在激活或加载中,阻止更新操作
if (activating || loading) {
return
}
@@ -761,7 +737,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
</IconButton>
)}
</Box>
{/* the second line show url's info or description */}
<Box sx={boxStyle}>
{
<>
@@ -824,7 +799,6 @@ const ProfileItemBase = (props: ProfileItemProps) => {
</>
}
</Box>
{/* the third line show extra info or last updated time */}
{hasExtra ? (
<Box sx={{ ...boxStyle, fontSize: 14 }}>
<span title={t('shared.labels.usedTotal')}>
+1 -17
View File
@@ -31,8 +31,6 @@ export interface ProfileViewerRef {
edit: (item: IProfileItem) => void
}
// create or edit the profile
// remote / local
type ProfileViewerProps = Props & { ref?: Ref<ProfileViewerRef> }
// 同后端 constants::profile::MIN_UPDATE_INTERVAL
@@ -45,7 +43,6 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
const [loading, setLoading] = useState(false)
const { profiles } = useProfiles()
// file input
const fileDataRef = useRef<string | null>(null)
const { control, watch, setValue, reset, handleSubmit, getValues } =
@@ -94,7 +91,6 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
handleSubmit(async (form) => {
setLoading(true)
try {
// 基本验证
if (!form.type) {
throw new Error(t('profiles.modals.profileForm.errors.typeRequired'))
}
@@ -102,7 +98,6 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
throw new Error(t('profiles.modals.profileForm.errors.urlRequired'))
}
// 处理表单数据
const option = form.option ? { ...form.option } : undefined
if (option?.timeout_seconds) {
option.timeout_seconds = +option.timeout_seconds
@@ -123,16 +118,14 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
const isRemote = form.type === 'remote'
const isUpdate = openType === 'edit'
// 判断是否是当前激活的配置
const isActivating = isUpdate && form.uid === (profiles?.current ?? '')
// 保存原始代理设置以便回退成功后恢复
// Preserve proxy settings when the remote retry succeeds through another route.
const originalOptions = {
with_proxy: form.option?.with_proxy,
self_proxy: form.option?.self_proxy,
}
// 执行创建或更新操作,本地配置不需要回退机制
if (!isRemote) {
if (openType === 'new') {
await createProfile(item, fileDataRef.current)
@@ -145,9 +138,7 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
await patchProfile(form.uid, item)
}
} else {
// 远程配置使用回退机制
try {
// 尝试正常操作
if (openType === 'new') {
await createProfile(item, fileDataRef.current)
} else {
@@ -159,12 +150,10 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
await patchProfile(form.uid, item)
}
} catch {
// 首次创建/更新失败,尝试使用自身代理
showNotice.info(
'profiles.modals.profileForm.feedback.notifications.creationRetry',
)
// 使用自身代理的配置
const retryItem = {
...item,
option: {
@@ -174,7 +163,6 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
},
}
// 使用自身代理再次尝试
if (openType === 'new') {
await createProfile(retryItem, fileDataRef.current)
} else {
@@ -185,7 +173,6 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
}
await patchProfile(form.uid, retryItem)
// 编辑模式下恢复原始代理设置
await patchProfile(form.uid, { option: originalOptions })
}
@@ -195,12 +182,10 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
}
}
// 成功后的操作
setOpen(false)
setTimeout(() => reset(), 500)
fileDataRef.current = null
// 优化:UI先关闭,异步通知父组件
setTimeout(() => {
onChange(isActivating)
}, 0)
@@ -359,7 +344,6 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
control={control}
render={({ field }) => {
const interval = Number(field.value)
// 0 和空值表示不自动更新,不提醒
const tooFrequent =
Number.isFinite(interval) &&
interval > 0 &&
-18
View File
@@ -26,7 +26,6 @@ import { useAppRefreshers, useProxiesData } from '@/providers/app-data-context'
import { showNotice } from '@/services/notice-service'
import parseTraffic from '@/utils/parse-traffic'
// 样式化组件 - 类型框
const TypeBox = styled(Box)<{ component?: React.ElementType }>(({ theme }) => ({
display: 'inline-block',
border: '1px solid #ccc',
@@ -39,7 +38,6 @@ const TypeBox = styled(Box)<{ component?: React.ElementType }>(({ theme }) => ({
lineHeight: 1.25,
}))
// 解析过期时间
const parseExpire = (expire?: number) => {
if (!expire) return '-'
return dayjs(expire * 1000).format('YYYY-MM-DD')
@@ -54,15 +52,12 @@ export const ProviderButton = () => {
const providers = proxyView?.providers ?? []
const providerUnavailable = proxyView?.providerState === 'unavailable'
// 更新单个代理提供者
const updateProvider = useLockFn(async (name: string) => {
try {
// 设置更新状态
setUpdating((prev) => ({ ...prev, [name]: true }))
await updateProxyProvider(name)
// 刷新数据
await refreshProxy()
showNotice.success(
@@ -77,22 +72,18 @@ export const ProviderButton = () => {
message: String(err),
})
} finally {
// 清除更新状态
setUpdating((prev) => ({ ...prev, [name]: false }))
}
})
// 更新所有代理提供者
const updateAllProviders = useLockFn(async () => {
try {
// 获取所有provider的名称
const allProviders = providers.map(({ name }) => name)
if (allProviders.length === 0) {
showNotice.info('proxies.feedback.notifications.provider.none')
return
}
// 设置所有provider为更新中状态
const newUpdating = allProviders.reduce(
(acc, key) => {
acc[key] = true
@@ -102,19 +93,15 @@ export const ProviderButton = () => {
)
setUpdating(newUpdating)
// 改为串行逐个更新所有provider
for (const name of allProviders) {
try {
await updateProxyProvider(name)
// 每个更新完成后更新状态
setUpdating((prev) => ({ ...prev, [name]: false }))
} catch (err) {
console.error(`更新 ${name} 失败`, err)
// 继续执行下一个,不中断整体流程
}
}
// 刷新数据
await refreshProxy()
showNotice.success('proxies.feedback.notifications.provider.allUpdated')
@@ -123,7 +110,6 @@ export const ProviderButton = () => {
message: String(err),
})
} finally {
// 清除所有更新状态
setUpdating({})
}
})
@@ -190,7 +176,6 @@ export const ProviderButton = () => {
: null
const isUpdating = updating[key]
// 订阅信息
const sub = provider.subscriptionInfo
const hasSubInfo = !!sub
const upload = sub?.upload || 0
@@ -198,7 +183,6 @@ export const ProviderButton = () => {
const total = sub?.total || 0
const expire = sub?.expire || 0
// 流量使用进度
const progress =
total > 0
? Math.min(
@@ -272,7 +256,6 @@ export const ProviderButton = () => {
}
secondary={
<>
{/* 订阅信息 */}
{hasSubInfo && (
<>
<Box
@@ -296,7 +279,6 @@ export const ProviderButton = () => {
</span>
</Box>
{/* 进度条 */}
<LinearProgress
variant="determinate"
value={progress}
@@ -23,14 +23,7 @@ interface ProxyListStateInput {
const isSubscriptionProfile = (item: { type?: string }): boolean =>
item.type === 'remote' || item.type === 'local'
/**
* What the proxy page should show.
*
* Deliberately does *not* answer "is there anything to render". That question is answered by
* the list itself, in `hasRenderableItems`, because predicting it from beside the renderer is
* how the two came to disagree. This decides only the things knowable without building a list:
* direct mode, still-loading, and having no usable subscription to render from.
*/
/** Decides only pre-render states; the built list owns whether it has renderable content. */
export type ProxyListState =
| { kind: 'direct' }
| { kind: 'loading' }
@@ -67,12 +60,7 @@ export const resolveProxyListState = ({
return { kind: 'render' }
}
/**
* Why a list that turned out to be empty is empty.
*
* Only reachable once the renderer has built its list and found nothing, so it explains an
* observed emptiness rather than predicting one.
*/
/** Explains an empty list only after the renderer observes it. */
export const resolveEmptyListReason = ({
runningMode,
isProxyViewError,
+2 -24
View File
@@ -65,11 +65,6 @@ interface Props {
chainConfigData?: string | null
}
/**
* The empty state to draw when the render list turns out to contain nothing.
*
* Shared by both list components so the observation and its explanation stay together.
*/
function useEmptyRenderList() {
const { isProxyViewError } = useProxiesData()
const { runningMode } = useSystemData()
@@ -103,7 +98,6 @@ function useProxyRenderState(
const timeout = verge?.default_latency_timeout || 10000
// 测全部延迟
const handleCheckAll = useStableCallback(
useLockFn(async (groupName: string) => {
debugLog(`[ProxyGroups] 开始测试所有延迟,组: ${groupName}`)
@@ -133,8 +127,6 @@ function useProxyRenderState(
} catch (error) {
console.error(`[ProxyGroups] 延迟测试出错,组: ${groupName}`, error)
} finally {
// Re-sorting is no longer poked from here: the delay store announces that the test
// settled and the render list recomputes from that.
onProxies()
}
}),
@@ -254,7 +246,6 @@ function ChainProxyGroups(props: {
const virtualItems = virtualizer.getVirtualItems()
const activeStickyIndex = activeStickyIndexRef.current
// 从 localStorage 恢复滚动位置
useLayoutEffect(() => {
if (renderList.length === 0) return
const node = parentRef.current
@@ -335,7 +326,6 @@ function ChainProxyGroups(props: {
}
})
// The list is built; whether it holds anything is now an observation, not a guess.
if (!hasRenderableItems(renderList)) return emptyList
return (
@@ -376,11 +366,9 @@ function NormalProxyGroups(props: { mode: string }) {
} = useProxyRenderState(mode, false, null)
const emptyList = useEmptyRenderList()
const renderFirstRef = useRef(true)
// 恢复滚动位置期间设为 true,避免程序化滚动触发的 scroll 事件把中间值写回存储
// Do not persist intermediate positions produced while restoring virtual scroll.
const isRestoringRef = useRef(false)
// 目前无法使用 StickyVirtualList 的 initialOffset 值设置初始化,具体原因需排查
// 从 localStorage 恢复滚动位置
useLayoutEffect(() => {
if (renderList.length === 0) return
if (!renderFirstRef.current) return
@@ -388,15 +376,12 @@ function NormalProxyGroups(props: { mode: string }) {
if (!node) return
const savedPosition = getScrollPosition()
// 未保存过位置或位置为 0(顶部)时无需恢复
if (!savedPosition) {
renderFirstRef.current = false
return
}
// 虚拟列表初始使用预估高度,真实高度测量完成后总高度才会稳定。
// 尤其是过滤后节点数变少时,预估总高度常常不足以一次性滚动到目标位置,
// 因此跨帧重试,直到到达目标位置(或内容确实不够高)为止。
// Retry across frames until virtual-list measurements can reach the saved offset.
isRestoringRef.current = true
let rafId = 0
let attempts = 0
@@ -436,7 +421,6 @@ function NormalProxyGroups(props: { mode: string }) {
const handleScroll = useCallback(
(event: Event) => {
// 恢复位置过程中产生的滚动不写回存储,避免中间的钳制值覆盖真实位置
if (isRestoringRef.current) return
const target = event.target as HTMLElement | null
const nextScrollTop = target?.scrollTop ?? 0
@@ -480,7 +464,6 @@ function NormalProxyGroups(props: { mode: string }) {
[handleProxyGroupChange],
)
// 滚到对应的节点
const handleLocation = useStableCallback((group: ProxyGroupView) => {
if (!group) return
const { name, now } = group
@@ -501,7 +484,6 @@ function NormalProxyGroups(props: { mode: string }) {
}
})
// 定位到指定的代理组
const handleGroupLocationByName = useCallback(
(groupName: string) => {
const index = renderList.findIndex(
@@ -525,7 +507,6 @@ function NormalProxyGroups(props: { mode: string }) {
return Array.from(new Set(names))
}, [renderList])
// 点击代理组改变展开状态,先滚动到sticky的代理组位置,再收起展开状态
const handleGroupToggle = useCallback(
async (group: ProxyGroupView) => {
const index = renderList.findIndex(
@@ -589,7 +570,6 @@ function NormalProxyGroups(props: { mode: string }) {
[handleChangeProxy, handleCheckAll, onHeadState, handleLocation],
)
// The list is built; whether it holds anything is now an observation, not a guess.
if (!hasRenderableItems(renderList)) return emptyList
return (
@@ -605,7 +585,6 @@ function NormalProxyGroups(props: { mode: string }) {
renderItem={renderProxyItem}
/>
{/* 代理组导航栏 */}
{mode === 'rule' && (
<ProxyGroupNavigator
proxyGroupNames={proxyGroupNames}
@@ -640,7 +619,6 @@ export const ProxyGroups = (props: Props) => {
case 'empty':
return <ProxyEmptyState reason={listState.reason} />
case 'render':
// Whether there is anything to draw is the list's own answer, given below.
return isChainMode ? (
<ChainProxyGroups mode={mode} chainConfigData={chainConfigData} />
) : (
-11
View File
@@ -5,7 +5,6 @@ import { compileStringMatcher } from '@/utils/search-matcher'
import type { ResolvedMemberOccurrence } from './use-render-list'
// default | delay | alphabet
export type ProxySortType = 0 | 1 | 2
export type ProxySearchState = {
@@ -27,16 +26,9 @@ export function filterSort(
return sp
}
/**
* 可以通过延迟数/节点类型 过滤
*/
const regex1 = /delay([=<>])(\d+|timeout|error)/i
const regex2 = /type=(.*)/i
/**
* filter the proxy
* according to the regular conditions
*/
function filterProxies(
proxies: ResolvedMemberOccurrence[],
groupName: string,
@@ -90,9 +82,6 @@ function filterProxies(
return proxies.filter(({ member }) => compiled.matcher(member.ref.name))
}
/**
* sort the proxy
*/
function sortProxies(
proxies: ResolvedMemberOccurrence[],
groupName: string,
+2 -8
View File
@@ -5,21 +5,18 @@ import { hasRenderableItems, type IRenderItem } from './use-render-list'
const group = (hidden = false) =>
({ name: 'Proxies', hidden }) as unknown as IRenderItem['group']
/** A group header row. On its own it is only content when the group is visible. */
const header = (hidden = false): IRenderItem => ({
type: 0,
key: 'header',
group: group(hidden),
})
/** A member row — in chain mode the list is made entirely of these. */
const member = (key: string): IRenderItem => ({
type: 2,
key,
group: group(),
})
/** A column of members, which is how the chain list renders at column counts above one. */
const memberColumn = (key: string): IRenderItem => ({
type: 4,
key,
@@ -32,9 +29,7 @@ describe('hasRenderableItems', () => {
})
test('chain mode is answered by the chain list itself', () => {
// This is the case the old prediction got wrong in both directions: it asked whether any
// Selector or URLTest group existed, which is unrelated to what the chain list is built
// from. Here there are rows, so there is content, whatever groups happen to exist.
// Rendered rows, not group types, determine whether chain mode is empty.
expect(hasRenderableItems([member('chain:a')])).toBe(true)
expect(hasRenderableItems([memberColumn('chain-col:a')])).toBe(true)
})
@@ -54,8 +49,7 @@ describe('hasRenderableItems', () => {
})
test('rows inside a hidden but expanded group are still rows on screen', () => {
// Truthfulness over tidiness: the user can see these, so calling the page empty would be
// a lie. The old predicate said "empty" here.
// Visible member rows mean the page is not empty even without a visible group header.
expect(hasRenderableItems([header(true), member('member:a')])).toBe(true)
})
})
-14
View File
@@ -24,7 +24,6 @@ import { updateRuleProvider } from 'tauri-plugin-mihomo-api'
import { useAppRefreshers, useRulesData } from '@/providers/app-data-context'
import { showNotice } from '@/services/notice-service'
// 辅助组件 - 类型框
const TypeBox = styled(Box)<{ component?: React.ElementType }>(({ theme }) => ({
display: 'inline-block',
border: '1px solid #ccc',
@@ -44,18 +43,14 @@ export const ProviderButton = () => {
const { refreshRules, refreshRuleProviders } = useAppRefreshers()
const [updating, setUpdating] = useState<Record<string, boolean>>({})
// 检查是否有提供者
const hasProviders = Object.keys(ruleProviders || {}).length > 0
// 更新单个规则提供者
const updateProvider = useLockFn(async (name: string) => {
try {
// 设置更新状态
setUpdating((prev) => ({ ...prev, [name]: true }))
await updateRuleProvider(name)
// 刷新数据
await refreshRules()
await refreshRuleProviders()
@@ -71,22 +66,18 @@ export const ProviderButton = () => {
message: String(err),
})
} finally {
// 清除更新状态
setUpdating((prev) => ({ ...prev, [name]: false }))
}
})
// 更新所有规则提供者
const updateAllProviders = useLockFn(async () => {
try {
// 获取所有provider的名称
const allProviders = Object.keys(ruleProviders || {})
if (allProviders.length === 0) {
showNotice.info('rules.feedback.notifications.provider.none')
return
}
// 设置所有provider为更新中状态
const newUpdating = allProviders.reduce(
(acc, key) => {
acc[key] = true
@@ -96,19 +87,15 @@ export const ProviderButton = () => {
)
setUpdating(newUpdating)
// 改为串行逐个更新所有provider
for (const name of allProviders) {
try {
await updateRuleProvider(name)
// 每个更新完成后更新状态
setUpdating((prev) => ({ ...prev, [name]: false }))
} catch (err) {
console.error(`更新 ${name} 失败`, err)
// 继续执行下一个,不中断整体流程
}
}
// 刷新数据
await refreshRules()
await refreshRuleProviders()
@@ -118,7 +105,6 @@ export const ProviderButton = () => {
message: String(err),
})
} finally {
// 清除所有更新状态
setUpdating({})
}
})
+1 -18
View File
@@ -132,7 +132,6 @@ function parseList(str: string): string[] {
.filter(Boolean)
}
// 默认DNS配置
const DEFAULT_DNS_CONFIG = {
enable: true,
listen: ':53',
@@ -251,13 +250,12 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
hosts: '',
})
// 用于YAML编辑模式, 初始化标记:阻止 updateValuesFromYaml 在配置加载前误执行
// Prevent YAML-to-form sync before configuration loads.
const [yamlContent, setYamlContent] = useReducer(
(_: string, next: string) => next,
'{ isInitValue: true }',
)
// 从配置对象更新表单值
const updateValuesFromConfig = useCallback((config: any) => {
if (!config) return
@@ -388,7 +386,6 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
setYamlContent(yaml.dump(config, { forceQuotes: true }))
}, [generateDnsConfig, values.hosts])
// 重置为默认值
const resetToDefaults = useCallback(() => {
setValues({
enable: DEFAULT_DNS_CONFIG.enable,
@@ -425,7 +422,6 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
updateYamlFromValues()
}, [updateYamlFromValues])
// 从YAML更新表单值
const updateValuesFromYaml = useCallback(() => {
try {
const parsedYaml = yaml.load(yamlContent) as any
@@ -503,14 +499,11 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
[initDnsConfig],
)
// 生成DNS配置对象
// 处理保存操作
const onSave = useLockFn(async () => {
try {
let config: Record<string, any>
if (visualization) {
// 使用表单值生成配置
config = {}
const dnsConfig = generateDnsConfig()
@@ -523,7 +516,6 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
config.hosts = hosts
}
} else {
// 使用YAML编辑器的值
const parsedConfig = yaml.load(yamlContent)
if (typeof parsedConfig !== 'object' || parsedConfig === null) {
throw new Error(t('settings.modals.dns.errors.invalid'))
@@ -531,10 +523,8 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
config = parsedConfig as Record<string, any>
}
// 保存配置
await invoke('save_dns_config', { dnsConfig: config })
// 验证配置
const validation = await invoke<ValidationOutcome>(
'validate_dns_config',
{},
@@ -547,7 +537,6 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
: 'Configuration validation skipped'
let cleanErrorMsg = errorMsg
// 提取关键错误信息
if (errorMsg.includes('level=error')) {
const errorLines = errorMsg
.split('\n')
@@ -575,7 +564,6 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
return
}
// 如果DNS开关当前是打开的,则需要应用新的DNS配置
if (clash?.dns?.enable) {
await invoke('apply_dns_config', { apply: true })
mutateClash()
@@ -588,12 +576,10 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
}
})
// YAML编辑器内容变更处理
const handleYamlChange = (value?: string) => {
setYamlContent(value || '')
}
// 处理表单值变化
const handleChange = (field: string) => (event: any) => {
const value =
event.target.type === 'checkbox'
@@ -606,7 +592,6 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
[field]: value,
}
// 当可视化编辑模式下的值变化时,自动更新YAML
if (visualization) {
setTimeout(() => {
updateYamlFromValues()
@@ -667,7 +652,6 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
onCancel={() => setOpen(false)}
onOk={onSave}
>
{/* Warning message */}
<Typography
variant="body2"
color="warning.main"
@@ -1053,7 +1037,6 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
/>
</Item>
{/* Hosts 配置部分 */}
<Typography
variant="subtitle1"
sx={{ mt: 3, mb: 0, fontWeight: 'bold' }}
@@ -9,30 +9,23 @@ import { useClash } from '@/hooks/use-clash'
import { restartCore } from '@/services/cmds'
import { showNotice } from '@/services/notice-service'
// 定义开发环境的URL列表
// 这些URL在开发模式下会被自动包含在允许的来源中
// 在生产环境中,这些URL会被过滤掉
// 这样可以确保在生产环境中不会意外暴露开发环境的URL
// Development origins must never be persisted into production configuration.
const DEV_URLS = [
'tauri://localhost',
'http://tauri.localhost',
'http://localhost:3000',
]
// 获取完整的源列表,包括开发URL
const getFullOrigins = (origins: string[]) => {
// 合并现有源和开发URL,并去重
const allOrigins = [...origins, ...DEV_URLS]
const uniqueOrigins = [...new Set(allOrigins)]
return uniqueOrigins
}
// 过滤基础URL(确保后续添加)
const filterBaseOriginsForUI = (origins: string[]) => {
return origins.filter((origin: string) => !DEV_URLS.includes(origin.trim()))
}
// 统一使用的按钮样式
const buttonStyle = {
borderRadius: '8px',
textTransform: 'none',
@@ -47,7 +40,6 @@ const buttonStyle = {
},
}
// 添加按钮样式
const addButtonStyle = {
...buttonStyle,
backgroundColor: '#4CAF50',
@@ -57,7 +49,6 @@ const addButtonStyle = {
},
}
// 删除按钮样式
const deleteButtonStyle = {
...buttonStyle,
backgroundColor: '#FF5252',
@@ -85,7 +76,6 @@ export const HeaderConfiguration = forwardRef<ClashHeaderConfigingRef>(
const lastKeyRef = useRef(0) // 用于生成唯一的key
// CORS配置状态管理
const [corsConfig, setCorsConfig] = useState<{
allowPrivateNetwork: boolean
allowOrigins: AllowOriginItem[]
@@ -101,7 +91,6 @@ export const HeaderConfiguration = forwardRef<ClashHeaderConfigingRef>(
}
})
// 处理CORS配置变更
const handleCorsConfigChange = (
key: 'allowPrivateNetwork' | 'allowOrigins',
value: boolean | AllowOriginItem[],
@@ -112,7 +101,6 @@ export const HeaderConfiguration = forwardRef<ClashHeaderConfigingRef>(
}))
}
// 添加新的允许来源
const handleAddOrigin = () => {
lastKeyRef.current += 1
handleCorsConfigChange('allowOrigins', [
@@ -121,24 +109,20 @@ export const HeaderConfiguration = forwardRef<ClashHeaderConfigingRef>(
])
}
// 更新允许来源列表中的某一项
const handleUpdateOrigin = (index: number, value: string) => {
const newOrigins = [...corsConfig.allowOrigins]
newOrigins[index] = { ...newOrigins[index], value }
handleCorsConfigChange('allowOrigins', newOrigins)
}
// 删除允许来源列表中的某一项
const handleDeleteOrigin = (index: number) => {
const newOrigins = [...corsConfig.allowOrigins]
newOrigins.splice(index, 1)
handleCorsConfigChange('allowOrigins', newOrigins)
}
// 保存配置请求
const { loading, run: saveConfig } = useRequest(
async () => {
// 保存时使用完整的源列表(包括开发URL)
const fullOrigins = getFullOrigins(
corsConfig.allowOrigins.map((origin) => origin.value),
)
@@ -40,18 +40,15 @@ export function GuardState<T>(props: Props<T>) {
childProps[valueProps] = value
childProps[onChangeProps] = async (...args: any[]) => {
// 多次操作无效
if (lockRef.current) return
lockRef.current = true
try {
const newValue = onFormat ? onFormat(...args) : (args[0] as T)
// 先在ui上响应操作
onChange(newValue)
const now = Date.now()
// save the old value
if (waitTime <= 0 || now - lastRef.current >= waitTime) {
saveRef.current = value
}
@@ -62,14 +59,12 @@ export function GuardState<T>(props: Props<T>) {
await onGuard(newValue, value!)
lockRef.current = false
} else {
// debounce guard
clearTimeout(timeRef.current)
timeRef.current = setTimeout(async () => {
try {
await onGuard(newValue, saveRef.current!)
} catch (err: any) {
// 状态回退
onChange(saveRef.current!)
onCatch(err)
} finally {
@@ -78,7 +73,6 @@ export function GuardState<T>(props: Props<T>) {
}, waitTime)
}
} catch (err: any) {
// 状态回退
onChange(saveRef.current!)
onCatch(err)
lockRef.current = false
@@ -191,7 +191,6 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
const { systemProxyAddress } = useSystemData()
const displayedMixedPort = useDisplayedMixedPort()
// 为当前状态计算系统代理地址
const getSystemProxyAddress = useMemo(() => {
const isPacMode = value.pac ?? false
@@ -250,14 +249,11 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
close: () => setOpen(false),
}))
// 获取网络接口和主机名
const fetchNetworkInterfaces = async () => {
try {
// 获取系统网络接口信息
const interfaces = await getNetworkInterfacesInfo()
const ipAddresses: string[] = []
// 从interfaces中提取IPv4和IPv6地址
interfaces.forEach((iface) => {
iface.addr.forEach((address) => {
if (address.V4 && address.V4.ip) {
@@ -269,7 +265,6 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
})
})
// 获取当前系统的主机名
let hostname = ''
try {
hostname = await getSystemHostname()
@@ -278,12 +273,9 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
console.error('获取主机名失败:', err)
}
// 构建选项列表
const options = ['127.0.0.1', 'localhost']
// 确保主机名添加到列表,即使它是空字符串也记录下来
if (hostname) {
// 如果主机名不是localhost或127.0.0.1,则添加它
if (hostname !== 'localhost' && hostname !== '127.0.0.1') {
hostname = hostname + '.local'
options.push(hostname)
@@ -295,16 +287,13 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
debugLog('主机名为空')
}
// 添加IP地址
options.push(...ipAddresses)
// 去重
const uniqueOptions = Array.from(new Set(options))
debugLog('最终选项列表:', uniqueOptions)
setHostOptions(uniqueOptions)
} catch (error) {
console.error('获取网络接口失败:', error)
// 失败时至少提供基本选项
setHostOptions(['127.0.0.1', 'localhost'])
}
}
@@ -325,7 +314,6 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
return
}
// 修改验证规则,允许IP和主机名
const ipv4Regex =
/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
const ipv6Regex =
@@ -369,7 +357,6 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
let pacContent = value.pac_content
if (pacContent) {
pacContent = pacContent.replace(/%proxy_host%/g, value.proxy_host)
// 将 mixed-port 转换为字符串
const mixedPortStr = displayedMixedPort.toString()
pacContent = pacContent.replace(/%mixed-port%/g, mixedPortStr)
}
@@ -378,7 +365,6 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
patch.pac_file_content = pacContent
}
// 处理IPv6地址,如果是IPv6地址但没有被方括号包围,则添加方括号
let proxyHost = value.proxy_host
if (
ipv6Regex.test(proxyHost) &&
@@ -392,7 +378,6 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
patch.proxy_host = proxyHost
}
// 判断是否需要重置系统代理
const needResetProxy =
value.pac !== proxy_auto_config ||
proxyHost !== proxy_host ||
@@ -402,7 +387,6 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
Promise.resolve().then(async () => {
try {
// 乐观更新本地状态
if (Object.keys(patch).length > 0) {
mutateVerge({ ...verge, ...patch }, false)
}
@@ -413,7 +397,6 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
try {
await invalidateProxyState()
// 如果需要重置代理且代理当前启用
if (needResetProxy && enabled) {
const [currentSysProxy, currentAutoProxy] = await Promise.all([
getSystemProxy(),
@@ -439,7 +422,6 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
console.error('配置保存失败:', err)
mutateVerge()
showNotice.error(err)
// setOpen(true);
}
})
})
@@ -587,7 +569,6 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
setValue((v) => ({
...v,
use_default: e,
// 当取消选择use_default且当前bypass为空时,填充默认值
bypass: nextBypass,
}))
return
@@ -697,6 +678,5 @@ const FlexBox = styled('div')`
.label {
flex: none;
//width: 85px;
}
`
@@ -20,10 +20,6 @@ interface State {
showDetails: boolean
}
/**
* 流量统计专用错误边界组件
* 处理图表和流量统计组件的错误,提供优雅的降级体验
*/
export class TrafficErrorBoundary extends Component<Props, State> {
private retryCount = 0
private maxRetries = 3
@@ -39,7 +35,6 @@ export class TrafficErrorBoundary extends Component<Props, State> {
}
static getDerivedStateFromError(error: Error): Partial<State> {
// 更新状态以显示降级UI
return { hasError: true, error }
}
@@ -51,17 +46,14 @@ export class TrafficErrorBoundary extends Component<Props, State> {
errorInfo,
})
// 调用错误回调
if (this.props.onError) {
this.props.onError(error, errorInfo)
}
// 发送错误到监控系统(如果有的话)
this.reportError(error, errorInfo)
}
private reportError = (error: Error, errorInfo: ErrorInfo) => {
// 这里可以集成错误监控服务
const errorReport = {
message: error.message,
stack: error.stack,
@@ -72,8 +64,6 @@ export class TrafficErrorBoundary extends Component<Props, State> {
}
console.error('[TrafficErrorBoundary] 错误报告:', errorReport)
// TODO: 发送到错误监控服务
// sendErrorReport(errorReport);
}
private handleRetry = () => {
@@ -104,12 +94,10 @@ export class TrafficErrorBoundary extends Component<Props, State> {
render() {
if (this.state.hasError) {
// 如果提供了自定义降级组件,使用它
if (this.props.fallbackComponent) {
return this.props.fallbackComponent
}
// 默认错误UI
return (
<TrafficErrorFallback
error={this.state.error}
@@ -129,9 +117,6 @@ export class TrafficErrorBoundary extends Component<Props, State> {
}
}
/**
* 错误降级UI组件
*/
interface TrafficErrorFallbackProps {
error: Error | null
errorInfo: ErrorInfo | null
@@ -283,10 +268,6 @@ const TrafficErrorFallback: React.FC<TrafficErrorFallbackProps> = ({
)
}
/**
* 轻量级流量统计错误边界
* 用于小型流量显示组件,提供最小化的错误UI
*/
export const LightweightTrafficErrorBoundary: React.FC<{
children: ReactNode
}> = ({ children }) => {