Compare commits

..
Author SHA1 Message Date
Tunglies 25bc4db8e9 refactor(ui): share the switch adapter and drop dead memos
Three settings files each defined the same boolean switch-format
adapter; it is exported once from the Switch module. The update dialog
memoized trivial arithmetic, the profile-more reset callback keyed on
a per-render document object instead of its stable setter, and the
profile viewer's imperative handle had no dependency array.
2026-11-19 23:16:46 +08:00
Tunglies 5043b8706d perf(ui): batch notice removal and hoist drag sensors
hideNoticesByCode removed matching notices one by one, notifying
subscribers per item; it now filters in one pass and notifies once.
The chain list, test card and grouped editor list allocated their drag
sensor arrays per render; they are module constants now.
2026-11-19 23:16:44 +08:00
Tunglies 2b812f5fa5 perf(ui): hoist hot regexes and stabilize clash mutators
The clash log parser and the URI validators recompiled their patterns
per call; the patterns are module constants now. mutateClash and
invalidateClashConfig are stable callbacks so consumers can keep them
in dependency arrays; mutateClash revalidates through the module-level
query helper instead of the per-render refetch closure (no caller reads
its resolved value).
2026-11-19 23:16:35 +08:00
Tunglies 7074cc5c25 perf(ui): memoize derived validation and list computations
The TUN dialog re-split its route-exclusion list, the rule provider
dialog re-sorted its entries and the group-delays hook re-stringified
its group key on every render; each now recomputes only when its input
identity changes. The provider-button hunk re-indents its JSX block
because the sorted entries moved out of the render expression.
2026-11-19 23:16:33 +08:00
Tunglies a85566a2cb perf(ui): hoist static style, menu and OS identities
Dialog controls rebuilt static option arrays, style objects and label
maps on every render; the sysproxy viewer also probed the OS and split
the default bypass string per render. These are now module constants or
single memos keyed on their real inputs (translation function, active
stage).
2026-11-19 23:16:25 +08:00
29 changed files with 372 additions and 359 deletions
Generated
+8 -73
View File
@@ -821,9 +821,9 @@ checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "bytes"
version = "1.12.2"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
dependencies = [
"serde",
]
@@ -1191,7 +1191,7 @@ name = "clash-verge-logging"
version = "0.1.0"
dependencies = [
"anyhow",
"flexi_logger 0.32.0",
"flexi_logger",
"log",
"parking_lot 0.13.0",
"tracing-estuary",
@@ -2425,19 +2425,6 @@ dependencies = [
"thiserror 2.0.20",
]
[[package]]
name = "flexi_logger"
version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e87b74024da93123949cca26cb6e366744234fdd4d7914eb3dfeab0baa82d51"
dependencies = [
"jiff",
"log",
"nu-ansi-term",
"regex",
"thiserror 2.0.20",
]
[[package]]
name = "float16"
version = "0.1.5"
@@ -3750,58 +3737,6 @@ dependencies = [
"system-deps 6.2.2",
]
[[package]]
name = "jiff"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5d126d72eb017f10b302e73bdeca446bea405ee449af4d9e7866d6b082d83e"
dependencies = [
"jiff-core",
"jiff-static",
"jiff-tzdb-platform",
"log",
"portable-atomic",
"portable-atomic-util",
"serde_core",
"windows-link 0.2.1",
]
[[package]]
name = "jiff-core"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6b46a105a9874634dd96231021526bf24ca04955a5998c59a9c7666e634b7b8"
dependencies = [
"log",
]
[[package]]
name = "jiff-static"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0127e9bde3c6130d6169e7d8d68676e4be69c4bf7573c308b6f960a5089c428"
dependencies = [
"jiff-core",
"proc-macro2",
"quote",
"syn 3.0.5",
]
[[package]]
name = "jiff-tzdb"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc"
[[package]]
name = "jiff-tzdb-platform"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc65b284afcfa8f6cf189c7274c805505314a7ab975c60e1f548bff56525420e"
dependencies = [
"jiff-tzdb",
]
[[package]]
name = "jni"
version = "0.21.1"
@@ -7137,9 +7072,9 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.40.4"
version = "0.40.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e80749408e2d8bec0ffa303012cf4e1b3b355f4a09087b4fdf7473680f6a2de"
checksum = "a86bac2f7d06e6384984118ad727f5694110f0ec44d924d05c8fdec3d030bee6"
dependencies = [
"libc",
"memchr",
@@ -8541,7 +8476,7 @@ dependencies = [
"anyhow",
"compact_str",
"console-subscriber",
"flexi_logger 0.31.10",
"flexi_logger",
"log",
"nu-ansi-term",
"parking_lot 0.12.5",
@@ -10201,9 +10136,9 @@ dependencies = [
[[package]]
name = "zip"
version = "9.7.3"
version = "9.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e50f7b2212e4635244be3c363b53273d159f2523eb7db3096c1d2861c1b603"
checksum = "80cc68510ea7553c30a69c732de5278e94183f68765af6c642dbccefd6ec777e"
dependencies = [
"aes",
"bzip2",
+1 -1
View File
@@ -73,7 +73,7 @@ tokio = { version = "1.54.1", features = [
"time",
"sync",
] }
flexi_logger = "0.32.0"
flexi_logger = "0.31.10"
log = "0.4.35"
reqwest = { version = "0.13.5", features = [
"json",
@@ -12,7 +12,7 @@ parking_lot = { workspace = true }
serde = { workspace = true, features = ["derive"] }
# sysinfo 0.38.2 conflicts with dark-light
# see https://github.com/GuillaumeGomez/sysinfo/issues/1623
sysinfo = { version = "0.40.4", default-features = false, features = ["network", "system"] }
sysinfo = { version = "0.40.3", default-features = false, features = ["network", "system"] }
[target.'cfg(not(windows))'.dependencies]
libc = "0.2.191"
+2 -2
View File
@@ -77,7 +77,7 @@ tauri-plugin-dialog = "2.8.4"
tauri-plugin-fs = "2.7.1"
tauri-plugin-deep-link = "2.6.3"
tauri-plugin-window-state = "2.5.0"
zip = "9.7.3"
zip = "9.6.0"
flate2 = "1.1.11"
reqwest_dav = "0.3.3"
aes-gcm = { version = "0.11.1" }
@@ -101,7 +101,7 @@ tokio-rustls = "0.26.6"
rustls = { version = "0.23.46", features = ["ring"] }
webpki-roots = "1.0.12"
dark-light = "3.0.0"
bytes = "1.12.2"
bytes = "1.12.1"
tokio-util = { version = "0.7.20", features = ["time"] }
specta = { version = "=2.0.0-rc.26", features = ["derive", "function", "serde_json"] }
tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] }
+9 -9
View File
@@ -53,6 +53,15 @@ const StyledTextField = styled(TextField)(({ theme }) => ({
},
}))
const iconStyle = {
style: {
height: '24px',
width: '24px',
cursor: 'pointer',
} as React.CSSProperties,
inheritViewBox: true,
}
const useControllableState = <T,>(options: {
controlled: T | undefined
defaultValue: T
@@ -119,15 +128,6 @@ export const BaseSearchBox = ({
defaultValue: defaultUseRegularExpression,
})
const iconStyle = {
style: {
height: '24px',
width: '24px',
cursor: 'pointer',
} as React.CSSProperties,
inheritViewBox: true,
}
useEffect(() => {
onSearchRef.current = onSearch
}, [onSearch])
+7
View File
@@ -1,6 +1,13 @@
import { styled } from '@mui/material/styles'
import { default as MuiSwitch, SwitchProps } from '@mui/material/Switch'
/**
* MUI Switch delivers the boolean as the second onChange argument, so
* switch handlers use this adapter to stay boolean-only.
*/
export const switchChangeValue = (_event: unknown, value: boolean): boolean =>
value
export const Switch = styled((props: SwitchProps) => (
<MuiSwitch
focusVisibleClassName=".Mui-focusVisible"
+1 -1
View File
@@ -10,7 +10,7 @@ export { BaseSplitChipEditor } from './base-split-chip-editor'
export { BaseStyledSelect } from './base-styled-select'
export { BaseStyledTextField } from './base-styled-text-field'
export { MonacoEditor } from './monaco-editor'
export { Switch } from './base-switch'
export { Switch, switchChangeValue } from './base-switch'
export { TooltipIcon } from './base-tooltip-icon'
export { VirtualList, type VirtualListHandle } from './virtual-list'
export {
+3 -1
View File
@@ -23,6 +23,8 @@ import { emitTestAll } from '@/services/bus'
import { EnhancedCard } from './enhanced-card'
const TEST_LIST_SENSORS = [PointerSensor]
// 自定义滚动条样式
const ScrollBox = styled(Box)(({ theme }) => ({
maxHeight: '180px',
@@ -205,7 +207,7 @@ export const TestCard = () => {
}
>
<ScrollBox>
<DragDropProvider sensors={[PointerSensor]} onDragEnd={onDragEnd}>
<DragDropProvider sensors={TEST_LIST_SENSORS} onDragEnd={onDragEnd}>
{renderTestItems}
</DragDropProvider>
</ScrollBox>
+3 -2
View File
@@ -5,6 +5,8 @@ import { type PointerEvent, useCallback } from 'react'
import { useWindowControls } from '@/hooks/use-window'
import getSystem from '@/utils/get-system'
const OS = getSystem()
const RESIZE_HANDLES = [
{ direction: 'North', position: 'north' },
{ direction: 'NorthEast', position: 'north-east' },
@@ -38,7 +40,7 @@ export const WindowResizeHandles = () => {
[currentWindow],
)
if (getSystem() !== 'linux' || maximized) return null
if (OS !== 'linux' || maximized) return null
return (
<div
@@ -59,7 +61,6 @@ export const WindowResizeHandles = () => {
}
export const WindowControls = () => {
const OS = getSystem()
const { maximized, minimize, close, toggleMaximize } = useWindowControls()
// 通过前端对 tauri 窗口进行翻转全屏时会短暂地与系统图标重叠渲染。
+26 -20
View File
@@ -1,4 +1,5 @@
import { Alert, Box, Typography } from '@mui/material'
import { useMemo } from 'react'
import { Trans, useTranslation } from 'react-i18next'
const stageHints = {
@@ -14,26 +15,31 @@ interface Props {
export const EnhanceHint = ({ stage }: Props) => {
const { t } = useTranslation()
const orderComponents = Object.fromEntries(
Object.keys(stageHints).map((key) => [
key,
<Box
key={key}
component={key === stage ? 'strong' : 'span'}
sx={
key === stage
? {
fontWeight: 'bold',
color: 'primary.contrastText',
bgcolor: 'primary.main',
borderRadius: 0.5,
px: 0.5,
boxDecorationBreak: 'clone',
}
: undefined
}
/>,
]),
// The component map identity changes only when the active stage changes.
const orderComponents = useMemo(
() =>
Object.fromEntries(
Object.keys(stageHints).map((key) => [
key,
<Box
key={key}
component={key === stage ? 'strong' : 'span'}
sx={
key === stage
? {
fontWeight: 'bold',
color: 'primary.contrastText',
bgcolor: 'primary.main',
borderRadius: 0.5,
px: 0.5,
boxDecorationBreak: 'clone',
}
: undefined
}
/>,
]),
),
[stage],
)
return (
@@ -56,6 +56,8 @@ interface GroupedVirtualListProps<T> {
style?: CSSProperties
}
const GROUPED_LIST_SENSORS = [PointerSensor, KeyboardSensor]
/**
* 用于编辑规则/节点/代理组功能的 prepend/original/append 分组虚拟化列表
*/
@@ -141,7 +143,7 @@ export function GroupedVirtualList<T>(props: GroupedVirtualListProps<T>) {
return (
<DragDropProvider
sensors={[PointerSensor, KeyboardSensor]}
sensors={GROUPED_LIST_SENSORS}
onDragStart={onDragStart}
onDragOver={onDragOver}
onDragEnd={onDragEnd}
+5 -2
View File
@@ -112,9 +112,12 @@ export const ProfileMore = (props: Props) => {
document.markSaved(currentValue)
})
// document gets a fresh identity every render; setValue is the stable
// useState setter, so the callback keys on it instead.
const { setValue } = document
const handleResetToDefault = useCallback(() => {
document.setValue(DEFAULT_SCRIPT)
}, [document])
setValue(DEFAULT_SCRIPT)
}, [setValue])
return (
<>
+20 -15
View File
@@ -61,21 +61,26 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
},
})
useImperativeHandle(ref, () => ({
create: () => {
setOpenType('new')
setOpen(true)
},
edit: (item: IProfileItem) => {
if (item) {
Object.entries(item).forEach(([key, value]) => {
setValue(key as any, value)
})
}
setOpenType('edit')
setOpen(true)
},
}))
// The handle only closes over stable form/state setters.
useImperativeHandle(
ref,
() => ({
create: () => {
setOpenType('new')
setOpen(true)
},
edit: (item: IProfileItem) => {
if (item) {
Object.entries(item).forEach(([key, value]) => {
setValue(key as any, value)
})
}
setOpenType('edit')
setOpen(true)
},
}),
[setValue],
)
const handleOk = useLockFn(
handleSubmit(async (form) => {
+3 -4
View File
@@ -57,6 +57,8 @@ const chainPointerSensor = PointerSensor.configure({
activationConstraints: () => undefined,
})
const CHAIN_SENSORS = [chainPointerSensor, KeyboardSensor]
type RuntimeConfigWithProxySequence = IConfigData & { proxies?: unknown }
interface ProxyChainProps {
@@ -665,10 +667,7 @@ export const ProxyChain = ({
</Button>
</Box>
) : (
<DragDropProvider
sensors={[chainPointerSensor, KeyboardSensor]}
onDragEnd={handleDragEnd}
>
<DragDropProvider sensors={CHAIN_SENSORS} onDragEnd={handleDragEnd}>
<Box sx={{ borderRadius: 1, minHeight: 60, p: 1 }}>
{currentProxyChain.map((proxy, index) => (
<SortableProxyChainItem
+113 -110
View File
@@ -17,7 +17,7 @@ import {
} from '@mui/material'
import { useLockFn } from 'ahooks'
import dayjs from 'dayjs'
import { useState } from 'react'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { updateRuleProvider } from 'tauri-plugin-mihomo-api'
@@ -42,6 +42,11 @@ export const ProviderButton = () => {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
const { ruleProviders } = useRulesData()
const sortedProviderEntries = useMemo(
() => Object.entries(ruleProviders || {}).sort(),
[ruleProviders],
)
const { refreshRules, refreshRuleProviders } = useAppRefreshers()
const [updating, setUpdating] = useState<Record<string, boolean>>({})
@@ -166,121 +171,119 @@ export const ProviderButton = () => {
<DialogContent>
<List sx={{ py: 0, minHeight: 250 }}>
{Object.entries(ruleProviders || {})
.sort()
.map(([key, item]) => {
const provider = item
const time = dayjs(provider.updatedAt)
const isUpdating = updating[key]
{sortedProviderEntries.map(([key, item]) => {
const provider = item
const time = dayjs(provider.updatedAt)
const isUpdating = updating[key]
return (
<ListItem
key={key}
sx={[
{
p: 0,
mb: '8px',
borderRadius: 2,
overflow: 'hidden',
transition: 'all 0.2s',
},
({ palette: { mode, primary } }) => {
const bgcolor = mode === 'light' ? '#ffffff' : '#24252f'
const hoverColor =
mode === 'light'
? alpha(primary.main, 0.1)
: alpha(primary.main, 0.2)
return (
<ListItem
key={key}
sx={[
{
p: 0,
mb: '8px',
borderRadius: 2,
overflow: 'hidden',
transition: 'all 0.2s',
},
({ palette: { mode, primary } }) => {
const bgcolor = mode === 'light' ? '#ffffff' : '#24252f'
const hoverColor =
mode === 'light'
? alpha(primary.main, 0.1)
: alpha(primary.main, 0.2)
return {
backgroundColor: bgcolor,
'&:hover': {
backgroundColor: hoverColor,
borderColor: alpha(primary.main, 0.3),
},
}
},
]}
>
<ListItemText
sx={{ px: 2, py: 1 }}
primary={
<Box
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<Typography
variant="subtitle1"
component="div"
noWrap
title={key}
sx={{ display: 'flex', alignItems: 'center' }}
>
<span style={{ marginRight: '8px' }}>{key}</span>
<TypeBox component="span">
{provider.ruleCount}
</TypeBox>
</Typography>
<Typography
variant="body2"
color="text.secondary"
noWrap
>
<small>{t('shared.labels.updateAt')}: </small>
{time.fromNow()}
</Typography>
</Box>
return {
backgroundColor: bgcolor,
'&:hover': {
backgroundColor: hoverColor,
borderColor: alpha(primary.main, 0.3),
},
}
secondary={
<Box sx={{ display: 'flex' }}>
<TypeBox component="span">
{typeof provider.vehicleType === 'string'
? provider.vehicleType
: provider.vehicleType.Unknown}
</TypeBox>
<TypeBox component="span">
{typeof provider.behavior === 'string'
? provider.behavior
: provider.behavior.Unknown}
</TypeBox>
</Box>
}
/>
<Divider orientation="vertical" flexItem />
<Box
sx={{
width: 40,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
<IconButton
size="small"
color="primary"
onClick={() => updateProvider(key)}
disabled={isUpdating}
aria-label={t('rules.page.provider.actions.update')}
},
]}
>
<ListItemText
sx={{ px: 2, py: 1 }}
primary={
<Box
sx={{
animation: isUpdating
? 'spin 1s linear infinite'
: 'none',
'@keyframes spin': {
'0%': { transform: 'rotate(0deg)' },
'100%': { transform: 'rotate(360deg)' },
},
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
title={t('rules.page.provider.actions.update')}
>
<RefreshRounded />
</IconButton>
</Box>
</ListItem>
)
})}
<Typography
variant="subtitle1"
component="div"
noWrap
title={key}
sx={{ display: 'flex', alignItems: 'center' }}
>
<span style={{ marginRight: '8px' }}>{key}</span>
<TypeBox component="span">
{provider.ruleCount}
</TypeBox>
</Typography>
<Typography
variant="body2"
color="text.secondary"
noWrap
>
<small>{t('shared.labels.updateAt')}: </small>
{time.fromNow()}
</Typography>
</Box>
}
secondary={
<Box sx={{ display: 'flex' }}>
<TypeBox component="span">
{typeof provider.vehicleType === 'string'
? provider.vehicleType
: provider.vehicleType.Unknown}
</TypeBox>
<TypeBox component="span">
{typeof provider.behavior === 'string'
? provider.behavior
: provider.behavior.Unknown}
</TypeBox>
</Box>
}
/>
<Divider orientation="vertical" flexItem />
<Box
sx={{
width: 40,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
<IconButton
size="small"
color="primary"
onClick={() => updateProvider(key)}
disabled={isUpdating}
aria-label={t('rules.page.provider.actions.update')}
sx={{
animation: isUpdating
? 'spin 1s linear infinite'
: 'none',
'@keyframes spin': {
'0%': { transform: 'rotate(0deg)' },
'100%': { transform: 'rotate(360deg)' },
},
}}
title={t('rules.page.provider.actions.update')}
>
<RefreshRounded />
</IconButton>
</Box>
</ListItem>
)
})}
</List>
</DialogContent>
@@ -42,6 +42,8 @@ const HOTKEY_FUNC_LABELS: Record<(typeof HOTKEY_FUNC)[number], string> = {
reactivate_profiles: 'settings.modals.hotkey.functions.reactivateProfiles',
}
const EMPTY_KEYS: string[] = []
export const HotkeyViewer = forwardRef<DialogRef>((props, ref) => {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
@@ -132,7 +134,7 @@ export const HotkeyViewer = forwardRef<DialogRef>((props, ref) => {
<ItemWrapper key={func} data-setting-target={HOTKEY_FUNC_LABELS[func]}>
<Typography>{t(HOTKEY_FUNC_LABELS[func])}</Typography>
<HotkeyInput
value={hotkeyMap[func] ?? []}
value={hotkeyMap[func] ?? EMPTY_KEYS}
onChange={(v) => setHotkeyMap((m) => ({ ...m, [func]: v }))}
/>
</ItemWrapper>
+17 -12
View File
@@ -17,7 +17,13 @@ import { exists } from '@tauri-apps/plugin-fs'
import { forwardRef, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { BaseDialog, DialogRef, Switch, TooltipIcon } from '@/components/base'
import {
BaseDialog,
DialogRef,
Switch,
TooltipIcon,
switchChangeValue,
} from '@/components/base'
import { DEFAULT_HOVER_DELAY } from '@/components/proxy/proxy-group-navigator'
import { useVerge } from '@/hooks/use-verge'
import { useWindowDecorations } from '@/hooks/use-window'
@@ -104,7 +110,6 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
close: () => setOpen(false),
}))
const onSwitchFormat = (_e: any, value: boolean) => value
const onError = (err: any) => {
showNotice.error(err)
}
@@ -134,7 +139,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={decorated}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onFormat={switchChangeValue}
onChange={async () => {
await toggleDecorations()
}}
@@ -151,7 +156,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.traffic_graph ?? true}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onFormat={switchChangeValue}
onChange={(e) => onChangeData({ traffic_graph: e })}
onGuard={(e) => patchVerge({ traffic_graph: e })}
>
@@ -167,7 +172,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.enable_memory_usage ?? true}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onFormat={switchChangeValue}
onChange={(e) => onChangeData({ enable_memory_usage: e })}
onGuard={(e) => patchVerge({ enable_memory_usage: e })}
>
@@ -185,7 +190,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.enable_group_icon ?? true}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onFormat={switchChangeValue}
onChange={(e) => onChangeData({ enable_group_icon: e })}
onGuard={(e) => patchVerge({ enable_group_icon: e })}
>
@@ -203,7 +208,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.pause_render_traffic_stats_on_blur ?? true}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onFormat={switchChangeValue}
onChange={(e) =>
onChangeData({ pause_render_traffic_stats_on_blur: e })
}
@@ -271,7 +276,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.enable_hover_jump_navigator ?? true}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onFormat={switchChangeValue}
onChange={(e) => onChangeData({ enable_hover_jump_navigator: e })}
onGuard={(e) => patchVerge({ enable_hover_jump_navigator: e })}
>
@@ -373,7 +378,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.collapse_navbar ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onFormat={switchChangeValue}
onChange={(e) => onChangeData({ collapse_navbar: e })}
onGuard={(e) => patchVerge({ collapse_navbar: e })}
>
@@ -420,7 +425,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.enable_tray_speed ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onFormat={switchChangeValue}
onChange={(e) => onChangeData({ enable_tray_speed: e })}
onGuard={(e) => patchVerge({ enable_tray_speed: e })}
>
@@ -440,7 +445,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onFormat={switchChangeValue}
onChange={(e) => onChangeData({ enable_tray_icon: e })}
onGuard={(e) => patchVerge({ enable_tray_icon: e })}
>
@@ -494,7 +499,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.tray_inline_outbound_modes ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onFormat={switchChangeValue}
onChange={(e) => onChangeData({ tray_inline_outbound_modes: e })}
onGuard={(e) => patchVerge({ tray_inline_outbound_modes: e })}
>
+54 -35
View File
@@ -8,7 +8,7 @@ import {
TextField,
} from '@mui/material'
import { useLockFn } from 'ahooks'
import { forwardRef, useState } from 'react'
import { forwardRef, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { BaseDialog, DialogRef, Switch, TooltipIcon } from '@/components/base'
@@ -17,6 +17,20 @@ import { showNotice } from '@/services/notice-service'
import { useSettingDialog } from '../settings-search-context'
const APP_LOG_LEVEL_OPTIONS = [
'trace',
'debug',
'info',
'warn',
'error',
'silent',
].map((level) => ({
value: level,
label: level[0].toUpperCase() + level.slice(1).toLowerCase(),
}))
const PROXY_LAYOUT_COLUMN_VALUES = [1, 2, 3, 4, 5]
const buildInitialValues = (verge?: IVergeConfig | null) => ({
appLogLevel: verge?.app_log_level ?? 'warn',
appLogMaxSize: verge?.app_log_max_size ?? 128,
@@ -38,6 +52,40 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
const { t } = useTranslation()
const { verge, patchVerge } = useVerge()
const autoLogCleanOptions = useMemo(
() => [
{
key: t('settings.modals.misc.options.autoLogClean.never'),
value: 0,
},
{
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
n: 1,
}),
value: 1,
},
{
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
n: 7,
}),
value: 2,
},
{
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
n: 30,
}),
value: 3,
},
{
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
n: 90,
}),
value: 4,
},
],
[t],
)
const [open, setOpen] = useState(false)
const [values, setValues] = useState(() => buildInitialValues(null))
@@ -104,9 +152,9 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
}))
}
>
{['trace', 'debug', 'info', 'warn', 'error', 'silent'].map((i) => (
<MenuItem value={i} key={i}>
{i[0].toUpperCase() + i.slice(1).toLowerCase()}
{APP_LOG_LEVEL_OPTIONS.map(({ value, label }) => (
<MenuItem value={value} key={value}>
{label}
</MenuItem>
))}
</Select>
@@ -285,7 +333,7 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
<MenuItem value={6} key={6}>
{t('settings.modals.misc.options.proxyLayoutColumns.auto')}
</MenuItem>
{[1, 2, 3, 4, 5].map((i) => (
{PROXY_LAYOUT_COLUMN_VALUES.map((i) => (
<MenuItem value={i} key={i}>
{i}
</MenuItem>
@@ -312,36 +360,7 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
}
>
{/* 1: 1天, 2: 7天, 3: 30天, 4: 90天*/}
{[
{
key: t('settings.modals.misc.options.autoLogClean.never'),
value: 0,
},
{
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
n: 1,
}),
value: 1,
},
{
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
n: 7,
}),
value: 2,
},
{
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
n: 30,
}),
value: 3,
},
{
key: t('settings.modals.misc.options.autoLogClean.retainDays', {
n: 90,
}),
value: 4,
},
].map((i) => (
{autoLogCleanOptions.map((i) => (
<MenuItem key={i.value} value={i.value}>
{i.key}
</MenuItem>
+17 -15
View File
@@ -84,6 +84,19 @@ const splitBypass = (value?: string) =>
.map((item) => item.trim())
.filter(Boolean)
const OS = getSystem()
const DEFAULT_BYPASS =
OS === 'windows'
? 'localhost;127.*;192.168.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;*.local;<local>'
: OS === 'linux'
? 'localhost,127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,::1'
: '127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,localhost,*.local,*.crashlytics.com,<local>'
const DEFAULT_BYPASS_CHIPS = splitBypass(DEFAULT_BYPASS)
const BYPASS_SEPARATOR = OS === 'windows' ? ';' : ','
const buildInitialValues = (verge?: IVergeConfig | null) => ({
guard: verge?.enable_proxy_guard,
enable_bypass_check: verge?.enable_bypass_check ?? true,
@@ -97,8 +110,7 @@ const buildInitialValues = (verge?: IVergeConfig | null) => ({
export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
const { t } = useTranslation()
const systemName = getSystem()
const isWindows = systemName === 'windows'
const isWindows = OS === 'windows'
const validReg = useMemo(() => getValidReg(isWindows), [isWindows])
const [open, setOpen] = useState(false)
@@ -130,17 +142,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
queryFn: getEmbeddedServerPort,
})
const separator = useMemo(() => (isWindows ? ';' : ','), [isWindows])
const defaultBypass = () => {
if (isWindows) {
return 'localhost;127.*;192.168.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;*.local;<local>'
}
if (systemName === 'linux') {
return 'localhost,127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,::1'
}
return '127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,localhost,*.local,*.crashlytics.com,<local>'
}
const separator = BYPASS_SEPARATOR
const { systemProxyAddress } = useSystemData()
const displayedMixedPort = useDisplayedMixedPort()
@@ -503,7 +505,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
checked={value.use_default}
onChange={(_, e) => {
if (!e && !value.bypass) {
const nextBypass = defaultBypass()
const nextBypass = DEFAULT_BYPASS
setValue((v) => ({
...v,
use_default: e,
@@ -575,7 +577,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
/>
<Box sx={{ padding: '0 2px 5px' }}>
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
{splitBypass(defaultBypass()).map((item) => (
{DEFAULT_BYPASS_CHIPS.map((item) => (
<Chip key={item} label={item} size="small" />
))}
</Box>
+6 -6
View File
@@ -20,6 +20,12 @@ import { showNotice } from '@/services/notice-service'
import { useSettingDialog } from '../settings-search-context'
const textProps = {
size: 'small',
autoComplete: 'off',
sx: { width: 135 },
} as const
export function ThemeViewer(props: { ref?: React.Ref<DialogRef> }) {
const { ref } = props
const { t } = useTranslation()
@@ -45,12 +51,6 @@ export function ThemeViewer(props: { ref?: React.Ref<DialogRef> }) {
close: () => setOpen(false),
}))
const textProps = {
size: 'small',
autoComplete: 'off',
sx: { width: 135 },
} as const
const handleChange = (field: keyof typeof theme) => (e: any) => {
setTheme((t) => ({ ...t, [field]: e.target.value }))
}
+4 -3
View File
@@ -9,7 +9,7 @@ import {
} from '@mui/material'
import { useLockFn } from 'ahooks'
import type { Ref } from 'react'
import { useState } from 'react'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
@@ -58,8 +58,9 @@ export function TunViewer({ ref }: { ref?: Ref<DialogRef> }) {
dnsMode: '',
})
const routeExcludeAddressItems = splitRouteExcludeAddress(
values.routeExcludeAddress,
const routeExcludeAddressItems = useMemo(
() => splitRouteExcludeAddress(values.routeExcludeAddress),
[values.routeExcludeAddress],
)
const routeExcludeAddressError =
values.autoRoute &&
@@ -189,10 +189,7 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
void openExternalUrl(url).catch(showNotice.error)
}
const progress = useMemo(() => {
if (total <= 0) return 0
return Math.min((downloaded / total) * 100, 100)
}, [downloaded, total])
const progress = total <= 0 ? 0 : Math.min((downloaded / total) * 100, 100)
useImperativeHandle(ref, () => ({
open: () => {
+10 -5
View File
@@ -5,7 +5,13 @@ import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { updateGeo, type LogLevel } from 'tauri-plugin-mihomo-api'
import { BaseDialog, DialogRef, Switch, TooltipIcon } from '@/components/base'
import {
BaseDialog,
DialogRef,
Switch,
TooltipIcon,
switchChangeValue,
} from '@/components/base'
import { useClash } from '@/hooks/use-clash'
import { useClashLog } from '@/hooks/use-clash-log'
import { useDisplayedMixedPort } from '@/hooks/use-displayed-mixed-port'
@@ -69,7 +75,6 @@ const SettingClash = ({ onError }: Props) => {
const corsRef = useRef<DialogRef>(null)
const tunnelRef = useRef<DialogRef>(null)
const onSwitchFormat = (_e: any, value: boolean) => value
const onChangeData = (patch: Partial<IConfigData>) => {
mutateClash((old) => ({ ...old!, ...patch }), false)
}
@@ -173,7 +178,7 @@ const SettingClash = ({ onError }: Props) => {
value={allowLan ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onFormat={switchChangeValue}
onChange={(e) => onChangeData({ 'allow-lan': e })}
onGuard={(e) => patchClash({ 'allow-lan': e })}
>
@@ -213,7 +218,7 @@ const SettingClash = ({ onError }: Props) => {
value={ipv6 ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onFormat={switchChangeValue}
onChange={(e) => onChangeData({ ipv6: e })}
onGuard={(e) => patchClash({ ipv6: e })}
>
@@ -235,7 +240,7 @@ const SettingClash = ({ onError }: Props) => {
value={unifiedDelay ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onFormat={switchChangeValue}
onChange={(e) => onChangeData({ 'unified-delay': e })}
onGuard={(e) => patchClash({ 'unified-delay': e })}
>
+3 -8
View File
@@ -1,8 +1,7 @@
import { Box } from '@mui/material'
import React from 'react'
import { useTranslation } from 'react-i18next'
import { Switch, TooltipIcon } from '@/components/base'
import { Switch, TooltipIcon, switchChangeValue } from '@/components/base'
import ProxyControlSwitches from '@/components/shared/proxy-control-switches'
import { useVerge } from '@/hooks/use-verge'
@@ -20,10 +19,6 @@ const SettingSystem = ({ onError }: Props) => {
const { enable_auto_launch, enable_silent_start } = verge ?? {}
const onSwitchFormat = (
_e: React.ChangeEvent<HTMLInputElement>,
value: boolean,
) => value
const onChangeData = (patch: Partial<IVergeConfig>) => {
mutateVerge({ ...verge, ...patch })
}
@@ -52,7 +47,7 @@ const SettingSystem = ({ onError }: Props) => {
value={enable_auto_launch ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onFormat={switchChangeValue}
onChange={(e) => {
onChangeData({ enable_auto_launch: e })
}}
@@ -85,7 +80,7 @@ const SettingSystem = ({ onError }: Props) => {
value={enable_silent_start ?? false}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onFormat={switchChangeValue}
onChange={(e) => onChangeData({ enable_silent_start: e })}
onGuard={(e) => patchVerge({ enable_silent_start: e })}
>
+22 -12
View File
@@ -1,5 +1,6 @@
import { useLockFn } from 'ahooks'
import i18n from 'i18next'
import { useCallback } from 'react'
import { getVersion } from 'tauri-plugin-mihomo-api'
import {
@@ -86,23 +87,29 @@ export const useClashMode = (shouldFetch: boolean = true) => {
}
export const useClash = () => {
const { data: clash, refetch } = useRuntimeConfig()
const { data: clash } = useRuntimeConfig()
const { data: versionData, refetch: mutateVersion } = useQuery({
queryKey: ['getVersion'],
queryFn: getVersion,
})
const mutateClash = (updater?: MutateClashUpdater, revalidate?: boolean) => {
if (updater === undefined) {
return refetch()
}
void setCacheData<IConfigData>(['getRuntimeConfig'], updater)
if (revalidate !== false) {
return refetch()
}
return Promise.resolve()
}
// Stable identity: consumers pass mutateClash into their own callbacks.
// revalidateQuery hits the same cache key refetch would, without capturing
// the per-render refetch closure.
const mutateClash = useCallback(
(updater?: MutateClashUpdater, revalidate?: boolean) => {
if (updater === undefined) {
return revalidateQuery(['getRuntimeConfig'])
}
void setCacheData<IConfigData>(['getRuntimeConfig'], updater)
if (revalidate !== false) {
return revalidateQuery(['getRuntimeConfig'])
}
return Promise.resolve()
},
[],
)
const patchClash = useLockFn(async (patch: Partial<IConfigData>) => {
await mutate(() => patchClashConfig(patch), {
@@ -143,7 +150,10 @@ export const useClashInfo = () => {
})
})
const invalidateClashConfig = () => revalidateQuery(['getClashConfig'])
const invalidateClashConfig = useCallback(
() => revalidateQuery(['getClashConfig']),
[],
)
return {
clashInfo,
+2 -2
View File
@@ -1,4 +1,4 @@
import { useCallback, useSyncExternalStore } from 'react'
import { useCallback, useMemo, useSyncExternalStore } from 'react'
import delayManager, { type DelaySnapshot } from '@/services/delay'
import type { ResolvedProxyMember } from '@/types/proxy-view'
@@ -32,7 +32,7 @@ export const useGroupsDelays = (
groups: readonly string[],
): ReadonlyMap<string, DelaySnapshot> => {
// Group membership must remain unambiguous when names contain spaces.
const groupKey = JSON.stringify(groups)
const groupKey = useMemo(() => JSON.stringify(groups), [groups])
const subscribe = useCallback(
(onSettle: () => void) => {
+6 -4
View File
@@ -177,13 +177,15 @@ export async function getProxyView(): Promise<ProxyViewV1> {
return view
}
// getClashLogs matches both patterns against every log line.
const CLASH_LOG_REGEX = /time="(.+?)"\s+level=(.+?)\s+msg="(.+?)"/
const CLASH_LOG_NEW_REGEX = /(.+?)\s+(.+?)\s+(.+)/
export async function getClashLogs() {
const regex = /time="(.+?)"\s+level=(.+?)\s+msg="(.+?)"/
const newRegex = /(.+?)\s+(.+?)\s+(.+)/
const logs = await commands.getClashLogs()
return logs.reduce<ILogItem[]>((acc, log) => {
const result = log.match(regex)
const result = log.match(CLASH_LOG_REGEX)
if (result) {
const [_, _time, type, payload] = result
const time = dayjs(_time).format('MM-DD HH:mm:ss')
@@ -191,7 +193,7 @@ export async function getClashLogs() {
return acc
}
const result2 = log.match(newRegex)
const result2 = log.match(CLASH_LOG_NEW_REGEX)
if (result2) {
const [_, time, type, payload] = result2
acc.push({ time, type, payload })
+15 -3
View File
@@ -514,9 +514,21 @@ export function hideNotice(id: number) {
}
function hideNoticesByCode(code: string) {
notices
.filter((notice) => notice.code === code)
.forEach(({ id }) => hideNotice(id))
// One subscriber notification for the whole batch; per-notice removal
// would notify once per item.
const remaining: NoticeItem[] = []
let removed = false
for (const notice of notices) {
if (notice.code === code) {
removed = true
if (notice.timerId) clearTimeout(notice.timerId)
} else {
remaining.push(notice)
}
}
if (!removed) return
notices = remaining
notifySubscribers()
}
export function syncSidecarFailure(snapshot: SidecarFailureSnapshot) {
+7 -7
View File
@@ -241,17 +241,17 @@ export function parseUrlLike(
: result
}
// Both predicates run per parsed proxy URI.
const IPV4_REGEX = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/
const IPV6_REGEX =
/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::$|^::1$|^([0-9a-fA-F]{1,4}:)*::([0-9a-fA-F]{1,4}:)*[0-9a-fA-F]{1,4}$/
export function isIPv4(address: string): boolean {
// Check if the address is IPv4
const ipv4Regex = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/
return ipv4Regex.test(address)
return IPV4_REGEX.test(address)
}
export function isIPv6(address: string): boolean {
// Check if the address is IPv6 - simplified regex to avoid backreference issues
const ipv6Regex =
/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::$|^::1$|^([0-9a-fA-F]{1,4}:)*::([0-9a-fA-F]{1,4}:)*[0-9a-fA-F]{1,4}$/
return ipv6Regex.test(address)
return IPV6_REGEX.test(address)
}
export function decodeBase64OrOriginal(str: string): string {