feat(collection): implement saved search results as collections

This commit is contained in:
yiling
2026-05-25 17:29:45 +08:00
parent 0e5a4972b6
commit 794e7b3367
24 changed files with 2462 additions and 63 deletions
@@ -6,6 +6,7 @@ import type { AssetInfo } from '@/dtos/asset'
import type { SearchCondition, SearchSort } from '@/dtos/search'
import type { CreateUploadTaskRequest } from '@/dtos/upload'
import type { ShareLinkInfo } from '@/dtos/share'
import type { CollectionInfo } from '@/dtos/collection'
import { useFieldStore } from '@/ui/stores/fields'
import { useUploadStore } from '@/ui/stores/upload'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
@@ -70,6 +71,9 @@ interface FileBrowserProps {
isPublic?: boolean
onRemoveFromShare?: (items: AssetInfo[]) => void
fieldVisibility?: Record<string, boolean>
collection?: CollectionInfo
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onUpdateCollection?: (updates: { name?: string; filter?: any }) => void
}
type FileWithId = {
@@ -110,6 +114,8 @@ export function FileBrowser({
isPublic,
onRemoveFromShare,
fieldVisibility,
collection,
onUpdateCollection,
}: FileBrowserProps) {
const [contextMenuItem, setContextMenuItem] = useState<AssetInfo | null>(null)
const [moveCopyMode, setMoveCopyMode] = useState<'move' | 'copy' | null>(null)
@@ -745,6 +751,8 @@ export function FileBrowser({
sort={sort}
onSortChange={onSortChange}
isRecentlyDeleted={isRecentlyDeleted}
collection={collection}
onUpdateCollection={onUpdateCollection}
/>
)}
{displayStyle === 'list' ? (
+60 -14
View File
@@ -1,5 +1,6 @@
import { type FieldInfo as MetadataFieldInfo } from '@/dtos/metadata'
import type { SearchCondition, SearchSort } from '@/dtos/search'
import type { CollectionInfo } from '@/dtos/collection'
import { client } from '@/ui/api/client'
import { useMutation, useQuery } from '@tanstack/react-query'
import type { InferRequestType, InferResponseType } from 'hono/client'
@@ -8,11 +9,13 @@ import { FieldsManager } from '../fields-manager'
import { ManageFieldsDialog } from '../manage-fields-dialog'
import { MembersDialog } from '../members-dialog'
import { SearchFilterDialog } from '../search/search-filter-dialog'
import { FilterPanel } from '../search/filter-panel'
import { SortControl } from '../search/sort-control'
import { Avatar, AvatarFallback } from '../ui/avatar'
import { Button } from '../ui/button'
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'
import { Separator } from '../ui/separator'
import { Filter } from 'lucide-react'
type FileBrowserToolbarProps = {
teamId: string
@@ -24,6 +27,9 @@ type FileBrowserToolbarProps = {
sort?: SearchSort
onSortChange: (sort?: SearchSort) => void
isRecentlyDeleted?: boolean
collection?: CollectionInfo
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onUpdateCollection?: (updates: { name?: string; filter?: any }) => void
}
export function FileBrowserToolbar({
@@ -36,6 +42,8 @@ export function FileBrowserToolbar({
sort,
onSortChange,
isRecentlyDeleted,
collection,
onUpdateCollection,
}: FileBrowserToolbarProps) {
const [popoverOpen, setPopoverOpen] = useState(false)
const [searchDialogOpen, setSearchDialogOpen] = useState(false)
@@ -43,6 +51,7 @@ export function FileBrowserToolbar({
const [isMembersDialogOpen, setIsMembersDialogOpen] = useState(false)
const activeFiltersCount = filterConditions.length
const isCollection = !!collection
const { data: members } = useQuery({
queryKey: ['projects', projectId, 'members'],
@@ -147,20 +156,57 @@ export function FileBrowserToolbar({
<Separator orientation="vertical" />
<Button
onClick={() => setSearchDialogOpen(true)}
disabled={isRecentlyDeleted}
variant={activeFiltersCount > 0 ? 'secondary' : 'ghost'}
size="sm"
className="inline-flex items-center gap-2 px-4 py-2 hover:bg-primary/10 font-semibold rounded-xl cursor-pointer h-8"
>
<span>Search</span>
{activeFiltersCount > 0 && (
<span className="ml-1 px-1.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-primary/50 border border-primary-foreground/20">
{activeFiltersCount}
</span>
)}
</Button>
{isCollection ? (
<Popover>
<PopoverTrigger asChild>
<Button
variant={activeFiltersCount > 0 ? 'secondary' : 'ghost'}
size="sm"
className="inline-flex items-center gap-2 px-4 py-2 hover:bg-primary/10 font-semibold rounded-xl cursor-pointer h-8"
>
<Filter className="h-4 w-4" />
<span>Filter</span>
{activeFiltersCount > 0 && (
<span className="ml-1 px-1.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-primary/50 border border-primary-foreground/20">
{activeFiltersCount}
</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-[400px] p-0" align="start">
<FilterPanel
fields={fields}
conditions={filterConditions}
onChange={(newConditions) => {
onFilterChange(newConditions)
onUpdateCollection?.({
filter: {
...collection.filter,
conditions: newConditions,
},
})
}}
excludeFields={[]}
hidePrefix
/>
</PopoverContent>
</Popover>
) : (
<Button
onClick={() => setSearchDialogOpen(true)}
disabled={isRecentlyDeleted}
variant={activeFiltersCount > 0 ? 'secondary' : 'ghost'}
size="sm"
className="inline-flex items-center gap-2 px-4 py-2 hover:bg-primary/10 font-semibold rounded-xl cursor-pointer h-8"
>
<span>Search</span>
{activeFiltersCount > 0 && (
<span className="ml-1 px-1.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-primary/50 border border-primary-foreground/20">
{activeFiltersCount}
</span>
)}
</Button>
)}
</div>
<div className="flex items-center gap-2">
+41 -17
View File
@@ -1,6 +1,7 @@
import type { AssetInfo, AssetInfoPaginatedList } from '@/dtos/asset'
import { type FieldInfo as MetadataFieldInfo } from '@/dtos/metadata'
import type { SearchCondition, SearchSort } from '@/dtos/search'
import type { CollectionInfo } from '@/dtos/collection'
import { client } from '@/ui/api/client'
import { useMutation } from '@tanstack/react-query'
import { InferRequestType, InferResponseType } from 'hono/client'
@@ -29,6 +30,9 @@ type FileSystemManagerProps = {
projectName: string
assetId: string
rootFolderId: string
collection?: CollectionInfo
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onUpdateCollection?: (updates: { name?: string; filter?: any }) => void
}
export default function FileSystemManager({
@@ -37,6 +41,8 @@ export default function FileSystemManager({
projectName,
assetId,
rootFolderId,
collection,
onUpdateCollection,
}: FileSystemManagerProps) {
const navigate = useNavigate()
const queryClient = useQueryClient()
@@ -89,7 +95,17 @@ export default function FileSystemManager({
}
}, [teamId, fetchMembers, fetchMetadata])
const [filterConditions, setFilterConditions] = useState<SearchCondition[]>([])
const initialFilterConditions = useMemo(() => {
return collection?.filter?.conditions || []
}, [collection])
const [filterConditions, setFilterConditions] =
useState<SearchCondition[]>(initialFilterConditions)
useEffect(() => {
setFilterConditions(initialFilterConditions)
}, [initialFilterConditions])
const sortKey = `project:${projectId}:sort`
const sort = (metadata[sortKey] as SearchSort | undefined) || { field: 'custom', order: 'asc' }
const setSort = (newSort: SearchSort | undefined) => {
@@ -98,7 +114,8 @@ export default function FileSystemManager({
}
}
const isFiltering = filterConditions.length > 0
const isCollection = !!collection
const isFiltering = filterConditions.length > 0 || isCollection
const {
fileListLeftSidebarCollapsed: isLeftSidebarCollapsed,
@@ -135,8 +152,10 @@ export default function FileSystemManager({
ancestorFolders: folderInfo?.ancestorFolders ?? [],
currentAsset: isRecentlyDeleted
? { name: 'Recently Deleted', type: 'folder' }
: { name: folderInfo?.name, type: 'folder' },
isRootFolder: !isRecentlyDeleted && assetId === rootFolderId,
: isCollection
? { name: collection.name, type: 'folder' }
: { name: folderInfo?.name, type: 'folder' },
isRootFolder: !isRecentlyDeleted && !isCollection && assetId === rootFolderId,
onFolderClick: (id: string) => {
navigate({
to: '/projects/$projectId/folders/$folderId',
@@ -167,18 +186,21 @@ export default function FileSystemManager({
} = useInfiniteQuery<AssetInfoPaginatedList>({
queryKey: isRecentlyDeleted
? ['projects', projectId, 'recently-deleted', 'folder']
: ['search', teamId, assetId, 'folder', filterConditions, sort],
: ['search', teamId, assetId, 'folder', filterConditions, sort, isCollection],
queryFn: async ({ pageParam }) => {
if (isRecentlyDeleted) {
const res = await client.api.projects[':projectId']['recently-deleted'].$get({
param: { projectId: projectId },
query: {
assetType: 'folder',
after: pageParam as string,
},
})
if (!res.ok) throw new Error('failed to fetch recently deleted folders')
return (await res.json()) as unknown as AssetInfoPaginatedList
if (isRecentlyDeleted || isCollection) {
if (isRecentlyDeleted) {
const res = await client.api.projects[':projectId']['recently-deleted'].$get({
param: { projectId: projectId },
query: {
assetType: 'folder',
after: pageParam as string,
},
})
if (!res.ok) throw new Error('failed to fetch recently deleted folders')
return (await res.json()) as unknown as AssetInfoPaginatedList
}
return { data: [], pageInfo: { total: 0 } }
}
if (isFiltering) {
return { data: [], pageInfo: { total: 0 } }
@@ -212,7 +234,7 @@ export default function FileSystemManager({
} = useInfiniteQuery<AssetInfoPaginatedList>({
queryKey: isRecentlyDeleted
? ['projects', projectId, 'recently-deleted', 'file']
: ['search', teamId, assetId, 'file', filterConditions, sort],
: ['search', teamId, assetId, 'file', filterConditions, sort, isCollection],
queryFn: async ({ pageParam }) => {
if (isRecentlyDeleted) {
const res = await client.api.projects[':projectId']['recently-deleted'].$get({
@@ -231,7 +253,7 @@ export default function FileSystemManager({
json: {
assetType: 'file',
after: pageParam as string,
recursively: isFiltering,
recursively: isFiltering || isCollection,
conditions: filterConditions,
sort,
},
@@ -450,6 +472,8 @@ export default function FileSystemManager({
sort={sort}
onSortChange={setSort}
dragState={dragState}
collection={collection}
onUpdateCollection={onUpdateCollection}
/>
{!isRightSidebarCollapsed && (
+67 -1
View File
@@ -14,6 +14,7 @@ import {
MoreHorizontal,
Share2,
LayoutGrid,
Bookmark,
} from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { useInView } from 'react-intersection-observer'
@@ -21,6 +22,7 @@ import { useDraggable, useDroppable } from '@dnd-kit/react'
import type { DragState } from './dnd-types'
import { toast } from 'sonner'
import type { ShareLinkInfo } from '@/dtos/share'
import type { CollectionInfo } from '@/dtos/collection'
interface FolderTreeProps {
teamId: string
@@ -61,6 +63,47 @@ export function FolderTree({
enabled: !!teamId && !!projectId,
})
const { data: collectionsData } = useQuery({
queryKey: ['collections', teamId, projectId],
queryFn: async () => {
const res = await client.api.teams[':teamId'].projects[':projectId'].collections.$get({
param: { teamId, projectId },
query: { first: '100' },
})
if (!res.ok) throw new Error('Failed to fetch collections')
return (await res.json()) as unknown as { data: CollectionInfo[] }
},
enabled: !!teamId && !!projectId,
})
const { mutate: createCollection } = useMutation({
mutationFn: async () => {
const res = await client.api.teams[':teamId'].projects[':projectId'].collections.$post({
param: { teamId, projectId },
json: {
name: 'Untitled Collection',
filter: {
conditions: [],
recursively: true,
},
},
})
if (!res.ok) throw new Error('Failed to create collection')
return await res.json()
},
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['collections', teamId, projectId] })
toast.success('Collection created')
navigate({
to: '/projects/$projectId/collections/$collectionId',
params: { projectId, collectionId: data.id },
})
},
onError: (err) => {
toast.error(`Error: ${err.message}`)
},
})
const { mutate: createShareLink } = useMutation({
mutationFn: async () => {
const res = await client.api.teams[':teamId'].projects[':projectId'].shares.$post({
@@ -148,10 +191,33 @@ export function FolderTree({
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
Collections
</h3>
<button className="text-muted-foreground hover:text-foreground">
<button
onClick={() => createCollection()}
className="text-muted-foreground hover:text-foreground"
>
<Plus className="h-3.5 w-3.5" />
</button>
</header>
<div className="space-y-0.5">
{collectionsData?.data.map((collection) => (
<div
key={collection.id}
className="group flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
onClick={() =>
navigate({
to: '/projects/$projectId/collections/$collectionId',
params: { projectId, collectionId: collection.id },
})
}
>
<div className="flex h-4 w-4 items-center justify-center">
<Bookmark className="h-4 w-4 text-sidebar-primary" />
</div>
<span className="flex-1 truncate text-sidebar-foreground">{collection.name}</span>
</div>
))}
</div>
</div>
<div>
@@ -7,17 +7,18 @@ import { Dialog, DialogContent } from '@/ui/components/ui/dialog'
import { Input } from '@/ui/components/ui/input'
import { formatSize } from '@/ui/lib/format'
import { cn } from '@/ui/lib/utils'
import { useQuery } from '@tanstack/react-query'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { toast } from 'sonner'
import {
AlertCircle,
ChevronDown,
ChevronUp,
FileIcon,
FolderIcon,
Loader2,
Search,
X,
AlertCircle,
ChevronDown,
ChevronUp,
FileIcon,
FolderIcon,
Loader2,
Search,
X,
} from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { FilterPanel } from './filter-panel'
@@ -44,6 +45,7 @@ export function SearchFilterDialog({
onApply,
}: SearchFilterDialogProps) {
const navigate = useNavigate()
const queryClient = useQueryClient()
const initialKeyword = useMemo(() => {
const cond = initialConditions.find((c) => c.field === 'name' && c.operator === 'contains')
@@ -95,6 +97,44 @@ export function SearchFilterDialog({
)
}, [debouncedSearchInput, conditions])
const { mutate: saveAsCollection, isPending: isSaving } = useMutation({
mutationFn: async () => {
let name = debouncedSearchInput.trim()
if (!name && conditions.length > 0) {
const first = conditions[0]
const field = fields.find((f) => f.id === first.field)
const fieldName = field?.config?.name || first.field
name = `${fieldName} ${first.operator} ${first.value}`
}
if (!name) name = 'Untitled Collection'
const res = await client.api.teams[':teamId'].projects[':projectId'].collections.$post({
param: { teamId, projectId },
json: {
name,
filter: {
conditions: combinedConditions,
recursively: true,
},
},
})
if (!res.ok) throw new Error('Failed to save collection')
return await res.json()
},
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['collections', teamId, projectId] })
toast.success('Collection saved')
onOpenChange(false)
navigate({
to: '/projects/$projectId/collections/$collectionId',
params: { projectId, collectionId: data.id },
})
},
onError: (err) => {
toast.error(`Error: ${err.message}`)
},
})
const { data: searchResults, isLoading } = useQuery({
queryKey: ['search-preview', teamId, assetId, combinedConditions],
queryFn: async () => {
@@ -343,11 +383,17 @@ export function SearchFilterDialog({
variant="outline"
size="xs"
className="h-8 text-[10px] font-semibold uppercase tracking-wider"
onClick={() => {
// Future implementation for saving collections
}}
disabled={!hasActiveCriteria || isSaving}
onClick={() => saveAsCollection()}
>
Save as collection
{isSaving ? (
<>
<Loader2 className="mr-2 h-3 w-3 animate-spin" />
Saving...
</>
) : (
'Save as collection'
)}
</Button>
</div>
</div>
+22
View File
@@ -23,6 +23,7 @@ import { Route as ShareShareIdFilesFileIdRouteImport } from './routes/share/$sha
import { Route as ProjectsProjectIdSharesShareIdRouteImport } from './routes/projects/$projectId/shares/$shareId'
import { Route as ProjectsProjectIdFoldersFolderIdRouteImport } from './routes/projects/$projectId/folders/$folderId'
import { Route as ProjectsProjectIdFilesFileIdRouteImport } from './routes/projects/$projectId/files/$fileId'
import { Route as ProjectsProjectIdCollectionsCollectionIdRouteImport } from './routes/projects/$projectId/collections/$collectionId'
const SignupRoute = SignupRouteImport.update({
id: '/signup',
@@ -94,6 +95,12 @@ const ProjectsProjectIdFilesFileIdRoute = ProjectsProjectIdFilesFileIdRouteImpor
path: '/projects/$projectId/files/$fileId',
getParentRoute: () => rootRouteImport,
} as any)
const ProjectsProjectIdCollectionsCollectionIdRoute =
ProjectsProjectIdCollectionsCollectionIdRouteImport.update({
id: '/projects/$projectId/collections/$collectionId',
path: '/projects/$projectId/collections/$collectionId',
getParentRoute: () => rootRouteImport,
} as any)
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
@@ -105,6 +112,7 @@ export interface FileRoutesByFullPath {
'/projects/$projectId/': typeof ProjectsProjectIdIndexRoute
'/share/$shareId/': typeof ShareShareIdIndexRoute
'/teams/$teamId/': typeof TeamsTeamIdIndexRoute
'/projects/$projectId/collections/$collectionId': typeof ProjectsProjectIdCollectionsCollectionIdRoute
'/projects/$projectId/files/$fileId': typeof ProjectsProjectIdFilesFileIdRoute
'/projects/$projectId/folders/$folderId': typeof ProjectsProjectIdFoldersFolderIdRoute
'/projects/$projectId/shares/$shareId': typeof ProjectsProjectIdSharesShareIdRoute
@@ -120,6 +128,7 @@ export interface FileRoutesByTo {
'/projects/$projectId': typeof ProjectsProjectIdIndexRoute
'/share/$shareId': typeof ShareShareIdIndexRoute
'/teams/$teamId': typeof TeamsTeamIdIndexRoute
'/projects/$projectId/collections/$collectionId': typeof ProjectsProjectIdCollectionsCollectionIdRoute
'/projects/$projectId/files/$fileId': typeof ProjectsProjectIdFilesFileIdRoute
'/projects/$projectId/folders/$folderId': typeof ProjectsProjectIdFoldersFolderIdRoute
'/projects/$projectId/shares/$shareId': typeof ProjectsProjectIdSharesShareIdRoute
@@ -137,6 +146,7 @@ export interface FileRoutesById {
'/projects/$projectId/': typeof ProjectsProjectIdIndexRoute
'/share/$shareId/': typeof ShareShareIdIndexRoute
'/teams/$teamId/': typeof TeamsTeamIdIndexRoute
'/projects/$projectId/collections/$collectionId': typeof ProjectsProjectIdCollectionsCollectionIdRoute
'/projects/$projectId/files/$fileId': typeof ProjectsProjectIdFilesFileIdRoute
'/projects/$projectId/folders/$folderId': typeof ProjectsProjectIdFoldersFolderIdRoute
'/projects/$projectId/shares/$shareId': typeof ProjectsProjectIdSharesShareIdRoute
@@ -155,6 +165,7 @@ export interface FileRouteTypes {
| '/projects/$projectId/'
| '/share/$shareId/'
| '/teams/$teamId/'
| '/projects/$projectId/collections/$collectionId'
| '/projects/$projectId/files/$fileId'
| '/projects/$projectId/folders/$folderId'
| '/projects/$projectId/shares/$shareId'
@@ -170,6 +181,7 @@ export interface FileRouteTypes {
| '/projects/$projectId'
| '/share/$shareId'
| '/teams/$teamId'
| '/projects/$projectId/collections/$collectionId'
| '/projects/$projectId/files/$fileId'
| '/projects/$projectId/folders/$folderId'
| '/projects/$projectId/shares/$shareId'
@@ -186,6 +198,7 @@ export interface FileRouteTypes {
| '/projects/$projectId/'
| '/share/$shareId/'
| '/teams/$teamId/'
| '/projects/$projectId/collections/$collectionId'
| '/projects/$projectId/files/$fileId'
| '/projects/$projectId/folders/$folderId'
| '/projects/$projectId/shares/$shareId'
@@ -202,6 +215,7 @@ export interface RootRouteChildren {
TeamsTeamIdSettingsRoute: typeof TeamsTeamIdSettingsRoute
ProjectsProjectIdIndexRoute: typeof ProjectsProjectIdIndexRoute
TeamsTeamIdIndexRoute: typeof TeamsTeamIdIndexRoute
ProjectsProjectIdCollectionsCollectionIdRoute: typeof ProjectsProjectIdCollectionsCollectionIdRoute
ProjectsProjectIdFilesFileIdRoute: typeof ProjectsProjectIdFilesFileIdRoute
ProjectsProjectIdFoldersFolderIdRoute: typeof ProjectsProjectIdFoldersFolderIdRoute
ProjectsProjectIdSharesShareIdRoute: typeof ProjectsProjectIdSharesShareIdRoute
@@ -307,6 +321,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ProjectsProjectIdFilesFileIdRouteImport
parentRoute: typeof rootRouteImport
}
'/projects/$projectId/collections/$collectionId': {
id: '/projects/$projectId/collections/$collectionId'
path: '/projects/$projectId/collections/$collectionId'
fullPath: '/projects/$projectId/collections/$collectionId'
preLoaderRoute: typeof ProjectsProjectIdCollectionsCollectionIdRouteImport
parentRoute: typeof rootRouteImport
}
}
}
@@ -333,6 +354,7 @@ const rootRouteChildren: RootRouteChildren = {
TeamsTeamIdSettingsRoute: TeamsTeamIdSettingsRoute,
ProjectsProjectIdIndexRoute: ProjectsProjectIdIndexRoute,
TeamsTeamIdIndexRoute: TeamsTeamIdIndexRoute,
ProjectsProjectIdCollectionsCollectionIdRoute: ProjectsProjectIdCollectionsCollectionIdRoute,
ProjectsProjectIdFilesFileIdRoute: ProjectsProjectIdFilesFileIdRoute,
ProjectsProjectIdFoldersFolderIdRoute: ProjectsProjectIdFoldersFolderIdRoute,
ProjectsProjectIdSharesShareIdRoute: ProjectsProjectIdSharesShareIdRoute,
@@ -0,0 +1,101 @@
import { client } from '@/ui/api/client'
import FileSystemManager from '@/ui/components/file-system-manager'
import { useTeamContextStore } from '@/ui/stores/team-context'
import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { createFileRoute } from '@tanstack/react-router'
import { useEffect } from 'react'
const projectInfoQueryOptions = (projectId: string) => ({
queryKey: ['projects', projectId],
queryFn: async () => {
const res = await client.api.projects[':projectId'].$get({
param: { projectId: projectId },
})
if (!res.ok) throw new Error('Failed to fetch project')
return await res.json()
},
})
const collectionInfoQueryOptions = (teamId: string, projectId: string, collectionId: string) => ({
queryKey: ['collections', teamId, projectId, collectionId],
queryFn: async () => {
const res = await client.api.teams[':teamId'].projects[':projectId'].collections[
':collectionId'
].$get({
param: { teamId, projectId, collectionId },
})
if (!res.ok) throw new Error('Failed to fetch collection')
return await res.json()
},
})
function CollectionPage() {
const { projectId, collectionId } = Route.useParams()
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
useEffect(() => {
ensureTeamIdForProject(projectId)
}, [projectId, ensureTeamIdForProject])
const { data: projectInfo } = useSuspenseQuery(projectInfoQueryOptions(projectId))
const { data: collection, refetch: refetchCollection } = useQuery({
...collectionInfoQueryOptions(teamId || '', projectId, collectionId),
enabled: !!teamId,
})
const { mutate: updateCollection } = useMutation({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mutationFn: async (updates: { name?: string; filter?: any }) => {
const res = await client.api.teams[':teamId'].projects[':projectId'].collections[
':collectionId'
].$patch({
param: { teamId: teamId!, projectId, collectionId },
json: updates,
})
if (!res.ok) throw new Error('Failed to update collection')
return await res.json()
},
onSuccess: () => {
refetchCollection()
},
})
const rootFolderId = projectInfo?.rootFolder
const { data: rootFolder } = useQuery({
queryKey: ['folders', teamId!, rootFolderId!],
queryFn: async () => {
const res = await client.api.teams[':teamId'].folders[':folderId'].$get({
param: { teamId: teamId!, folderId: rootFolderId! },
})
if (!res.ok) throw new Error('Failed to fetch folder')
return await res.json()
},
enabled: !!teamId && !!rootFolderId,
})
if (!teamId || !rootFolderId || !rootFolder || !collection) {
return <div>Loading collection...</div>
}
return (
<FileSystemManager
teamId={teamId}
projectId={projectId}
projectName={projectInfo.name ?? ''}
assetId={rootFolderId}
rootFolderId={rootFolderId}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
collection={collection as any}
onUpdateCollection={updateCollection}
/>
)
}
export const Route = createFileRoute('/projects/$projectId/collections/$collectionId')({
component: CollectionPage,
loader: ({ context: { queryClient }, params: { projectId } }) =>
queryClient.ensureQueryData(projectInfoQueryOptions(projectId)),
pendingComponent: () => <div>Loading collection...</div>,
})