Files
clash-verge-rev/src/components/proxy/proxy-render.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

344 lines
8.9 KiB
TypeScript

import {
ExpandLessRounded,
ExpandMoreRounded,
InboxRounded,
} from '@mui/icons-material'
import {
alpha,
Box,
ListItemText,
ListItemButton,
Typography,
styled,
Chip,
Tooltip,
} from '@mui/material'
import { memo, useId, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useIconCache } from '@/hooks/use-icon-cache'
import { useVerge } from '@/hooks/use-verge'
import { useThemeMode } from '@/services/states'
import type { ResolvedProxyMember } from '@/types/proxy-view'
import { ProxyGroupHeaderBlock } from './proxy-group-header-block'
import { ProxyGroupTools } from './proxy-group-tools'
import { ProxyHead } from './proxy-head'
import { ProxyItem } from './proxy-item'
import { ProxyItemMini } from './proxy-item-mini'
import type { HeadState } from './use-head-state'
import type { IRenderItem } from './use-render-list'
interface RenderProps {
item: IRenderItem
stickyed?: boolean
isChainMode?: boolean
onLocation: (groupName: string) => void
onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onChangeProxy: (
group: IRenderItem['group'],
member: ResolvedProxyMember,
) => void
onGroupToggle?: (group: IRenderItem['group']) => void
}
const ProxyGroupHeader = (props: RenderProps) => {
const { t } = useTranslation()
const {
item,
stickyed = false,
onLocation,
onCheckAll,
onHeadState,
onGroupToggle,
} = props
const { group, headState } = item
const { verge } = useVerge()
const enable_group_icon = verge?.enable_group_icon ?? true
const toolsOnLeft = verge?.proxy_group_tools_position === 'left'
const headerId = useId()
const mode = useThemeMode()
const isDark = mode === 'dark'
const itembackgroundcolor = isDark ? '#282A36' : '#ffffff'
const iconCachePath = useIconCache({
icon: group.icon,
cacheKey: group.name.replaceAll(' ', ''),
enabled: enable_group_icon,
})
const nameBlock = (
<ProxyGroupHeaderBlock
key="name"
group={headerId}
block="name"
sx={{ flex: '0 1 auto', mr: toolsOnLeft ? 1 : 0 }}
>
{enable_group_icon && group.icon?.trim().startsWith('http') && (
<img
src={iconCachePath === '' ? group.icon : iconCachePath}
alt={group.name}
width="32px"
style={{ marginRight: '12px', borderRadius: '6px' }}
/>
)}
{enable_group_icon && group.icon?.trim().startsWith('data') && (
<img
src={group.icon}
alt={group.name}
width="32px"
style={{ marginRight: '12px', borderRadius: '6px' }}
/>
)}
{enable_group_icon && group.icon?.trim().startsWith('<svg') && (
<img
src={`data:image/svg+xml;charset=utf-8,${encodeURIComponent(group.icon)}`}
alt={group.name}
width="32px"
/>
)}
<ListItemText
sx={{ flex: '0 1 auto', minWidth: 0 }}
primary={<StyledPrimary>{group.name}</StyledPrimary>}
secondary={
<Box
sx={{
display: 'flex',
alignItems: 'center',
pt: '2px',
overflow: 'hidden',
whiteSpace: 'nowrap',
}}
>
<Box
component="span"
sx={{
marginTop: '2px',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
<StyledTypeBox>{group.type}</StyledTypeBox>
<StyledSubtitle sx={{ color: 'text.secondary' }}>
{group.now}
</StyledSubtitle>
</Box>
</Box>
}
slotProps={{
secondary: {
component: 'div',
sx: {
display: 'flex',
alignItems: 'center',
color: '#ccc',
},
},
}}
/>
</ProxyGroupHeaderBlock>
)
const proxyCount = (
<Tooltip title={t('proxies.page.labels.proxyCount')} arrow>
<div
style={{
minWidth: '50px',
display: 'flex',
justifyContent: toolsOnLeft ? 'start' : 'end',
alignItems: 'center',
}}
>
<Chip
size="small"
label={`${group.members.length}`}
sx={{
mr: toolsOnLeft ? 0 : 1,
backgroundColor: (theme) => alpha(theme.palette.primary.main, 0.1),
color: (theme) => theme.palette.primary.main,
}}
/>
</div>
</Tooltip>
)
const toolsBlock = (
<ProxyGroupHeaderBlock
key="tools"
group={headerId}
block="tools"
sx={{
flex: '1 1 auto',
justifyContent: toolsOnLeft ? 'start' : 'end',
mr: toolsOnLeft ? 2 : 0,
}}
>
{toolsOnLeft && proxyCount}
<ProxyGroupTools
side={toolsOnLeft ? 'left' : 'right'}
url={group.testUrl!}
groupName={group.name}
headState={headState!}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onHeadState={onHeadState}
/>
{!toolsOnLeft && proxyCount}
</ProxyGroupHeaderBlock>
)
return (
<div style={{ padding: '4px 8px' }}>
<ListItemButton
dense
sx={{
boxShadow:
stickyed && headState?.open
? '0 4px 8px rgba(0, 0, 0, 0.2) !important'
: undefined,
}}
style={{
background: itembackgroundcolor,
height: '100%',
borderRadius: '8px',
}}
onClick={() => {
if (headState?.open) {
onGroupToggle?.(group)
}
onHeadState?.(group.name, { open: !headState?.open })
}}
>
<Box sx={{ width: '100%' }}>
<Box sx={{ display: 'flex', alignItems: 'center', width: '100%' }}>
{toolsOnLeft ? toolsBlock : nameBlock}
{toolsOnLeft ? nameBlock : toolsBlock}
{headState?.open ? <ExpandLessRounded /> : <ExpandMoreRounded />}
</Box>
</Box>
</ListItemButton>
</div>
)
}
const ProxyEmptyRow = () => {
const { t } = useTranslation()
return (
<Box
sx={{
py: 2,
pl: 0,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
}}
>
<InboxRounded sx={{ fontSize: '2.5em', color: 'inherit' }} />
<Typography sx={{ color: 'inherit' }}>
{t('proxies.page.empty.noProxies')}
</Typography>
</Box>
)
}
export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
const { item, onLocation, onCheckAll, onHeadState, onChangeProxy } = props
const { type, group, headState, member, memberCol } = item
const showType = headState?.showType
const memberColItemsMemo = useMemo(() => {
if (type !== 4 || !memberCol) return null
return memberCol.map((occurrence) => (
<ProxyItemMini
key={`${item.key}-${occurrence.memberIndex}`}
group={group}
member={occurrence.member}
selected={group.now === occurrence.member.ref.name}
showType={showType}
onClick={(nextMember) => onChangeProxy(group, nextMember)}
/>
))
}, [type, memberCol, item.key, group, showType, onChangeProxy])
if (type === 0) return <ProxyGroupHeader {...props} />
if (type === 1) {
return (
<ProxyHead
sx={{ pl: 2, pr: 3, mt: 0.5, mb: 1 }}
url={group.testUrl!}
groupName={group.name}
headState={headState!}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onHeadState={onHeadState}
/>
)
}
if (type === 2) {
return (
<ProxyItem
group={group}
member={member!.member}
selected={group.now === member?.member.ref.name}
showType={headState?.showType}
sx={{ py: 0, pl: 2 }}
onClick={(nextMember) => onChangeProxy(group, nextMember)}
/>
)
}
if (type === 3) {
return <ProxyEmptyRow />
}
if (type === 4) {
return (
<Box
sx={{
height: 56,
display: 'grid',
my: 0.5,
gap: 1,
px: 2,
gridTemplateColumns: `repeat(${item.col! || 2}, 1fr)`,
}}
>
{memberColItemsMemo}
</Box>
)
}
return null
})
const StyledPrimary = styled('span')`
font-size: 16px;
font-weight: 700;
line-height: 1.5;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
`
const StyledSubtitle = styled('span')`
font-size: 13px;
overflow: hidden;
color: text.secondary;
text-overflow: ellipsis;
white-space: nowrap;
`
const StyledTypeBox = styled(Box)(({ theme }) => ({
display: 'inline-block',
border: '1px solid #ccc',
borderColor: alpha(theme.palette.primary.main, 0.5),
color: alpha(theme.palette.primary.main, 0.8),
borderRadius: 4,
fontSize: 10,
padding: '0 4px',
lineHeight: 1.5,
marginRight: '8px',
}))