import { client } from '@/ui/api/client' import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from '@/ui/components/ui/alert-dialog' import { Button } from '@/ui/components/ui/button' import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, } from '@/ui/components/ui/dialog' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from '@/ui/components/ui/dropdown-menu' import { Input } from '@/ui/components/ui/input' import { usePermissions } from '@/ui/hooks/use-permissions' import { cn } from '@/ui/lib/utils' import { useDraggable, useDroppable } from '@dnd-kit/react' import type { AssetInfo, AssetInfoPaginatedList, CollectionInfo, ShareLinkInfo } from '@shumai/dtos' import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { useMatch, useNavigate, useParams } from '@tanstack/react-router' import { Bookmark, ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown, Clapperboard, Folder, LayoutGrid, Loader2, MoreHorizontal, Plus, Share2, Trash2, } from 'lucide-react' import { useEffect, useMemo, useState } from 'react' import { useInView } from 'react-intersection-observer' import { toast } from 'sonner' import type { DragState } from './dnd-types' 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 { canEdit } = usePermissions(projectId) 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, fetchNextPage: fetchNextShareLinks, hasNextPage: hasNextShareLinks, isFetchingNextPage: isFetchingNextShareLinks, } = useInfiniteQuery({ queryKey: ['shares', projectId], queryFn: async ({ pageParam }) => { const res = await client.api.projects[':projectId'].shares.$get({ param: { projectId }, query: { first: '20', after: pageParam as string }, }) if (!res.ok) throw new Error('Failed to fetch share links') return (await res.json()) as unknown as { data: ShareLinkInfo[] pageInfo: { cursor?: string; total?: number } } }, initialPageParam: '', getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined, enabled: !!projectId, }) const { data: collectionsData, fetchNextPage: fetchNextCollections, hasNextPage: hasNextCollections, isFetchingNextPage: isFetchingNextCollections, } = useInfiniteQuery({ queryKey: ['collections', projectId], queryFn: async ({ pageParam }) => { const res = await client.api.projects[':projectId'].collections.$get({ param: { projectId }, query: { first: '20', after: pageParam as string }, }) if (!res.ok) throw new Error('Failed to fetch collections') return (await res.json()) as unknown as { data: CollectionInfo[] pageInfo: { cursor?: string; total?: number } } }, initialPageParam: '', getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined, enabled: !!projectId, }) const { ref: collectionsInViewRef, inView: collectionsInView } = useInView() const { ref: sharesInViewRef, inView: sharesInView } = useInView() useEffect(() => { if (collectionsInView && hasNextCollections && !isFetchingNextCollections) { fetchNextCollections() } }, [collectionsInView, hasNextCollections, isFetchingNextCollections, fetchNextCollections]) useEffect(() => { if (sharesInView && hasNextShareLinks && !isFetchingNextShareLinks) { fetchNextShareLinks() } }, [sharesInView, hasNextShareLinks, isFetchingNextShareLinks, fetchNextShareLinks]) const collections = useMemo( () => collectionsData?.pages.flatMap((p) => p.data) || [], [collectionsData], ) const shareLinks = useMemo( () => shareLinksData?.pages.flatMap((p) => p.data) || [], [shareLinksData], ) 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 params = useParams({ from: '/projects/$projectId/collections/$collectionId', shouldThrow: false, }) const shareParams = useParams({ from: '/projects/$projectId/shares/$shareId', shouldThrow: false, }) const [renameId, setRenameId] = useState(null) const [renameType, setRenameType] = useState<'collection' | 'share'>('collection') const [renameName, setRenameName] = useState('') const [isRenameOpen, setIsRenameOpen] = useState(false) const [deleteId, setDeleteId] = useState(null) const [deleteType, setDeleteType] = useState<'collection' | 'share'>('collection') const [isDeleteOpen, setIsDeleteOpen] = useState(false) const { mutate: renameCollection } = useMutation({ mutationFn: async ({ id, name }: { id: string; name: string }) => { const res = await client.api.collections[':collectionId'].$patch({ param: { collectionId: id }, json: { name }, }) if (!res.ok) throw new Error('Failed to rename collection') return await res.json() }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['collections', projectId] }) toast.success('Collection renamed') setIsRenameOpen(false) }, onError: (err) => { toast.error(`Error: ${err.message}`) }, }) const { mutate: deleteCollection } = useMutation({ mutationFn: async (id: string) => { const res = await client.api.collections[':collectionId'].$delete({ param: { collectionId: id }, }) if (!res.ok) throw new Error('Failed to delete collection') return await res.json() }, onSuccess: (_, deletedId) => { queryClient.invalidateQueries({ queryKey: ['collections', projectId] }) toast.success('Collection deleted') setIsDeleteOpen(false) if (params?.collectionId === deletedId) { navigate({ to: '/projects/$projectId', params: { projectId }, }) } }, onError: (err) => { toast.error(`Error: ${err.message}`) }, }) const { mutate: renameShareLink } = useMutation({ mutationFn: async ({ id, name }: { id: string; name: string }) => { const res = await client.api.shares[':shareId'].$put({ param: { shareId: id }, json: { name }, }) if (!res.ok) throw new Error('Failed to rename share link') return await res.json() }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['shares', projectId] }) toast.success('Share link renamed') setIsRenameOpen(false) }, onError: (err) => { toast.error(`Error: ${err.message}`) }, }) const { mutate: deleteShareLink } = useMutation({ mutationFn: async (id: string) => { const res = await client.api.shares[':shareId'].$delete({ param: { shareId: id }, }) if (!res.ok) throw new Error('Failed to delete share link') return id }, onSuccess: (deletedId) => { queryClient.invalidateQueries({ queryKey: ['shares', projectId] }) toast.success('Share link deleted') setIsDeleteOpen(false) if (shareParams?.shareId === deletedId) { navigate({ to: '/projects/$projectId', params: { projectId }, }) } }, onError: (err) => { toast.error(`Error: ${err.message}`) }, }) return (
setIsAssetsExpanded(!isAssetsExpanded)} >

Assets

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

Collections

{isCollectionsExpanded ? ( ) : ( )}
{canEdit && ( )}
navigate({ to: '/projects/$projectId/collections', params: { projectId }, }) } >
All Collections ({collectionsData?.pages[0]?.pageInfo?.total || 0})
{collections.map((collection) => { const isColActive = params?.collectionId === collection.id return (
navigate({ to: '/projects/$projectId/collections/$collectionId', params: { projectId, collectionId: collection.id }, }) } >
{collection.name}
{canEdit && (
e.stopPropagation()} > { setRenameId(collection.id) setRenameType('collection') setRenameName(collection.name) setIsRenameOpen(true) }} > Rename { setDeleteId(collection.id) setDeleteType('collection') setIsDeleteOpen(true) }} > Delete
)}
) })}
{isFetchingNextCollections && (
)}
)} {!hideShares && (
setIsSharesExpanded(!isSharesExpanded)} >

Share Links

{isSharesExpanded ? ( ) : ( )}
{canEdit && (
)}
navigate({ to: '/projects/$projectId/shares', params: { projectId }, }) } >
All Share Links ({shareLinksData?.pages[0]?.pageInfo?.total || 0})
{shareLinks.map((link) => ( { setRenameId(id) setRenameType('share') setRenameName(currentName) setIsRenameOpen(true) }} onDeleteTrigger={(id) => { setDeleteId(id) setDeleteType('share') setIsDeleteOpen(true) }} /> ))}
{isFetchingNextShareLinks && (
)}
)} {/* Rename Dialog */} e.stopPropagation()}> Rename {renameType === 'collection' ? 'Collection' : 'Share Link'}
setRenameName(e.target.value)} placeholder="Enter new name" onKeyDown={(e) => { if (e.key === 'Enter' && renameName.trim()) { if (renameType === 'collection') { renameCollection({ id: renameId!, name: renameName }) } else { renameShareLink({ id: renameId!, name: renameName }) } } }} />
{/* Delete Confirmation Alert Dialog */} e.stopPropagation()}> Delete {deleteType === 'collection' ? 'Collection' : 'Share Link'}? Are you sure you want to delete this{' '} {deleteType === 'collection' ? 'collection' : 'share link'}? This action cannot be undone. Cancel { if (deleteType === 'collection') { deleteCollection(deleteId!) } else { deleteShareLink(deleteId!) } }} > Delete
) } function ShareLinkItem({ link, projectId, dragState, canEdit, onRenameTrigger, onDeleteTrigger, }: { link: ShareLinkInfo projectId: string dragState?: DragState canEdit?: boolean onRenameTrigger: (id: string, currentName: string) => void onDeleteTrigger: (id: string) => void }) { 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}
{canEdit && (
e.stopPropagation()} > { onRenameTrigger(link.id, link.name) }} > Rename { onDeleteTrigger(link.id) }} > Delete
)}
) } interface FolderTreeItemProps { teamId: string projectId: string folder: AssetInfo level: number isRoot?: boolean dragState?: DragState onSelect?: (folder: AssetInfo) => void selectedFolderId?: string canEdit?: boolean } function FolderTreeItem({ teamId, projectId, folder, level, isRoot, dragState, onSelect, selectedFolderId, canEdit, }: 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 || !canEdit, }) const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({ id: `tree:${folder.id!}`, data: { type: 'folder', item: folder, }, disabled: dragState?.draggedIds.has(folder.id!) || !!onSelect || !canEdit, }) 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 && }
)}
)}
) }