fix(webui): avoid refetching all pages on file/folder reorder

This commit is contained in:
yiling
2026-06-15 19:20:45 +08:00
parent d766edbbd0
commit 3b4751bcb2
@@ -2,8 +2,9 @@
import { client } from '@/ui/api/client'
import type { InferRequestType, InferResponseType } from 'hono/client'
import type { AssetInfo } from '@shumai/dtos'
import type { AssetInfo, AssetInfoPaginatedList, SearchSort } from '@shumai/dtos'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import type { InfiniteData } from '@tanstack/react-query'
import { useState } from 'react'
import { toast } from 'sonner'
import type { DragEndEvent, DragStartEvent } from '@dnd-kit/react'
@@ -31,6 +32,55 @@ export function useFileSystemDnd({
const queryClient = useQueryClient()
const [dragState, setDragState] = useState<DragState | undefined>(undefined)
const updateLocalCache = (isFolder: boolean, updatedItem: AssetInfo) => {
const assetType = isFolder ? 'folder' : 'file'
const queryKeyPrefix = ['search', teamId, assetId, assetType]
const queries = queryClient.getQueriesData<InfiniteData<AssetInfoPaginatedList>>({
queryKey: queryKeyPrefix,
})
for (const [queryKey, oldData] of queries) {
if (!oldData) continue
const sort = queryKey[5] as SearchSort | undefined
const isDesc = sort?.order === 'desc'
const allItems = oldData.pages.flatMap((page) => page.data ?? [])
const itemIndex = allItems.findIndex((item) => item.id === updatedItem.id)
if (itemIndex === -1) {
continue
}
allItems[itemIndex] = { ...allItems[itemIndex], ...updatedItem }
allItems.sort((a, b) => {
const indexA = a.sortIndex ?? ''
const indexB = b.sortIndex ?? ''
if (indexA === indexB) return 0
const comp = indexA.localeCompare(indexB)
return isDesc ? -comp : comp
})
let pointer = 0
const newPages = oldData.pages.map((page) => {
const pageSize = page.data ? page.data.length : 0
const pageData = allItems.slice(pointer, pointer + pageSize)
pointer += pageSize
return {
...page,
data: pageData,
}
})
queryClient.setQueryData<InfiniteData<AssetInfoPaginatedList>>(queryKey, {
...oldData,
pages: newPages,
})
}
}
const $reparent = client.api.projects[':projectId'].reparent.$post
const { mutate: reparentAssets } = useMutation<
InferResponseType<typeof $reparent, 204>,
@@ -185,11 +235,9 @@ export function useFileSystemDnd({
: { afterIndex: targetItem.sortIndex ?? undefined },
},
{
onSuccess: () => {
onSuccess: (updatedFolder) => {
toast.success('Folder reordered')
queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
updateLocalCache(true, updatedFolder)
onClearSelection()
},
onError: (err) => {
@@ -207,11 +255,9 @@ export function useFileSystemDnd({
: { afterIndex: targetItem.sortIndex ?? undefined },
},
{
onSuccess: () => {
onSuccess: (updatedFile) => {
toast.success('File reordered')
queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId],
})
updateLocalCache(false, updatedFile)
onClearSelection()
},
onError: (err) => {