perf(proxies): reduce remaining projection and menu churn (#8622)

This commit is contained in:
Tunglies
2026-11-17 02:55:21 +00:00
committed by GitHub
parent 9f7b390cd4
commit 1b212f9a28
6 changed files with 357 additions and 273 deletions
+91 -56
View File
@@ -31,6 +31,7 @@ import {
} from '@mui/material'
import { useLockFn } from 'ahooks'
import {
memo,
useCallback,
useEffect,
useEffectEvent,
@@ -204,14 +205,11 @@ const optionValue = (memberIndex: number, member: ResolvedProxyMember) =>
const sortProxyOptions = (
options: ProxyOption[],
sortType: ProxySortType,
sortType: 0 | 1,
delayOf: (member: ResolvedProxyMember) => number,
latencyTimeout?: number,
) => {
if (sortType === 0) return options
if (sortType === 2) {
return [...options].sort((a, b) => a.name.localeCompare(b.name))
}
const effectiveTimeout =
typeof latencyTimeout === 'number' && latencyTimeout > 0
@@ -433,6 +431,72 @@ interface PersistentProxySelectProps
onChange: (value: string) => void
}
const ProxyMenuOption = memo(function ProxyMenuOption({
option,
selected,
isFixed,
fixedProxyInUsed,
delay,
onChange,
}: {
option: ProxyOption
selected: boolean
isFixed: boolean
fixedProxyInUsed: boolean
delay: number
onChange: (value: string) => void
}) {
return (
<MenuItem
role="option"
aria-selected={selected}
selected={selected}
disabled={option.disabled}
onClick={() => {
if (!option.disabled) onChange(option.value)
}}
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
width: '100%',
pr: 1,
}}
>
{isFixed && (
<span
style={{
position: 'absolute',
fontSize: '12px',
top: '-5px',
right: '5px',
...(!fixedProxyInUsed && {
filter: 'grayscale(1)',
}),
}}
>
📌
</span>
)}
<Typography noWrap sx={{ flex: 1, mr: 1 }}>
{option.name}
</Typography>
{!option.disabled && (
<Chip
size="small"
label={delayManager.formatDelay(delay)}
color={convertDelayColor(delay)}
sx={{
minWidth: '60px',
height: '22px',
flexShrink: 0,
}}
/>
)}
</MenuItem>
)
})
const PersistentProxySelect = ({
groupName,
fixed,
@@ -485,54 +549,15 @@ const PersistentProxySelect = ({
: delayManager.getDelayFix(option.member, groupName)
return (
<MenuItem
<ProxyMenuOption
key={option.value}
role="option"
aria-selected={selected}
option={option}
selected={selected}
disabled={option.disabled}
onClick={() => {
if (!option.disabled) onChange(option.value)
}}
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
width: '100%',
pr: 1,
}}
>
{isFixed && (
<span
style={{
position: 'absolute',
fontSize: '12px',
top: '-5px',
right: '5px',
...(!fixedProxyInUsed && {
filter: 'grayscale(1)',
}),
}}
>
📌
</span>
)}
<Typography noWrap sx={{ flex: 1, mr: 1 }}>
{option.name}
</Typography>
{!option.disabled && (
<Chip
size="small"
label={delayManager.formatDelay(delay)}
color={convertDelayColor(delay)}
sx={{
minWidth: '60px',
height: '22px',
flexShrink: 0,
}}
/>
)}
</MenuItem>
isFixed={isFixed}
fixedProxyInUsed={fixedProxyInUsed}
delay={delay}
onChange={onChange}
/>
)
})
}
@@ -898,18 +923,28 @@ export const CurrentProxyCard = () => {
refreshProxy()
})
const nameSortedProxyOptions = useMemo(
() =>
!isDirectMode && openSelect === 'proxy' && sortType === 2
? [...unsortedProxyOptions].sort((a, b) => a.name.localeCompare(b.name))
: unsortedProxyOptions,
[isDirectMode, openSelect, sortType, unsortedProxyOptions],
)
const proxyOptions = useMemo(
() =>
isDirectMode || openSelect !== 'proxy' || typeof delays === 'number'
? []
: sortProxyOptions(
unsortedProxyOptions,
sortType,
delays.of,
defaultLatencyTimeout!,
),
: sortType === 2
? nameSortedProxyOptions
: sortProxyOptions(
unsortedProxyOptions,
sortType,
delays.of,
defaultLatencyTimeout!,
),
[
delays,
nameSortedProxyOptions,
isDirectMode,
openSelect,
unsortedProxyOptions,
+13 -8
View File
@@ -571,6 +571,17 @@ function NormalProxyGroups(props: { mode: string }) {
[renderList],
)
const onStickyHeadState = useCallback(
async (groupName: string, patch: Partial<HeadState>) => {
if (patch.filterText !== undefined) {
handleGroupLocationByName(groupName)
await stickyListRef.current?.waitForScrollEnd()
}
onHeadState(groupName, patch)
},
[handleGroupLocationByName, onHeadState],
)
const renderGroupItem = useCallback(
(item: IRenderItem, _index: number, stickyed: boolean) => (
<ProxyRender
@@ -578,13 +589,7 @@ function NormalProxyGroups(props: { mode: string }) {
stickyed={stickyed}
onLocation={handleLocation}
onCheckAll={handleCheckAll}
onHeadState={async (groupName, patch) => {
if (stickyed && patch.filterText !== undefined) {
handleGroupLocationByName(groupName)
await stickyListRef.current?.waitForScrollEnd()
}
onHeadState(groupName, patch)
}}
onHeadState={stickyed ? onStickyHeadState : onHeadState}
onChangeProxy={handleChangeProxy}
onGroupToggle={handleGroupToggle}
/>
@@ -595,7 +600,7 @@ function NormalProxyGroups(props: { mode: string }) {
onHeadState,
handleLocation,
handleGroupToggle,
handleGroupLocationByName,
onStickyHeadState,
],
)
+183 -179
View File
@@ -43,7 +43,7 @@ interface RenderProps {
onGroupToggle?: (group: IRenderItem['group']) => void
}
export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
const ProxyGroupHeader = (props: RenderProps) => {
const { t } = useTranslation()
const {
item,
@@ -51,11 +51,9 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
onLocation,
onCheckAll,
onHeadState,
onChangeProxy,
onGroupToggle,
isChainMode: _ = false,
} = props
const { type, group, headState, member, memberCol } = item
const { group, headState } = item
const { verge } = useVerge()
const enable_group_icon = verge?.enable_group_icon ?? true
const toolsOnLeft = verge?.proxy_group_tools_position === 'left'
@@ -69,11 +67,187 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
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(group)}
onCheckDelay={() => onCheckAll(group.name)}
onHeadState={(p) => onHeadState(group.name, p)}
/>
{!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
}
if (type !== 4 || !memberCol) return null
return memberCol.map((occurrence) => (
<ProxyItemMini
@@ -87,161 +261,7 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
))
}, [type, memberCol, item.key, group, showType, onChangeProxy])
if (type === 0) {
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(group)}
onCheckDelay={() => onCheckAll(group.name)}
onHeadState={(p) => onHeadState(group.name, p)}
/>
{!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>
)
}
if (type === 0) return <ProxyGroupHeader {...props} />
if (type === 1) {
return (
@@ -271,23 +291,7 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
}
if (type === 3) {
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>
)
return <ProxyEmptyRow />
}
if (type === 4) {
+66 -26
View File
@@ -68,6 +68,7 @@ type GroupCache = {
/// does not throw away every other group's sorted order.
delays: DelaySnapshot | undefined
occurrences: ResolvedMemberOccurrence[] | undefined
projected: ResolvedMemberOccurrence[] | undefined
items: IRenderItem[]
}
@@ -260,11 +261,15 @@ export const useRenderList = (
const groupCacheRef = useRef<Map<string, GroupCache> | null>(null)
const cachedViewRef = useRef(proxyView)
const prevListRef = useRef<IRenderItem[]>([])
const prevGroupItemsRef = useRef<IRenderItem[][]>([])
const prevModeRef = useRef(mode)
const renderList = useMemo<IRenderItem[]>(() => {
const cache = (groupCacheRef.current ??= new Map())
if (cachedViewRef.current !== proxyView) {
cache.clear()
prevGroupItemsRef.current = []
prevListRef.current = []
cachedViewRef.current = proxyView
}
if (!proxyView) return []
@@ -301,7 +306,7 @@ export const useRenderList = (
}))
}
const retList = renderGroups.flatMap((group) => {
const groupItems = renderGroups.map((group) => {
const isFlat = group === proxyView.global
const headState = headStates[group.name] || DEFAULT_STATE
const cached = cache.get(group.name)
@@ -316,6 +321,51 @@ export const useRenderList = (
return cached.items
}
// Duplicate names share one item listener until the delay-store fix lands.
const refreshRepeated =
repeatedNameGroups.has(group.name) &&
cached?.delays !== groupDelays.get(group.name)
let resolved =
cached?.group === group && !refreshRepeated
? cached.occurrences
: undefined
let projected: ResolvedMemberOccurrence[] | undefined
if (headState.open || isFlat) {
resolved ??= resolveOccurrences(proxyView, group)
projected = filterSort(
resolved,
group.name,
headState.filterText,
headState.sortType,
latencyTimeout!,
{
matchCase: headState.filterMatchCase,
matchWholeWord: headState.filterMatchWholeWord,
useRegularExpression: headState.filterUseRegularExpression,
},
)
// Repeated names still need new member props while item listeners share a key.
if (
!refreshRepeated &&
cached?.group === group &&
cached.headState === headState &&
cached.col === col &&
cached.projected?.length === projected.length &&
projected.every(
(member, index) => member === cached.projected?.[index],
)
) {
cache.set(group.name, {
...cached,
latencyTimeout,
delays: groupDelays.get(group.name),
})
return cached.items
}
} else {
resolved = undefined
}
const ret: IRenderItem[] = [
isFlat
? { type: 1, key: `head-${group.name}`, group, headState }
@@ -328,29 +378,8 @@ export const useRenderList = (
testUrl: group.testUrl!,
},
]
// Duplicate names share one item listener until the delay-store fix lands.
const refreshRepeated =
repeatedNameGroups.has(group.name) &&
cached?.delays !== groupDelays.get(group.name)
let resolved =
cached?.group === group && !refreshRepeated
? cached.occurrences
: undefined
if (headState.open || isFlat) {
resolved ??= resolveOccurrences(proxyView, group)
const occurrences = filterSort(
resolved,
group.name,
headState.filterText,
headState.sortType,
latencyTimeout!,
{
matchCase: headState.filterMatchCase,
matchWholeWord: headState.filterMatchWholeWord,
useRegularExpression: headState.filterUseRegularExpression,
},
)
if (projected) {
const occurrences = projected
if (occurrences.length === 0) {
ret.push({ type: 3, key: `empty-${group.name}`, group, headState })
} else if (col > 1) {
@@ -375,8 +404,6 @@ export const useRenderList = (
})),
)
}
} else {
resolved = undefined
}
cache.set(group.name, {
@@ -386,11 +413,24 @@ export const useRenderList = (
latencyTimeout: latencyTimeout!,
delays: groupDelays.get(group.name),
occurrences: resolved,
projected,
items: ret,
})
return ret
})
if (
prevModeRef.current === mode &&
prevGroupItemsRef.current.length === groupItems.length &&
groupItems.every(
(items, index) => items === prevGroupItemsRef.current[index],
)
) {
return prevListRef.current
}
prevModeRef.current = mode
prevGroupItemsRef.current = groupItems
const retList = groupItems.flat()
const filtered =
mode === 'rule' ? retList.filter((item) => !item.group.hidden) : retList
if (
+3 -3
View File
@@ -31,12 +31,12 @@ export const useGroupDelays = (
export const useGroupsDelays = (
groups: readonly string[],
): ReadonlyMap<string, DelaySnapshot> => {
// Subscribe by group membership; callers rebuild the array on every render.
const groupKey = groups.join(' ')
// Group membership must remain unambiguous when names contain spaces.
const groupKey = JSON.stringify(groups)
const subscribe = useCallback(
(onSettle: () => void) => {
const names = groupKey ? groupKey.split(' ') : []
const names: string[] = JSON.parse(groupKey)
const unsubscribes = names.map((name) =>
delayManager.addGroupListener(name, onSettle),
)
+1 -1
View File
@@ -132,7 +132,7 @@ class DelayManager {
const cached = this.groupSetSnapshots.get(groupKey)
if (cached) return cached
const names = groupKey ? groupKey.split(' ') : []
const names: string[] = JSON.parse(groupKey)
const snapshots = new Map(
names.map((name) => [name, this.groupDelays(name)]),
)