Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

6.3 KB
Raw Blame
'use client';

import { Flexbox } from '@lobehub/ui';
import { memo, type ReactNode, useMemo } from 'react';

import AsyncBoundary from '@/components/AsyncBoundary';
import { useFolderPath } from '@/features/ResourceManager/hooks/useFolderPath';
import { useResourceManagerUrlSync } from '@/features/ResourceManager/hooks/useResourceManagerUrlSync';
import { useResourceManagerStore } from '@/features/ResourceManager/store';
import {
  getResourceQueryVisibility,
  getResourceSourceFilter,
  sortFileList,
} from '@/features/ResourceManager/store/selectors';
import { useFetchResources, useResourceStore } from '@/store/file/slices/resource/hooks';

import { KnowledgeBaseListProvider } from '../KnowledgeBaseListProvider';
import EmptyPlaceholder from './EmptyPlaceholder';
import FileDetailPanel from './FileDetailPanel';
import Header from './Header';
import { useResetSelectionOnQueryChange } from './hooks/useResetSelectionOnQueryChange';
import ListView from './ListView';
import MasonryView from './MasonryView';
import SearchResultsOverlay from './SearchResultsOverlay';
import { useCheckTaskStatus } from './useCheckTaskStatus';

/**
 * Explore resource items in a library
 *
 * Works with FileTree
 *
 * It's a un-reusable component for business logic only.
 * So we depend on context, not props.
 */
interface ResourceExplorerProps {
  /** Rendered between the toolbar and the list (a library's cover header). */
  hero?: ReactNode;
}

const ResourceExplorer = memo<ResourceExplorerProps>(({ hero }) => {
  // Sync store state with URL query parameters
  useResourceManagerUrlSync();

  // Get state from Resource Manager store
  const [
    libraryId,
    category,
    viewMode,
    searchQuery,
    sorter,
    sortType,
    listVisibility,
    sourceFilter,
  ] = useResourceManagerStore((s) => [
    s.libraryId,
    s.category,
    s.viewMode,
    s.searchQuery,
    s.sorter,
    s.sortType,
    s.listVisibility,
    getResourceSourceFilter(s),
  ]);

  // Get folder path for empty state check
  const { currentFolderId } = useFolderPath();

  // Build query params for SWR
  const queryParams = useMemo(
    () => ({
      // Only use category filter when NOT in a specific library
      // When viewing a library, show all items regardless of category
      category: libraryId ? undefined : category,
      // Outside a library the explorer is the drive: every uploaded file,
      // including those filed into libraries (tagged on the row), and no pages.
      filesOnly: !libraryId,
      includeContentPreview: viewMode === 'masonry',
      libraryId,
      parentId: currentFolderId || null,
      showFilesInKnowledgeBase: !libraryId,
      sortType,
      sorter,
      sourceFilter,
      // The two-mode narrowing belongs to the resource home. A concrete
      // library supplies its own visibility boundary and must not inherit the
      // user's last home filter.
      visibility: getResourceQueryVisibility(libraryId, listVisibility),
    }),
    [
      category,
      libraryId,
      currentFolderId,
      sortType,
      sorter,
      listVisibility,
      sourceFilter,
      viewMode,
    ],
  );

  // Use SWR for data fetching with automatic caching and revalidation.
  // `error` / `mutate` were previously discarded, so a failed resource fetch fell
  // through to the "create your first resource" onboarding empty (Read §1.1
  // failure-as-empty). Capture them and branch the failure before empty.
  const { isLoading, isValidating, error, mutate } = useFetchResources(queryParams);

  // Get resource data from store (updated by SWR hook)
  const { resourceList } = useResourceStore();

  // Map ResourceItem[] to FileListItem[] for compatibility
  // TODO: Eventually update all consumers to use ResourceItem directly
  const rawData = resourceList?.map((item) => ({
    ...item,
    // Ensure all FileListItem fields are present with proper types
    chunkCount: item.chunkCount ?? null,
    chunkingError: item.chunkingError ?? null,
    chunkingStatus: (item.chunkingStatus ?? null) as any,
    embeddingError: item.embeddingError ?? null,
    embeddingStatus: (item.embeddingStatus ?? null) as any,
    finishEmbedding: item.finishEmbedding ?? false,
    url: item.url ?? '',
  }));

  // Sort data using current sort settings
  const data = sortFileList(rawData, sorter, sortType, { groupFolders: Boolean(libraryId) });

  // Check task status
  useCheckTaskStatus(data);

  useResetSelectionOnQueryChange({
    category,
    currentFolderId,
    libraryId,
    searchQuery,
  });

  // Inline split-screen dock: rendered next to the list so a file click can
  // show its detail without leaving the surface.
  const detailPanelMount = useMemo(() => <FileDetailPanel />, []);

  const showEmptyStatus = !isLoading && !isValidating && data?.length === 0;

  return (
    <KnowledgeBaseListProvider>
      <Flexbox height={'100%'}>
        <Header />
        {hero}
        <Flexbox horizontal flex={1} style={{ minHeight: 0, overflow: 'hidden' }}>
          <div style={{ flex: 1, overflow: 'hidden', position: 'relative', minWidth: 0 }}>
            {/*
              AsyncBoundary gates error → empty → data. `isLoading` stays false here
              because the list/masonry views own their own skeletons (loading is a
              content swap inside them, not a full relayout), so the boundary only
              arbitrates the failed-vs-empty-vs-data precedence the call site got wrong.
            */}
            <AsyncBoundary
              data={data}
              empty={<EmptyPlaceholder />}
              error={error}
              errorVariant={'block'}
              isEmpty={showEmptyStatus}
              onRetry={() => mutate()}
            >
              {viewMode === 'list' ? (
                <ListView
                  isLoading={isLoading}
                  isValidating={isValidating}
                  queryParams={queryParams}
                />
              ) : (
                <MasonryView
                  isLoading={isLoading}
                  isValidating={isValidating}
                  queryParams={queryParams}
                />
              )}
            </AsyncBoundary>
            <SearchResultsOverlay />
          </div>
          {detailPanelMount}
        </Flexbox>
      </Flexbox>
    </KnowledgeBaseListProvider>
  );
});

ResourceExplorer.displayName = 'ResourceExplorer';

export default ResourceExplorer;