Compare commits

..
7 changed files with 100 additions and 123 deletions
+4 -6
View File
@@ -6,8 +6,7 @@ import { createRoot } from 'react-dom/client'
import { SWRConfig } from 'swr' import { SWRConfig } from 'swr'
import { VirtualList } from '../../src/components/base/virtual-list' import { VirtualList } from '../../src/components/base/virtual-list'
import { ConnectionRowItem } from '../../src/components/connection/connection-row-item' import { VisibleConnectionRowItem } from '../../src/components/connection/connection-row-item'
import { useConnectionRowViews } from '../../src/components/connection/connection-row-view'
import LogItem from '../../src/components/log/log-item' import LogItem from '../../src/components/log/log-item'
import { initializeLanguage } from '../../src/services/i18n' import { initializeLanguage } from '../../src/services/i18n'
import { setPreloadConfig } from '../../src/services/preload' import { setPreloadConfig } from '../../src/services/preload'
@@ -35,10 +34,9 @@ export function Components() {
}), }),
[], [],
) )
const rows = useConnectionRowViews(connections)
return ( return (
<VirtualList <VirtualList
count={scenario === 'logs' ? logs.length : rows.length} count={scenario === 'logs' ? logs.length : connections.length}
estimateSize={scenario === 'logs' ? 50 : 56} estimateSize={scenario === 'logs' ? 50 : 56}
style={{ height: 640, margin: 24 }} style={{ height: 640, margin: 24 }}
renderItem={(index) => renderItem={(index) =>
@@ -48,8 +46,8 @@ export function Components() {
searchState={searchState} searchState={searchState}
/> />
) : ( ) : (
<ConnectionRowItem <VisibleConnectionRowItem
row={rows[index]} connection={connections[index]}
closed={false} closed={false}
onShowDetail={() => {}} onShowDetail={() => {}}
/> />
+10 -8
View File
@@ -210,7 +210,7 @@ impl<'a> MemberResolver<'a> {
.collect() .collect()
} }
fn resolve(&self, name: String, scoped: Option<&String>) -> ProxyMemberRef { fn resolve(&self, name: String, scoped: impl FnOnce(&str) -> Option<&'a String>) -> ProxyMemberRef {
if self.group_names.contains(&name) { if self.group_names.contains(&name) {
ProxyMemberRef::Group { name } ProxyMemberRef::Group { name }
} else if let Some(record_id) = self.core_node_ids.get(&name) { } else if let Some(record_id) = self.core_node_ids.get(&name) {
@@ -225,7 +225,7 @@ impl<'a> MemberResolver<'a> {
} }
} else { } else {
let candidates = self.provider_candidates.get(&name).map_or(&[][..], Vec::as_slice); let candidates = self.provider_candidates.get(&name).map_or(&[][..], Vec::as_slice);
match (scoped, candidates) { match (scoped(&name), candidates) {
(Some(record_id), _) | (None, [(_, record_id)]) => ProxyMemberRef::Node { (Some(record_id), _) | (None, [(_, record_id)]) => ProxyMemberRef::Node {
name, name,
record_id: record_id.clone(), record_id: record_id.clone(),
@@ -415,12 +415,14 @@ fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> Pro
.unwrap_or_default() .unwrap_or_default()
.into_iter() .into_iter()
.map(|member| { .map(|member| {
let (occurrence, scoped) = seen resolver.resolve(member, |member| {
.entry(member.clone()) let (occurrence, scoped) = seen
.or_insert_with(|| (0, resolver.scoped_candidates(&name, &member))); .entry(member.to_owned())
let picked = scoped.get(*occurrence).or_else(|| scoped.first()).copied(); .or_insert_with(|| (0, resolver.scoped_candidates(&name, member)));
*occurrence += 1; let picked = scoped.get(*occurrence).or_else(|| scoped.first()).copied();
resolver.resolve(member, picked) *occurrence += 1;
picked
})
}) })
.collect(); .collect();
@@ -1,12 +1,15 @@
import { CloseRounded } from '@mui/icons-material' import { CloseRounded } from '@mui/icons-material'
import { IconButton } from '@mui/material' import { IconButton } from '@mui/material'
import { useLockFn } from 'ahooks' import { useLockFn } from 'ahooks'
import { memo, useCallback } from 'react' import { memo, useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { closeConnection } from 'tauri-plugin-mihomo-api' import { closeConnection } from 'tauri-plugin-mihomo-api'
import { RelativeTime } from './connection-relative-time' import { RelativeTime } from './connection-relative-time'
import type { ConnectionRowView } from './connection-row-view' import {
createConnectionRowView,
type ConnectionRowView,
} from './connection-row-view'
import type { ConnectionRuleKind } from './connection-rule' import type { ConnectionRuleKind } from './connection-rule'
interface Props { interface Props {
@@ -70,7 +73,7 @@ const actionStyle = {
transform: 'translateY(-50%)', transform: 'translateY(-50%)',
} as const } as const
export const ConnectionRowItem = memo( const ConnectionRowItem = memo(
function ConnectionRowItem({ row, closed, onShowDetail }: Props) { function ConnectionRowItem({ row, closed, onShowDetail }: Props) {
const { t } = useTranslation() const { t } = useTranslation()
const onDelete = useLockFn(async () => closeConnection(row.id)) const onDelete = useLockFn(async () => closeConnection(row.id))
@@ -129,3 +132,11 @@ export const ConnectionRowItem = memo(
prev.closed === next.closed && prev.closed === next.closed &&
prev.onShowDetail === next.onShowDetail, prev.onShowDetail === next.onShowDetail,
) )
export const VisibleConnectionRowItem = memo(function VisibleConnectionRowItem({
connection,
...props
}: Omit<Props, 'row'> & { connection: IConnectionsItem }) {
const row = useMemo(() => createConnectionRowView(connection), [connection])
return <ConnectionRowItem row={row} {...props} />
})
@@ -1,5 +1,3 @@
import { useMemo, useRef } from 'react'
const TRAFFIC_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] const TRAFFIC_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
export interface ConnectionRowView { export interface ConnectionRowView {
@@ -85,7 +83,7 @@ export const getConnectionTypeLabel = (connection: IConnectionsItem) => {
export const getConnectionStartTime = (connection: IConnectionsItem) => export const getConnectionStartTime = (connection: IConnectionsItem) =>
Date.parse(connection.start || '') || 0 Date.parse(connection.start || '') || 0
const createConnectionRowView = (connection: IConnectionsItem) => { export const createConnectionRowView = (connection: IConnectionsItem) => {
const uploadSpeed = connection.curUpload ?? 0 const uploadSpeed = connection.curUpload ?? 0
const downloadSpeed = connection.curDownload ?? 0 const downloadSpeed = connection.curDownload ?? 0
@@ -114,66 +112,3 @@ const createConnectionRowView = (connection: IConnectionsItem) => {
searchableProcess: connection.metadata.process || '', searchableProcess: connection.metadata.process || '',
} satisfies ConnectionRowView } satisfies ConnectionRowView
} }
const sameConnectionRowView = (
left: ConnectionRowView,
right: ConnectionRowView,
) =>
left.host === right.host &&
left.process === right.process &&
left.network === right.network &&
left.type === right.type &&
left.chains === right.chains &&
left.rule === right.rule &&
left.time === right.time &&
left.source === right.source &&
left.destination === right.destination &&
left.uploadText === right.uploadText &&
left.downloadText === right.downloadText &&
left.uploadSpeedText === right.uploadSpeedText &&
left.downloadSpeedText === right.downloadSpeedText &&
left.upload === right.upload &&
left.download === right.download &&
left.uploadSpeed === right.uploadSpeed &&
left.downloadSpeed === right.downloadSpeed &&
left.searchableHost === right.searchableHost &&
left.searchableDestinationIP === right.searchableDestinationIP &&
left.searchableProcess === right.searchableProcess
export const useConnectionRowViews = (connections: IConnectionsItem[]) => {
const previousRowsRef = useRef(new Map<string, ConnectionRowView>())
const previousConnectionsRef = useRef(new Map<string, IConnectionsItem>())
return useMemo(() => {
const previousRows = previousRowsRef.current
const previousConnections = previousConnectionsRef.current
const nextRows = new Map<string, ConnectionRowView>()
const nextConnections = new Map<string, IConnectionsItem>()
const rows: ConnectionRowView[] = []
connections.forEach((connection) => {
nextConnections.set(connection.id, connection)
const previousRow = previousRows.get(connection.id)
const previousConnection = previousConnections.get(connection.id)
let row: ConnectionRowView
if (previousRow && previousConnection === connection) {
row = previousRow
} else {
const nextRow = createConnectionRowView(connection)
row =
previousRow && sameConnectionRowView(previousRow, nextRow)
? previousRow
: nextRow
}
nextRows.set(connection.id, row)
rows.push(row)
})
previousRowsRef.current = nextRows
previousConnectionsRef.current = nextConnections
return rows
}, [connections])
}
+58 -18
View File
@@ -218,11 +218,51 @@ const getConnectionCellValue = (
} }
} }
const compareConnectionCellValue = ( type TrafficSortField = 'download' | 'upload' | 'dlSpeed' | 'ulSpeed'
field: ColumnField, type DisplaySortField = Exclude<ColumnField, TrafficSortField>
const connectionSortKey = (field: DisplaySortField, row: IConnectionsItem) => {
switch (field) {
case 'host':
return getConnectionHost(row)
case 'process':
return getConnectionProcess(row)
case 'source':
return getConnectionSource(row)
case 'remoteDestination':
return getConnectionDestination(row)
case 'chains':
return formatConnectionChains(row.chains)
case 'rule':
return getConnectionRule(row)
case 'type':
return getConnectionTypeLabel(row)
case 'time':
return getConnectionStartTime(row)
}
}
const sortByConnectionKey = (
connections: IConnectionsItem[],
field: DisplaySortField,
direction: number,
) => {
return connections
.map((row) => ({ row, key: connectionSortKey(field, row) }))
.sort((a, b) => {
const order =
typeof a.key === 'number'
? (Number(a.key) || 0) - (Number(b.key) || 0)
: String(a.key).localeCompare(String(b.key))
return order * direction
})
.map(({ row }) => row)
}
const compareConnectionTraffic = (
field: TrafficSortField,
left: IConnectionsItem, left: IConnectionsItem,
right: IConnectionsItem, right: IConnectionsItem,
getSnapshot: (row: IConnectionsItem) => TableRowSnapshot,
) => { ) => {
switch (field) { switch (field) {
case 'download': case 'download':
@@ -234,14 +274,6 @@ const compareConnectionCellValue = (
case 'ulSpeed': case 'ulSpeed':
return (left.curUpload ?? 0) - (right.curUpload ?? 0) return (left.curUpload ?? 0) - (right.curUpload ?? 0)
} }
const leftValue = getConnectionCellValue(field, getSnapshot(left))
const rightValue = getConnectionCellValue(field, getSnapshot(right))
if (typeof leftValue === 'number' || typeof rightValue === 'number') {
return (Number(leftValue) || 0) - (Number(rightValue) || 0)
}
return String(leftValue ?? '').localeCompare(String(rightValue ?? ''))
} }
const renderCell = ( const renderCell = (
@@ -597,13 +629,21 @@ export const ConnectionTable = (props: Props) => {
const sortedConnections = useMemo(() => { const sortedConnections = useMemo(() => {
if (!sorting) return connections if (!sorting) return connections
const direction = sorting.desc ? -1 : 1 const { id, desc } = sorting
return [...connections].sort( const direction = desc ? -1 : 1
(left, right) => if (
compareConnectionCellValue(sorting.id, left, right, getRowSnapshot) * id === 'download' ||
direction, id === 'upload' ||
) id === 'dlSpeed' ||
}, [connections, sorting, getRowSnapshot]) id === 'ulSpeed'
) {
return [...connections].sort(
(left, right) => compareConnectionTraffic(id, left, right) * direction,
)
}
return sortByConnectionKey(connections, id, direction)
}, [connections, sorting])
const tableWidth = useMemo( const tableWidth = useMemo(
() => visibleColumns.reduce((total, column) => total + column.size, 0), () => visibleColumns.reduce((total, column) => total + column.size, 0),
+5 -12
View File
@@ -30,11 +30,8 @@ import {
ConnectionDetail, ConnectionDetail,
ConnectionDetailRef, ConnectionDetailRef,
} from '@/components/connection/connection-detail' } from '@/components/connection/connection-detail'
import { ConnectionRowItem } from '@/components/connection/connection-row-item' import { VisibleConnectionRowItem } from '@/components/connection/connection-row-item'
import { import { getConnectionStartTime } from '@/components/connection/connection-row-view'
getConnectionStartTime,
useConnectionRowViews,
} from '@/components/connection/connection-row-view'
import type { ConnectionRuleKind } from '@/components/connection/connection-rule' import type { ConnectionRuleKind } from '@/components/connection/connection-rule'
import { ConnectionTable } from '@/components/connection/connection-table' import { ConnectionTable } from '@/components/connection/connection-table'
import { useConnectionData } from '@/hooks/use-connection-data' import { useConnectionData } from '@/hooks/use-connection-data'
@@ -145,10 +142,6 @@ const ConnectionsPage = () => {
curOrderOpt, curOrderOpt,
]) ])
const displayRows = useConnectionRowViews(
isTableLayout ? EMPTY_CONNECTIONS : filterConn,
)
const detailRef = useRef<ConnectionDetailRef>(null!) const detailRef = useRef<ConnectionDetailRef>(null!)
const selectConnectionsType = useCallback( const selectConnectionsType = useCallback(
@@ -339,11 +332,11 @@ const ConnectionsPage = () => {
) : ( ) : (
<VirtualList <VirtualList
key={connectionsType} key={connectionsType}
count={displayRows.length} count={filterConn.length}
estimateSize={56} estimateSize={56}
renderItem={(i) => ( renderItem={(i) => (
<ConnectionRowItem <VisibleConnectionRowItem
row={displayRows[i]} connection={filterConn[i]}
closed={connectionsType === 'closed'} closed={connectionsType === 'closed'}
onShowDetail={showDetailById} onShowDetail={showDetailById}
/> />
+8 -10
View File
@@ -52,21 +52,16 @@ const LogPage = () => {
}) })
}, [logData, logState, match, searchState.text]) }, [logData, logState, match, searchState.text])
const filteredLogs = useMemo(
() => (isDescending ? [...filterLogs].reverse() : filterLogs),
[filterLogs, isDescending],
)
const scrollRef = useRef({ isNearBottom: true }) const scrollRef = useRef({ isNearBottom: true })
const virtuosoRef = useRef<VirtualListHandle>(null) const virtuosoRef = useRef<VirtualListHandle>(null)
useEffect(() => { useEffect(() => {
if (!isDescending && scrollRef.current.isNearBottom) { if (!isDescending && scrollRef.current.isNearBottom) {
virtuosoRef.current?.scrollToIndex(filteredLogs.length - 1, { virtuosoRef.current?.scrollToIndex(filterLogs.length - 1, {
behavior: 'smooth', behavior: 'smooth',
}) })
} }
}, [isDescending, filteredLogs.length]) }, [isDescending, filterLogs.length])
const handleLogLevelChange = (newLevel: LogFilter) => { const handleLogLevelChange = (newLevel: LogFilter) => {
setClashLog((pre) => ({ ...pre!, logFilter: newLevel })) setClashLog((pre) => ({ ...pre!, logFilter: newLevel }))
@@ -176,13 +171,16 @@ const LogPage = () => {
/> />
</Box> </Box>
{filteredLogs.length > 0 ? ( {filterLogs.length > 0 ? (
<VirtualList <VirtualList
ref={virtuosoRef} ref={virtuosoRef}
count={filteredLogs.length} count={filterLogs.length}
estimateSize={50} estimateSize={50}
renderItem={(i) => ( renderItem={(i) => (
<LogItem value={filteredLogs[i]} searchState={searchState} /> <LogItem
value={filterLogs[isDescending ? filterLogs.length - 1 - i : i]}
searchState={searchState}
/>
)} )}
onScroll={(event) => { onScroll={(event) => {
const element = event.currentTarget as HTMLDivElement const element = event.currentTarget as HTMLDivElement