Files
clash-verge-rev/src/components/shared/proxy-control-switches.tsx
T
Tunglies 48eab2c21e perf(ui): stabilize hot-path render identities across profile, proxy, log and settings views (#8694)
* 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.

* 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.

* 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.

* 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.

* 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.

* 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.

* 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.

* 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.

* chore(changelog): drop the render efficiency entry
2026-11-23 07:45:24 +00:00

240 lines
7.0 KiB
TypeScript

import {
DeleteForeverRounded,
PauseCircleOutlineRounded,
PlayCircleOutlineRounded,
SettingsRounded,
WarningRounded,
} from '@mui/icons-material'
import { Box, Typography, alpha, useTheme } from '@mui/material'
import { useLockFn } from 'ahooks'
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { type DialogRef, Switch, TooltipIcon } from '@/components/base'
import { SysproxyViewer } from '@/components/setting/mods/sysproxy-viewer'
import { TunViewer } from '@/components/setting/mods/tun-viewer'
import { useServiceUninstaller } from '@/hooks/use-service-uninstaller'
import { useSystemProxyState } from '@/hooks/use-system-proxy-state'
import { useSystemState } from '@/hooks/use-system-state'
import { useVerge } from '@/hooks/use-verge'
import { showNotice } from '@/services/notice-service'
import { requestService } from '@/services/service-request'
interface ProxySwitchProps {
label?: string
onError?: (err: Error) => void
noRightPadding?: boolean
}
interface SwitchRowProps {
label: string
active: boolean
disabled?: boolean
infoTitle: string
onInfoClick?: () => void
extraIcons?: React.ReactNode
/** Return false to roll back without reporting an error. */
onToggle: (value: boolean) => Promise<boolean | void>
onError?: (err: Error) => void
highlight?: boolean
}
/**
* 抽取的子组件:统一的开关 UI
* active = 真实状态OS/配置 乐观更新
*/
const SwitchRow = ({
label,
active,
disabled,
infoTitle,
onInfoClick,
extraIcons,
onToggle,
onError,
highlight,
}: SwitchRowProps) => {
const theme = useTheme()
const [checked, setChecked] = useState(active)
const pendingRef = useRef(false)
if (pendingRef.current) {
if (active === checked) pendingRef.current = false
} else if (checked !== active) {
setChecked(active)
}
const handleChange = (_: React.ChangeEvent, value: boolean) => {
pendingRef.current = true
setChecked(value)
onToggle(value)
.then((applied) => {
if (applied === false) setChecked(active)
})
.catch((err: any) => {
setChecked(active)
onError?.(err)
})
.finally(() => {
pendingRef.current = false
})
}
return (
<Box
sx={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
p: 1,
pr: 2,
borderRadius: 1.5,
bgcolor: highlight
? alpha(theme.palette.success.main, 0.07)
: 'transparent',
opacity: disabled ? 0.6 : 1,
transition: 'background-color 0.3s',
}}
>
<Box sx={{ display: 'flex', alignItems: 'center' }}>
{active ? (
<PlayCircleOutlineRounded sx={{ color: 'success.main', mr: 1 }} />
) : (
<PauseCircleOutlineRounded sx={{ color: 'text.disabled', mr: 1 }} />
)}
<Typography
variant="subtitle1"
sx={{ fontWeight: 500, fontSize: '15px' }}
>
{label}
</Typography>
<TooltipIcon
title={infoTitle}
icon={SettingsRounded}
onClick={onInfoClick}
sx={{ ml: 1 }}
/>
{extraIcons}
</Box>
<Switch
edge="end"
disabled={disabled}
checked={checked}
onChange={handleChange}
/>
</Box>
)
}
const ProxyControlSwitches = ({
label,
onError,
noRightPadding = false,
}: ProxySwitchProps) => {
const { t } = useTranslation()
const { verge, mutateVerge, patchVerge } = useVerge()
const { uninstallServiceAndStartSidecar } = useServiceUninstaller()
const { indicator: systemProxyIndicator, toggleSystemProxy } =
useSystemProxyState()
const { runState, isTunModeAvailable, isLoading } = useSystemState()
// Offer to uninstall only a service that is actually there and working.
const isServiceInstallReady = runState.serviceUsable
const sysproxyRef = useRef<DialogRef>(null)
const tunRef = useRef<DialogRef>(null)
const { enable_tun_mode } = verge ?? {}
// Enabling needs a running core; disabling only writes OS state and must stay available.
const handleSystemProxyToggle = async (value: boolean) => {
if (value && !isLoading && runState.mode === 'NotRunning') {
showNotice.error('settings.feedback.errors.sysproxy.coreNotReady')
return false
}
await toggleSystemProxy(value)
}
const handleTunToggle = async (value: boolean) => {
if (value && !isTunModeAvailable) {
requestService({
reason: 'tunNeedsService',
restore: { enable_tun_mode: value },
})
return false
}
mutateVerge((prev) => ({ ...prev, enable_tun_mode: value }))
await patchVerge({ enable_tun_mode: value })
}
const onUninstallService = useLockFn(async () => {
try {
await uninstallServiceAndStartSidecar()
} catch (err) {
showNotice.error(err)
}
})
const isSystemProxyMode =
label === t('settings.sections.system.toggles.systemProxy') || !label
const isTunMode = label === t('settings.sections.system.toggles.tunMode')
return (
<Box sx={{ width: '100%', pr: noRightPadding ? 1 : 2 }}>
{isSystemProxyMode && (
<SwitchRow
label={t('settings.sections.proxyControl.fields.systemProxy')}
active={systemProxyIndicator}
infoTitle={t('settings.sections.proxyControl.tooltips.systemProxy')}
onInfoClick={() => sysproxyRef.current?.open()}
onToggle={handleSystemProxyToggle}
onError={onError}
highlight={systemProxyIndicator}
/>
)}
{isTunMode && (
<SwitchRow
label={t('settings.sections.proxyControl.fields.tunMode')}
active={(enable_tun_mode && isTunModeAvailable) || false}
infoTitle={t('settings.sections.proxyControl.tooltips.tunMode')}
onInfoClick={() => tunRef.current?.open()}
onToggle={handleTunToggle}
onError={onError}
highlight={(enable_tun_mode && isTunModeAvailable) || false}
extraIcons={
<>
{!isTunModeAvailable && (
<TooltipIcon
title={t(
'settings.sections.proxyControl.tooltips.tunUnavailable',
)}
icon={WarningRounded}
sx={{ color: 'warning.main', ml: 1 }}
/>
)}
{isServiceInstallReady && (
<TooltipIcon
title={t(
'settings.sections.proxyControl.actions.uninstallService',
)}
icon={DeleteForeverRounded}
color="secondary"
data-setting-target="service-uninstall"
onClick={onUninstallService}
sx={{ ml: 1 }}
/>
)}
</>
}
/>
)}
{isSystemProxyMode && <SysproxyViewer ref={sysproxyRef} />}
{isTunMode && <TunViewer ref={tunRef} />}
</Box>
)
}
export default ProxyControlSwitches