refactor: migrate to @dnd-kit/react and simplify sortable components (#7819)

* refactor: migrate to @dnd-kit/react and simplify sortable components

* chore: enable css formatting in biome.json

* refactor(profile): simplify icon rendering logic and add alt text

* style(profiles): add overflow hidden to profile grid container

* refactor(profile): add radix for parseInt and improve type safety in profiles

* docs: update changelog with drag-and-drop styling improvements

* refactor(profile): move hasValidName function out of ProxiesEditorViewer

* refactor(proxy): refactor proxy chain into sortable components

* feat(proxy): add drop state styling and arrow animations to proxy chain

* style(profiles): reduce horizontal padding in profile grid

* feat(profile): add vertical margin to editor viewer items

* chore: refresh pnpm lockfile

* fix: preserve drag and drop behavior

---------

Co-authored-by: Tunglies <77394545+Tunglies@users.noreply.github.com>
This commit is contained in:
oomeow
2026-08-28 08:17:02 +00:00
committed by GitHub
co-authored by Tunglies
parent 181dfb87a4
commit b6de05ffe4
22 changed files with 1105 additions and 1115 deletions
+36 -87
View File
@@ -1,17 +1,4 @@
import {
DndContext,
KeyboardSensor,
PointerSensor,
closestCenter,
useSensor,
useSensors,
} from '@dnd-kit/core'
import {
SortableContext,
sortableKeyboardCoordinates,
useSortable,
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { DragDropProvider, KeyboardSensor, PointerSensor } from '@dnd-kit/react'
import {
Box,
List,
@@ -23,7 +10,6 @@ import {
} from '@mui/material'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import type { CSSProperties } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Outlet, useNavigate } from 'react-router'
@@ -31,7 +17,7 @@ import { Outlet, useNavigate } from 'react-router'
import iconDark from '@/assets/image/icon_dark.svg?react'
import iconLight from '@/assets/image/icon_light.svg?react'
import LogoSvg from '@/assets/image/logo.svg?react'
import { BaseErrorBoundary } from '@/components/base'
import { BaseErrorBoundary, SortableItem } from '@/components/base'
import { LayoutItem } from '@/components/layout/layout-item'
import { LayoutTraffic } from '@/components/layout/layout-traffic'
import { NoticeManager } from '@/components/layout/notice-manager'
@@ -68,43 +54,22 @@ type MenuContextPosition = { top: number; left: number }
interface SortableNavMenuItemProps {
item: NavItem
label: string
index: number
}
const SortableNavMenuItem = ({ item, label }: SortableNavMenuItemProps) => {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({
id: item.path,
})
const style: CSSProperties = {
transform: CSS.Transform.toString(transform),
transition,
}
if (isDragging) {
style.zIndex = 100
}
const SortableNavMenuItem = ({
item,
label,
index,
}: SortableNavMenuItemProps) => {
return (
<LayoutItem
to={item.path}
icon={item.icon}
sortable={{
setNodeRef,
attributes,
listeners,
style,
isDragging,
}}
>
{label}
</LayoutItem>
<SortableItem id={item.path} index={index}>
{(sortable) => (
<LayoutItem to={item.path} icon={item.icon} sortable={sortable}>
{label}
</LayoutItem>
)}
</SortableItem>
)
}
@@ -131,17 +96,6 @@ const Layout = () => {
const windowControlsRef = useRef<any>(null)
const { decorated } = useWindowDecorations()
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: {
distance: 6,
},
}),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
}),
)
const handleMenuOrderOptimisticUpdate = useCallback(
(order: string[]) => {
mutateVerge(
@@ -365,32 +319,27 @@ const Layout = () => {
)}
{menuUnlocked ? (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleMenuDragEnd}
>
<SortableContext items={menuOrder}>
<List
className="the-menu"
onContextMenu={handleMenuContextMenu}
>
{menuOrder.map((path) => {
const item = navItemMap.get(path)
if (!item) {
return null
}
return (
<SortableNavMenuItem
key={item.path}
item={item}
label={t(item.label)}
/>
)
})}
</List>
</SortableContext>
</DndContext>
<List className="the-menu" onContextMenu={handleMenuContextMenu}>
<DragDropProvider
sensors={[PointerSensor, KeyboardSensor]}
onDragEnd={handleMenuDragEnd}
>
{menuOrder.map((path) => {
const item = navItemMap.get(path)
if (!item) {
return null
}
return (
<SortableNavMenuItem
key={item.path}
item={item}
label={t(item.label)}
index={menuOrder.indexOf(path)}
/>
)
})}
</DragDropProvider>
</List>
) : (
<List className="the-menu" onContextMenu={handleMenuContextMenu}>
{menuOrder.map((path) => {
+18 -12
View File
@@ -1,5 +1,6 @@
import type { DragEndEvent } from '@dnd-kit/core'
import { arrayMove } from '@dnd-kit/sortable'
import { arrayMove } from '@dnd-kit/helpers'
import type { DragEndEvent } from '@dnd-kit/react'
import { isSortable } from '@dnd-kit/react/sortable'
import { useCallback, useEffect, useMemo, useReducer } from 'react'
type MenuOrderAction = { type: 'sync'; payload: string[] }
@@ -92,21 +93,26 @@ export const useNavMenuOrder = <T extends { path: string }>({
if (!enabled) {
return
}
const { operation, canceled } = event
const { source, target } = operation
const { active, over } = event
if (!over || active.id === over.id) {
if (canceled || !target || !isSortable(source)) return
const { index: newIndex, initialIndex: oldIndex } = source.sortable
if (
oldIndex < 0 ||
newIndex < 0 ||
oldIndex >= menuOrder.length ||
newIndex >= menuOrder.length ||
oldIndex === newIndex
) {
return
}
const activeId = String(active.id)
const overId = String(over.id)
const activeId = menuOrder[oldIndex]
const overId = menuOrder[newIndex]
const oldIndex = menuOrder.indexOf(activeId)
const newIndex = menuOrder.indexOf(overId)
if (oldIndex === -1 || newIndex === -1) {
return
}
if (activeId == null || overId == null || activeId === overId) return
const previousOrder = [...menuOrder]
const nextOrder = arrayMove(menuOrder, oldIndex, newIndex)
+121 -161
View File
@@ -1,20 +1,10 @@
import {
closestCenter,
type CollisionDetection,
DndContext,
type DragEndEvent,
DragOverlay,
DragDropProvider,
KeyboardSensor,
pointerWithin,
PointerSensor,
useSensor,
useSensors,
} from '@dnd-kit/core'
import {
SortableContext,
sortableKeyboardCoordinates,
type SortingStrategy,
} from '@dnd-kit/sortable'
type DragEndEvent,
} from '@dnd-kit/react'
import { isSortable } from '@dnd-kit/react/sortable'
import {
CheckBoxOutlineBlankRounded,
CheckBoxRounded,
@@ -42,12 +32,12 @@ import {
BaseStyledTextField,
type DialogRef,
} from '@/components/base'
import { ProfileItem } from '@/components/profile/profile-item'
import { ProfileMore } from '@/components/profile/profile-more'
import {
ProfileViewer,
type ProfileViewerRef,
} from '@/components/profile/profile-viewer'
import { SortableProfileItem } from '@/components/profile/sortable-profile-item'
import { ConfigViewer } from '@/components/setting/mods/config-viewer'
import { useListen } from '@/hooks/use-listen'
import { useProfiles } from '@/hooks/use-profiles'
@@ -78,48 +68,9 @@ import { debugLog } from '@/utils/debug'
// 与 src-tauri/src/main.rs 的 worker_limit 上限(8)保持一致,避免前后端更新风暴不对齐
const PROFILE_UPDATE_WORKER_LIMIT = 8
const PROFILE_SWITCH_LOADING_DELAY = 400
const profileCollisionDetection: CollisionDetection = (args) => {
const pointerCollisions = pointerWithin(args)
return pointerCollisions.length > 0 ? pointerCollisions : closestCenter(args)
}
// Equivalent to rectSortingStrategy without copying the full rect array for every item.
const profileRectSortingStrategy: SortingStrategy = ({
rects,
activeIndex,
overIndex,
index,
}) => {
let newIndex = index
if (index === activeIndex) {
newIndex = overIndex
} else if (
activeIndex < overIndex &&
index > activeIndex &&
index <= overIndex
) {
newIndex = index - 1
} else if (
activeIndex > overIndex &&
index >= overIndex &&
index < activeIndex
) {
newIndex = index + 1
}
const oldRect = rects[index]
const newRect = rects[newIndex]
if (!oldRect || !newRect) return null
return {
x: newRect.left - oldRect.left,
y: newRect.top - oldRect.top,
scaleX: newRect.width / oldRect.width,
scaleY: newRect.height / oldRect.height,
}
}
const profilePointerSensor = PointerSensor.configure({
activationConstraints: () => undefined,
})
interface ProfileSwitchRequest {
profile: string
@@ -138,6 +89,7 @@ const ProfilePage = () => {
const { addListener } = useListen()
const [url, setUrl] = useState('')
const [disabled, setDisabled] = useState(false)
const [profileDndRevision, setProfileDndRevision] = useState(0)
const [activatings, setActivatings] = useState<string[]>([])
const [switchTarget, setSwitchTarget] = useState<string | null>(null)
const [visibleSwitchingProfile, setVisibleSwitchingProfile] = useState<
@@ -165,14 +117,6 @@ const ProfilePage = () => {
)
const currentProfileRef = useRef<string | undefined>(undefined)
const profilePageMountedRef = useRef(true)
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: { distance: 8 },
}),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
}),
)
const { current } = location.state || {}
const {
@@ -268,7 +212,7 @@ const ProfilePage = () => {
const type1 = ['local', 'remote']
return items.filter((i) => i && type1.includes(i.type!))
return items.filter((i) => i?.type && type1.includes(i.type))
}, [profiles])
const currentActivatings = () => {
@@ -366,12 +310,31 @@ const ProfilePage = () => {
}
const onDragEnd = async (event: DragEndEvent) => {
const { active, over } = event
if (over) {
if (active.id !== over.id) {
await reorderProfile(active.id.toString(), over.id.toString())
mutateProfiles()
}
const { operation, canceled } = event
const { source, target } = operation
if (canceled || !target || !isSortable(source)) return
const { index: newIndex, initialIndex: oldIndex } = source.sortable
if (
oldIndex < 0 ||
newIndex < 0 ||
oldIndex >= profileItems.length ||
newIndex >= profileItems.length ||
oldIndex === newIndex
) {
return
}
const activeId = profileItems[oldIndex]?.uid
const overId = profileItems[newIndex]?.uid
if (activeId == null || overId == null || activeId === overId) return
try {
await reorderProfile(activeId, overId)
mutateProfiles()
} catch (error) {
setProfileDndRevision((revision) => revision + 1)
showNotice.error(error)
}
}
@@ -933,100 +896,97 @@ const ProfilePage = () => {
</Button>
</Stack>
<DndContext
sensors={sensors}
collisionDetection={profileCollisionDetection}
onDragEnd={onDragEnd}
<Box
sx={{
pl: '10px',
pr: '10px',
height: 'calc(100% - 48px)',
overflowY: 'auto',
}}
>
<Box
sx={{
pl: '10px',
pr: '10px',
height: 'calc(100% - 48px)',
overflowY: 'auto',
}}
<DragDropProvider
key={profileDndRevision}
sensors={[profilePointerSensor, KeyboardSensor]}
onDragEnd={onDragEnd}
>
<Box sx={{ mb: 1.5 }}>
<Grid container spacing={{ xs: 1, lg: 1 }}>
<SortableContext
strategy={profileRectSortingStrategy}
items={profileItems.map((x) => {
return x.uid
})}
>
{profileItems.map((item) => (
<Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }} key={item.file}>
<SortableProfileItem
id={item.uid}
selected={(switchTarget ?? profiles.current) === item.uid}
activating={
activatings.includes(item.uid) ||
visibleSwitchingProfile === item.uid
}
itemData={item}
timerUpdateRevision={
timerUpdateRevisions.get(item.uid) ?? 0
}
completedUpdateRevision={
completedUpdateRevisions.get(item.uid) ?? 0
}
mutateProfiles={mutateProfiles}
onSelect={(f) => onSelect(item.uid, f)}
onEdit={() => viewerRef.current?.edit(item)}
onSave={async (prev, curr) => {
if (prev !== curr && profiles.current === item.uid) {
await onEnhance(false)
}
}}
onDelete={() => {
if (batchMode) {
toggleProfileSelection(item.uid)
} else {
onDelete(item.uid)
}
}}
batchMode={batchMode}
isSelected={selectedProfiles.has(item.uid)}
onSelectionChange={() => toggleProfileSelection(item.uid)}
/>
</Grid>
))}
</SortableContext>
</Grid>
<Box
sx={{
mb: 1.5,
display: 'grid',
overflow: 'hidden',
gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))',
gap: 1,
px: 0.5,
}}
>
{profileItems.map((item, index) => (
<ProfileItem
key={item.uid}
id={item.uid}
index={index}
selected={(switchTarget ?? profiles.current) === item.uid}
activating={
activatings.includes(item.uid) ||
visibleSwitchingProfile === item.uid
}
itemData={item}
timerUpdateRevision={timerUpdateRevisions.get(item.uid) ?? 0}
completedUpdateRevision={
completedUpdateRevisions.get(item.uid) ?? 0
}
mutateProfiles={mutateProfiles}
onSelect={(f) => onSelect(item.uid, f)}
onEdit={() => viewerRef.current?.edit(item)}
onSave={async (prev, curr) => {
if (prev !== curr && profiles.current === item.uid) {
await onEnhance(false)
}
}}
onDelete={() => {
if (batchMode) {
toggleProfileSelection(item.uid)
} else {
onDelete(item.uid)
}
}}
batchMode={batchMode}
isSelected={selectedProfiles.has(item.uid)}
onSelectionChange={() => toggleProfileSelection(item.uid)}
/>
))}
</Box>
<Divider
variant="middle"
flexItem
sx={{ width: `calc(100% - 32px)`, borderColor: dividercolor }}
></Divider>
<Box sx={{ mt: 1.5, mb: '10px' }}>
<Grid container spacing={{ xs: 1, lg: 1 }}>
<Grid size={{ xs: 12, sm: 6, md: 6, lg: 6 }}>
<ProfileMore
id="Merge"
onSave={async (prev, curr) => {
if (prev !== curr) {
await onEnhance(false)
}
}}
/>
</Grid>
<Grid size={{ xs: 12, sm: 6, md: 6, lg: 6 }}>
<ProfileMore
id="Script"
logInfo={chainLogs['Script']}
onSave={async (prev, curr) => {
if (prev !== curr) {
await onEnhance(false)
}
}}
/>
</Grid>
</DragDropProvider>
<Divider
variant="middle"
flexItem
sx={{ width: `calc(100% - 32px)`, borderColor: dividercolor }}
></Divider>
<Box sx={{ mt: 1.5, mb: '10px' }}>
<Grid container spacing={{ xs: 1, lg: 1 }}>
<Grid size={{ xs: 12, sm: 6, md: 6, lg: 6 }}>
<ProfileMore
id="Merge"
onSave={async (prev, curr) => {
if (prev !== curr) {
await onEnhance(false)
}
}}
/>
</Grid>
</Box>
<Grid size={{ xs: 12, sm: 6, md: 6, lg: 6 }}>
<ProfileMore
id="Script"
logInfo={chainLogs['Script']}
onSave={async (prev, curr) => {
if (prev !== curr) {
await onEnhance(false)
}
}}
/>
</Grid>
</Grid>
</Box>
<DragOverlay />
</DndContext>
</Box>
<ProfileViewer
ref={viewerRef}