Compare commits

..
Author SHA1 Message Date
Tunglies f0e1460a04 perf(home): build traffic range snapshots in one pass
The 200ms graph snapshot built three to four intermediate arrays on the
compressed path before posting to the worker. It now fills one
preallocated result in a single pass and only sorts when the compressed
and raw ranges actually interleave.
2026-11-19 21:46:06 +08:00
Tunglies e90f8c500f perf(log): reuse the empty logs fallback identity
A fresh [] fallback gave the subscription hook's refresh callback and
snapshot effect a new identity on every render while logs streamed; the
empty list is now a shared module constant.
2026-11-19 21:46:04 +08:00
Tunglies 36f79c6033 perf(proxy): stable group location and chain list identities
The sticky-header scroll callback depended on the render list identity,
re-creating the item renderer on every list rebuild; it now reads the
list through a stable ref callback. Rebinding no longer allocates new
chain items and arrays when values are unchanged, so the 15s proxy-view
refresh stops re-serializing identical chains to localStorage, and the
chain delay key join is memoized.
2026-11-19 21:45:54 +08:00
Tunglies d535c1b7d1 perf(proxy): stable tool callbacks and shared delay entries
Group headers and heads passed freshly-created closures into the
memoized tools, defeating it on every render; the tool callbacks are now
groupName-parameterized and forwarded directly. Cached delay entries are
write-once, so the defensive copy on read and the second copy in the
delay-state reducer were dropped.
2026-11-19 21:45:45 +08:00
Tunglies d162478100 perf(ui): hoist static dialog identities and memoize settings search
The DNS viewer rebuilt Monaco's options object per keystroke, the update
dialog rebuilt its markdown component map and plugin array per progress
chunk (remounting link and blockquote subtrees), and the settings search
rescanned the ~180-entry catalog on unrelated renders such as arrow-key
selection. These identities are now module constants or single memos;
the width-dependent minimap option is applied at editor mount.
2026-11-19 21:45:34 +08:00
Tunglies f4761e763a perf(ui): keep mutateVerge identity stable across renders
mutateVerge was a per-render closure that dozens of consumer callbacks
depended on, and its updater fell back to a render-time config snapshot.
It now keeps a stable identity, revalidates through the module-level
query helper, and passes the live cache value (preload snapshot when the
cache is still empty) to function updaters; object-form callers were
migrated to updater functions.
2026-11-19 21:45:27 +08:00
Tunglies 01e28608ef perf(profile): derive editor policy names and dedupe pasted proxies
The groups editor re-read both profile files and re-parsed three YAML
documents on every prepend/append/delete edit. The origin names are now
read once per open and folded into a memoized policy list, and batch
pasted proxy names dedupe through a Set instead of a linear scan.
2026-11-19 21:45:19 +08:00
Tunglies 0013fb3680 perf(profile): stabilize profile grid callbacks and context menus
ProfileItem is memoized, but the grid passed five freshly-created closure
props per render, so URL keystrokes and switch spinners re-rendered every
card. The callbacks are now uid/item-parameterized stable handlers, and
the context-menu label map and item literals are hoisted or gated on the
menu being open.
2026-11-19 21:45:05 +08:00
47 changed files with 884 additions and 818 deletions
+1
View File
@@ -63,6 +63,7 @@
<details>
<summary><strong> 🚀 优化改进 </strong></summary>
- 优化首页流量图与代理、订阅、日志、设置页面的渲染效率,长列表滚动与实时刷新更流畅
- 优化连接、规则和日志筛选:切换页面后保留过滤条件
- 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组
- 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件
+9 -9
View File
@@ -53,15 +53,6 @@ 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
@@ -128,6 +119,15 @@ 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,13 +1,6 @@
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, switchChangeValue } from './base-switch'
export { Switch } from './base-switch'
export { TooltipIcon } from './base-tooltip-icon'
export { VirtualList, type VirtualListHandle } from './virtual-list'
export {
+7 -9
View File
@@ -23,8 +23,6 @@ import { emitTestAll } from '@/services/bus'
import { EnhancedCard } from './enhanced-card'
const TEST_LIST_SENSORS = [PointerSensor]
// 自定义滚动条样式
const ScrollBox = styled(Box)(({ theme }) => ({
maxHeight: '180px',
@@ -89,18 +87,18 @@ export const TestCard = () => {
x.uid === uid ? { ...x, ...patch } : x,
)
mutateVerge({ ...verge, test_list: newList })
mutateVerge((prev) => ({ ...prev, test_list: newList }))
},
[testList, verge, mutateVerge],
[testList, mutateVerge],
)
const onDeleteTestListItem = useCallback(
(uid: string) => {
const newList = testList.filter((x) => x.uid !== uid)
patchVerge({ test_list: newList })
mutateVerge({ ...verge, test_list: newList })
mutateVerge((prev) => ({ ...prev, test_list: newList }))
},
[testList, verge, patchVerge, mutateVerge],
[testList, patchVerge, mutateVerge],
)
const onDragEnd = useCallback(
@@ -131,7 +129,7 @@ export const TestCard = () => {
newList.splice(newIndex, 0, removed)
// 优化:先本地更新,再异步 patch,避免UI卡死
mutateVerge({ ...verge, test_list: newList })
mutateVerge((prev) => ({ ...prev, test_list: newList }))
const patchFn = () => {
try {
patchVerge({ test_list: newList })
@@ -143,7 +141,7 @@ export const TestCard = () => {
setTimeout(patchFn, 0)
}
},
[testList, verge, mutateVerge, patchVerge],
[testList, mutateVerge, patchVerge],
)
// 仅在verge首次加载时初始化测试列表
@@ -207,7 +205,7 @@ export const TestCard = () => {
}
>
<ScrollBox>
<DragDropProvider sensors={TEST_LIST_SENSORS} onDragEnd={onDragEnd}>
<DragDropProvider sensors={[PointerSensor]} onDragEnd={onDragEnd}>
{renderTestItems}
</DragDropProvider>
</ScrollBox>
+2 -3
View File
@@ -5,8 +5,6 @@ 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' },
@@ -40,7 +38,7 @@ export const WindowResizeHandles = () => {
[currentWindow],
)
if (OS !== 'linux' || maximized) return null
if (getSystem() !== 'linux' || maximized) return null
return (
<div
@@ -61,6 +59,7 @@ export const WindowResizeHandles = () => {
}
export const WindowControls = () => {
const OS = getSystem()
const { maximized, minimize, close, toggleMaximize } = useWindowControls()
// 通过前端对 tauri 窗口进行翻转全屏时会短暂地与系统图标重叠渲染。
+20 -26
View File
@@ -1,5 +1,4 @@
import { Alert, Box, Typography } from '@mui/material'
import { useMemo } from 'react'
import { Trans, useTranslation } from 'react-i18next'
const stageHints = {
@@ -15,31 +14,26 @@ interface Props {
export const EnhanceHint = ({ stage }: Props) => {
const { t } = useTranslation()
// 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],
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
}
/>,
]),
)
return (
@@ -56,8 +56,6 @@ interface GroupedVirtualListProps<T> {
style?: CSSProperties
}
const GROUPED_LIST_SENSORS = [PointerSensor, KeyboardSensor]
/**
* 用于编辑规则/节点/代理组功能的 prepend/original/append 分组虚拟化列表
*/
@@ -143,7 +141,7 @@ export function GroupedVirtualList<T>(props: GroupedVirtualListProps<T>) {
return (
<DragDropProvider
sensors={GROUPED_LIST_SENSORS}
sensors={[PointerSensor, KeyboardSensor]}
onDragStart={onDragStart}
onDragOver={onDragOver}
onDragEnd={onDragEnd}
+23 -11
View File
@@ -176,7 +176,10 @@ export const GroupsEditorViewer = (props: Props) => {
},
})
const [groupList, setGroupList] = useState<IProxyGroupConfig[]>([])
const [proxyPolicyList, setProxyPolicyList] = useState<string[]>([])
const [originPolicy, setOriginPolicy] = useState<{
proxyNames: string[]
groupNames: string[]
}>({ proxyNames: [], groupNames: [] })
const [proxyProviderList, setProxyProviderList] = useState<string[]>([])
const [prependSeq, setPrependSeq] = useState<IProxyGroupConfig[]>([])
const [appendSeq, setAppendSeq] = useState<IProxyGroupConfig[]>([])
@@ -353,6 +356,9 @@ export const GroupsEditorViewer = (props: Props) => {
}
}, [prependSeq, appendSeq, deleteSeq])
// Origin policy names come from profile files that this dialog never
// rewrites while open, so they are read once per open; the live seq states
// are folded in by the derived proxyPolicyList below.
const fetchProxyPolicy = useCallback(async () => {
const data = await readProfileFile(profileUid)
const proxiesData = await readProfileFile(proxiesUid)
@@ -388,17 +394,13 @@ export const GroupsEditorViewer = (props: Props) => {
(name): name is string => typeof name === 'string' && name.length > 0,
)
const computedPolicyList = builtinProxyPolicies.concat(
prependSeq.map((group: IProxyGroupConfig) => group.name),
(originGroupsObj?.['proxy-groups'] || [])
.map((group: IProxyGroupConfig) => group.name)
.filter((name) => !deleteSeq.includes(name)),
appendSeq.map((group: IProxyGroupConfig) => group.name),
setOriginPolicy({
proxyNames,
)
setProxyPolicyList(Array.from(new Set(computedPolicyList)))
}, [appendSeq, deleteSeq, prependSeq, profileUid, proxiesUid])
groupNames: (originGroupsObj?.['proxy-groups'] || []).map(
(group) => group.name,
),
})
}, [profileUid, proxiesUid])
const fetchProfile = useCallback(async () => {
const data = await readProfileFile(profileUid)
const mergeData = await readProfileFile(mergeUid)
@@ -442,6 +444,16 @@ export const GroupsEditorViewer = (props: Props) => {
fetchProxyPolicy()
}, [fetchProxyPolicy, open])
const proxyPolicyList = useMemo(() => {
const computedPolicyList = builtinProxyPolicies.concat(
prependSeq.map((group) => group.name),
originPolicy.groupNames.filter((name) => !deleteSeq.includes(name)),
appendSeq.map((group) => group.name),
originPolicy.proxyNames,
)
return Array.from(new Set(computedPolicyList))
}, [appendSeq, deleteSeq, originPolicy, prependSeq])
useEffect(() => {
if (!open) return
fetchContent()
+194 -186
View File
@@ -61,6 +61,31 @@ const round = keyframes`
to { transform: rotate(360deg); }
`
type ContextMenuItem = {
label: string
handler: () => void
disabled: boolean
}
const menuLabels: Record<string, TranslationKey> = {
home: 'profiles.components.menu.home',
select: 'profiles.components.menu.select',
shareQrCode: 'profiles.components.menu.shareQrCode',
editInfo: 'profiles.components.menu.editInfo',
editFile: 'profiles.components.menu.editFile',
editRules: 'profiles.components.menu.editRules',
editProxies: 'profiles.components.menu.editProxies',
editGroups: 'profiles.components.menu.editGroups',
extendConfig: 'profiles.components.menu.extendConfig',
extendScript: 'profiles.components.menu.extendScript',
openFile: 'profiles.components.menu.openFile',
update: 'profiles.components.menu.update',
updateViaProxy: 'profiles.components.menu.updateViaProxy',
delete: 'shared.actions.delete',
} as const
const EMPTY_CONTEXT_MENU: ContextMenuItem[] = []
export interface ProfileItemProps {
id: string
index: number
@@ -68,13 +93,13 @@ export interface ProfileItemProps {
activating: boolean
itemData: IProfileItem
mutateProfiles: () => Promise<void>
onSelect: (force: boolean) => void
onEdit: () => void
onSave?: (prev?: string, curr?: string) => void
onDelete: () => void
onSelect: (uid: string, force: boolean) => void
onEdit: (item: IProfileItem) => void
onSave?: (uid: string, prev?: string, curr?: string) => void
onDelete: (uid: string) => void
batchMode?: boolean
isSelected?: boolean
onSelectionChange?: () => void
onSelectionChange?: (uid: string) => void
timerUpdateRevision: number
completedUpdateRevision: number
}
@@ -322,7 +347,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const onEditInfo = () => {
setAnchorEl(null)
onEdit()
onEdit(itemData)
}
const onShareQrCode = () => {
@@ -362,7 +387,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const onForceSelect = () => {
setAnchorEl(null)
onSelect(true)
onSelect(id, true)
}
const onOpenFile = useLockFn(async () => {
@@ -412,175 +437,158 @@ const ProfileItemBase = (props: ProfileItemProps) => {
}
})
type ContextMenuItem = {
label: string
handler: () => void
disabled: boolean
}
const menuLabels: Record<string, TranslationKey> = {
home: 'profiles.components.menu.home',
select: 'profiles.components.menu.select',
shareQrCode: 'profiles.components.menu.shareQrCode',
editInfo: 'profiles.components.menu.editInfo',
editFile: 'profiles.components.menu.editFile',
editRules: 'profiles.components.menu.editRules',
editProxies: 'profiles.components.menu.editProxies',
editGroups: 'profiles.components.menu.editGroups',
extendConfig: 'profiles.components.menu.extendConfig',
extendScript: 'profiles.components.menu.extendScript',
openFile: 'profiles.components.menu.openFile',
update: 'profiles.components.menu.update',
updateViaProxy: 'profiles.components.menu.updateViaProxy',
delete: 'shared.actions.delete',
} as const
const urlModeMenu: ContextMenuItem[] = [
...(hasHome
? [
{
label: menuLabels.home,
handler: onOpenHome,
disabled: false,
} satisfies ContextMenuItem,
]
: []),
{
label: menuLabels.select,
handler: onForceSelect,
disabled: false,
},
{
label: menuLabels.shareQrCode,
handler: onShareQrCode,
disabled: false,
},
{
label: menuLabels.editInfo,
handler: onEditInfo,
disabled: false,
},
{
label: menuLabels.editFile,
handler: onEditFile,
disabled: false,
},
{
label: menuLabels.editRules,
handler: onEditRules,
disabled: !option?.rules,
},
{
label: menuLabels.editProxies,
handler: onEditProxies,
disabled: !option?.proxies,
},
{
label: menuLabels.editGroups,
handler: onEditGroups,
disabled: !option?.groups,
},
{
label: menuLabels.extendConfig,
handler: onEditMerge,
disabled: !option?.merge,
},
{
label: menuLabels.extendScript,
handler: onEditScript,
disabled: !option?.script,
},
{
label: menuLabels.openFile,
handler: onOpenFile,
disabled: false,
},
{
label: menuLabels.update,
handler: () => onUpdate(0),
disabled: false,
},
{
label: menuLabels.updateViaProxy,
handler: () => onUpdate(2),
disabled: false,
},
{
label: menuLabels.delete,
handler: () => {
setAnchorEl(null)
if (batchMode) {
if (onSelectionChange) {
onSelectionChange()
}
} else {
setConfirmOpen(true)
}
},
disabled: false,
},
]
const fileModeMenu: ContextMenuItem[] = [
{
label: menuLabels.select,
handler: onForceSelect,
disabled: false,
},
{
label: menuLabels.editInfo,
handler: onEditInfo,
disabled: false,
},
{
label: menuLabels.editFile,
handler: onEditFile,
disabled: false,
},
{
label: menuLabels.editRules,
handler: onEditRules,
disabled: !option?.rules,
},
{
label: menuLabels.editProxies,
handler: onEditProxies,
disabled: !option?.proxies,
},
{
label: menuLabels.editGroups,
handler: onEditGroups,
disabled: !option?.groups,
},
{
label: menuLabels.extendConfig,
handler: onEditMerge,
disabled: !option?.merge,
},
{
label: menuLabels.extendScript,
handler: onEditScript,
disabled: !option?.script,
},
{
label: menuLabels.openFile,
handler: onOpenFile,
disabled: false,
},
{
label: menuLabels.delete,
handler: () => {
setAnchorEl(null)
if (batchMode) {
if (onSelectionChange) {
onSelectionChange()
}
} else {
setConfirmOpen(true)
}
},
disabled: false,
},
]
// The context menu is closed on almost every render; building its items
// only while open keeps the idle path allocation-free.
const menuItems: ContextMenuItem[] =
anchorEl === null
? EMPTY_CONTEXT_MENU
: hasUrl
? [
...(hasHome
? [
{
label: menuLabels.home,
handler: onOpenHome,
disabled: false,
} satisfies ContextMenuItem,
]
: []),
{
label: menuLabels.select,
handler: onForceSelect,
disabled: false,
},
{
label: menuLabels.shareQrCode,
handler: onShareQrCode,
disabled: false,
},
{
label: menuLabels.editInfo,
handler: onEditInfo,
disabled: false,
},
{
label: menuLabels.editFile,
handler: onEditFile,
disabled: false,
},
{
label: menuLabels.editRules,
handler: onEditRules,
disabled: !option?.rules,
},
{
label: menuLabels.editProxies,
handler: onEditProxies,
disabled: !option?.proxies,
},
{
label: menuLabels.editGroups,
handler: onEditGroups,
disabled: !option?.groups,
},
{
label: menuLabels.extendConfig,
handler: onEditMerge,
disabled: !option?.merge,
},
{
label: menuLabels.extendScript,
handler: onEditScript,
disabled: !option?.script,
},
{
label: menuLabels.openFile,
handler: onOpenFile,
disabled: false,
},
{
label: menuLabels.update,
handler: () => onUpdate(0),
disabled: false,
},
{
label: menuLabels.updateViaProxy,
handler: () => onUpdate(2),
disabled: false,
},
{
label: menuLabels.delete,
handler: () => {
setAnchorEl(null)
if (batchMode) {
if (onSelectionChange) {
onSelectionChange(id)
}
} else {
setConfirmOpen(true)
}
},
disabled: false,
},
]
: [
{
label: menuLabels.select,
handler: onForceSelect,
disabled: false,
},
{
label: menuLabels.editInfo,
handler: onEditInfo,
disabled: false,
},
{
label: menuLabels.editFile,
handler: onEditFile,
disabled: false,
},
{
label: menuLabels.editRules,
handler: onEditRules,
disabled: !option?.rules,
},
{
label: menuLabels.editProxies,
handler: onEditProxies,
disabled: !option?.proxies,
},
{
label: menuLabels.editGroups,
handler: onEditGroups,
disabled: !option?.groups,
},
{
label: menuLabels.extendConfig,
handler: onEditMerge,
disabled: !option?.merge,
},
{
label: menuLabels.extendScript,
handler: onEditScript,
disabled: !option?.script,
},
{
label: menuLabels.openFile,
handler: onOpenFile,
disabled: false,
},
{
label: menuLabels.delete,
handler: () => {
setAnchorEl(null)
if (batchMode) {
if (onSelectionChange) {
onSelectionChange(id)
}
} else {
setConfirmOpen(true)
}
},
disabled: false,
},
]
const boxStyle = {
height: 26,
@@ -599,7 +607,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
await profileDocument.reload()
return
}
onSave?.(profileDocument.savedValue, currentValue)
onSave?.(id, profileDocument.savedValue, currentValue)
profileDocument.markSaved(currentValue)
})
@@ -614,7 +622,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
await mergeDocument.reload()
return
}
onSave?.(mergeDocument.savedValue, currentValue)
onSave?.(id, mergeDocument.savedValue, currentValue)
mergeDocument.markSaved(currentValue)
})
@@ -632,7 +640,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
await scriptDocument.reload()
return
}
onSave?.(scriptDocument.savedValue, currentValue)
onSave?.(id, scriptDocument.savedValue, currentValue)
scriptDocument.markSaved(currentValue)
})
@@ -646,7 +654,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
e.stopPropagation()
return
}
onSelect(false)
onSelect(id, false)
}}
onContextMenu={(event) => {
const { clientX, clientY } = event
@@ -687,7 +695,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
onClick={(e) => {
e.stopPropagation()
if (onSelectionChange) {
onSelectionChange()
onSelectionChange(id)
}
}}
>
@@ -853,7 +861,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
e.preventDefault()
}}
>
{(hasUrl ? urlModeMenu : fileModeMenu).map((item) => (
{menuItems.map((item) => (
<MenuItem
key={item.label}
onClick={item.handler}
@@ -897,7 +905,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
profileUid={uid!}
property={option?.rules ?? ''}
open={true}
onSave={onSave}
onSave={(prev, curr) => onSave?.(id, prev, curr)}
onClose={() => setRulesOpen(false)}
/>
)}
@@ -906,7 +914,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
profileUid={uid!}
property={option?.proxies ?? ''}
open={true}
onSave={onSave}
onSave={(prev, curr) => onSave?.(id, prev, curr)}
onClose={() => setProxiesOpen(false)}
/>
)}
@@ -917,7 +925,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
profileUid={uid!}
property={option?.groups ?? ''}
open={true}
onSave={onSave}
onSave={(prev, curr) => onSave?.(id, prev, curr)}
onClose={() => {
setGroupsOpen(false)
}}
@@ -963,7 +971,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
onCancel={() => setConfirmOpen(false)}
onClose={() => setConfirmOpen(false)}
onOk={() => {
onDelete()
onDelete(id)
setConfirmOpen(false)
}}
>
+2 -5
View File
@@ -112,12 +112,9 @@ 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(() => {
setValue(DEFAULT_SCRIPT)
}, [setValue])
document.setValue(DEFAULT_SCRIPT)
}, [document])
return (
<>
+15 -20
View File
@@ -61,26 +61,21 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
},
})
// 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],
)
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)
},
}))
const handleOk = useLockFn(
handleSubmit(async (form) => {
@@ -180,7 +180,7 @@ export const ProxiesEditorViewer = (props: Props) => {
// 优化:异步分片解析,避免主线程阻塞,解析完成后批量setState
const handleParseAsync = (cb: (proxies: IProxyConfig[]) => void) => {
const proxies: IProxyConfig[] = []
const names: string[] = []
const names = new Set<string>()
let uris: string
try {
uris = atob(proxyUri)
@@ -198,9 +198,9 @@ export const ProxiesEditorViewer = (props: Props) => {
const uri = lines[idx]
try {
const proxy = parseUri(uri.trim())
if (!names.includes(proxy.name)) {
if (!names.has(proxy.name)) {
proxies.push(proxy)
names.push(proxy.name)
names.add(proxy.name)
}
} catch (err) {
console.warn(
+32 -6
View File
@@ -3,6 +3,7 @@ import * as yaml from 'js-yaml'
import {
getRecord,
rebindNode,
sameSource,
type ProxyNodeView,
type ProxyViewV1,
} from '@/types/proxy-view'
@@ -20,22 +21,47 @@ export const rebindProxyChainItems = (
items: readonly ProxyChainItem[],
candidates: readonly ProxyNodeView[],
proxyView: ProxyViewV1,
): ProxyChainItem[] =>
items.map((item) => {
): ProxyChainItem[] => {
// The proxy view refreshes on a fixed cadence; reusing item and array
// identities while the rebound values are equal keeps persistence effects
// and memoized chain rows from reprocessing identical content.
let reboundItems: ProxyChainItem[] | undefined
items.forEach((item, index) => {
const rebound = rebindNode(candidates, {
name: item.name,
source: item.source,
})
const record =
rebound === undefined ? undefined : getRecord(proxyView, rebound.recordId)
return {
const source = rebound?.source ?? item.source
const type = rebound?.type ?? item.type
const delay = record?.history.at(-1)?.delay
const sourceReused =
item.source === source ||
(item.source !== undefined &&
source !== undefined &&
sameSource(item.source, source))
if (
item.recordId === rebound?.recordId &&
sourceReused &&
item.type === type &&
item.delay === delay
) {
return
}
reboundItems ??= [...items]
reboundItems[index] = {
...item,
recordId: rebound?.recordId,
source: rebound?.source ?? item.source,
type: rebound?.type ?? item.type,
delay: record?.history.at(-1)?.delay,
source,
type,
delay,
}
})
return reboundItems ?? (items as ProxyChainItem[])
}
interface ParsedChainConfig {
proxies?: Array<{
+4 -3
View File
@@ -57,8 +57,6 @@ const chainPointerSensor = PointerSensor.configure({
activationConstraints: () => undefined,
})
const CHAIN_SENSORS = [chainPointerSensor, KeyboardSensor]
type RuntimeConfigWithProxySequence = IConfigData & { proxies?: unknown }
interface ProxyChainProps {
@@ -667,7 +665,10 @@ export const ProxyChain = ({
</Button>
</Box>
) : (
<DragDropProvider sensors={CHAIN_SENSORS} onDragEnd={handleDragEnd}>
<DragDropProvider
sensors={[chainPointerSensor, KeyboardSensor]}
onDragEnd={handleDragEnd}
>
<Box sx={{ borderRadius: 1, minHeight: 60, p: 1 }}>
{currentProxyChain.map((proxy, index) => (
<SortableProxyChainItem
+19 -17
View File
@@ -31,9 +31,9 @@ interface Props {
url?: string
groupName: string
headState: HeadState
onLocation: () => void
onCheckDelay: () => void
onHeadState: (val: Partial<HeadState>) => void
onLocation: (groupName: string) => void
onCheckDelay: (groupName: string) => void
onHeadState: (groupName: string, val: Partial<HeadState>) => void
}
export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
@@ -76,7 +76,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
// 因此对写入 headState 的动作做防抖,避免每输入一个字符就过滤一次。
const { run: applyFilter, flush: flushFilter } = useDebounceFn(
(state: SearchState) => {
onHeadState({
onHeadState(groupName, {
filterText: state.text,
filterMatchCase: state.matchCase,
filterMatchWholeWord: state.matchWholeWord,
@@ -125,7 +125,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.preventDefault()
e.stopPropagation()
}}
onChange={(e) => onHeadState({ testUrl: e.target.value })}
onChange={(e) => onHeadState(groupName, { testUrl: e.target.value })}
sx={{ flex: '1 1 auto', input: { py: 0.65, px: 1 } }}
/>
)}
@@ -155,8 +155,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
onLocation()
flushSync(() => onHeadState(groupName, { open: true }))
onLocation(groupName)
}}
>
<MyLocationRounded fontSize="inherit" />
@@ -171,16 +171,16 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
flushSync(() => onHeadState(groupName, { open: true }))
// Remind the user that it is custom test url
if (testUrl?.trim() && textState !== 'filter') {
onHeadState({ textState: 'url' })
onHeadState(groupName, { textState: 'url' })
}
if (testUrl?.trim() && !isValidUrl(testUrl)) {
showNotice.warning('proxies.feedback.warnings.invalidTestUrl')
return
}
onCheckDelay()
onCheckDelay(groupName)
}}
>
<NetworkCheckRounded fontSize="inherit" />
@@ -201,8 +201,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
onHeadState({
flushSync(() => onHeadState(groupName, { open: true }))
onHeadState(groupName, {
sortType: ((sortType + 1) % 3) as ProxySortType,
})
}}
@@ -219,7 +219,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
onHeadState({
onHeadState(groupName, {
textState: textState === 'url' ? null : 'url',
})
setTimeout(() => inputRef.current?.focus())
@@ -245,8 +245,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
onHeadState({ showType: !showType })
flushSync(() => onHeadState(groupName, { open: true }))
onHeadState(groupName, { showType: !showType })
}}
>
{showType ? (
@@ -265,8 +265,10 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
e.stopPropagation()
if (!headState.open && textState !== 'filter')
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
onHeadState({ textState: textState === 'filter' ? null : 'filter' })
flushSync(() => onHeadState(groupName, { open: true }))
onHeadState(groupName, {
textState: textState === 'filter' ? null : 'filter',
})
setTimeout(() => inputRef.current?.focus())
}}
>
+2 -2
View File
@@ -93,7 +93,7 @@ interface ProxyGroupsChainProps {
// Shared callbacks
onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onLocation: (group: any) => void
onLocation: (groupName: string) => void
onGroupSelect: (groupName: string) => void
onScrollToTop: () => void
}
@@ -245,7 +245,7 @@ function ProxyVirtualList({
activeStickyIndex: number | null
isChainMode?: boolean
measureElement: (node: Element | null) => void
onLocation: (group: any) => void
onLocation: (groupName: string) => void
onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onChangeProxy: (group: ProxyGroupView, member: ResolvedProxyMember) => void
+33 -26
View File
@@ -324,16 +324,20 @@ function ChainProxyGroups(props: {
scrollTopRef.current = 0
}, [])
const handleLocation = useStableCallback((group: ProxyGroupView) => {
if (!group) return
const { name, now } = group
const handleLocation = useStableCallback((groupName: string) => {
// Flat (type 1) headers such as GLOBAL carry the same live group.
const headerIndex = renderList.findIndex(
(e) => (e.type === 0 || e.type === 1) && e.group?.name === groupName,
)
const now = renderList[headerIndex]?.group?.now
if (!now) return
const index = renderList.findIndex(
(item) =>
item.group?.name === name &&
((item.type === 2 && item.member?.member.ref.name === now) ||
(item.type === 4 &&
item.memberCol?.some(({ member }) => member.ref.name === now))),
(e) =>
e.group?.name === groupName &&
((e.type === 2 && e.member?.member.ref.name === now) ||
(e.type === 4 &&
e.memberCol?.some(({ member }) => member.ref.name === now))),
)
if (index >= 0) {
@@ -496,13 +500,17 @@ function NormalProxyGroups(props: { mode: string }) {
[globalGroupName, select, setHeadState],
)
const handleLocation = useStableCallback((group: ProxyGroupView) => {
if (!group) return
const { name, now } = group
const handleLocation = useStableCallback((groupName: string) => {
// Flat (type 1) headers such as GLOBAL carry the same live group.
const headerIndex = renderList.findIndex(
(e) => (e.type === 0 || e.type === 1) && e.group?.name === groupName,
)
const now = renderList[headerIndex]?.group?.now
if (!now) return
const index = renderList.findIndex(
(e) =>
e.group?.name === name &&
e.group?.name === groupName &&
((e.type === 2 && e.member?.member.ref.name === now) ||
(e.type === 4 &&
e.memberCol?.some(({ member }) => member.ref.name === now))),
@@ -516,21 +524,20 @@ function NormalProxyGroups(props: { mode: string }) {
}
})
const handleGroupLocationByName = useCallback(
(groupName: string) => {
const index = renderList.findIndex(
(item) => item.type === 0 && item.group?.name === groupName,
)
// Stable identity: this feeds the sticky-header render callback; a
// [renderList] dep would re-create it on every list rebuild.
const handleGroupLocationByName = useStableCallback((groupName: string) => {
const index = renderList.findIndex(
(item) => item.type === 0 && item.group?.name === groupName,
)
if (index >= 0) {
stickyListRef.current?.scrollToIndex(index, {
align: 'start',
behavior: 'smooth',
})
}
},
[renderList],
)
if (index >= 0) {
stickyListRef.current?.scrollToIndex(index, {
align: 'start',
behavior: 'smooth',
})
}
})
const proxyGroupNames = useMemo(() => {
const names = renderList
+18 -12
View File
@@ -30,9 +30,9 @@ interface Props {
url?: string
groupName: string
headState: HeadState
onLocation: () => void
onCheckDelay: () => void
onHeadState: (val: Partial<HeadState>) => void
onLocation: (groupName: string) => void
onCheckDelay: (groupName: string) => void
onHeadState: (groupName: string, val: Partial<HeadState>) => void
}
const defaultSx: SxProps = {}
@@ -81,7 +81,7 @@ export const ProxyHead = ({
size="small"
color="inherit"
title={t('proxies.page.tooltips.locate')}
onClick={onLocation}
onClick={() => onLocation(groupName)}
>
<MyLocationRounded />
</IconButton>
@@ -95,13 +95,13 @@ export const ProxyHead = ({
// Remind the user that it is custom test url
if (testUrl?.trim() && textState !== 'filter') {
debugLog(`[ProxyHead] 使用自定义测试URL: ${testUrl}`)
onHeadState({ textState: 'url' })
onHeadState(groupName, { textState: 'url' })
}
if (testUrl?.trim() && !isValidUrl(testUrl)) {
showNotice.warning('proxies.feedback.warnings.invalidTestUrl')
return
}
onCheckDelay()
onCheckDelay(groupName)
}}
>
<NetworkCheckRounded />
@@ -118,7 +118,9 @@ export const ProxyHead = ({
][sortType]
}
onClick={() =>
onHeadState({ sortType: ((sortType + 1) % 3) as ProxySortType })
onHeadState(groupName, {
sortType: ((sortType + 1) % 3) as ProxySortType,
})
}
>
{sortType !== 1 && sortType !== 2 && <SortRounded />}
@@ -131,7 +133,9 @@ export const ProxyHead = ({
color="inherit"
title={t('proxies.page.tooltips.delayCheckUrl')}
onClick={() =>
onHeadState({ textState: textState === 'url' ? null : 'url' })
onHeadState(groupName, {
textState: textState === 'url' ? null : 'url',
})
}
>
{textState === 'url' ? (
@@ -149,7 +153,7 @@ export const ProxyHead = ({
? t('proxies.page.tooltips.showBasic')
: t('proxies.page.tooltips.showDetail')
}
onClick={() => onHeadState({ showType: !showType })}
onClick={() => onHeadState(groupName, { showType: !showType })}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
@@ -159,7 +163,9 @@ export const ProxyHead = ({
color="inherit"
title={t('proxies.page.tooltips.filter')}
onClick={() =>
onHeadState({ textState: textState === 'filter' ? null : 'filter' })
onHeadState(groupName, {
textState: textState === 'filter' ? null : 'filter',
})
}
>
{textState === 'filter' ? <SearchOffRounded /> : <SearchRounded />}
@@ -176,7 +182,7 @@ export const ProxyHead = ({
useRegularExpression: filterUseRegularExpression,
}}
onSearch={(_, state) =>
onHeadState({
onHeadState(groupName, {
filterText: state.text,
filterMatchCase: state.matchCase,
filterMatchWholeWord: state.matchWholeWord,
@@ -197,7 +203,7 @@ export const ProxyHead = ({
size="small"
variant="outlined"
placeholder={t('proxies.page.placeholders.delayCheckUrl')}
onChange={(e) => onHeadState({ testUrl: e.target.value })}
onChange={(e) => onHeadState(groupName, { testUrl: e.target.value })}
sx={{ ml: 0.5, flex: '1 1 auto', input: { py: 0.65, px: 1 } }}
/>
)}
+7 -7
View File
@@ -33,7 +33,7 @@ interface RenderProps {
item: IRenderItem
stickyed?: boolean
isChainMode?: boolean
onLocation: (group: IRenderItem['group']) => void
onLocation: (groupName: string) => void
onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onChangeProxy: (
@@ -179,9 +179,9 @@ const ProxyGroupHeader = (props: RenderProps) => {
url={group.testUrl!}
groupName={group.name}
headState={headState!}
onLocation={() => onLocation(group)}
onCheckDelay={() => onCheckAll(group.name)}
onHeadState={(p) => onHeadState(group.name, p)}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onHeadState={onHeadState}
/>
{!toolsOnLeft && proxyCount}
</ProxyGroupHeaderBlock>
@@ -270,9 +270,9 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
url={group.testUrl!}
groupName={group.name}
headState={headState!}
onLocation={() => onLocation(group)}
onCheckDelay={() => onCheckAll(group.name)}
onHeadState={(p) => onHeadState(group.name, p)}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onHeadState={onHeadState}
/>
)
}
+13 -9
View File
@@ -175,15 +175,19 @@ export const useRenderList = (
chainOccurrencesRef.current = chainOccurrences
const chainDelayGroup =
mode === 'rule' && selectedGroup ? selectedGroup : CHAIN_DELAY_GROUP
const chainDelayKey = chainOccurrences
.map(({ member }) => {
if (member.kind !== 'node') return `${member.kind}:${member.ref.name}`
const source = member.node.source
return source.kind === 'provider'
? `provider:${source.providerName}:${source.proxyName}`
: `core:${source.proxyName}`
})
.join('\u0000')
const chainDelayKey = useMemo(
() =>
chainOccurrences
.map(({ member }) => {
if (member.kind !== 'node') return `${member.kind}:${member.ref.name}`
const source = member.node.source
return source.kind === 'provider'
? `provider:${source.providerName}:${source.proxyName}`
: `core:${source.proxyName}`
})
.join('\u0000'),
[chainOccurrences],
)
useEffect(() => {
if (!isChainMode || !chainDelayKey) return
+110 -113
View File
@@ -17,7 +17,7 @@ import {
} from '@mui/material'
import { useLockFn } from 'ahooks'
import dayjs from 'dayjs'
import { useMemo, useState } from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { updateRuleProvider } from 'tauri-plugin-mihomo-api'
@@ -42,11 +42,6 @@ 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>>({})
@@ -171,119 +166,121 @@ export const ProviderButton = () => {
<DialogContent>
<List sx={{ py: 0, minHeight: 250 }}>
{sortedProviderEntries.map(([key, item]) => {
const provider = item
const time = dayjs(provider.updatedAt)
const isUpdating = updating[key]
{Object.entries(ruleProviders || {})
.sort()
.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>
}
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',
}}
return {
backgroundColor: bgcolor,
'&:hover': {
backgroundColor: hoverColor,
borderColor: alpha(primary.main, 0.3),
},
}
},
]}
>
<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={{
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>
}
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={{
animation: isUpdating
? 'spin 1s linear infinite'
: 'none',
'@keyframes spin': {
'0%': { transform: 'rotate(0deg)' },
'100%': { transform: 'rotate(360deg)' },
},
width: 40,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
title={t('rules.page.provider.actions.update')}
>
<RefreshRounded />
</IconButton>
</Box>
</ListItem>
)
})}
<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>
+35 -23
View File
@@ -51,6 +51,25 @@ const Item = styled(ListItem)(() => ({
},
}))
// Static editor settings; a per-render object would re-trigger Monaco's
// updateOptions and listener resubscription on every keystroke. The minimap
// depends on the live window width and is applied at editor mount instead.
const MONACO_OPTIONS = {
tabSize: 2,
mouseWheelZoom: true,
quickSuggestions: {
strings: true,
comments: true,
other: true,
},
padding: {
top: 33,
},
fontFamily: MONACO_FONT_FAMILY,
fontLigatures: false,
smoothScrolling: true,
} as const
type NameserverPolicy = Record<string, any>
function parseNameserverPolicy(str: string): NameserverPolicy {
@@ -520,9 +539,21 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
}
})
const handleYamlChange = (value?: string) => {
const handleYamlChange = useCallback((value?: string) => {
setYamlContent(value || '')
}
}, [])
const handleEditorMount = useCallback(
(editorInstance: MonacoEditorInstance) => {
editorRef.current = editorInstance
editorInstance.updateOptions({
minimap: {
enabled: document.documentElement.clientWidth >= 1500,
},
})
},
[],
)
const handleChange = (field: string) => (event: any) => {
const value =
@@ -1052,27 +1083,8 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
value={yamlContent}
theme={themeMode === 'light' ? 'light' : 'vs-dark'}
className="flex-grow"
onMount={(editorInstance) => {
editorRef.current = editorInstance
}}
options={{
tabSize: 2,
minimap: {
enabled: document.documentElement.clientWidth >= 1500,
},
mouseWheelZoom: true,
quickSuggestions: {
strings: true,
comments: true,
other: true,
},
padding: {
top: 33,
},
fontFamily: MONACO_FONT_FAMILY,
fontLigatures: false,
smoothScrolling: true,
}}
onMount={handleEditorMount}
options={MONACO_OPTIONS}
onChange={handleYamlChange}
/>
)}
@@ -42,8 +42,6 @@ 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)
@@ -134,7 +132,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] ?? EMPTY_KEYS}
value={hotkeyMap[func] ?? []}
onChange={(v) => setHotkeyMap((m) => ({ ...m, [func]: v }))}
/>
</ItemWrapper>
+13 -18
View File
@@ -17,13 +17,7 @@ import { exists } from '@tauri-apps/plugin-fs'
import { forwardRef, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
BaseDialog,
DialogRef,
Switch,
TooltipIcon,
switchChangeValue,
} from '@/components/base'
import { BaseDialog, DialogRef, Switch, TooltipIcon } 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'
@@ -110,11 +104,12 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
close: () => setOpen(false),
}))
const onSwitchFormat = (_e: any, value: boolean) => value
const onError = (err: any) => {
showNotice.error(err)
}
const onChangeData = (patch: Partial<IVergeConfig>) => {
mutateVerge({ ...verge, ...patch })
mutateVerge((prev) => ({ ...prev, ...patch }))
}
return (
@@ -139,7 +134,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={decorated}
valueProps="checked"
onCatch={onError}
onFormat={switchChangeValue}
onFormat={onSwitchFormat}
onChange={async () => {
await toggleDecorations()
}}
@@ -156,7 +151,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.traffic_graph ?? true}
valueProps="checked"
onCatch={onError}
onFormat={switchChangeValue}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ traffic_graph: e })}
onGuard={(e) => patchVerge({ traffic_graph: e })}
>
@@ -172,7 +167,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.enable_memory_usage ?? true}
valueProps="checked"
onCatch={onError}
onFormat={switchChangeValue}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_memory_usage: e })}
onGuard={(e) => patchVerge({ enable_memory_usage: e })}
>
@@ -190,7 +185,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.enable_group_icon ?? true}
valueProps="checked"
onCatch={onError}
onFormat={switchChangeValue}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_group_icon: e })}
onGuard={(e) => patchVerge({ enable_group_icon: e })}
>
@@ -208,7 +203,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.pause_render_traffic_stats_on_blur ?? true}
valueProps="checked"
onCatch={onError}
onFormat={switchChangeValue}
onFormat={onSwitchFormat}
onChange={(e) =>
onChangeData({ pause_render_traffic_stats_on_blur: e })
}
@@ -276,7 +271,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.enable_hover_jump_navigator ?? true}
valueProps="checked"
onCatch={onError}
onFormat={switchChangeValue}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_hover_jump_navigator: e })}
onGuard={(e) => patchVerge({ enable_hover_jump_navigator: e })}
>
@@ -378,7 +373,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.collapse_navbar ?? false}
valueProps="checked"
onCatch={onError}
onFormat={switchChangeValue}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ collapse_navbar: e })}
onGuard={(e) => patchVerge({ collapse_navbar: e })}
>
@@ -425,7 +420,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.enable_tray_speed ?? false}
valueProps="checked"
onCatch={onError}
onFormat={switchChangeValue}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_tray_speed: e })}
onGuard={(e) => patchVerge({ enable_tray_speed: e })}
>
@@ -445,7 +440,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
}
valueProps="checked"
onCatch={onError}
onFormat={switchChangeValue}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_tray_icon: e })}
onGuard={(e) => patchVerge({ enable_tray_icon: e })}
>
@@ -499,7 +494,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
value={verge?.tray_inline_outbound_modes ?? false}
valueProps="checked"
onCatch={onError}
onFormat={switchChangeValue}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ tray_inline_outbound_modes: e })}
onGuard={(e) => patchVerge({ tray_inline_outbound_modes: e })}
>
+35 -54
View File
@@ -8,7 +8,7 @@ import {
TextField,
} from '@mui/material'
import { useLockFn } from 'ahooks'
import { forwardRef, useMemo, useState } from 'react'
import { forwardRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { BaseDialog, DialogRef, Switch, TooltipIcon } from '@/components/base'
@@ -17,20 +17,6 @@ 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,
@@ -52,40 +38,6 @@ 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))
@@ -152,9 +104,9 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
}))
}
>
{APP_LOG_LEVEL_OPTIONS.map(({ value, label }) => (
<MenuItem value={value} key={value}>
{label}
{['trace', 'debug', 'info', 'warn', 'error', 'silent'].map((i) => (
<MenuItem value={i} key={i}>
{i[0].toUpperCase() + i.slice(1).toLowerCase()}
</MenuItem>
))}
</Select>
@@ -333,7 +285,7 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
<MenuItem value={6} key={6}>
{t('settings.modals.misc.options.proxyLayoutColumns.auto')}
</MenuItem>
{PROXY_LAYOUT_COLUMN_VALUES.map((i) => (
{[1, 2, 3, 4, 5].map((i) => (
<MenuItem value={i} key={i}>
{i}
</MenuItem>
@@ -360,7 +312,36 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
}
>
{/* 1: 1天, 2: 7天, 3: 30天, 4: 90天*/}
{autoLogCleanOptions.map((i) => (
{[
{
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) => (
<MenuItem key={i.value} value={i.value}>
{i.key}
</MenuItem>
+16 -18
View File
@@ -84,19 +84,6 @@ 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,
@@ -110,7 +97,8 @@ const buildInitialValues = (verge?: IVergeConfig | null) => ({
export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
const { t } = useTranslation()
const isWindows = OS === 'windows'
const systemName = getSystem()
const isWindows = systemName === 'windows'
const validReg = useMemo(() => getValidReg(isWindows), [isWindows])
const [open, setOpen] = useState(false)
@@ -142,7 +130,17 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
queryFn: getEmbeddedServerPort,
})
const separator = BYPASS_SEPARATOR
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 { systemProxyAddress } = useSystemData()
const displayedMixedPort = useDisplayedMixedPort()
@@ -328,7 +326,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
Promise.resolve().then(async () => {
try {
if (Object.keys(patch).length > 0) {
mutateVerge({ ...verge, ...patch })
mutateVerge((prev) => ({ ...prev, ...patch }))
}
if (Object.keys(patch).length > 0) {
await patchVerge(patch)
@@ -505,7 +503,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
checked={value.use_default}
onChange={(_, e) => {
if (!e && !value.bypass) {
const nextBypass = DEFAULT_BYPASS
const nextBypass = defaultBypass()
setValue((v) => ({
...v,
use_default: e,
@@ -577,7 +575,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
/>
<Box sx={{ padding: '0 2px 5px' }}>
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
{DEFAULT_BYPASS_CHIPS.map((item) => (
{splitBypass(defaultBypass()).map((item) => (
<Chip key={item} label={item} size="small" />
))}
</Box>
+6 -6
View File
@@ -20,12 +20,6 @@ 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()
@@ -51,6 +45,12 @@ 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 }))
}
+3 -4
View File
@@ -9,7 +9,7 @@ import {
} from '@mui/material'
import { useLockFn } from 'ahooks'
import type { Ref } from 'react'
import { useMemo, useState } from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
@@ -58,9 +58,8 @@ export function TunViewer({ ref }: { ref?: Ref<DialogRef> }) {
dnsMode: '',
})
const routeExcludeAddressItems = useMemo(
() => splitRouteExcludeAddress(values.routeExcludeAddress),
[values.routeExcludeAddress],
const routeExcludeAddressItems = splitRouteExcludeAddress(
values.routeExcludeAddress,
)
const routeExcludeAddressError =
values.autoRoute &&
+86 -84
View File
@@ -114,6 +114,84 @@ const getAlertTypeFromClassName = (
return match?.[1] as GitHubAlertType | null
}
const openUrlWithNotice = (url: string) => {
void openExternalUrl(url).catch(showNotice.error)
}
// Renderer map is static; a per-render identity would remount every link and
// blockquote subtree while download progress re-renders the dialog.
const MARKDOWN_COMPONENTS: ReactMarkdownOptions['components'] = {
a: ({ href, children, ...props }) => {
const isFragment = href?.startsWith('#') ?? false
const renderedHref = isFragment
? `#${UPDATE_MARKDOWN_ID_PREFIX}${href?.slice(1)}`
: href
? '#'
: undefined
return (
<a
{...props}
href={renderedHref}
target={undefined}
rel={undefined}
onClick={(event) => {
if (isFragment) return
event.preventDefault()
if (!href) return
openUrlWithNotice(href)
}}
onAuxClick={(event) => {
if (isFragment) return
event.preventDefault()
if (event.button === 1 && href) {
openUrlWithNotice(href)
}
}}
>
{children}
</a>
)
},
blockquote: ({ className, children }) => {
const alertType = getAlertTypeFromClassName(className)
if (!alertType) {
return <blockquote className={className}>{children}</blockquote>
}
return (
<Box
component="blockquote"
className={className}
sx={(theme) => {
const color = GITHUB_ALERTS[alertType].color
return {
m: '12px 0 18px',
px: 2,
py: 1,
borderLeft: `4px solid ${color}`,
borderRadius: 1,
bgcolor: alpha(color, theme.palette.mode === 'dark' ? 0.16 : 0.08),
'& p': {
my: 0.75,
},
'& .markdown-alert-title': {
display: 'flex',
alignItems: 'center',
gap: 0.75,
fontWeight: 700,
lineHeight: 1.4,
},
}
}}
>
{children}
</Box>
)
},
}
const findFirstTextNode = (node: MarkdownNode): MarkdownNode | null => {
if (node.type === 'text') return node
for (const child of node.children ?? []) {
@@ -185,11 +263,10 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
})
const { downloaded, total } = download
const openUrlWithNotice = (url: string) => {
void openExternalUrl(url).catch(showNotice.error)
}
const progress = total <= 0 ? 0 : Math.min((downloaded / total) * 100, 100)
const progress = useMemo(() => {
if (total <= 0) return 0
return Math.min((downloaded / total) * 100, 100)
}, [downloaded, total])
useImperativeHandle(ref, () => ({
open: () => {
@@ -209,8 +286,8 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
) as Record<GitHubAlertType, string>,
[t],
)
const remarkGitHubAlertsPlugin = useMemo(
() => () => remarkGitHubAlerts(githubAlertLabels),
const remarkPlugins = useMemo(
() => [() => remarkGitHubAlerts(githubAlertLabels)],
[githubAlertLabels],
)
@@ -472,83 +549,8 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
{open && (
<Suspense fallback={<LinearProgress />}>
<LazyReactMarkdown
remarkPlugins={[remarkGitHubAlertsPlugin]}
components={{
a: ({ href, children, ...props }) => {
const isFragment = href?.startsWith('#') ?? false
const renderedHref = isFragment
? `#${UPDATE_MARKDOWN_ID_PREFIX}${href?.slice(1)}`
: href
? '#'
: undefined
return (
<a
{...props}
href={renderedHref}
target={undefined}
rel={undefined}
onClick={(event) => {
if (isFragment) return
event.preventDefault()
if (!href) return
openUrlWithNotice(href)
}}
onAuxClick={(event) => {
if (isFragment) return
event.preventDefault()
if (event.button === 1 && href) {
openUrlWithNotice(href)
}
}}
>
{children}
</a>
)
},
blockquote: ({ className, children }) => {
const alertType = getAlertTypeFromClassName(className)
if (!alertType) {
return (
<blockquote className={className}>{children}</blockquote>
)
}
return (
<Box
component="blockquote"
className={className}
sx={(theme) => {
const color = GITHUB_ALERTS[alertType].color
return {
m: '12px 0 18px',
px: 2,
py: 1,
borderLeft: `4px solid ${color}`,
borderRadius: 1,
bgcolor: alpha(
color,
theme.palette.mode === 'dark' ? 0.16 : 0.08,
),
'& p': {
my: 0.75,
},
'& .markdown-alert-title': {
display: 'flex',
alignItems: 'center',
gap: 0.75,
fontWeight: 700,
lineHeight: 1.4,
},
}
}}
>
{children}
</Box>
)
},
}}
remarkPlugins={remarkPlugins}
components={MARKDOWN_COMPONENTS}
>
{markdownContent}
</LazyReactMarkdown>
+5 -10
View File
@@ -5,13 +5,7 @@ import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { updateGeo, type LogLevel } from 'tauri-plugin-mihomo-api'
import {
BaseDialog,
DialogRef,
Switch,
TooltipIcon,
switchChangeValue,
} from '@/components/base'
import { BaseDialog, DialogRef, Switch, TooltipIcon } from '@/components/base'
import { useClash } from '@/hooks/use-clash'
import { useClashLog } from '@/hooks/use-clash-log'
import { useDisplayedMixedPort } from '@/hooks/use-displayed-mixed-port'
@@ -75,6 +69,7 @@ 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)
}
@@ -178,7 +173,7 @@ const SettingClash = ({ onError }: Props) => {
value={allowLan ?? false}
valueProps="checked"
onCatch={onError}
onFormat={switchChangeValue}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ 'allow-lan': e })}
onGuard={(e) => patchClash({ 'allow-lan': e })}
>
@@ -218,7 +213,7 @@ const SettingClash = ({ onError }: Props) => {
value={ipv6 ?? false}
valueProps="checked"
onCatch={onError}
onFormat={switchChangeValue}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ ipv6: e })}
onGuard={(e) => patchClash({ ipv6: e })}
>
@@ -240,7 +235,7 @@ const SettingClash = ({ onError }: Props) => {
value={unifiedDelay ?? false}
valueProps="checked"
onCatch={onError}
onFormat={switchChangeValue}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ 'unified-delay': e })}
onGuard={(e) => patchClash({ 'unified-delay': e })}
>
+9 -4
View File
@@ -1,7 +1,8 @@
import { Box } from '@mui/material'
import React from 'react'
import { useTranslation } from 'react-i18next'
import { Switch, TooltipIcon, switchChangeValue } from '@/components/base'
import { Switch, TooltipIcon } from '@/components/base'
import ProxyControlSwitches from '@/components/shared/proxy-control-switches'
import { useVerge } from '@/hooks/use-verge'
@@ -19,8 +20,12 @@ 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 })
mutateVerge((prev) => ({ ...prev, ...patch }))
}
return (
@@ -47,7 +52,7 @@ const SettingSystem = ({ onError }: Props) => {
value={enable_auto_launch ?? false}
valueProps="checked"
onCatch={onError}
onFormat={switchChangeValue}
onFormat={onSwitchFormat}
onChange={(e) => {
onChangeData({ enable_auto_launch: e })
}}
@@ -80,7 +85,7 @@ const SettingSystem = ({ onError }: Props) => {
value={enable_silent_start ?? false}
valueProps="checked"
onCatch={onError}
onFormat={switchChangeValue}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_silent_start: e })}
onGuard={(e) => patchVerge({ enable_silent_start: e })}
>
@@ -72,7 +72,7 @@ const SettingVergeBasic = ({ onError }: Props) => {
const backupRef = useRef<DialogRef>(null)
const onChangeData = (patch: any) => {
mutateVerge({ ...verge, ...patch })
mutateVerge((prev) => ({ ...prev, ...patch }))
}
const onCopyClashEnv = useCallback(async () => {
+15 -6
View File
@@ -10,7 +10,7 @@ import {
TextField,
Typography,
} from '@mui/material'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import getSystem from '@/utils/get-system'
@@ -21,6 +21,9 @@ import {
type SearchDialog,
} from './settings-search-context'
// Constant for the runtime; module-level like the other getSystem() callers.
const OS = getSystem()
export function SettingsSearch({
children,
}: {
@@ -40,11 +43,17 @@ export function SettingsSearch({
const originalScrollRef = useRef(0)
const resultScrollRef = useRef(0)
const cancelLocateRef = useRef<() => void>(() => {})
const results = searchSettings(
query,
getSystem(),
(key) => t(key),
(key) => t(key, { lng: 'en' }),
// The catalog scan touches every entry with translations; memoizing keeps
// unrelated state (arrow-key selection) from re-running it.
const results = useMemo(
() =>
searchSettings(
query,
OS,
(key) => t(key),
(key) => t(key, { lng: 'en' }),
),
[query, t],
)
const searching = !!query.trim()
const scroller = () =>
@@ -163,7 +163,7 @@ const ProxyControlSwitches = ({
})
return false
}
mutateVerge({ ...verge, enable_tun_mode: value })
mutateVerge((prev) => ({ ...prev, enable_tun_mode: value }))
await patchVerge({ enable_tun_mode: value })
}
+12 -22
View File
@@ -1,6 +1,5 @@
import { useLockFn } from 'ahooks'
import i18n from 'i18next'
import { useCallback } from 'react'
import { getVersion } from 'tauri-plugin-mihomo-api'
import {
@@ -87,29 +86,23 @@ export const useClashMode = (shouldFetch: boolean = true) => {
}
export const useClash = () => {
const { data: clash } = useRuntimeConfig()
const { data: clash, refetch } = useRuntimeConfig()
const { data: versionData, refetch: mutateVersion } = useQuery({
queryKey: ['getVersion'],
queryFn: getVersion,
})
// 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 mutateClash = (updater?: MutateClashUpdater, revalidate?: boolean) => {
if (updater === undefined) {
return refetch()
}
void setCacheData<IConfigData>(['getRuntimeConfig'], updater)
if (revalidate !== false) {
return refetch()
}
return Promise.resolve()
}
const patchClash = useLockFn(async (patch: Partial<IConfigData>) => {
await mutate(() => patchClashConfig(patch), {
@@ -150,10 +143,7 @@ export const useClashInfo = () => {
})
})
const invalidateClashConfig = useCallback(
() => revalidateQuery(['getClashConfig']),
[],
)
const invalidateClashConfig = () => revalidateQuery(['getClashConfig'])
return {
clashInfo,
+2 -2
View File
@@ -1,4 +1,4 @@
import { useCallback, useMemo, useSyncExternalStore } from 'react'
import { useCallback, 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 = useMemo(() => JSON.stringify(groups), [groups])
const groupKey = JSON.stringify(groups)
const subscribe = useCallback(
(onSettle: () => void) => {
+4 -1
View File
@@ -12,6 +12,9 @@ const FLUSH_DELAY_MS = 50
type LogType = ILogItem['type']
const DEFAULT_LOG_TYPES: LogType[] = ['debug', 'info', 'warning', 'error']
// Shared empty fallback: a fresh [] would give `refresh` a new identity on
// every render and re-run the snapshot effect while logs stream.
const EMPTY_LOGS: ILogItem[] = []
const LOG_LEVEL_FILTERS: Record<LogLevel, LogType[]> = {
DEBUG: DEFAULT_LOG_TYPES,
INFO: ['info', 'warning', 'error'],
@@ -55,7 +58,7 @@ export const useLogData = () => {
const { response, refresh, setData } = useMihomoWsSubscription<ILogItem[]>({
subscriptionKey: enableLog ? 'getClashLog' : null,
fallbackData: [],
fallbackData: EMPTY_LOGS,
connect: () => MihomoWebSocket.connect_logs(logLevel),
setupHandlers: ({ next, scheduleReconnect, isMounted }) => {
let flushTimer: ReturnType<typeof setTimeout> | null = null
+1 -1
View File
@@ -61,7 +61,7 @@ export function useProxyDelayState(
}
const cachedUpdate = delayManager.getDelayUpdate(name, groupName)
if (cachedUpdate) {
setDelayState({ ...cachedUpdate })
setDelayState(cachedUpdate)
return
}
+25 -19
View File
@@ -3,12 +3,16 @@ import { useCallback } from 'react'
import { getVergeConfig, patchVergeConfig } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { getPreloadConfig, setPreloadConfig } from '@/services/preload'
import { setCacheData, useQuery } from '@/services/query-client'
import {
revalidateQuery,
setCacheData,
useQuery,
} from '@/services/query-client'
export const useVerge = () => {
const initialVergeConfig = getPreloadConfig()
const { data: verge, refetch } = useQuery({
const { data: verge } = useQuery({
queryKey: ['getVergeConfig'],
queryFn: async () => {
const config = await getVergeConfig()
@@ -20,23 +24,25 @@ export const useVerge = () => {
staleTime: 5000,
})
const mutateVerge = (
updaterOrData?:
| IVergeConfig
| ((prev: IVergeConfig | undefined) => IVergeConfig | undefined)
| undefined,
) => {
if (updaterOrData === undefined) {
void refetch()
return
}
void setCacheData<IVergeConfig>(
['getVergeConfig'],
typeof updaterOrData === 'function'
? (current) => updaterOrData(current ?? verge)
: updaterOrData,
)
}
// Stable identity: many consumers list mutateVerge in their own callback
// deps, so a per-render closure here would churn their memoization too.
// The updater receives the live cache value (preload snapshot when the
// cache is still empty) instead of a render-time snapshot, so an older
// render cannot clobber a newer cache write.
const mutateVerge = useCallback(
(
updater?: (prev: IVergeConfig | undefined) => IVergeConfig | undefined,
) => {
if (updater === undefined) {
void revalidateQuery(['getVergeConfig'])
return
}
void setCacheData<IVergeConfig>(['getVergeConfig'], (current) =>
updater(current ?? getPreloadConfig() ?? undefined),
)
},
[],
)
// Callers own the error toast (GuardState onCatch / page onError), so the
// funnel must not add a second one.
+46 -20
View File
@@ -462,9 +462,12 @@ const ProfilePage = () => {
[runProfileSwitchQueue],
)
const onSelect = async (profile: string, force: boolean) => {
await activateProfile(profile, true, force)
}
const onSelect = useCallback(
async (profile: string, force: boolean) => {
await activateProfile(profile, true, force)
},
[activateProfile],
)
useEffect(() => {
let cancelled = false
@@ -594,7 +597,7 @@ const ProfilePage = () => {
}
}
const toggleProfileSelection = (uid: string) => {
const toggleProfileSelection = useCallback((uid: string) => {
setSelectedProfiles((prev) => {
const newSet = new Set(prev)
if (newSet.has(uid)) {
@@ -604,7 +607,40 @@ const ProfilePage = () => {
}
return newSet
})
}
}, [])
// Item-grid callbacks stay identity-stable so ProfileItem's memo holds
// across unrelated page state (URL input keystrokes, switch spinners).
// onEnhance/onDelete are useLockFn wrappers whose identity changes every
// render, so they are read through refs here.
const onEnhanceRef = useRef(onEnhance)
onEnhanceRef.current = onEnhance
const onDeleteRef = useRef(onDelete)
onDeleteRef.current = onDelete
const handleItemEdit = useCallback((item: IProfileItem) => {
viewerRef.current?.edit(item)
}, [])
const handleItemSave = useCallback(
async (uid: string, prev?: string, curr?: string) => {
if (prev !== curr && profiles.current === uid) {
await onEnhanceRef.current(false)
}
},
[profiles],
)
const handleItemDelete = useCallback(
(uid: string) => {
if (batchMode) {
toggleProfileSelection(uid)
} else {
onDeleteRef.current(uid)
}
},
[batchMode, toggleProfileSelection],
)
const selectAllProfiles = () => {
setSelectedProfiles(new Set(profileItems.map((item) => item.uid!)))
@@ -908,23 +944,13 @@ const ProfilePage = () => {
completedUpdateRevisions.get(item.uid!) ?? 0
}
mutateProfiles={mutateProfiles}
onSelect={(f) => onSelect(item.uid!, f)}
onEdit={() => viewerRef.current?.edit(item)}
onSave={async (prev, curr) => {
if (prev !== curr && profiles.current === item.uid) {
await onEnhance(false)
}
}}
onDelete={() => {
if (batchMode) {
toggleProfileSelection(item.uid!)
} else {
onDelete(item.uid!)
}
}}
onSelect={onSelect}
onEdit={handleItemEdit}
onSave={handleItemSave}
onDelete={handleItemDelete}
batchMode={batchMode}
isSelected={selectedProfiles.has(item.uid!)}
onSelectionChange={() => toggleProfileSelection(item.uid!)}
onSelectionChange={toggleProfileSelection}
/>
))}
</Box>
+4 -6
View File
@@ -177,15 +177,13 @@ 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(CLASH_LOG_REGEX)
const result = log.match(regex)
if (result) {
const [_, _time, type, payload] = result
const time = dayjs(_time).format('MM-DD HH:mm:ss')
@@ -193,7 +191,7 @@ export async function getClashLogs() {
return acc
}
const result2 = log.match(CLASH_LOG_NEW_REGEX)
const result2 = log.match(newRegex)
if (result2) {
const [_, time, type, payload] = result2
acc.push({ time, type, payload })
+3 -1
View File
@@ -237,7 +237,9 @@ class DelayManager {
return undefined
}
return { ...entry }
// Entries are replaced, never mutated, so the cached object is shared
// directly; readers treat it as immutable.
return entry
}
getDelay(name: string, group: string) {
+3 -15
View File
@@ -514,21 +514,9 @@ export function hideNotice(id: number) {
}
function hideNoticesByCode(code: string) {
// 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()
notices
.filter((notice) => notice.code === code)
.forEach(({ id }) => hideNotice(id))
}
export function syncSidecarFailure(snapshot: SidecarFailureSnapshot) {
+1 -1
View File
@@ -156,7 +156,7 @@ export const selectRuleChainMembers = (
})
}
const sameSource = (
export const sameSource = (
left: ProxyNodeView['source'],
right: ProxyNodeView['source'],
) =>
+34 -13
View File
@@ -124,10 +124,10 @@ export class TrafficDataSampler {
) {
rawStart++
}
const rawData = this.rawBuffer.slice(rawStart)
const rawCount = this.rawBuffer.length - rawStart
if (minutes <= this.config.rawDataMinutes) {
return rawData
return this.rawBuffer.slice(rawStart)
}
const compressedCutoffUpper =
@@ -140,19 +140,40 @@ export class TrafficDataSampler {
) {
compressedStart++
}
let compressedEnd = compressedStart
while (
compressedEnd < this.compressedBuffer.length &&
this.compressedBuffer[compressedEnd].timestamp <= compressedCutoffUpper
) {
compressedEnd++
}
const compressedData = this.compressedBuffer
.slice(compressedStart)
.filter((p) => p.timestamp <= compressedCutoffUpper)
.map((p) => ({
up: p.up,
down: p.down,
timestamp: p.timestamp,
}))
// Single preallocated result; raw entries keep their stored identity.
const compressedCount = compressedEnd - compressedStart
const result: ITrafficDataPoint[] = new Array(compressedCount + rawCount)
for (let i = 0; i < compressedCount; i++) {
const point = this.compressedBuffer[compressedStart + i]
result[i] = {
up: point.up,
down: point.down,
timestamp: point.timestamp,
}
}
for (let i = 0; i < rawCount; i++) {
result[compressedCount + i] = this.rawBuffer[rawStart + i]
}
return [...compressedData, ...rawData].sort(
(a, b) => a.timestamp - b.timestamp,
)
// Compressed points precede raw ones except across the trim boundary;
// sort only when the two ranges actually interleave.
if (
compressedCount > 0 &&
rawCount > 0 &&
this.compressedBuffer[compressedEnd - 1].timestamp >
this.rawBuffer[rawStart].timestamp
) {
result.sort((a, b) => a.timestamp - b.timestamp)
}
return result
}
getStats(): ISamplerStats {
+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 {
return IPV4_REGEX.test(address)
// Check if the address is IPv4
const ipv4Regex = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/
return ipv4Regex.test(address)
}
export function isIPv6(address: string): boolean {
return IPV6_REGEX.test(address)
// 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)
}
export function decodeBase64OrOriginal(str: string): string {