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 { VirtualList } from '../../src/components/base/virtual-list'
import { ConnectionRowItem } from '../../src/components/connection/connection-row-item'
import { useConnectionRowViews } from '../../src/components/connection/connection-row-view'
import { VisibleConnectionRowItem } from '../../src/components/connection/connection-row-item'
import LogItem from '../../src/components/log/log-item'
import { initializeLanguage } from '../../src/services/i18n'
import { setPreloadConfig } from '../../src/services/preload'
@@ -35,10 +34,9 @@ export function Components() {
}),
[],
)
const rows = useConnectionRowViews(connections)
return (
<VirtualList
count={scenario === 'logs' ? logs.length : rows.length}
count={scenario === 'logs' ? logs.length : connections.length}
estimateSize={scenario === 'logs' ? 50 : 56}
style={{ height: 640, margin: 24 }}
renderItem={(index) =>
@@ -48,8 +46,8 @@ export function Components() {
searchState={searchState}
/>
) : (
<ConnectionRowItem
row={rows[index]}
<VisibleConnectionRowItem
connection={connections[index]}
closed={false}
onShowDetail={() => {}}
/>
+10 -8
View File
@@ -210,7 +210,7 @@ impl<'a> MemberResolver<'a> {
.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) {
ProxyMemberRef::Group { name }
} else if let Some(record_id) = self.core_node_ids.get(&name) {
@@ -225,7 +225,7 @@ impl<'a> MemberResolver<'a> {
}
} else {
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 {
name,
record_id: record_id.clone(),
@@ -415,12 +415,14 @@ fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> Pro
.unwrap_or_default()
.into_iter()
.map(|member| {
let (occurrence, scoped) = seen
.entry(member.clone())
.or_insert_with(|| (0, resolver.scoped_candidates(&name, &member)));
let picked = scoped.get(*occurrence).or_else(|| scoped.first()).copied();
*occurrence += 1;
resolver.resolve(member, picked)
resolver.resolve(member, |member| {
let (occurrence, scoped) = seen
.entry(member.to_owned())
.or_insert_with(|| (0, resolver.scoped_candidates(&name, member)));
let picked = scoped.get(*occurrence).or_else(|| scoped.first()).copied();
*occurrence += 1;
picked
})
})
.collect();
@@ -1,12 +1,15 @@
import { CloseRounded } from '@mui/icons-material'
import { IconButton } from '@mui/material'
import { useLockFn } from 'ahooks'
import { memo, useCallback } from 'react'
import { memo, useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { closeConnection } from 'tauri-plugin-mihomo-api'
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'
interface Props {
@@ -70,7 +73,7 @@ const actionStyle = {
transform: 'translateY(-50%)',
} as const
export const ConnectionRowItem = memo(
const ConnectionRowItem = memo(
function ConnectionRowItem({ row, closed, onShowDetail }: Props) {
const { t } = useTranslation()
const onDelete = useLockFn(async () => closeConnection(row.id))
@@ -129,3 +132,11 @@ export const ConnectionRowItem = memo(
prev.closed === next.closed &&
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']
export interface ConnectionRowView {
@@ -85,7 +83,7 @@ export const getConnectionTypeLabel = (connection: IConnectionsItem) => {
export const getConnectionStartTime = (connection: IConnectionsItem) =>
Date.parse(connection.start || '') || 0
const createConnectionRowView = (connection: IConnectionsItem) => {
export const createConnectionRowView = (connection: IConnectionsItem) => {
const uploadSpeed = connection.curUpload ?? 0
const downloadSpeed = connection.curDownload ?? 0
@@ -114,66 +112,3 @@ const createConnectionRowView = (connection: IConnectionsItem) => {
searchableProcess: connection.metadata.process || '',
} 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 = (
field: ColumnField,
type TrafficSortField = 'download' | 'upload' | 'dlSpeed' | 'ulSpeed'
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,
right: IConnectionsItem,
getSnapshot: (row: IConnectionsItem) => TableRowSnapshot,
) => {
switch (field) {
case 'download':
@@ -234,14 +274,6 @@ const compareConnectionCellValue = (
case 'ulSpeed':
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 = (
@@ -597,13 +629,21 @@ export const ConnectionTable = (props: Props) => {
const sortedConnections = useMemo(() => {
if (!sorting) return connections
const direction = sorting.desc ? -1 : 1
return [...connections].sort(
(left, right) =>
compareConnectionCellValue(sorting.id, left, right, getRowSnapshot) *
direction,
)
}, [connections, sorting, getRowSnapshot])
const { id, desc } = sorting
const direction = desc ? -1 : 1
if (
id === 'download' ||
id === 'upload' ||
id === 'dlSpeed' ||
id === 'ulSpeed'
) {
return [...connections].sort(
(left, right) => compareConnectionTraffic(id, left, right) * direction,
)
}
return sortByConnectionKey(connections, id, direction)
}, [connections, sorting])
const tableWidth = useMemo(
() => visibleColumns.reduce((total, column) => total + column.size, 0),
+5 -12
View File
@@ -30,11 +30,8 @@ import {
ConnectionDetail,
ConnectionDetailRef,
} from '@/components/connection/connection-detail'
import { ConnectionRowItem } from '@/components/connection/connection-row-item'
import {
getConnectionStartTime,
useConnectionRowViews,
} from '@/components/connection/connection-row-view'
import { VisibleConnectionRowItem } from '@/components/connection/connection-row-item'
import { getConnectionStartTime } from '@/components/connection/connection-row-view'
import type { ConnectionRuleKind } from '@/components/connection/connection-rule'
import { ConnectionTable } from '@/components/connection/connection-table'
import { useConnectionData } from '@/hooks/use-connection-data'
@@ -145,10 +142,6 @@ const ConnectionsPage = () => {
curOrderOpt,
])
const displayRows = useConnectionRowViews(
isTableLayout ? EMPTY_CONNECTIONS : filterConn,
)
const detailRef = useRef<ConnectionDetailRef>(null!)
const selectConnectionsType = useCallback(
@@ -339,11 +332,11 @@ const ConnectionsPage = () => {
) : (
<VirtualList
key={connectionsType}
count={displayRows.length}
count={filterConn.length}
estimateSize={56}
renderItem={(i) => (
<ConnectionRowItem
row={displayRows[i]}
<VisibleConnectionRowItem
connection={filterConn[i]}
closed={connectionsType === 'closed'}
onShowDetail={showDetailById}
/>
+8 -10
View File
@@ -52,21 +52,16 @@ const LogPage = () => {
})
}, [logData, logState, match, searchState.text])
const filteredLogs = useMemo(
() => (isDescending ? [...filterLogs].reverse() : filterLogs),
[filterLogs, isDescending],
)
const scrollRef = useRef({ isNearBottom: true })
const virtuosoRef = useRef<VirtualListHandle>(null)
useEffect(() => {
if (!isDescending && scrollRef.current.isNearBottom) {
virtuosoRef.current?.scrollToIndex(filteredLogs.length - 1, {
virtuosoRef.current?.scrollToIndex(filterLogs.length - 1, {
behavior: 'smooth',
})
}
}, [isDescending, filteredLogs.length])
}, [isDescending, filterLogs.length])
const handleLogLevelChange = (newLevel: LogFilter) => {
setClashLog((pre) => ({ ...pre!, logFilter: newLevel }))
@@ -176,13 +171,16 @@ const LogPage = () => {
/>
</Box>
{filteredLogs.length > 0 ? (
{filterLogs.length > 0 ? (
<VirtualList
ref={virtuosoRef}
count={filteredLogs.length}
count={filterLogs.length}
estimateSize={50}
renderItem={(i) => (
<LogItem value={filteredLogs[i]} searchState={searchState} />
<LogItem
value={filterLogs[isDescending ? filterLogs.length - 1 - i : i]}
searchState={searchState}
/>
)}
onScroll={(event) => {
const element = event.currentTarget as HTMLDivElement