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 }) => {
+3 -26
View File
@@ -4,23 +4,7 @@ import delayManager, { type DelaySnapshot } from '@/services/delay'
const NO_DELAYS: DelaySnapshot = { of: () => -1 }
/**
* The delays a list sorts by, as a value it can depend on.
*
* Delays live in a module-level store outside React, so a memo that reads them has nothing
* React can see and goes stale — which is why the two places that sorted by delay each grew
* their own way of forcing a recompute, and why both missed the single-proxy path.
*
* `useSyncExternalStore` rather than an effect plus state: the value is read during render
* while the store notifies from an animation frame, so a settle landing between the two would
* otherwise be dropped with nothing left to re-trigger it. It also keeps the identity stable
* between settles, which a snapshot rebuilt per render would not — that would re-sort on
* every render, which is worse than the hack it replaces.
*
* The store announces when a test *settles*, not on every measurement: a list re-sorting on
* each result would reshuffle for the length of a batch, moving rows out from under the
* pointer. Per-proxy displays stay live on their own subscription and are unaffected.
*/
/** Exposes the external delay store to React, updating sort order only after a test settles. */
export const useGroupDelays = (group: string | null): DelaySnapshot => {
const subscribe = useCallback(
(onSettle: () => void) =>
@@ -35,18 +19,11 @@ export const useGroupDelays = (group: string | null): DelaySnapshot => {
return useSyncExternalStore(subscribe, read, read)
}
/**
* The delays for several groups at once, keyed by group name.
*
* The map's identity changes whenever any of them settles, but each group's own entry keeps
* its identity unless that group settled — so a per-group cache is not thrown away wholesale
* because a neighbouring group finished a test.
*/
/** Preserves unchanged group snapshot identities when another group settles. */
export const useGroupsDelays = (
groups: readonly string[],
): ReadonlyMap<string, DelaySnapshot> => {
// Joined so the subscription tracks membership rather than the array identity, which a
// list rebuilds on every render.
// Subscribe by group membership; callers rebuild the array on every render.
const groupKey = groups.join(' ')
const subscribe = useCallback(
+2 -7
View File
@@ -69,11 +69,7 @@ describe('useRecordSelection', () => {
})
it('does not derive anything from a rendered selection list', () => {
// The regression this pins. It used to build the whole list from the profile it had
// rendered, so two selections made before that list refreshed were both derived from the
// same stale snapshot and the later one dropped the earlier group. Since a core start
// re-applies whatever the profile holds, the dropped choice came back on the next restart.
// Each call now carries one group, and the backend merges against the current profile.
// Pair-wise writes let the backend merge concurrent choices against fresh state.
record('Proxy', 'Node A')
record('Fallback', 'Node C')
@@ -91,8 +87,7 @@ describe('useRecordSelection', () => {
})
it('reports a failed write without throwing at the caller', async () => {
// Recording runs after the core has already been switched; failing the switch over it would
// be wrong, so the caller is never made to handle it.
// Persistence failure cannot roll back a core selection that already succeeded.
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
recordSelectedNode.mockRejectedValueOnce(new Error('no profile'))
+2 -18
View File
@@ -3,21 +3,8 @@ import { useCallback } from 'react'
import { forgetSelectedNode, recordSelectedNode } from '@/services/cmds'
/**
* Record which node a group is on, in the profile.
*
* The core keeps its own copy in `cache.db` and restores it when it starts, but neither half of
* that is something the app can rely on: `profile.store-selected` comes from a merge template a
* user is free to replace, and a service older than the durable runtime generation starts every
* core in a directory nothing has ever run in. So the app re-applies what the profile says once
* the core is up.
*
* Which makes this the rule: a selection the profile does not know about is one the next start
* will undo. Every path that moves a group has to come through here.
*
* Only the group and the node are sent. Sending the whole selection list — which is what this
* did while it built the array from `useProfiles().current` — made two selections made before
* that list refreshed into one overwriting the other, because both were derived from the same
* stale snapshot. The merge happens on the backend, against whatever the profile holds by then.
* Persists every group selection because core-local state is not durable across all run modes.
* Send only the changed pair so concurrent selections merge against fresh backend state.
*/
export const useRecordSelection = () => {
return useCallback(async (groupName: string, proxyName: string) => {
@@ -29,9 +16,6 @@ export const useRecordSelection = () => {
}, [])
}
/**
* Forget the persisted node selection for a group after its runtime fixed node is released.
*/
export const useForgetSelection = () => {
return useCallback(async (groupName: string) => {
try {
+2 -4
View File
@@ -15,7 +15,6 @@ import {
useQuery,
} from '@/services/query-client'
// 系统代理状态检测统一逻辑
export const useSystemProxyState = () => {
const { verge, mutateVerge } = useVerge()
const { sysproxy } = useSystemData()
@@ -33,7 +32,6 @@ export const useSystemProxyState = () => {
const { proxy_auto_config, proxy_host } = verge ?? {}
// OS 实际状态:enable + 地址匹配本应用
const indicator = (() => {
const host = proxy_host || '127.0.0.1'
if (proxy_auto_config) {
@@ -46,7 +44,7 @@ export const useSystemProxyState = () => {
}
})()
// "最后一次生效"模式:快速连续点击时,只执行最终状态
// Coalesce rapid clicks so only the latest requested state is applied.
const pendingRef = useRef<boolean | null>(null)
const busyRef = useRef(false)
@@ -82,7 +80,7 @@ export const useSystemProxyState = () => {
(prev) => (prev ? { ...prev, enable_system_proxy: confirmed } : prev),
false,
)
// Queued requests assumed the failed state was reached.
// Queued requests were based on a state that never landed.
pendingRef.current = null
throw error
} finally {
+3 -12
View File
@@ -9,10 +9,7 @@ import { useVisibility } from './use-visibility'
export const runStateQueryKey = ['getRuntimeState'] as const
/**
* Until the first snapshot arrives, assume the least capable environment: no service, no
* elevation, nothing asked of the user. Guessing "ready" here would flash a usable TUN toggle.
*/
/** Fail closed until the first snapshot so TUN never flashes as available. */
const unknownRunState: RunState = {
mode: 'NotRunning',
service: 'unknown',
@@ -26,13 +23,7 @@ const unknownRunState: RunState = {
serviceNeedsAttention: false,
}
/**
* The Run State: how the core is running and what backs it.
*
* One query key, kept fresh by `verge://run-state-changed` rather than polling. Every derived
* answer is computed in Rust and travels with the snapshot, so there is exactly one definition
* of "TUN can work" in the app.
*/
/** Event-driven run state; Rust owns all derived availability decisions. */
export function useSystemState() {
const pageVisible = useVisibility()
@@ -43,7 +34,7 @@ export function useSystemState() {
} = useQuery({
queryKey: runStateQueryKey,
queryFn: getRuntimeState,
// A safety net only: transitions are pushed, so this is not the primary path.
// A safety net only; transitions normally arrive by event.
refetchInterval: pageVisible ? 30000 : false,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
-6
View File
@@ -19,15 +19,10 @@ export const updateLastCheckTime = (timestamp?: number): number => {
return now
}
// --- useUpdate hook ---
export const useUpdate = (enabled: boolean = true) => {
const { verge } = useVerge()
const { auto_check_update } = verge || {}
// Determine if we should check for updates
// If enabled is explicitly false, don't check
// Otherwise, respect the auto_check_update setting (or default to true if null/undefined for manual triggers)
const shouldCheck = enabled && auto_check_update !== false
const fetchUpdate = async () => {
@@ -52,7 +47,6 @@ export const useUpdate = (enabled: boolean = true) => {
return { data }
}
// Shared last check timestamp
const { data: lastCheckUpdate } = useQuery({
queryKey: [LAST_CHECK_KEY],
queryFn: readLastCheckTime,
+2 -6
View File
@@ -34,17 +34,13 @@ export const useLayoutEvents = (
'getAutotemProxy',
])
},
// The Run State is pushed, not polled: every transition carries the new snapshot, so it
// is written straight into the cache instead of triggering a fetch.
// Transitions carry the full run-state snapshot, so write it directly to cache.
'verge://run-state-changed': (payload) => {
void setCacheDataAsync<RunState>(runStateQueryKey, payload)
},
'verge://notice-message': handleNotice,
},
// The Run State is the one thing here that arrives *only* by event, so it is the one
// thing a missed event leaves stale — until the next transition, which during startup can
// be a long time. Re-read once the listener is live, so the gap between the first read
// and the subscription cannot outlive the subscription.
// Re-read event-only state after subscribing to close the initial race window.
() => revalidateKeys(['getRuntimeState']),
)
}, [handleNotice])
+4 -33
View File
@@ -54,7 +54,6 @@ import {
deleteProfile,
enhanceProfiles,
getProfiles,
//restartCore,
getRuntimeLogs,
importProfile,
reorderProfile,
@@ -121,7 +120,6 @@ interface ProfileSwitchRequest {
force: boolean
}
// 记录profile切换状态
const debugProfileSwitch = (action: string, profile: string, extra?: any) => {
const timestamp = new Date().toISOString().substring(11, 23)
debugLog(`[Profile-Debug][${timestamp}] ${action}: ${profile}`, extra || '')
@@ -146,7 +144,6 @@ const ProfilePage = () => {
Map<string, number>
>(() => new Map())
// Batch selection states
const [batchMode, setBatchMode] = useState(false)
const [selectedProfiles, setSelectedProfiles] = useState<Set<string>>(
() => new Set(),
@@ -223,18 +220,14 @@ const ProfilePage = () => {
}
}, [addListener, mutateProfiles])
// 添加紧急恢复功能
const onEmergencyRefresh = useLockFn(async () => {
debugLog('[紧急刷新] 开始强制刷新所有数据')
try {
// 只失效 profiles 相关 query,不影响 WS 订阅、IP 缓存等其他 query
await revalidateQueries([['getProfiles'], ['getRuntimeLogs']])
// 强制重新获取配置数据
await mutateProfiles()
// 等待状态稳定后增强配置
await new Promise((resolve) => setTimeout(resolve, 500))
await onEnhance(false)
@@ -263,7 +256,6 @@ const ProfilePage = () => {
const viewerRef = useRef<ProfileViewerRef>(null)
const configRef = useRef<DialogRef>(null)
// distinguish type
const profileItems = useMemo(() => {
const items = profiles.items || []
@@ -278,7 +270,6 @@ const ProfilePage = () => {
const onImport = async () => {
if (!url) return
// 校验url是否为http/https
if (!/^https?:\/\//i.test(url)) {
showNotice.error('profiles.page.feedback.errors.invalidUrl')
return
@@ -291,7 +282,6 @@ const ProfilePage = () => {
await performRobustRefresh()
}
try {
// 尝试正常导入
await importProfile(url)
await handleImportSuccess('shared.feedback.notifications.importSuccess')
} catch (initialErr) {
@@ -305,7 +295,6 @@ const ProfilePage = () => {
showNotice.info('profiles.page.feedback.notifications.importRetry')
try {
// 使用自身代理尝试导入
await importProfile(url, {
with_proxy: false,
self_proxy: true,
@@ -314,7 +303,6 @@ const ProfilePage = () => {
'shared.feedback.notifications.importWithClashProxy',
)
} catch (retryErr) {
// 回退导入也失败
showNotice.error(
'profiles.page.feedback.notifications.importFail',
retryErr,
@@ -326,8 +314,7 @@ const ProfilePage = () => {
}
}
// 强化的刷新策略
// maxRetries 设为 1:useProfiles 内部 useQuery 已配置 retry:3,业务层只需 1 次额外重试
// `useProfiles` already retries three times; add only one business-level retry.
const performRobustRefresh = async () => {
let retryCount = 0
const maxRetries = 1
@@ -337,10 +324,8 @@ const ProfilePage = () => {
try {
debugLog(`[导入刷新] 第${retryCount + 1}次尝试刷新配置数据`)
// 强制刷新,绕过所有缓存
await mutateProfiles()
// 等待状态稳定
await new Promise((resolve) =>
setTimeout(resolve, baseDelay * (retryCount + 1)),
)
@@ -356,10 +341,8 @@ const ProfilePage = () => {
}
}
// 所有重试失败后的最后尝试
console.warn(`[导入刷新] 常规刷新失败,尝试清除缓存重新获取`)
try {
// 清除缓存并重新获取
await fetchCacheData(['getProfiles'], getProfiles)
await onEnhance(false)
showNotice.error(
@@ -566,7 +549,6 @@ const ProfilePage = () => {
}
})
// 更新所有订阅
const loadingCache = useLoadingCache()
const setLoadingCache = useSetLoadingCache()
const setLoadingProfiles = useCallback(
@@ -643,7 +625,6 @@ const ProfilePage = () => {
await Promise.allSettled(Array.from({ length: active }, worker))
} finally {
setLoadingProfiles(uids, false)
// 避免长时间批量更新后列表数据过晚刷新
void mutateProfiles()
}
},
@@ -664,11 +645,9 @@ const ProfilePage = () => {
if (text) setUrl(text)
}
// Batch selection functions
const toggleBatchMode = () => {
setBatchMode(!batchMode)
if (!batchMode) {
// Entering batch mode - clear previous selections
setSelectedProfiles(new Set())
}
}
@@ -701,11 +680,11 @@ const ProfilePage = () => {
const getSelectionState = () => {
if (selectedProfiles.size === 0) {
return 'none' // 无选择
return 'none'
} else if (selectedProfiles.size === profileItems.length) {
return 'all' // 全选
return 'all'
} else {
return 'partial' // 部分选择
return 'partial'
}
}
@@ -713,7 +692,6 @@ const ProfilePage = () => {
if (selectedProfiles.size === 0) return
try {
// Get all currently activating profiles
const currentActivating =
profiles.current && selectedProfiles.has(profiles.current)
? [profiles.current]
@@ -721,7 +699,6 @@ const ProfilePage = () => {
setActivatings((prev) => [...new Set([...prev, ...currentActivating])])
// Delete all selected profiles
for (const uid of selectedProfiles) {
await deleteProfile(uid)
}
@@ -729,12 +706,10 @@ const ProfilePage = () => {
await mutateProfiles()
await mutateLogs()
// If any deleted profile was current, enhance profiles
if (currentActivating.length > 0) {
await onEnhance(false)
}
// Clear selections and exit batch mode
setSelectedProfiles(new Set())
setBatchMode(false)
@@ -835,7 +810,6 @@ const ProfilePage = () => {
)}
</>
) : (
// Batch mode header
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<IconButton
size="small"
@@ -995,8 +969,6 @@ const ProfilePage = () => {
onSave={async (prev, curr) => {
if (prev !== curr && profiles.current === item.uid) {
await onEnhance(false)
// await restartCore();
// Notice.success(t("settings.feedback.notifications.clash.restartSuccess"), 1000);
}
}}
onDelete={() => {
@@ -1053,7 +1025,6 @@ const ProfilePage = () => {
ref={viewerRef}
onChange={async (isActivating) => {
mutateProfiles()
// 只有更改当前激活的配置时才触发全局重新加载
if (isActivating) {
await onEnhance(false)
}
+2 -20
View File
@@ -2,14 +2,7 @@
import { render, screen } from '@testing-library/react'
import { afterEach, beforeEach, expect, test, vi } from 'vitest'
/**
* Stub the Tauri boundary and nothing above it.
*
* Everything the provider mounts — SWR queries, the config hooks, the event subscription,
* the mihomo plugin — goes through `invoke` or `listen`, so replacing just those two leaves
* all the real application code running. A test that stubbed the hooks instead could not
* catch what this one exists to catch.
*/
// Stub only the Tauri boundary so the real provider tree still renders.
vi.mock('@tauri-apps/api/core', () => ({
invoke: vi.fn(async () => undefined),
Channel: class {},
@@ -22,7 +15,6 @@ vi.mock('@tauri-apps/api/event', () => ({
import { AppDataProvider } from './app-data-provider'
beforeEach(() => {
// The provider's queries poll; keep them from firing during the assertion.
vi.useFakeTimers({ shouldAdvanceTime: true })
})
@@ -30,14 +22,7 @@ afterEach(() => {
vi.useRealTimers()
})
/**
* Mounting the provider is the whole test.
*
* A hook inside `AppDataProvider` that reads a context `AppDataProvider` itself supplies
* throws during render and blanks the entire UI. That shipped once. `typecheck`, `lint`,
* `knip` and `web:build` all passed with it present, and so did an independent review —
* nothing but rendering can see it.
*/
// Rendering catches a provider reading its own context, which static checks cannot detect.
test('AppDataProvider mounts and renders its children', () => {
render(
<AppDataProvider>
@@ -49,9 +34,6 @@ test('AppDataProvider mounts and renders its children', () => {
})
test('AppDataProvider does not consume a context it provides', () => {
// The failure mode is specific enough to name: `useCtx` throws
// "<hook> must be used within AppDataProvider" when a provider reads its own context,
// which is indistinguishable at the type level from a legitimate call site.
const errors: unknown[] = []
const consoleError = vi
.spyOn(console, 'error')
+3 -26
View File
@@ -83,13 +83,11 @@ export async function getClashInfo() {
return invoke<IClashInfo | null>('get_clash_info')
}
// Fault-tolerant current proxy mode read (does not depend on mihomo /configs
// strict BaseConfig deserialization); used as a fallback for the home mode card.
// Fallback mode read independent of strict mihomo `/configs` deserialization.
export async function getClashMode() {
return invoke<string | null>('get_clash_mode')
}
// Get runtime config which controlled by verge
export async function getRuntimeConfig() {
return invoke<IConfigData | null>('get_runtime_config')
}
@@ -126,17 +124,11 @@ export async function syncTrayProxySelection() {
return invoke<void>('sync_tray_proxy_selection')
}
/**
* Record which node a group is on, in the current profile.
*
* Group and node, not the whole selection list: the merge happens in the backend against the
* profile as it stands, so two selections made in quick succession cannot overwrite each other.
*/
/** Sends one selection pair so the backend can merge against current profile state. */
export async function recordSelectedNode(groupName: string, node: string) {
return invoke<void>('record_selected_node', { groupName, node })
}
/** Forget the persisted node selection for one proxy group in the current profile. */
export async function forgetSelectedNode(groupName: string) {
return invoke<void>('forget_selected_node', { groupName })
}
@@ -373,7 +365,6 @@ export async function listLocalBackup() {
return invoke<ILocalBackupFile[]>('list_local_backup')
}
// 获取当前运行模式
export type RunningMode = 'Service' | 'Sidecar' | 'NotRunning'
type ServiceHealth =
@@ -389,12 +380,7 @@ type PendingServiceAction =
| 'reinstall'
| 'forceReinstall'
/**
* How the core is running and what backs it, as one consistent snapshot.
*
* The derived answers travel with it — `tunCapable`, `serviceUsable`,
* `serviceNeedsAttention` — so nothing here is recomputed from the raw fields.
*/
/** Consistent core/service snapshot with backend-derived availability flags. */
export interface RunState {
mode: RunningMode
service: ServiceHealth
@@ -412,40 +398,31 @@ export const getRuntimeState = async () => {
return invoke<RunState>('get_runtime_state')
}
/** Operation associated with a pending failure. */
export type FailedOperation =
| 'systemProxyEnable'
| 'systemProxyDisable'
| 'systemProxyRestore'
| 'systemProxyGuard'
/** Latest unresolved failure for one stable code. */
export interface PendingFailure {
/** Stable table key. */
code: string
/** Full diagnostic chain. */
detail: string
operation: FailedOperation
/** Identity for repeated failures under the same code. */
sequence: number
}
/** Read unresolved failures without consuming them. */
export const getPendingFailures = async () => {
return invoke<PendingFailure[]>('get_pending_failures')
}
// 获取应用运行时间
export const getAppUptime = async () => {
return invoke<number>('get_app_uptime')
}
// 安装系统服务
export const installService = async () => {
return invoke<void>('install_service')
}
// 卸载系统服务
export const uninstallService = async () => {
return invoke<void>('uninstall_service')
}
+5 -16
View File
@@ -1,10 +1,6 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
/**
* The delay API is the only thing stubbed. What is under test is when the manager announces
* that a group has settled — the granularity that decides whether a sorted list re-orders
* once per test or once per result.
*/
// Stub only the delay API; these tests cover group-settle notification granularity.
vi.mock('tauri-plugin-mihomo-api', () => ({
delayProxyByName: vi.fn(async () => ({ delay: 120 })),
healthcheckNodeInProvider: vi.fn(async () => ({ delay: 120 })),
@@ -26,7 +22,6 @@ const node = (name: string) =>
},
}) as unknown as ResolvedProxyMember
/** The manager coalesces notifications onto a frame; give it one. */
const nextFrame = () => new Promise((resolve) => setTimeout(resolve, 0))
let settles = 0
@@ -45,8 +40,7 @@ afterEach(() => {
describe('group settle notifications', () => {
test('a single test settles the group once', async () => {
// The bug this fixes: a single-proxy retest updated that proxy's own display but never
// told the list to re-sort, so a group sorted by delay kept a stale order.
// A single-proxy retest must invalidate delay sorting.
await delayManager.checkDelay(node('a') as never, 'g', 5000)
await nextFrame()
@@ -54,9 +48,7 @@ describe('group settle notifications', () => {
})
test('a batch settles the group once, however many proxies it covered', async () => {
// The granularity that matters. Announcing per result would re-sort continuously for
// the length of the test, moving rows out from under the pointer — and the symptom
// would be jumpy scrolling, which nothing else here could assert.
// A batch announces once to avoid reordering rows as individual results arrive.
const proxies = Array.from({ length: 20 }, (_, index) => node(`n${index}`))
await delayManager.checkListDelay(proxies as never, 'g', 5000, 4)
@@ -75,8 +67,7 @@ describe('group settle notifications', () => {
})
test('two listeners on one group both hear it', async () => {
// Group listeners used to be one-per-group, so a second view silently replaced the
// first one's subscription.
// Multiple views must not replace one another's group subscriptions.
let second = 0
const stop = delayManager.addGroupListener('g', () => {
second += 1
@@ -91,9 +82,7 @@ describe('group settle notifications', () => {
})
test('a single test inside a running batch waits for the batch', async () => {
// The window the batch counter exists for: the per-row delay button and "test all" hold
// separate locks, so a user can start one inside the other. Announcing then would sort a
// half-measured group, which is the reordering this design is meant to prevent.
// Nested batches must wait for the outermost settle before announcing.
const proxies = Array.from({ length: 6 }, (_, index) => node(`n${index}`))
const batch = delayManager.checkListDelay(proxies as never, 'g', 5000, 2)
+11 -61
View File
@@ -13,7 +13,6 @@ import {
import { debugLog } from '@/utils/debug'
import { classifyDelay, DEFAULT_DELAY_TIMEOUT } from '@/utils/delay'
/** A group's delays, handed to sorting as a value it can depend on. */
export type DelaySnapshot = {
of: (member: ResolvedProxyMember) => number
}
@@ -32,22 +31,16 @@ class DelayManager {
private cache = new Map<string, DelayUpdate>()
private urlMap = new Map<string, string>()
// 每个节点的监听
private listenerMap = new Map<string, (update: DelayUpdate) => void>()
// 每个分组的监听
private groupListenerMap = new Map<string, Set<() => void>>()
/// A stable handle per group, replaced when that group settles. Consumers compare its
/// identity, so it must not be rebuilt on every read.
// Consumers compare snapshot identity; replace it only when the group settles.
private groupSnapshots = new Map<string, DelaySnapshot>()
/// Keyed by the joined group names a consumer asked for; cleared whenever any group
/// settles, so the map identity changes while unaffected groups keep theirs.
private groupSetSnapshots = new Map<
string,
ReadonlyMap<string, DelaySnapshot>
>()
/// Batches in flight per group. A single test that lands inside one must not announce:
/// sorting from a half-measured group is the reordering this design exists to avoid.
// Suppress sort notifications until every measurement in a group batch settles.
private activeBatches = new Map<string, number>()
private pendingItemUpdates = new Map<string, DelayUpdate[]>()
@@ -126,27 +119,14 @@ class DelayManager {
private queueGroupNotification(group: string) {
if ((this.activeBatches.get(group) ?? 0) > 0) return
// Dropped so the next read builds a fresh identity. Only this group's snapshot changes;
// the set-level map is rebuilt too, but its other entries keep their identities.
// Invalidate the set wrapper while retaining unaffected per-group identities.
this.groupSnapshots.delete(group)
this.groupSetSnapshots.clear()
this.pendingGroupUpdates.add(group)
this.scheduleGroupFlush()
}
/**
* A handle to this group's delays whose identity changes only when a test settles.
*
* Read during render and compared by identity, so it is cached rather than rebuilt: a
* fresh object per read would make every consumer recompute on every render.
*/
/**
* The delays for a set of groups, keyed by group name.
*
* Cached so its identity is stable between settles, while each group's own snapshot keeps
* its identity unless *that* group settled — which is what lets a per-group cache survive
* a test in a neighbouring group.
*/
/** Cached set snapshot for `useSyncExternalStore` identity comparisons. */
groupsDelays(groupKey: string): ReadonlyMap<string, DelaySnapshot> {
const cached = this.groupSetSnapshots.get(groupKey)
if (cached) return cached
@@ -159,6 +139,7 @@ class DelayManager {
return snapshots
}
/** Cached group snapshot whose identity changes only when that group settles. */
groupDelays(group: string): DelaySnapshot {
const existing = this.groupSnapshots.get(group)
if (existing) return existing
@@ -180,7 +161,6 @@ class DelayManager {
debugLog(
`[DelayManager] 获取测试URL,组: ${group}, URL: ${url || '未设置'}`,
)
// 如果未设置URL,返回默认URL
return url || 'http://cp.cloudflare.com/generate_204'
}
@@ -198,16 +178,7 @@ class DelayManager {
this.listenerMap.delete(key)
}
/**
* Called when a delay test for `group` has settled: once per single test, and once for a
* whole batch however many proxies it covered.
*
* "Settled" rather than "changed" on purpose. Per-proxy display updates are already live
* through `setListener`; this exists for the things that must not move while results are
* still arriving, chiefly sort order.
*/
/// Returns its own unsubscribe, so two views may watch the same group without one
/// silently replacing the other's listener.
/** Multiple views may subscribe independently; notifications occur only after settle. */
addGroupListener(group: string, listener: () => void): () => void {
const listeners = this.groupListenerMap.get(group) ?? new Set()
listeners.add(listener)
@@ -278,13 +249,11 @@ class DelayManager {
}
if (details?.history && details.history.length > 0) {
// 0ms以error显示
return details.history[details.history.length - 1].delay || 1e6
}
return -1
}
// 统一延迟测试检测
async unifiedDelayCheck(
name: string,
url: string,
@@ -296,12 +265,7 @@ class DelayManager {
return delayProxyByName(name, url, timeout)
}
/**
* Test one proxy, then tell the group its ordering may have changed.
*
* The announcement is the point at which a sorted list is allowed to re-sort. It is
* deliberately *not* made per result inside a batch — see `checkListDelay`.
*/
/** A single test may notify immediately; a batch defers notification until it settles. */
async checkDelay(
member: InteractableProxyMember,
group: string,
@@ -328,7 +292,6 @@ class DelayManager {
`[DelayManager] 开始测试延迟,代理: ${name}, 组: ${group}, 超时: ${timeout}ms`,
)
// 先将状态设置为测试中
this.setDelay(name, group, -2)
const startTime = Date.now()
@@ -337,18 +300,15 @@ class DelayManager {
const url = this.getUrl(group)
debugLog(`[DelayManager] 调用API测试延迟,代理: ${name}, URL: ${url}`)
// 设置超时处理, delay = 0 为超时
const timeoutPromise = new Promise<ProxyDelay>((resolve) => {
setTimeout(() => resolve({ delay: 0 }), timeout)
})
// 使用Promise.race来实现超时控制
const result = await Promise.race([
this.unifiedDelayCheck(apiName, url, timeout, providerName),
timeoutPromise,
])
// 确保至少显示500ms的加载动画
const elapsedTime = Date.now() - startTime
if (elapsedTime < 500) {
await new Promise((resolve) => setTimeout(resolve, 500 - elapsedTime))
@@ -360,7 +320,6 @@ class DelayManager {
return this.setDelay(name, group, delay, { elapsed })
} catch (error) {
// 确保至少显示500ms的加载动画
await new Promise((resolve) => setTimeout(resolve, 500))
console.error(`[DelayManager] 延迟测试出错,代理: ${name}`, error)
const delay = 1e6 // error
@@ -381,7 +340,6 @@ class DelayManager {
)
const names = proxies.map((member) => member.ref.name)
this.activeBatches.set(group, (this.activeBatches.get(group) ?? 0) + 1)
// 设置正在延迟测试中
names.forEach((name) => {
this.setDelay(name, group, -2)
})
@@ -395,34 +353,28 @@ class DelayManager {
const currName = currMember.ref.name
try {
// 确保API调用前状态为测试中
this.setDelay(currName, group, -2)
// 添加一些随机延迟,避免所有请求同时发出和返回
// Stagger requests so a batch does not hit the core at once.
if (index > 1) {
// 第一个不延迟,保持响应性
await new Promise((resolve) =>
setTimeout(resolve, Math.random() * 200),
)
}
// Measured without announcing: a sorted list that re-ordered on every result would
// reshuffle continuously for the length of the test, with rows moving out from under
// the pointer. The group is told once, below, when the batch has settled.
// Do not reorder a list around the pointer while batch results are arriving.
await this.measureDelay(currMember, group, timeout)
} catch (error) {
console.error(
`[DelayManager] 批量测试单个代理出错,代理: ${currName}`,
error,
)
// 设置为错误状态
this.setDelay(currName, group, 1e6)
}
return help()
}
// 限制并发数,避免发送太多请求
const actualConcurrency = Math.min(concurrency, names.length, 10)
debugLog(`[DelayManager] 实际并发数: ${actualConcurrency}`)
@@ -434,8 +386,7 @@ class DelayManager {
try {
await Promise.all(promiseList)
} finally {
// In a `finally` so a throw cannot leave the group unannounced: the proxies would sit
// at -2 and the order would stay stale with nothing later to repair it.
// Always release the batch and notify; otherwise failures leave stale sort state.
const remaining = (this.activeBatches.get(group) ?? 1) - 1
if (remaining > 0) {
this.activeBatches.set(group, remaining)
@@ -474,8 +425,7 @@ class DelayManager {
case 'error':
return 'error.main'
case 'measured':
// How a measurement is graded is this widget's own decision; the thresholds differ
// from the signal icon's on purpose, because a colour has fewer steps than four bars.
// Colour and signal bars intentionally use different grading thresholds.
if (delay >= 400) return 'warning.main'
if (delay >= 250) return 'primary.main'
return 'success.main'
+3 -28
View File
@@ -2,36 +2,20 @@ import { listen, type UnlistenFn } from '@tauri-apps/api/event'
import type { RunState } from './cmds'
/**
* Every event pushed to the frontend, and what it carries.
*
* The names were string literals on both sides of the IPC seam, so renaming one was a silent
* no-op rather than a compile error. Declaring them here does not make the Rust side check
* itself, but it does mean the frontend has exactly one place to look and one payload type
* per name instead of a `listen<T>` guess at each call site.
*/
/** Centralizes frontend event names and payload types for the unchecked Rust IPC seam. */
interface VergeEvents {
/** The core's own configuration changed. */
'verge://refresh-clash-config': string
/** The app's configuration changed. */
'verge://refresh-verge-config': string
/** The set of profiles changed. */
'verge://refresh-profiles': string
/** The active profile's proxies changed. */
'verge://refresh-proxy-config': null
/** A backend message for the user: `[status, message]`. */
'verge://notice-message': [string, string]
/** A profile's auto-update timer was rescheduled. */
'verge://timer-updated': string
/** How the core is running changed; carries the whole snapshot. */
'verge://run-state-changed': RunState
/** Pending failures changed; reread the table. */
'verge://pending-failures-changed': null
/** Which profile is active changed. */
'profile-changed': string
'profile-update-started': { uid?: string }
'profile-update-completed': { uid?: string }
/** Frontend to frontend: the home card asks the test page to run every test. */
'verge://test-all': null
}
@@ -42,17 +26,8 @@ type VergeEventHandlers = {
}
/**
* Subscribe to backend events, returning the teardown.
*
* Registration is asynchronous, so a subscription can resolve after the caller has already
* torn down; that is tracked here rather than at each call site, where it was implemented
* four different ways and omitted in one of them.
*
* `onSubscribed` runs once every listener is live. Anything whose state arrives only by event
* needs it: between the first read and the listener being registered there is a gap, and a
* transition landing in it is not queued anywhere — it is simply missed, and the next event is
* whenever the backend happens to move again. Re-reading at that point closes the gap without
* going back to polling for it.
* Returns synchronous teardown for asynchronous registrations. `onSubscribed` lets callers
* reread event-only state after all listeners are live, closing the initial race window.
*/
export const subscribeVergeEvents = (
handlers: VergeEventHandlers,
+2 -27
View File
@@ -17,14 +17,11 @@ interface NoticeItem {
readonly duration: number
readonly message?: ReactNode
readonly i18n?: NoticeTranslationDescriptor
/** Stable classified failure code. */
readonly code?: string
/** Requested operation when known. */
readonly operation?: FailedOperation
timerId?: ReturnType<typeof setTimeout>
}
/** Failures owned by the recovery dialog. */
const CODES_A_DIALOG_REPORTS = new Set<string>([
'SYSPROXY_PRIVILEGE_REQUIRED',
'SYSPROXY_SIDECAR_WHILE_SERVICE_READY',
@@ -61,7 +58,6 @@ const DEFAULT_DURATIONS: Readonly<Record<NoticeType, number>> = {
}
const TRANSLATION_KEY_PATTERN = /^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/
/** Localized explanation for each stable failure code. */
const CODED_ERROR_TRANSLATION_KEYS: Readonly<Record<string, TranslationKey>> = {
CLASH_CONFIG_UPDATE_FAILED:
'settings.feedback.errors.clash.configUpdateFailed',
@@ -106,7 +102,6 @@ interface ParsedNoticeExtras {
params?: Record<string, unknown>
raw?: unknown
duration?: number
/** Code extracted before translation parameters are flattened. */
nestedCode?: string
}
@@ -166,7 +161,6 @@ function parseNoticeExtras(extras: NoticeExtra[]): ParsedNoticeExtras {
}
}
/** Replace structured failures in translation params with readable detail. */
function readableParams(
source: Record<string, unknown>,
): Record<string, unknown> {
@@ -178,7 +172,6 @@ function readableParams(
)
}
/** Find a classified failure nested in translation parameters. */
function nestedFailureCode(
source?: Record<string, unknown>,
): string | undefined {
@@ -243,10 +236,8 @@ function isPlainRecord(value: unknown): value is Record<string, unknown> {
return proto === Object.prototype || proto === null
}
/** Maximum code points rendered in a notice. */
const MAX_RENDERED_TEXT_CHARS = 500
/** Bound resolved display text by code point and append an ellipsis when truncated. */
export function boundNoticeText(text: string): string {
let end = 0
let counted = 0
@@ -267,7 +258,6 @@ function createRawDescriptor(message: string): NoticeTranslationDescriptor {
}
}
/** Messages longer than any real translation key are treated as raw text. */
const MAX_TRANSLATION_KEY_CHARS = 200
function isLikelyTranslationKey(key: string) {
@@ -309,13 +299,9 @@ function extractDisplayText(input: unknown): string | undefined {
}
}
/** What a failed Tauri command reports. */
export interface CommandFailure {
/** Stable identifier for the kind of failure, when the backend could classify it. */
code?: string
/** Requested operation when known by the command. */
operation?: FailedOperation
/** Human-readable diagnostic detail. */
detail: string
}
@@ -328,19 +314,16 @@ function isCommandFailure(input: unknown): input is CommandFailure {
)
}
/** Extract display text from a structured or legacy failure. */
export function errorDetail(input: unknown): string {
return extractDisplayText(input) ?? ''
}
/** Parse a classified command failure for notice rendering. */
function parseCommandFailure(input: unknown) {
if (!isCommandFailure(input) || !input.code) return undefined
const explanation = CODED_ERROR_TRANSLATION_KEYS[input.code]
return {
translationKey: explanation ?? 'shared.feedback.errors.operationFailed',
/** Whether this code has a specific explanation. */
explained: explanation !== undefined,
detail: input.detail.trim() || undefined,
}
@@ -513,16 +496,8 @@ function failureOperation(input: unknown): FailedOperation | undefined {
}
/**
* Shows a global notice; `showNotice.success / error / info` are the usual entry points.
*
* - `message`: i18n key string, `{ key, params }`, ReactNode, Error/any value (message is extracted)
* - `extras` parsed left-to-right: first plain object is i18n params; next value is raw payload; first number overrides duration (ms, 0 = persistent; defaults: success 3000 / info 5000 / error 8000)
* - Returns a notice id for manual closing via `hideNotice(id)`
*
* @example showNotice.success("profiles.page.feedback.notifications.batchDeleted");
* @example showNotice.error(err); // pass an Error directly
* @example showNotice.error("shared.feedback.notifications.common.refreshFailed", err); // Simply pass an Error directly; but we recommend using { err } with i18n key and placeholders.
* @example showNotice.error("profiles.page.feedback.errors.invalidUrl", { url }, 4000);
* Shows a global notice. Extras are parsed as i18n params, raw payload, then duration;
* returns an ID accepted by `hideNotice`.
*/
export const showNotice: ShowNotice = Object.assign(baseShowNotice, {
success: (message: NoticeContent, ...extras: NoticeExtra[]) =>
-13
View File
@@ -11,9 +11,6 @@ type Platform =
| 'cygwin'
| 'netbsd'
/**
* defines in `vite.config.ts`
*/
declare const OS_PLATFORM: Platform
type ValidationOutcome =
@@ -21,9 +18,6 @@ type ValidationOutcome =
| { status: 'invalid'; kind: string; message: string }
| { status: 'skipped'; reason: string }
/**
* Some interface for clash api
*/
interface IConfigData {
port: number
mode: string
@@ -213,12 +207,7 @@ interface IConnectionSetting {
layout: 'table' | 'list'
}
/**
* Some interface for command
*/
interface IClashInfo {
// status: string;
mixed_port?: number // clash mixed port
socks_port?: number // clash socks port
redir_port?: number // clash redir port
@@ -890,7 +879,6 @@ interface IVergeConfig {
sysproxy_tray_icon?: boolean
tun_tray_icon?: boolean
enable_tray_speed?: boolean
// enable_tray_icon?: boolean;
tray_proxy_groups_display_mode?: 'default' | 'inline' | 'disable'
tray_inline_outbound_modes?: boolean
enable_tun_mode?: boolean
@@ -980,7 +968,6 @@ interface IWebDavConfig {
password: string
}
// Traffic monitor types
interface ITrafficDataPoint {
up: number
down: number
-4
View File
@@ -47,10 +47,6 @@ const computeDebugEnabled = (): boolean => {
const isDebugLoggingEnabled = () =>
cachedDebugEnabled ?? (cachedDebugEnabled = computeDebugEnabled())
/**
* Logs to the console only when debug logging is enabled.
* Forwards all arguments to `console.log`; does nothing otherwise.
*/
export const debugLog = (...args: any[]) => {
if (!isDebugLoggingEnabled()) return
console.log(...args)
+2 -25
View File
@@ -1,23 +1,9 @@
/**
* What a delay number means, before anyone decides how to draw it.
*
* The core reports latency through a single number that encodes several non-measurements:
* sentinels for "never tested" and "testing now", zero and large values for timeouts, and
* absurd values for errors. Every surface agreed on those rules and restated them; they are
* stated once here.
*
* How a *measured* delay is graded — fast, slow, and the thresholds between — is deliberately
* not here. A three-colour chip and a four-bar signal icon draw different distinctions, and
* flattening them would be inventing a UI decision rather than removing a duplicate one.
*/
/** Normalizes latency values and the core's non-measurement sentinels. */
/** The delay above which the core is considered to have timed out. */
export const DEFAULT_DELAY_TIMEOUT = 10000
/** The value the core reports for a node whose test is in flight. */
const TESTING = -2
/** Above this, the number is not a latency at all. */
const IMPLAUSIBLE_DELAY = 1e5
export type DelayState =
@@ -25,7 +11,6 @@ export type DelayState =
| 'untested'
| 'error'
| 'timeout'
/** An actual latency measurement, in milliseconds. */
| 'measured'
export const classifyDelay = (
@@ -40,13 +25,7 @@ export const classifyDelay = (
return 'measured'
}
/**
* The order delays sort in: measured first and fastest first, then timeouts, then errors,
* then everything we have no measurement for.
*
* Ranks are compared before values so that a non-measurement can never sort ahead of a real
* one just because its sentinel happens to be a small number.
*/
/** Rank separately so sentinel magnitudes cannot outrank real measurements. */
const rankOf = (state: DelayState): number => {
switch (state) {
case 'measured':
@@ -62,7 +41,6 @@ const rankOf = (state: DelayState): number => {
}
}
/** A total order over delays, for sorting a proxy list fastest-first. */
export const compareByDelay = (
a: number,
b: number,
@@ -75,7 +53,6 @@ export const compareByDelay = (
const rankDifference = rankOf(aState) - rankOf(bState)
if (rankDifference !== 0) return rankDifference
// Within a rank, only a real measurement has a meaningful magnitude.
if (aState !== 'measured') return 0
return a - b
}