Compare commits

..
Author SHA1 Message Date
renovate[bot] 99815e7fe3 chore(deps): update cargo dependencies 2026-11-19 16:32:01 +00:00
31 changed files with 535 additions and 614 deletions
Generated
+73 -8
View File
@@ -821,9 +821,9 @@ checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "bytes"
version = "1.12.1"
version = "1.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
dependencies = [
"serde",
]
@@ -1191,7 +1191,7 @@ name = "clash-verge-logging"
version = "0.1.0"
dependencies = [
"anyhow",
"flexi_logger",
"flexi_logger 0.32.0",
"log",
"parking_lot 0.13.0",
"tracing-estuary",
@@ -2425,6 +2425,19 @@ 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"
@@ -3737,6 +3750,58 @@ 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"
@@ -7072,9 +7137,9 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.40.3"
version = "0.40.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a86bac2f7d06e6384984118ad727f5694110f0ec44d924d05c8fdec3d030bee6"
checksum = "3e80749408e2d8bec0ffa303012cf4e1b3b355f4a09087b4fdf7473680f6a2de"
dependencies = [
"libc",
"memchr",
@@ -8476,7 +8541,7 @@ dependencies = [
"anyhow",
"compact_str",
"console-subscriber",
"flexi_logger",
"flexi_logger 0.31.10",
"log",
"nu-ansi-term",
"parking_lot 0.12.5",
@@ -10136,9 +10201,9 @@ dependencies = [
[[package]]
name = "zip"
version = "9.6.0"
version = "9.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80cc68510ea7553c30a69c732de5278e94183f68765af6c642dbccefd6ec777e"
checksum = "63e50f7b2212e4635244be3c363b53273d159f2523eb7db3096c1d2861c1b603"
dependencies = [
"aes",
"bzip2",
+1 -1
View File
@@ -73,7 +73,7 @@ tokio = { version = "1.54.1", features = [
"time",
"sync",
] }
flexi_logger = "0.31.10"
flexi_logger = "0.32.0"
log = "0.4.35"
reqwest = { version = "0.13.5", features = [
"json",
-1
View File
@@ -63,7 +63,6 @@
<details>
<summary><strong> 🚀 优化改进 </strong></summary>
- 优化首页流量图与代理、订阅、日志、设置页面的渲染效率,长列表滚动与实时刷新更流畅
- 优化连接、规则和日志筛选:切换页面后保留过滤条件
- 优化全局模式代理列表:仅显示 `GLOBAL` 节点,选中其中的策略组时才显示该组
- 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件
@@ -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.3", default-features = false, features = ["network", "system"] }
sysinfo = { version = "0.40.4", 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.6.0"
zip = "9.7.3"
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.1"
bytes = "1.12.2"
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"] }
+6 -6
View File
@@ -87,18 +87,18 @@ export const TestCard = () => {
x.uid === uid ? { ...x, ...patch } : x,
)
mutateVerge((prev) => ({ ...prev, test_list: newList }))
mutateVerge({ ...verge, test_list: newList })
},
[testList, mutateVerge],
[testList, verge, mutateVerge],
)
const onDeleteTestListItem = useCallback(
(uid: string) => {
const newList = testList.filter((x) => x.uid !== uid)
patchVerge({ test_list: newList })
mutateVerge((prev) => ({ ...prev, test_list: newList }))
mutateVerge({ ...verge, test_list: newList })
},
[testList, patchVerge, mutateVerge],
[testList, verge, patchVerge, mutateVerge],
)
const onDragEnd = useCallback(
@@ -129,7 +129,7 @@ export const TestCard = () => {
newList.splice(newIndex, 0, removed)
// 优化:先本地更新,再异步 patch,避免UI卡死
mutateVerge((prev) => ({ ...prev, test_list: newList }))
mutateVerge({ ...verge, test_list: newList })
const patchFn = () => {
try {
patchVerge({ test_list: newList })
@@ -141,7 +141,7 @@ export const TestCard = () => {
setTimeout(patchFn, 0)
}
},
[testList, mutateVerge, patchVerge],
[testList, verge, mutateVerge, patchVerge],
)
// 仅在verge首次加载时初始化测试列表
+11 -23
View File
@@ -176,10 +176,7 @@ export const GroupsEditorViewer = (props: Props) => {
},
})
const [groupList, setGroupList] = useState<IProxyGroupConfig[]>([])
const [originPolicy, setOriginPolicy] = useState<{
proxyNames: string[]
groupNames: string[]
}>({ proxyNames: [], groupNames: [] })
const [proxyPolicyList, setProxyPolicyList] = useState<string[]>([])
const [proxyProviderList, setProxyProviderList] = useState<string[]>([])
const [prependSeq, setPrependSeq] = useState<IProxyGroupConfig[]>([])
const [appendSeq, setAppendSeq] = useState<IProxyGroupConfig[]>([])
@@ -356,9 +353,6 @@ 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)
@@ -394,13 +388,17 @@ export const GroupsEditorViewer = (props: Props) => {
(name): name is string => typeof name === 'string' && name.length > 0,
)
setOriginPolicy({
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),
proxyNames,
groupNames: (originGroupsObj?.['proxy-groups'] || []).map(
(group) => group.name,
),
})
}, [profileUid, proxiesUid])
)
setProxyPolicyList(Array.from(new Set(computedPolicyList)))
}, [appendSeq, deleteSeq, prependSeq, profileUid, proxiesUid])
const fetchProfile = useCallback(async () => {
const data = await readProfileFile(profileUid)
const mergeData = await readProfileFile(mergeUid)
@@ -444,16 +442,6 @@ 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()
+186 -194
View File
@@ -61,31 +61,6 @@ 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
@@ -93,13 +68,13 @@ export interface ProfileItemProps {
activating: boolean
itemData: IProfileItem
mutateProfiles: () => Promise<void>
onSelect: (uid: string, force: boolean) => void
onEdit: (item: IProfileItem) => void
onSave?: (uid: string, prev?: string, curr?: string) => void
onDelete: (uid: string) => void
onSelect: (force: boolean) => void
onEdit: () => void
onSave?: (prev?: string, curr?: string) => void
onDelete: () => void
batchMode?: boolean
isSelected?: boolean
onSelectionChange?: (uid: string) => void
onSelectionChange?: () => void
timerUpdateRevision: number
completedUpdateRevision: number
}
@@ -347,7 +322,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const onEditInfo = () => {
setAnchorEl(null)
onEdit(itemData)
onEdit()
}
const onShareQrCode = () => {
@@ -387,7 +362,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const onForceSelect = () => {
setAnchorEl(null)
onSelect(id, true)
onSelect(true)
}
const onOpenFile = useLockFn(async () => {
@@ -437,158 +412,175 @@ const ProfileItemBase = (props: ProfileItemProps) => {
}
})
// 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,
},
]
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,
},
]
const boxStyle = {
height: 26,
@@ -607,7 +599,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
await profileDocument.reload()
return
}
onSave?.(id, profileDocument.savedValue, currentValue)
onSave?.(profileDocument.savedValue, currentValue)
profileDocument.markSaved(currentValue)
})
@@ -622,7 +614,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
await mergeDocument.reload()
return
}
onSave?.(id, mergeDocument.savedValue, currentValue)
onSave?.(mergeDocument.savedValue, currentValue)
mergeDocument.markSaved(currentValue)
})
@@ -640,7 +632,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
await scriptDocument.reload()
return
}
onSave?.(id, scriptDocument.savedValue, currentValue)
onSave?.(scriptDocument.savedValue, currentValue)
scriptDocument.markSaved(currentValue)
})
@@ -654,7 +646,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
e.stopPropagation()
return
}
onSelect(id, false)
onSelect(false)
}}
onContextMenu={(event) => {
const { clientX, clientY } = event
@@ -695,7 +687,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
onClick={(e) => {
e.stopPropagation()
if (onSelectionChange) {
onSelectionChange(id)
onSelectionChange()
}
}}
>
@@ -861,7 +853,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
e.preventDefault()
}}
>
{menuItems.map((item) => (
{(hasUrl ? urlModeMenu : fileModeMenu).map((item) => (
<MenuItem
key={item.label}
onClick={item.handler}
@@ -905,7 +897,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
profileUid={uid!}
property={option?.rules ?? ''}
open={true}
onSave={(prev, curr) => onSave?.(id, prev, curr)}
onSave={onSave}
onClose={() => setRulesOpen(false)}
/>
)}
@@ -914,7 +906,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
profileUid={uid!}
property={option?.proxies ?? ''}
open={true}
onSave={(prev, curr) => onSave?.(id, prev, curr)}
onSave={onSave}
onClose={() => setProxiesOpen(false)}
/>
)}
@@ -925,7 +917,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
profileUid={uid!}
property={option?.groups ?? ''}
open={true}
onSave={(prev, curr) => onSave?.(id, prev, curr)}
onSave={onSave}
onClose={() => {
setGroupsOpen(false)
}}
@@ -971,7 +963,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
onCancel={() => setConfirmOpen(false)}
onClose={() => setConfirmOpen(false)}
onOk={() => {
onDelete(id)
onDelete()
setConfirmOpen(false)
}}
>
@@ -180,7 +180,7 @@ export const ProxiesEditorViewer = (props: Props) => {
// 优化:异步分片解析,避免主线程阻塞,解析完成后批量setState
const handleParseAsync = (cb: (proxies: IProxyConfig[]) => void) => {
const proxies: IProxyConfig[] = []
const names = new Set<string>()
const names: 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.has(proxy.name)) {
if (!names.includes(proxy.name)) {
proxies.push(proxy)
names.add(proxy.name)
names.push(proxy.name)
}
} catch (err) {
console.warn(
+6 -32
View File
@@ -3,7 +3,6 @@ import * as yaml from 'js-yaml'
import {
getRecord,
rebindNode,
sameSource,
type ProxyNodeView,
type ProxyViewV1,
} from '@/types/proxy-view'
@@ -21,47 +20,22 @@ export const rebindProxyChainItems = (
items: readonly ProxyChainItem[],
candidates: readonly ProxyNodeView[],
proxyView: ProxyViewV1,
): 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) => {
): ProxyChainItem[] =>
items.map((item) => {
const rebound = rebindNode(candidates, {
name: item.name,
source: item.source,
})
const record =
rebound === undefined ? undefined : getRecord(proxyView, rebound.recordId)
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] = {
return {
...item,
recordId: rebound?.recordId,
source,
type,
delay,
source: rebound?.source ?? item.source,
type: rebound?.type ?? item.type,
delay: record?.history.at(-1)?.delay,
}
})
return reboundItems ?? (items as ProxyChainItem[])
}
interface ParsedChainConfig {
proxies?: Array<{
+17 -19
View File
@@ -31,9 +31,9 @@ interface Props {
url?: string
groupName: string
headState: HeadState
onLocation: (groupName: string) => void
onCheckDelay: (groupName: string) => void
onHeadState: (groupName: string, val: Partial<HeadState>) => void
onLocation: () => void
onCheckDelay: () => void
onHeadState: (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(groupName, {
onHeadState({
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(groupName, { testUrl: e.target.value })}
onChange={(e) => onHeadState({ 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(groupName, { open: true }))
onLocation(groupName)
flushSync(() => onHeadState({ open: true }))
onLocation()
}}
>
<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(groupName, { open: true }))
flushSync(() => onHeadState({ open: true }))
// Remind the user that it is custom test url
if (testUrl?.trim() && textState !== 'filter') {
onHeadState(groupName, { textState: 'url' })
onHeadState({ textState: 'url' })
}
if (testUrl?.trim() && !isValidUrl(testUrl)) {
showNotice.warning('proxies.feedback.warnings.invalidTestUrl')
return
}
onCheckDelay(groupName)
onCheckDelay()
}}
>
<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(groupName, { open: true }))
onHeadState(groupName, {
flushSync(() => onHeadState({ open: true }))
onHeadState({
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(groupName, {
onHeadState({
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(groupName, { open: true }))
onHeadState(groupName, { showType: !showType })
flushSync(() => onHeadState({ open: true }))
onHeadState({ showType: !showType })
}}
>
{showType ? (
@@ -265,10 +265,8 @@ 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(groupName, { open: true }))
onHeadState(groupName, {
textState: textState === 'filter' ? null : 'filter',
})
flushSync(() => onHeadState({ open: true }))
onHeadState({ 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: (groupName: string) => void
onLocation: (group: any) => void
onGroupSelect: (groupName: string) => void
onScrollToTop: () => void
}
@@ -245,7 +245,7 @@ function ProxyVirtualList({
activeStickyIndex: number | null
isChainMode?: boolean
measureElement: (node: Element | null) => void
onLocation: (groupName: string) => void
onLocation: (group: any) => void
onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onChangeProxy: (group: ProxyGroupView, member: ResolvedProxyMember) => void
+26 -33
View File
@@ -324,20 +324,16 @@ function ChainProxyGroups(props: {
scrollTopRef.current = 0
}, [])
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 handleLocation = useStableCallback((group: ProxyGroupView) => {
if (!group) return
const { name, now } = group
const index = renderList.findIndex(
(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))),
(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))),
)
if (index >= 0) {
@@ -500,17 +496,13 @@ function NormalProxyGroups(props: { mode: string }) {
[globalGroupName, select, setHeadState],
)
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 handleLocation = useStableCallback((group: ProxyGroupView) => {
if (!group) return
const { name, now } = group
const index = renderList.findIndex(
(e) =>
e.group?.name === groupName &&
e.group?.name === name &&
((e.type === 2 && e.member?.member.ref.name === now) ||
(e.type === 4 &&
e.memberCol?.some(({ member }) => member.ref.name === now))),
@@ -524,20 +516,21 @@ function NormalProxyGroups(props: { mode: string }) {
}
})
// 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,
)
const handleGroupLocationByName = useCallback(
(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',
})
}
})
if (index >= 0) {
stickyListRef.current?.scrollToIndex(index, {
align: 'start',
behavior: 'smooth',
})
}
},
[renderList],
)
const proxyGroupNames = useMemo(() => {
const names = renderList
+12 -18
View File
@@ -30,9 +30,9 @@ interface Props {
url?: string
groupName: string
headState: HeadState
onLocation: (groupName: string) => void
onCheckDelay: (groupName: string) => void
onHeadState: (groupName: string, val: Partial<HeadState>) => void
onLocation: () => void
onCheckDelay: () => void
onHeadState: (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(groupName)}
onClick={onLocation}
>
<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(groupName, { textState: 'url' })
onHeadState({ textState: 'url' })
}
if (testUrl?.trim() && !isValidUrl(testUrl)) {
showNotice.warning('proxies.feedback.warnings.invalidTestUrl')
return
}
onCheckDelay(groupName)
onCheckDelay()
}}
>
<NetworkCheckRounded />
@@ -118,9 +118,7 @@ export const ProxyHead = ({
][sortType]
}
onClick={() =>
onHeadState(groupName, {
sortType: ((sortType + 1) % 3) as ProxySortType,
})
onHeadState({ sortType: ((sortType + 1) % 3) as ProxySortType })
}
>
{sortType !== 1 && sortType !== 2 && <SortRounded />}
@@ -133,9 +131,7 @@ export const ProxyHead = ({
color="inherit"
title={t('proxies.page.tooltips.delayCheckUrl')}
onClick={() =>
onHeadState(groupName, {
textState: textState === 'url' ? null : 'url',
})
onHeadState({ textState: textState === 'url' ? null : 'url' })
}
>
{textState === 'url' ? (
@@ -153,7 +149,7 @@ export const ProxyHead = ({
? t('proxies.page.tooltips.showBasic')
: t('proxies.page.tooltips.showDetail')
}
onClick={() => onHeadState(groupName, { showType: !showType })}
onClick={() => onHeadState({ showType: !showType })}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
@@ -163,9 +159,7 @@ export const ProxyHead = ({
color="inherit"
title={t('proxies.page.tooltips.filter')}
onClick={() =>
onHeadState(groupName, {
textState: textState === 'filter' ? null : 'filter',
})
onHeadState({ textState: textState === 'filter' ? null : 'filter' })
}
>
{textState === 'filter' ? <SearchOffRounded /> : <SearchRounded />}
@@ -182,7 +176,7 @@ export const ProxyHead = ({
useRegularExpression: filterUseRegularExpression,
}}
onSearch={(_, state) =>
onHeadState(groupName, {
onHeadState({
filterText: state.text,
filterMatchCase: state.matchCase,
filterMatchWholeWord: state.matchWholeWord,
@@ -203,7 +197,7 @@ export const ProxyHead = ({
size="small"
variant="outlined"
placeholder={t('proxies.page.placeholders.delayCheckUrl')}
onChange={(e) => onHeadState(groupName, { testUrl: e.target.value })}
onChange={(e) => onHeadState({ 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: (groupName: string) => void
onLocation: (group: IRenderItem['group']) => 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}
onCheckDelay={onCheckAll}
onHeadState={onHeadState}
onLocation={() => onLocation(group)}
onCheckDelay={() => onCheckAll(group.name)}
onHeadState={(p) => onHeadState(group.name, p)}
/>
{!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}
onCheckDelay={onCheckAll}
onHeadState={onHeadState}
onLocation={() => onLocation(group)}
onCheckDelay={() => onCheckAll(group.name)}
onHeadState={(p) => onHeadState(group.name, p)}
/>
)
}
+9 -13
View File
@@ -175,19 +175,15 @@ export const useRenderList = (
chainOccurrencesRef.current = chainOccurrences
const chainDelayGroup =
mode === 'rule' && selectedGroup ? selectedGroup : CHAIN_DELAY_GROUP
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],
)
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')
useEffect(() => {
if (!isChainMode || !chainDelayKey) return
+23 -35
View File
@@ -51,25 +51,6 @@ 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 {
@@ -539,21 +520,9 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
}
})
const handleYamlChange = useCallback((value?: string) => {
const handleYamlChange = (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 =
@@ -1083,8 +1052,27 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
value={yamlContent}
theme={themeMode === 'light' ? 'light' : 'vs-dark'}
className="flex-grow"
onMount={handleEditorMount}
options={MONACO_OPTIONS}
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,
}}
onChange={handleYamlChange}
/>
)}
@@ -109,7 +109,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
showNotice.error(err)
}
const onChangeData = (patch: Partial<IVergeConfig>) => {
mutateVerge((prev) => ({ ...prev, ...patch }))
mutateVerge({ ...verge, ...patch })
}
return (
@@ -326,7 +326,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
Promise.resolve().then(async () => {
try {
if (Object.keys(patch).length > 0) {
mutateVerge((prev) => ({ ...prev, ...patch }))
mutateVerge({ ...verge, ...patch })
}
if (Object.keys(patch).length > 0) {
await patchVerge(patch)
+83 -82
View File
@@ -114,84 +114,6 @@ 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 ?? []) {
@@ -263,6 +185,10 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
})
const { downloaded, total } = download
const openUrlWithNotice = (url: string) => {
void openExternalUrl(url).catch(showNotice.error)
}
const progress = useMemo(() => {
if (total <= 0) return 0
return Math.min((downloaded / total) * 100, 100)
@@ -286,8 +212,8 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
) as Record<GitHubAlertType, string>,
[t],
)
const remarkPlugins = useMemo(
() => [() => remarkGitHubAlerts(githubAlertLabels)],
const remarkGitHubAlertsPlugin = useMemo(
() => () => remarkGitHubAlerts(githubAlertLabels),
[githubAlertLabels],
)
@@ -549,8 +475,83 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
{open && (
<Suspense fallback={<LinearProgress />}>
<LazyReactMarkdown
remarkPlugins={remarkPlugins}
components={MARKDOWN_COMPONENTS}
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>
)
},
}}
>
{markdownContent}
</LazyReactMarkdown>
+1 -1
View File
@@ -25,7 +25,7 @@ const SettingSystem = ({ onError }: Props) => {
value: boolean,
) => value
const onChangeData = (patch: Partial<IVergeConfig>) => {
mutateVerge((prev) => ({ ...prev, ...patch }))
mutateVerge({ ...verge, ...patch })
}
return (
@@ -72,7 +72,7 @@ const SettingVergeBasic = ({ onError }: Props) => {
const backupRef = useRef<DialogRef>(null)
const onChangeData = (patch: any) => {
mutateVerge((prev) => ({ ...prev, ...patch }))
mutateVerge({ ...verge, ...patch })
}
const onCopyClashEnv = useCallback(async () => {
+6 -15
View File
@@ -10,7 +10,7 @@ import {
TextField,
Typography,
} from '@mui/material'
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import getSystem from '@/utils/get-system'
@@ -21,9 +21,6 @@ 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,
}: {
@@ -43,17 +40,11 @@ export function SettingsSearch({
const originalScrollRef = useRef(0)
const resultScrollRef = useRef(0)
const cancelLocateRef = useRef<() => void>(() => {})
// 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 results = searchSettings(
query,
getSystem(),
(key) => t(key),
(key) => t(key, { lng: 'en' }),
)
const searching = !!query.trim()
const scroller = () =>
@@ -163,7 +163,7 @@ const ProxyControlSwitches = ({
})
return false
}
mutateVerge((prev) => ({ ...prev, enable_tun_mode: value }))
mutateVerge({ ...verge, enable_tun_mode: value })
await patchVerge({ enable_tun_mode: value })
}
+1 -4
View File
@@ -12,9 +12,6 @@ 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'],
@@ -58,7 +55,7 @@ export const useLogData = () => {
const { response, refresh, setData } = useMihomoWsSubscription<ILogItem[]>({
subscriptionKey: enableLog ? 'getClashLog' : null,
fallbackData: EMPTY_LOGS,
fallbackData: [],
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
}
+19 -25
View File
@@ -3,16 +3,12 @@ import { useCallback } from 'react'
import { getVergeConfig, patchVergeConfig } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { getPreloadConfig, setPreloadConfig } from '@/services/preload'
import {
revalidateQuery,
setCacheData,
useQuery,
} from '@/services/query-client'
import { setCacheData, useQuery } from '@/services/query-client'
export const useVerge = () => {
const initialVergeConfig = getPreloadConfig()
const { data: verge } = useQuery({
const { data: verge, refetch } = useQuery({
queryKey: ['getVergeConfig'],
queryFn: async () => {
const config = await getVergeConfig()
@@ -24,25 +20,23 @@ export const useVerge = () => {
staleTime: 5000,
})
// 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),
)
},
[],
)
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,
)
}
// Callers own the error toast (GuardState onCatch / page onError), so the
// funnel must not add a second one.
+20 -46
View File
@@ -462,12 +462,9 @@ const ProfilePage = () => {
[runProfileSwitchQueue],
)
const onSelect = useCallback(
async (profile: string, force: boolean) => {
await activateProfile(profile, true, force)
},
[activateProfile],
)
const onSelect = async (profile: string, force: boolean) => {
await activateProfile(profile, true, force)
}
useEffect(() => {
let cancelled = false
@@ -597,7 +594,7 @@ const ProfilePage = () => {
}
}
const toggleProfileSelection = useCallback((uid: string) => {
const toggleProfileSelection = (uid: string) => {
setSelectedProfiles((prev) => {
const newSet = new Set(prev)
if (newSet.has(uid)) {
@@ -607,40 +604,7 @@ 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!)))
@@ -944,13 +908,23 @@ const ProfilePage = () => {
completedUpdateRevisions.get(item.uid!) ?? 0
}
mutateProfiles={mutateProfiles}
onSelect={onSelect}
onEdit={handleItemEdit}
onSave={handleItemSave}
onDelete={handleItemDelete}
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!)
}
}}
batchMode={batchMode}
isSelected={selectedProfiles.has(item.uid!)}
onSelectionChange={toggleProfileSelection}
onSelectionChange={() => toggleProfileSelection(item.uid!)}
/>
))}
</Box>
+1 -3
View File
@@ -237,9 +237,7 @@ class DelayManager {
return undefined
}
// Entries are replaced, never mutated, so the cached object is shared
// directly; readers treat it as immutable.
return entry
return { ...entry }
}
getDelay(name: string, group: string) {
+1 -1
View File
@@ -156,7 +156,7 @@ export const selectRuleChainMembers = (
})
}
export const sameSource = (
const sameSource = (
left: ProxyNodeView['source'],
right: ProxyNodeView['source'],
) =>
+13 -34
View File
@@ -124,10 +124,10 @@ export class TrafficDataSampler {
) {
rawStart++
}
const rawCount = this.rawBuffer.length - rawStart
const rawData = this.rawBuffer.slice(rawStart)
if (minutes <= this.config.rawDataMinutes) {
return this.rawBuffer.slice(rawStart)
return rawData
}
const compressedCutoffUpper =
@@ -140,40 +140,19 @@ export class TrafficDataSampler {
) {
compressedStart++
}
let compressedEnd = compressedStart
while (
compressedEnd < this.compressedBuffer.length &&
this.compressedBuffer[compressedEnd].timestamp <= compressedCutoffUpper
) {
compressedEnd++
}
// 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]
}
const compressedData = this.compressedBuffer
.slice(compressedStart)
.filter((p) => p.timestamp <= compressedCutoffUpper)
.map((p) => ({
up: p.up,
down: p.down,
timestamp: p.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
return [...compressedData, ...rawData].sort(
(a, b) => a.timestamp - b.timestamp,
)
}
getStats(): ISamplerStats {