import { create } from "@bufbuild/protobuf"; import { LoaderCircleIcon, Trash2Icon } from "lucide-react"; import { useEffect, useState } from "react"; import { toast } from "react-hot-toast"; import { AttachmentAudioRows, AttachmentDocumentRows, AttachmentLibraryEmptyState, AttachmentLibraryErrorState, AttachmentLibrarySkeletonGrid, AttachmentMediaGrid, AttachmentUnusedRows, } from "@/components/AttachmentLibrary"; import ConfirmDialog from "@/components/ConfirmDialog"; import PreviewImageDialog from "@/components/PreviewImageDialog"; import { Button } from "@/components/ui/button"; import { attachmentServiceClient } from "@/connect"; import { useAppSidebar } from "@/contexts/AppSidebarContext"; import { useSpaceContext } from "@/contexts/SpaceContext"; import { useAttachmentLibrary, useUnusedAttachmentLibrary } from "@/hooks/useAttachmentLibrary"; import { useBatchDeleteAttachments } from "@/hooks/useAttachmentQueries"; import useDialog from "@/hooks/useDialog"; import i18n from "@/i18n"; import { combineCELFilters } from "@/lib/cel-filter"; import { handleError } from "@/lib/error"; import { ListAttachmentsRequestSchema } from "@/types/proto/api/v1/attachment_service_pb"; import { useTranslate } from "@/utils/i18n"; const UNUSED_PAGE_SIZE = 1000; const BATCH_DELETE_SIZE = 100; const chunkNames = (names: string[], size: number) => { const chunks: string[][] = []; for (let index = 0; index < names.length; index += size) { chunks.push(names.slice(index, index + size)); } return chunks; }; const listUnusedAttachmentNames = async (filter: string | undefined, selectedSpaceName: string | undefined) => { if (selectedSpaceName) { return []; } const names: string[] = []; let pageToken = ""; do { const response = await attachmentServiceClient.listAttachments( create(ListAttachmentsRequestSchema, { filter: combineCELFilters("memo_id == null", filter), pageSize: UNUSED_PAGE_SIZE, pageToken, }), ); names.push(...response.attachments.map((attachment) => attachment.name)); pageToken = response.nextPageToken; } while (pageToken); return names; }; const Attachments = () => { const t = useTranslate(); const deleteUnusedAttachmentsDialog = useDialog(); const { attachmentSection, setAttachmentSection } = useAppSidebar(); const { memoFilter, selectedSpaceName } = useSpaceContext(); const [previewState, setPreviewState] = useState({ open: false, initialIndex: 0 }); const { mutateAsync: batchDeleteAttachments, isPending: isDeletingUnused } = useBatchDeleteAttachments(); const { audioItems, documentItems, error, fetchNextPage, hasNextPage, isError, isFetching, isFetchingNextPage, isLoading, mediaGroups, mediaPreviewItems, refetch, stats, } = useAttachmentLibrary(i18n.language, memoFilter); const { error: unusedError, isComplete: unusedIsComplete, isError: unusedIsError, isLoading: unusedIsLoading, refetch: refetchUnused, unusedItems: completeUnusedItems, } = useUnusedAttachmentLibrary(i18n.language, memoFilter, attachmentSection === "unused" && !selectedSpaceName); useEffect(() => { if (selectedSpaceName && attachmentSection === "unused") { setAttachmentSection("all"); } }, [attachmentSection, selectedSpaceName, setAttachmentSection]); const handlePreview = (itemId: string) => { const initialIndex = mediaPreviewItems.findIndex((item) => item.id === itemId); setPreviewState({ open: true, initialIndex: initialIndex >= 0 ? initialIndex : 0 }); }; const handleDeleteUnusedAttachments = async () => { try { const names = await listUnusedAttachmentNames(memoFilter, selectedSpaceName); if (names.length === 0) { await Promise.all([refetch(), refetchUnused()]); return; } for (const chunk of chunkNames(names, BATCH_DELETE_SIZE)) { await batchDeleteAttachments(chunk); } toast.success(t("resource.delete-all-unused-success")); await Promise.all([refetch(), refetchUnused()]); } catch (deleteError) { handleError(deleteError, toast.error, { context: "Failed to delete unused attachments", fallbackMessage: t("resource.delete-all-unused-error"), }); } }; const renderContent = () => { if (attachmentSection === "unused") { if (unusedIsError) { return ( refetchUnused()} /> ); } if (unusedIsLoading || !unusedIsComplete) { return ; } return completeUnusedItems.length === 0 ? (
{t("message.no-data")}
) : (

{t("attachment-library.unused.title")}

{t("attachment-library.unused.description")}

); } if (isLoading) { return ; } if (isError) { return refetch()} />; } if (attachmentSection === "all") { const total = stats.media + stats.documents + stats.audio; if (total === 0) return
{t("attachment-library.empty.all")}
; return (
{stats.media > 0 && (

{t("attachment-library.tabs.media")}

)} {stats.documents > 0 && (

{t("attachment-library.tabs.documents")}

)} {stats.audio > 0 && (

{t("attachment-library.tabs.audio")}

)}
); } if (attachmentSection === "media") { if (stats.media === 0) return ; return ; } if (attachmentSection === "documents") { if (stats.documents === 0) return ; return ; } if (attachmentSection === "audio") { if (stats.audio === 0) return ; return ; } return null; }; return (
{renderContent()} {attachmentSection !== "unused" && hasNextPage && (
)} {!isLoading && isFetching && !isFetchingNextPage && (
{t("resource.fetching-data")}
)}
setPreviewState((prev) => ({ ...prev, open }))} items={mediaPreviewItems} initialIndex={previewState.initialIndex} />
); }; export default Attachments;