import type { AssetInfoPaginatedList, AssetInfo } from '@shumai/dtos' import { client } from '@/ui/api/client' import { cn } from '@/ui/lib/utils' import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMatch, useNavigate, useParams } from '@tanstack/react-router' import { ChevronDown, ChevronsDownUp, ChevronsUpDown, ChevronRight, Clapperboard, Folder, Loader2, Trash2, Plus, Share2, LayoutGrid, Bookmark, } from 'lucide-react' import { useEffect, useMemo, useState } from 'react' import { useInView } from 'react-intersection-observer' import { useDraggable, useDroppable } from '@dnd-kit/react' import type { DragState } from './dnd-types' import { toast } from 'sonner' import type { ShareLinkInfo } from '@shumai/dtos' import type { CollectionInfo } from '@shumai/dtos' interface FolderTreeProps { teamId: string projectId: string projectName: string rootFolderId: string dragState?: DragState onSelect?: (folder: AssetInfo) => void selectedFolderId?: string hideCollections?: boolean hideShares?: boolean } export function FolderTree({ teamId, projectId, projectName, rootFolderId, dragState, onSelect, selectedFolderId, hideCollections, hideShares, }: FolderTreeProps) { const navigate = useNavigate() const queryClient = useQueryClient() const isRecentlyDeleted = useMatch({ from: '/projects/$projectId/recently-deleted', shouldThrow: false, }) const [isAssetsExpanded, setIsAssetsExpanded] = useState(true) const [isCollectionsExpanded, setIsCollectionsExpanded] = useState(true) const [isSharesExpanded, setIsSharesExpanded] = useState(true) const { data: shareLinksData } = useQuery({ queryKey: ['shares', projectId], queryFn: async () => { const res = await client.api.projects[':projectId'].shares.$get({ param: { projectId }, query: { first: '100' }, }) if (!res.ok) throw new Error('Failed to fetch share links') return (await res.json()) as unknown as { data: ShareLinkInfo[] } }, enabled: !!projectId, }) const { data: collectionsData } = useQuery({ queryKey: ['collections', projectId], queryFn: async () => { const res = await client.api.projects[':projectId'].collections.$get({ param: { projectId }, query: { first: '100' }, }) if (!res.ok) throw new Error('Failed to fetch collections') return (await res.json()) as unknown as { data: CollectionInfo[] } }, enabled: !!projectId, }) const { mutate: createCollection } = useMutation({ mutationFn: async () => { const res = await client.api.projects[':projectId'].collections.$post({ param: { projectId }, json: { name: 'Untitled Collection', filter: { sourceFolderId: rootFolderId, searchFilter: { conditions: [], recursively: true, }, }, }, }) if (!res.ok) throw new Error('Failed to create collection') return await res.json() }, onSuccess: (data) => { queryClient.invalidateQueries({ queryKey: ['collections', 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.projects[':projectId'].shares.$post({ param: { projectId }, json: { name: new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric', }), }, }) if (!res.ok) throw new Error('Failed to create share link') return await res.json() }, onSuccess: (data) => { queryClient.invalidateQueries({ queryKey: ['shares', projectId] }) toast.success('Share link created') navigate({ to: '/projects/$projectId/shares/$shareId', params: { projectId, shareId: data.id }, }) }, onError: (err) => { toast.error(`Error: ${err.message}`) }, }) const shareLinks = shareLinksData?.data ?? [] return (
setIsAssetsExpanded(!isAssetsExpanded)} >

Assets

{isAssetsExpanded ? ( ) : ( )}
navigate({ to: '/projects/$projectId/recently-deleted', params: { projectId }, }) } >
Recently Deleted
{!hideCollections && (
setIsCollectionsExpanded(!isCollectionsExpanded)} >

Collections

{isCollectionsExpanded ? ( ) : ( )}
{collectionsData?.data.map((collection) => (
navigate({ to: '/projects/$projectId/collections/$collectionId', params: { projectId, collectionId: collection.id }, }) } >
{collection.name}
))}
)} {!hideShares && (
setIsSharesExpanded(!isSharesExpanded)} >

Share Links

{isSharesExpanded ? ( ) : ( )}
All Share Links ({shareLinks.length})
{shareLinks.map((link) => ( ))}
)}
) } function ShareLinkItem({ link, projectId, dragState, }: { link: ShareLinkInfo projectId: string dragState?: DragState }) { const navigate = useNavigate() const params = useParams({ from: '/projects/$projectId/shares/$shareId', shouldThrow: false, }) const isActive = params?.shareId === link.id const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({ id: `share:${link.id}`, data: { type: 'share-link', id: link.id, }, }) const isValidDropTarget = !!dragState?.isActive return (
navigate({ to: '/projects/$projectId/shares/$shareId', params: { projectId, shareId: link.id }, }) } >
{link.name}
) } interface FolderTreeItemProps { teamId: string projectId: string folder: AssetInfo level: number isRoot?: boolean dragState?: DragState onSelect?: (folder: AssetInfo) => void selectedFolderId?: string } function FolderTreeItem({ teamId, projectId, folder, level, isRoot, dragState, onSelect, selectedFolderId, }: FolderTreeItemProps) { const [isExpanded, setIsExpanded] = useState(isRoot || false) const navigate = useNavigate() const params = useParams({ from: '/projects/$projectId/folders/$folderId', select: (p) => ({ folderId: p.folderId }), shouldThrow: false, }) const rootParams = useParams({ from: '/projects/$projectId/', shouldThrow: false, }) const isActive = isRoot ? !!rootParams : params?.folderId === folder.id const { data: childrenData, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading, } = useInfiniteQuery({ queryKey: [ 'folders', folder.id, 'children', { assetType: 'folder', }, ], queryFn: async ({ pageParam }) => { const res = await client.api.folders[':folderId'].children.$get({ param: { folderId: folder.id }, query: { assetType: 'folder', after: pageParam as string, first: '20', }, }) if (!res.ok) throw new Error('failed to fetch folder children') return (await res.json()) as unknown as AssetInfoPaginatedList }, initialPageParam: '', getNextPageParam: (lastPage) => { return lastPage.pageInfo?.cursor || undefined }, enabled: isExpanded || !!isRoot, }) const { ref, inView } = useInView() useEffect(() => { if (inView && hasNextPage && !isFetchingNextPage) { fetchNextPage() } }, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]) const childrenFolders = childrenData?.pages.flatMap((page) => page.data ?? []) ?? [] const handleToggleExpand = (e: React.MouseEvent) => { e.stopPropagation() setIsExpanded(!isExpanded) } const handleFolderClick = () => { if (onSelect) { onSelect(folder) return } if (isRoot) { navigate({ to: '/projects/$projectId', params: { projectId }, }) } else { navigate({ to: '/projects/$projectId/folders/$folderId', params: { projectId, folderId: folder.id! }, }) } } const { ref: setDraggableRef, isDragging } = useDraggable({ id: `tree:${folder.id!}`, data: { type: 'folder', item: folder, }, disabled: !!isRoot || !!onSelect, }) const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({ id: `tree:${folder.id!}`, data: { type: 'folder', item: folder, }, disabled: dragState?.draggedIds.has(folder.id!) || !!onSelect, }) const setNodeRef = (node: HTMLDivElement | null) => { setDraggableRef(node) setDroppableRef(node) } const isValidDropTarget = useMemo(() => { if (onSelect) return false if (!dragState?.isActive) return false if (dragState.draggedIds.has(folder.id!)) return false return true }, [dragState, folder.id, onSelect]) const showDropFeedback = isOver && isValidDropTarget const isSelected = selectedFolderId === folder.id return (
{!isRoot && ( )} {isRoot ? ( ) : ( )} {folder.name}
{isExpanded && (
{isLoading && (
)} {childrenFolders.map((child) => ( ))} {hasNextPage && (
{isFetchingNextPage && }
)}
)}
) }