feat: sticky groups (#7195)

* feat(proxy): implement sticky virtual list and group tools

- Add new StickyVirtualList component for better performance with sticky headers
- Create ProxyGroupTools component for filtering, sorting and testing proxy groups
- Enhance proxy groups with improved scrolling and group toggle functionality
- Integrate search box with click event handling
- Remove redundant ProxyHead component usage

* style: remove unused import and update TypeScript types

* refactor: convert function component to forwardRef component to fix biome lint error

* feat(proxy): extract proxy chain UI to separate component

* refactor: remove custom throttle implementation and simplify dependencies

* feat(proxy): improve proxy groups UI and scrolling behavior

- Add initialOffset prop to StickyVirtualList for better scroll position restoration
- Refactor ProxyGroups component to separate chain and normal modes
- Implement scroll position persistence for both chain and normal modes
- Add sticky shadow effect for expanded proxy groups
- Remove unnecessary ScrollTopButton component
- Optimize scroll event handling with throttling
- Improve code organization with custom hooks and component separation

* docs(proxy-groups): Add TODO comment for initial render position issue

* feat(proxy): improve scroll position handling and UI display

* refactor(proxy): simplify scroll handling logic and remove unused code

* fix(sticky-virtual-list): remove duplicate styles and add padding

* refactor(proxy): rename scroll offset variables and functions for clarity

* refactor: remove unnecessary refs and simplify onClick handlers

* fix(proxy-groups): handle initial scroll position state

* feat(zed): add biome formatter configuration

* refactor(proxy): remove unused headState import and type annotations

* style(proxy): improve type imports and conditional rendering

* .

* feat(proxy): add ProxyHead component to render in global mode

* chore: ignore .zed directory

* docs: update changelog
This commit is contained in:
oomeow
2026-07-02 13:22:40 +00:00
committed by GitHub
parent c2ddb5c111
commit dd3ef698f5
13 changed files with 1593 additions and 769 deletions
+2 -1
View File
@@ -21,7 +21,7 @@
- 增加 TrustTunnel, OpenVPN, Tailscale, GostRelay 节点显示支持
- 全局扩展脚本增加恢复默认按钮
- DNS 添加 fake-ip-range6 可配置项
- DNS 添加 fake-ip-range6 可配置项
</details>
@@ -32,5 +32,6 @@
- 更健壮的 Mihomo API 通信机制
- 关闭 autofill 弹出窗口
- 改进切换订阅后激活选中节点的逻辑
- 实现代理组粘性滚动列表
</details>
@@ -1,5 +1,4 @@
import { Box, CircularProgress } from '@mui/material'
import React from 'react'
interface BaseLoadingOverlayProps {
isLoading: boolean
+5 -1
View File
@@ -2,7 +2,8 @@ import { ClearRounded } from '@mui/icons-material'
import { Box, SvgIcon, TextField, styled, IconButton } from '@mui/material'
import Tooltip from '@mui/material/Tooltip'
import {
ChangeEvent,
type ChangeEvent,
type MouseEvent,
useCallback,
useEffect,
useMemo,
@@ -35,6 +36,7 @@ type SearchProps = {
useRegularExpression?: boolean
searchState?: Partial<SearchOptionState>
onSearch: (match: (content: string) => boolean, state: SearchState) => void
onClick?: (e: MouseEvent<HTMLDivElement>) => void
}
const StyledTextField = styled(TextField)(({ theme }) => ({
@@ -80,6 +82,7 @@ export const BaseSearchBox = ({
matchWholeWord: defaultMatchWholeWord = false,
useRegularExpression: defaultUseRegularExpression = false,
onSearch,
onClick,
}: SearchProps) => {
const { t } = useTranslation()
const onSearchRef = useRef(onSearch)
@@ -199,6 +202,7 @@ export const BaseSearchBox = ({
placeholder={placeholder ?? t('shared.placeholders.filter')}
sx={{ input: { py: 0.65, px: 1.25 } }}
value={text}
onClick={onClick}
onChange={handleChangeText}
error={!!effectiveErrorMessage}
slotProps={{
+4
View File
@@ -16,3 +16,7 @@ export { MonacoEditor } from './monaco-editor'
export { Switch } from './base-switch'
export { TooltipIcon } from './base-tooltip-icon'
export { VirtualList, type VirtualListHandle } from './virtual-list'
export {
StickyVirtualList,
type StickyVirtualListHandle,
} from './sticky-virtual-list'
+301
View File
@@ -0,0 +1,301 @@
import { useVirtualizer } from '@tanstack/react-virtual'
import {
forwardRef,
type ReactNode,
useCallback,
useImperativeHandle,
useMemo,
useRef,
} from 'react'
type ScrollToIndexOptions = {
align?: 'auto' | 'center' | 'end' | 'start'
behavior?: ScrollBehavior
}
const findGroupSectionIndex = (groupIndexes: number[], itemIndex: number) => {
let low = 0
let high = groupIndexes.length - 1
let matchedIndex = -1
while (low <= high) {
const middle = Math.floor((low + high) / 2)
if (groupIndexes[middle] <= itemIndex) {
matchedIndex = middle
low = middle + 1
} else {
high = middle - 1
}
}
return matchedIndex
}
export interface StickyVirtualListHandle {
getScrollElement: () => HTMLDivElement | null
isItemScrolledPastStart: (index: number, tolerance?: number) => boolean
scrollToIndex: (index: number, options?: ScrollToIndexOptions) => void
isScrolling: () => boolean
waitForScrollEnd: () => Promise<void>
}
export interface StickyVirtualListProps<TItem> {
initialOffset?: number
items: TItem[]
isGroupItem: (item: TItem, index: number) => boolean
getItemKey: (item: TItem, index: number) => React.Key
// 组项预估高度
estimateGroupItemHeight: number
// 非组项预估高度
estimateItemHeight: number
renderGroupItem: (item: TItem, index: number, stickyed: boolean) => ReactNode
renderItem: (item: TItem, index: number) => ReactNode
className?: string
style?: React.CSSProperties
overscan?: number
}
export const StickyVirtualList = forwardRef(function StickyVirtualListInner<
TItem,
>(
props: StickyVirtualListProps<TItem>,
ref: React.ForwardedRef<StickyVirtualListHandle>,
) {
const {
initialOffset = 0,
items,
isGroupItem,
getItemKey,
estimateGroupItemHeight,
estimateItemHeight,
renderGroupItem,
renderItem,
className,
style,
overscan = 8,
} = props
const scrollParentRef = useRef<HTMLDivElement>(null)
const getEstimatedItemHeight = useCallback(
(index: number) =>
isGroupItem(items[index], index)
? estimateGroupItemHeight
: estimateItemHeight,
[estimateGroupItemHeight, estimateItemHeight, isGroupItem, items],
)
const groupIndexes = useMemo(
() =>
items.reduce<number[]>((indexes, item, index) => {
if (isGroupItem(item, index)) indexes.push(index)
return indexes
}, []),
[isGroupItem, items],
)
const groupSections = useMemo(
() =>
groupIndexes.map((groupIndex, index) => ({
groupIndex,
nextGroupIndex: groupIndexes[index + 1] ?? items.length,
})),
[groupIndexes, items.length],
)
const estimatedOffsets = useMemo(() => {
const offsets = new Array<number>(items.length + 1)
offsets[0] = 0
for (let i = 0; i < items.length; i++) {
offsets[i + 1] = offsets[i] + getEstimatedItemHeight(i)
}
return offsets
}, [getEstimatedItemHeight, items.length])
const rowVirtualizer = useVirtualizer({
initialOffset,
count: items.length,
estimateSize: getEstimatedItemHeight,
getItemKey: (index) => getItemKey(items[index], index),
getScrollElement: () => scrollParentRef.current,
overscan,
})
const virtualItems = rowVirtualizer.getVirtualItems()
const getVirtualOffset = useCallback(
(index: number) => {
return (
rowVirtualizer.measurementsCache[index]?.start ??
estimatedOffsets[index]
)
},
[estimatedOffsets, rowVirtualizer],
)
const visibleGroupSections = useMemo(() => {
if (!virtualItems.length || !groupSections.length) return []
const firstVirtualIndex = virtualItems[0].index
const lastVirtualIndex = virtualItems[virtualItems.length - 1].index
const matchedFirstSectionIndex = findGroupSectionIndex(
groupIndexes,
firstVirtualIndex,
)
const lastSectionIndex = findGroupSectionIndex(
groupIndexes,
lastVirtualIndex,
)
if (lastSectionIndex < 0) return []
const firstSectionIndex =
matchedFirstSectionIndex >= 0 ? matchedFirstSectionIndex : 0
return groupSections.slice(
firstSectionIndex,
Math.min(lastSectionIndex + 2, groupSections.length),
)
}, [groupIndexes, groupSections, virtualItems])
const isGroupSticky = useCallback(
(groupIndex: number, tolerance = 0) => {
const scroller = scrollParentRef.current
if (!scroller) return false
return scroller.scrollTop > getVirtualOffset(groupIndex) + tolerance
},
[getVirtualOffset],
)
useImperativeHandle(
ref,
() => ({
getScrollElement: () => scrollParentRef.current,
isItemScrolledPastStart: (index, tolerance = 0) => {
return isGroupSticky(index, tolerance)
},
scrollToIndex: (index, options) => {
rowVirtualizer.scrollToIndex(index, options)
},
isScrolling: () => rowVirtualizer.isScrolling,
waitForScrollEnd: () => {
return new Promise((resolve) => {
let maxCheckCount = 5
const interval = setInterval(() => {
if (!rowVirtualizer.isScrolling || maxCheckCount < 0) {
clearInterval(interval)
resolve()
return
}
maxCheckCount -= 1
}, 100)
})
},
}),
[isGroupSticky, rowVirtualizer],
)
return (
<div
ref={scrollParentRef}
className={className}
style={{
overflowY: 'auto',
contain: 'strict',
width: '100%',
height: '100%',
overflowAnchor: 'none',
...style,
}}
>
<div
style={{
height: rowVirtualizer.getTotalSize(),
position: 'relative',
width: '100%',
paddingBottom: 10,
}}
>
<div
style={{
inset: 0,
pointerEvents: 'none',
position: 'absolute',
zIndex: 10,
}}
>
{visibleGroupSections.map(({ groupIndex, nextGroupIndex }) => {
const group = items[groupIndex]
const start = getVirtualOffset(groupIndex)
const end =
nextGroupIndex < items.length
? getVirtualOffset(nextGroupIndex)
: rowVirtualizer.getTotalSize()
const stickyed = isGroupSticky(groupIndex, 1)
return (
<div
key={getItemKey(group, groupIndex)}
style={{
position: 'absolute',
top: start,
left: 0,
width: '100%',
height: Math.max(end - start, estimateGroupItemHeight),
}}
>
<div
data-index={groupIndex}
style={{
pointerEvents: 'auto',
position: 'sticky',
top: 0,
zIndex: 1,
}}
>
{renderGroupItem(group, groupIndex, stickyed)}
</div>
</div>
)
})}
</div>
{virtualItems.map((virtualRow) => {
const item = items[virtualRow.index]
const isGroup = isGroupItem(item, virtualRow.index)
return (
<div
key={virtualRow.key}
ref={rowVirtualizer.measureElement}
data-index={virtualRow.index}
style={{
left: 0,
position: 'absolute',
top: 0,
transform: `translateY(${virtualRow.start}px)`,
width: '100%',
zIndex: 1,
...(isGroup && {
opacity: 0,
zIndex: -10,
}),
}}
>
{isGroup
? renderGroupItem(item, virtualRow.index, false) // 渲染组,以便动态计算组高度
: renderItem(item, virtualRow.index)}
</div>
)
})}
</div>
</div>
)
}) as <TItem>(
props: StickyVirtualListProps<TItem> & {
ref?: React.Ref<StickyVirtualListHandle>
},
) => React.ReactElement
+1 -1
View File
@@ -1,7 +1,7 @@
import {
closestCenter,
DndContext,
DragEndEvent,
type DragEndEvent,
KeyboardSensor,
PointerSensor,
useSensor,
+252
View File
@@ -0,0 +1,252 @@
import AccessTimeRounded from '@mui/icons-material/AccessTimeRounded'
import FilterAltOffRounded from '@mui/icons-material/FilterAltOffRounded'
import FilterAltRounded from '@mui/icons-material/FilterAltRounded'
import MyLocationRounded from '@mui/icons-material/MyLocationRounded'
import NetworkCheckRounded from '@mui/icons-material/NetworkCheckRounded'
import SortByAlphaRounded from '@mui/icons-material/SortByAlphaRounded'
import SortRounded from '@mui/icons-material/SortRounded'
import VisibilityOffRounded from '@mui/icons-material/VisibilityOffRounded'
import VisibilityRounded from '@mui/icons-material/VisibilityRounded'
import WifiTetheringOffRounded from '@mui/icons-material/WifiTetheringOffRounded'
import WifiTetheringRounded from '@mui/icons-material/WifiTetheringRounded'
import { Box, IconButton, type SxProps, TextField } from '@mui/material'
import { memo, useEffect } from 'react'
import { flushSync } from 'react-dom'
import { useTranslation } from 'react-i18next'
import { useVerge } from '@/hooks/use-verge'
import delayManager from '@/services/delay'
import { BaseSearchBox } from '../base'
import type { ProxySortType } from './use-filter-sort'
import type { HeadState } from './use-head-state'
interface Props {
sx?: SxProps
url?: string
groupName: string
headState: HeadState
onLocation: () => void
onCheckDelay: () => void
onHeadState: (val: Partial<HeadState>) => void
}
export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) {
const {
sx,
url,
groupName,
headState,
onCheckDelay,
onHeadState,
onLocation,
} = props
const {
showType,
sortType,
filterText,
textState,
testUrl,
filterMatchCase,
filterMatchWholeWord,
filterUseRegularExpression,
} = headState
const { t } = useTranslation()
const { verge } = useVerge()
const defaultLatencyUrl =
verge?.default_latency_test?.trim() ||
'http://cp.cloudflare.com/generate_204'
useEffect(() => {
delayManager.setUrl(groupName, testUrl?.trim() || url || defaultLatencyUrl)
}, [groupName, testUrl, defaultLatencyUrl, url])
return (
<Box
sx={{
display: 'flex',
alignItems: 'center',
gap: 0.5,
...sx,
}}
>
{textState === 'filter' && (
<Box sx={{ display: 'inline-block', width: 180 }}>
<BaseSearchBox
value={filterText}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
}}
searchState={{
matchCase: filterMatchCase,
matchWholeWord: filterMatchWholeWord,
useRegularExpression: filterUseRegularExpression,
}}
onSearch={(_, state) =>
onHeadState({
filterText: state.text,
filterMatchCase: state.matchCase,
filterMatchWholeWord: state.matchWholeWord,
filterUseRegularExpression: state.useRegularExpression,
})
}
/>
</Box>
)}
{textState === 'url' && (
<TextField
autoComplete="new-password"
hiddenLabel
autoSave="off"
value={testUrl}
size="small"
variant="outlined"
placeholder={t('proxies.page.placeholders.delayCheckUrl')}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
}}
onChange={(e) => onHeadState({ testUrl: e.target.value })}
sx={{ width: 180, input: { py: 0.65, px: 1 } }}
/>
)}
<IconButton
size="small"
color="inherit"
title={t('proxies.page.tooltips.locate')}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
onLocation()
}}
>
<MyLocationRounded fontSize="inherit" />
</IconButton>
<IconButton
size="small"
color="inherit"
title={t('proxies.page.tooltips.delayCheck')}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
// Remind the user that it is custom test url
if (testUrl?.trim() && textState !== 'filter') {
onHeadState({ textState: 'url' })
}
onCheckDelay()
}}
>
<NetworkCheckRounded fontSize="inherit" />
</IconButton>
<IconButton
size="small"
color="inherit"
title={
[
t('proxies.page.tooltips.sortDefault'),
t('proxies.page.tooltips.sortDelay'),
t('proxies.page.tooltips.sortName'),
][sortType]
}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
onHeadState({
sortType: ((sortType + 1) % 3) as ProxySortType,
})
}}
>
{sortType !== 1 && sortType !== 2 && <SortRounded fontSize="inherit" />}
{sortType === 1 && <AccessTimeRounded fontSize="inherit" />}
{sortType === 2 && <SortByAlphaRounded fontSize="inherit" />}
</IconButton>
<IconButton
size="small"
color="inherit"
title={t('proxies.page.tooltips.delayCheckUrl')}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
onHeadState({
textState: textState === 'url' ? null : 'url',
})
}}
>
{textState === 'url' ? (
<WifiTetheringRounded fontSize="inherit" />
) : (
<WifiTetheringOffRounded fontSize="inherit" />
)}
</IconButton>
<IconButton
size="small"
color="inherit"
title={
showType
? t('proxies.page.tooltips.showBasic')
: t('proxies.page.tooltips.showDetail')
}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
onHeadState({ showType: !showType })
}}
>
{showType ? (
<VisibilityRounded fontSize="inherit" />
) : (
<VisibilityOffRounded fontSize="inherit" />
)}
</IconButton>
<IconButton
size="small"
color="inherit"
title={t('proxies.page.tooltips.filter')}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
if (!headState.open)
// eslint-disable-next-line @eslint-react/dom-no-flush-sync
flushSync(() => onHeadState({ open: true }))
onHeadState({
textState: textState === 'filter' ? null : 'filter',
filterText: '',
})
}}
>
{textState === 'filter' ? (
<FilterAltRounded fontSize="inherit" />
) : (
<FilterAltOffRounded fontSize="inherit" />
)}
</IconButton>
</Box>
)
})
+492
View File
@@ -0,0 +1,492 @@
import { ExpandMoreRounded } from '@mui/icons-material'
import {
Alert,
Box,
Chip,
IconButton,
Menu,
MenuItem,
Snackbar,
Typography,
} from '@mui/material'
import { useTheme } from '@mui/material/styles'
import {
type Key,
type MouseEvent,
type RefObject,
useCallback,
useEffect,
useMemo,
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
import { updateProxyChainConfigInRuntime } from '@/services/cmds'
import { ScrollTopButton } from '../layout/scroll-top-button'
import { ProxyChain } from './proxy-chain'
import { ProxyRender } from './proxy-render'
import type { HeadState } from './use-head-state'
import type { IRenderItem } from './use-render-list'
// ---- Types ----
interface ProxyChainItem {
id: string
name: string
type?: string
delay?: number
}
type VirtualListItem = {
key: Key
index: number
start: number
end: number
}
interface ProxyGroupOption {
name: string
type: string
all?: unknown[]
}
// ---- Props ----
interface ChainRuleHeaderProps {
title: string
selectLabel: string
currentGroup: ProxyGroupOption | null
canSelectGroup: boolean
onMenuOpen: (event: MouseEvent<HTMLElement>) => void
}
interface GroupSelectMenuProps {
anchorEl: HTMLElement | null
groups: ProxyGroupOption[]
selectedGroup: string | null
emptyText: string
onClose: () => void
onSelect: (groupName: string) => void
}
interface ProxyGroupsChainProps {
mode: string
chainConfigData?: string | null
availableGroups: any[]
activeSelectedGroup: string | null
showScrollTop: boolean
// Virtual list data (from parent's virtualizer)
parentRef: RefObject<HTMLDivElement | null>
totalSize: number
virtualItems: VirtualListItem[]
renderList: IRenderItem[]
activeStickyIndex: number | null
measureElement: (node: Element | null) => void
// Shared callbacks
onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onLocation: (group: any) => void
onGroupSelect: (groupName: string) => void
onScrollToTop: () => void
}
// ---- Sub-components ----
function ChainRuleHeader({
title,
selectLabel,
currentGroup,
canSelectGroup,
onMenuOpen,
}: ChainRuleHeaderProps) {
return (
<Box sx={{ borderBottom: '1px solid', borderColor: 'divider' }}>
<Box
sx={{
px: 2,
py: 1.5,
borderBottom: '1px solid',
borderColor: 'divider',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
<Typography variant="h6" sx={{ fontWeight: 600, fontSize: '16px' }}>
{title}
</Typography>
{currentGroup && (
<Chip
size="small"
label={`${currentGroup.name} (${currentGroup.type})`}
variant="outlined"
sx={{
fontSize: '12px',
maxWidth: '200px',
'& .MuiChip-label': {
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
}}
/>
)}
</Box>
{canSelectGroup && (
<IconButton
size="small"
onClick={onMenuOpen}
sx={{
border: '1px solid',
borderColor: 'divider',
borderRadius: '4px',
padding: '4px 8px',
}}
>
<Typography variant="body2" sx={{ mr: 0.5, fontSize: '12px' }}>
{selectLabel}
</Typography>
<ExpandMoreRounded fontSize="small" />
</IconButton>
)}
</Box>
</Box>
)
}
function GroupSelectMenu({
anchorEl,
groups,
selectedGroup,
emptyText,
onClose,
onSelect,
}: GroupSelectMenuProps) {
return (
<Menu
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={onClose}
slotProps={{
paper: {
sx: {
maxHeight: 300,
minWidth: 200,
},
},
}}
>
{groups.map((group) => (
<MenuItem
key={group.name}
onClick={() => onSelect(group.name)}
selected={selectedGroup === group.name}
sx={{ fontSize: '14px', py: 1 }}
>
<Box
sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start',
}}
>
<Typography variant="body2" sx={{ fontWeight: 500 }}>
{group.name}
</Typography>
<Typography variant="caption" color="text.secondary">
{group.type} · {group.all?.length ?? 0} 节点
</Typography>
</Box>
</MenuItem>
))}
{groups.length === 0 && (
<MenuItem disabled>
<Typography variant="body2" color="text.secondary">
{emptyText}
</Typography>
</MenuItem>
)}
</Menu>
)
}
function ProxyVirtualList({
parentRef,
height,
totalSize,
virtualItems,
renderList,
activeStickyIndex,
isChainMode,
measureElement,
onLocation,
onCheckAll,
onHeadState,
onChangeProxy,
}: {
parentRef: RefObject<HTMLDivElement | null>
height: string
totalSize: number
virtualItems: VirtualListItem[]
renderList: IRenderItem[]
activeStickyIndex: number | null
isChainMode?: boolean
measureElement: (node: Element | null) => void
onLocation: (group: any) => void
onCheckAll: (groupName: string) => void
onHeadState: (groupName: string, patch: Partial<HeadState>) => void
onChangeProxy: (group: IProxyGroupItem, proxy: IProxyItem) => void
}) {
const theme = useTheme()
const stickyBackground =
theme.palette.mode === 'dark' ? '#1e1f27' : 'var(--background-color)'
return (
<div ref={parentRef} style={{ height, overflow: 'auto' }}>
<div style={{ height: totalSize, position: 'relative' }}>
{virtualItems.map((virtualItem) => (
<div
key={virtualItem.key}
data-index={virtualItem.index}
ref={measureElement}
style={{
position:
virtualItem.index === activeStickyIndex ? 'sticky' : 'absolute',
top: 0,
left: 0,
zIndex: virtualItem.index === activeStickyIndex ? 5 : undefined,
display:
virtualItem.index === activeStickyIndex
? 'flow-root'
: undefined,
backgroundColor:
virtualItem.index === activeStickyIndex
? stickyBackground
: undefined,
width: '100%',
transform:
virtualItem.index === activeStickyIndex
? undefined
: `translateY(${virtualItem.start}px)`,
}}
>
<ProxyRender
item={renderList[virtualItem.index]}
onLocation={onLocation}
onCheckAll={onCheckAll}
onHeadState={onHeadState}
onChangeProxy={onChangeProxy}
isChainMode={isChainMode}
/>
</div>
))}
<div style={{ height: 8 }} />
</div>
</div>
)
}
// ---- Main Chain Component ----
export function ProxyGroupsChain(props: ProxyGroupsChainProps) {
const { t } = useTranslation()
const {
mode,
chainConfigData,
availableGroups,
activeSelectedGroup,
showScrollTop,
parentRef,
totalSize,
virtualItems,
renderList,
activeStickyIndex,
measureElement,
onCheckAll,
onHeadState,
onLocation,
onGroupSelect,
onScrollToTop,
} = props
// Chain-specific state
const [proxyChain, setProxyChain] = useState<ProxyChainItem[]>(() => {
try {
const saved = localStorage.getItem('proxy-chain-items')
if (saved) {
return JSON.parse(saved)
}
} catch {
// ignore
}
return []
})
useEffect(() => {
if (proxyChain.length > 0) {
localStorage.setItem('proxy-chain-items', JSON.stringify(proxyChain))
} else {
localStorage.removeItem('proxy-chain-items')
}
}, [proxyChain])
const [ruleMenuAnchor, setRuleMenuAnchor] = useState<null | HTMLElement>(null)
const [duplicateWarning, setDuplicateWarning] = useState<{
open: boolean
message: string
}>({ open: false, message: '' })
// Compute current group for rule header
const currentGroup = useMemo(() => {
if (!activeSelectedGroup) return null
return (
availableGroups.find(
(group: any) => group.name === activeSelectedGroup,
) ?? null
)
}, [activeSelectedGroup, availableGroups])
// Handlers
const handleGroupMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
setRuleMenuAnchor(event.currentTarget)
}
const handleGroupMenuClose = () => {
setRuleMenuAnchor(null)
}
const handleGroupSelect = (groupName: string) => {
onGroupSelect(groupName)
handleGroupMenuClose()
if (mode === 'rule') {
updateProxyChainConfigInRuntime(null)
localStorage.removeItem('proxy-chain-group')
localStorage.removeItem('proxy-chain-exit-node')
localStorage.removeItem('proxy-chain-items')
setProxyChain([])
}
}
const handleCloseDuplicateWarning = useCallback(() => {
setDuplicateWarning({ open: false, message: '' })
}, [])
const handleChangeProxy = useCallback(
(_group: IProxyGroupItem, proxy: IProxyItem) => {
// 使用函数式更新来避免状态延迟问题
setProxyChain((prev) => {
// 检查是否已经存在相同名称的代理,防止重复添加
if (prev.some((item) => item.name === proxy.name)) {
const warningMessage = t('proxies.page.chain.duplicateNode')
setDuplicateWarning({
open: true,
message: warningMessage,
})
return prev // 返回原来的状态,不做任何更改
}
// 安全获取延迟数据,如果没有延迟数据则设为 undefined
const delay =
proxy.history && proxy.history.length > 0
? proxy.history[proxy.history.length - 1].delay
: undefined
const chainItem: ProxyChainItem = {
id: `${proxy.name}_${Date.now()}`,
name: proxy.name,
type: proxy.type,
delay,
}
return [...prev, chainItem]
})
},
[t],
)
// Render virtual list for chain mode
const renderProxyList = (height: string) => (
<ProxyVirtualList
parentRef={parentRef}
height={height}
totalSize={totalSize}
virtualItems={virtualItems}
renderList={renderList}
activeStickyIndex={activeStickyIndex}
isChainMode
measureElement={measureElement}
onLocation={onLocation}
onCheckAll={onCheckAll}
onHeadState={onHeadState}
onChangeProxy={handleChangeProxy}
/>
)
const showRuleHeader = mode === 'rule' && availableGroups.length > 0
return (
<>
<Box sx={{ display: 'flex', height: '100%', gap: 2 }}>
<Box sx={{ flex: 1, position: 'relative' }}>
{showRuleHeader && (
<ChainRuleHeader
title={t('proxies.page.rules.title')}
selectLabel={t('proxies.page.rules.select')}
currentGroup={currentGroup}
canSelectGroup={availableGroups.length > 0}
onMenuOpen={handleGroupMenuOpen}
/>
)}
{renderProxyList(
showRuleHeader ? 'calc(100% - 80px)' : 'calc(100% - 14px)',
)}
<ScrollTopButton show={showScrollTop} onClick={onScrollToTop} />
</Box>
<Box sx={{ width: '400px', minWidth: '300px' }}>
<ProxyChain
proxyChain={proxyChain}
onUpdateChain={setProxyChain}
chainConfigData={chainConfigData}
mode={mode}
selectedGroup={activeSelectedGroup}
/>
</Box>
</Box>
<Snackbar
open={duplicateWarning.open}
autoHideDuration={3000}
onClose={handleCloseDuplicateWarning}
anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
>
<Alert
onClose={handleCloseDuplicateWarning}
severity="warning"
variant="filled"
>
{duplicateWarning.message}
</Alert>
</Snackbar>
<GroupSelectMenu
anchorEl={ruleMenuAnchor}
groups={availableGroups}
selectedGroup={activeSelectedGroup}
emptyText="暂无可用代理组"
onClose={handleGroupMenuClose}
onSelect={handleGroupSelect}
/>
</>
)
}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -11,7 +11,7 @@ import {
SortByAlphaRounded,
SortRounded,
} from '@mui/icons-material'
import { Box, IconButton, TextField, SxProps } from '@mui/material'
import { Box, IconButton, TextField, type SxProps } from '@mui/material'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
+105 -69
View File
@@ -20,15 +20,16 @@ import { useIconCache } from '@/hooks/use-icon-cache'
import { useVerge } from '@/hooks/use-verge'
import { useThemeMode } from '@/services/states'
import { ProxyGroupTools } from './proxy-group-tools'
import { ProxyHead } from './proxy-head'
import { ProxyItem } from './proxy-item'
import { ProxyItemMini } from './proxy-item-mini'
import { HeadState } from './use-head-state'
import type { HeadState } from './use-head-state'
import type { IRenderItem } from './use-render-list'
interface RenderProps {
item: IRenderItem
indent: boolean
stickyed?: boolean
isChainMode?: boolean
onLocation: (group: IRenderItem['group']) => void
onCheckAll: (groupName: string) => void
@@ -37,24 +38,26 @@ interface RenderProps {
group: IRenderItem['group'],
proxy: IRenderItem['proxy'] & { name: string },
) => void
onGroupToggle?: (group: IRenderItem['group']) => void
}
export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
const { t } = useTranslation()
const {
indent,
item,
stickyed = false,
onLocation,
onCheckAll,
onHeadState,
onChangeProxy,
onGroupToggle,
isChainMode: _ = false,
} = props
const { type, group, headState, proxy, proxyCol } = item
const { verge } = useVerge()
const enable_group_icon = verge?.enable_group_icon ?? true
const mode = useThemeMode()
const isDark = mode === 'light' ? false : true
const isDark = mode === 'dark'
const itembackgroundcolor = isDark ? '#282A36' : '#ffffff'
const iconCachePath = useIconCache({
icon: group.icon,
@@ -72,101 +75,135 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
<ProxyItemMini
key={`${item.key}-${proxyItem?.name ?? 'unknown'}`}
group={group}
proxy={proxyItem!}
proxy={proxyItem}
selected={group.now === proxyItem?.name}
showType={showType}
onClick={() => onChangeProxy(group, proxyItem!)}
onClick={() => onChangeProxy(group, proxyItem)}
/>
))
}, [type, proxyCol, item.key, group, showType, onChangeProxy])
if (type === 0) {
return (
<ListItemButton
dense
style={{
background: itembackgroundcolor,
height: '100%',
margin: '8px 8px',
borderRadius: '8px',
}}
onClick={() => onHeadState(group.name, { open: !headState?.open })}
>
{enable_group_icon &&
group.icon &&
group.icon.trim().startsWith('http') && (
<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 })
}}
>
{enable_group_icon && group.icon?.trim().startsWith('http') && (
<img
src={iconCachePath === '' ? group.icon : iconCachePath}
alt="group icon"
width="32px"
style={{ marginRight: '12px', borderRadius: '6px' }}
/>
)}
{enable_group_icon &&
group.icon &&
group.icon.trim().startsWith('data') && (
{enable_group_icon && group.icon?.trim().startsWith('data') && (
<img
src={group.icon}
alt="group icon"
width="32px"
style={{ marginRight: '12px', borderRadius: '6px' }}
/>
)}
{enable_group_icon &&
group.icon &&
group.icon.trim().startsWith('<svg') && (
{enable_group_icon && group.icon?.trim().startsWith('<svg') && (
<img
src={`data:image/svg+xml;base64,${btoa(group.icon)}`}
alt="group icon"
width="32px"
/>
)}
<ListItemText
primary={<StyledPrimary>{group.name}</StyledPrimary>}
secondary={
<Box
sx={{
overflow: 'hidden',
display: 'flex',
alignItems: 'center',
pt: '2px',
}}
>
<Box component="span" sx={{ marginTop: '2px' }}>
<StyledTypeBox>{group.type}</StyledTypeBox>
<StyledSubtitle sx={{ color: 'text.secondary' }}>
{group.now}
</StyledSubtitle>
<ListItemText
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>
</Box>
}
slotProps={{
secondary: {
component: 'div',
sx: { display: 'flex', alignItems: 'center', color: '#ccc' },
},
}}
/>
<Box sx={{ display: 'flex', alignItems: 'center' }}>
<Tooltip title={t('proxies.page.labels.proxyCount')} arrow>
<Chip
size="small"
label={`${group.all.length}`}
sx={{
mr: 1,
backgroundColor: (theme) =>
alpha(theme.palette.primary.main, 0.1),
color: (theme) => theme.palette.primary.main,
}}
}
slotProps={{
secondary: {
component: 'div',
sx: { display: 'flex', alignItems: 'center', color: '#ccc' },
},
}}
/>
<Box sx={{ display: 'flex', alignItems: 'center' }}>
<ProxyGroupTools
url={group.testUrl}
groupName={group.name}
headState={headState!}
onLocation={() => onLocation(group)}
onCheckDelay={() => onCheckAll(group.name)}
onHeadState={(p) => onHeadState(group.name, p)}
/>
</Tooltip>
{headState?.open ? <ExpandLessRounded /> : <ExpandMoreRounded />}
</Box>
</ListItemButton>
<Tooltip title={t('proxies.page.labels.proxyCount')} arrow>
<div
style={{
minWidth: '50px',
display: 'flex',
justifyContent: 'end',
alignItems: 'center',
}}
>
<Chip
size="small"
label={`${group.all.length}`}
sx={{
mr: 1,
backgroundColor: (theme) =>
alpha(theme.palette.primary.main, 0.1),
color: (theme) => theme.palette.primary.main,
}}
/>
</div>
</Tooltip>
{headState?.open ? <ExpandLessRounded /> : <ExpandMoreRounded />}
</Box>
</ListItemButton>
</div>
)
}
if (type === 1) {
return (
<ProxyHead
sx={{ pl: 2, pr: 3, mt: indent ? 1 : 0.5, mb: 1 }}
sx={{ pl: 2, pr: 3, mt: 0.5, mb: 1 }}
url={group.testUrl}
groupName={group.name}
headState={headState!}
@@ -214,10 +251,9 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) {
sx={{
height: 56,
display: 'grid',
my: 0.5,
gap: 1,
pl: 2,
pr: 2,
pb: 1,
px: 2,
gridTemplateColumns: `repeat(${item.col! || 2}, 1fr)`,
}}
>
+9 -6
View File
@@ -428,12 +428,15 @@ export const useRenderList = (
},
)
ret.push({
type: 1,
key: `head-${group.name}`,
group,
headState,
})
// 全局模式下,添加组头
if (!useRule) {
ret.push({
type: 1,
key: `head-${group.name}`,
group,
headState,
})
}
if (!proxies.length) {
ret.push({
+1 -1
View File
@@ -139,7 +139,7 @@ const ProxyPage = () => {
return (
<BasePage
full
contentStyle={{ height: '101.5%' }}
contentStyle={{ height: '100%' }}
title={
isChainMode ? (
<Box