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.

8.8 KB
Raw Blame
import { type DropdownItem } from '@lobehub/ui';
import { confirmModal, DropdownMenu, Icon, toast, Tooltip } from '@lobehub/ui';
import {
  BookMinusIcon,
  BookPlusIcon,
  CircleEllipsisIcon,
  FileBoxIcon,
  Trash2Icon,
} from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';

import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import RepoIcon from '@/components/LibIcon';
import { useKnowledgeBaseListContext } from '@/features/ResourceManager/components/KnowledgeBaseListProvider';
import { useResourceManagerStore } from '@/features/ResourceManager/store';
import { openWorkspaceDeleteAllModal } from '@/features/WorkspaceDeleteAllModal';
import { usePermission } from '@/hooks/usePermission';
import { useKnowledgeBaseStore } from '@/store/library';

import ActionIconWithChevron from './ActionIconWithChevron';

export type MultiSelectActionType =
  | 'addToKnowledgeBase'
  | 'moveToOtherKnowledgeBase'
  | 'batchChunking'
  | 'delete'
  | 'deleteLibrary'
  | 'removeFromKnowledgeBase';

interface BatchActionsDropdownProps {
  onActionClick: (type: MultiSelectActionType) => Promise<void>;
  selectCount: number;
}

const BatchActionsDropdown = memo<BatchActionsDropdownProps>(({ selectCount, onActionClick }) => {
  const { t } = useTranslation(['components', 'common', 'file', 'knowledgeBase']);

  const libraryId = useResourceManagerStore((s) => s.libraryId);
  const [resolveSelectedResourceIds, selectAllState, listVisibility] = useResourceManagerStore(
    (s) => [s.resolveSelectedResourceIds, s.selectAllState, s.listVisibility],
  );
  const addFilesToKnowledgeBase = useKnowledgeBaseStore((s) => s.addFilesToKnowledgeBase);
  const knowledgeBases = useKnowledgeBaseListContext();
  const activeWorkspaceId = useActiveWorkspaceId();
  const { allowed: canEditResources, reason } = usePermission('edit_own_content');
  const isWorkspaceDeleteAll = !!activeWorkspaceId && selectAllState === 'all';

  const menuItems = useMemo<DropdownItem[]>(() => {
    const items: DropdownItem[] = [];

    // Show delete library option only when in a knowledge base and no files selected
    if (!canEditResources) return items;

    if (libraryId && selectCount === 0) {
      items.push({
        danger: true,
        icon: <Icon icon={Trash2Icon} />,
        key: 'deleteLibrary',
        label: t('header.actions.deleteLibrary', { ns: 'file' }),
        onClick: async () => {
          confirmModal({
            cancelText: t('cancel', { ns: 'common' }),
            content: t('library.list.confirmRemoveLibrary', { ns: 'file' }),
            okButtonProps: {
              danger: true,
            },
            okText: t('delete', { ns: 'common' }),
            onOk: async () => {
              await onActionClick('deleteLibrary');
            },
            title: t('header.actions.deleteLibrary', { ns: 'file' }),
          });
        },
      });
      return items;
    }

    // Filter out current knowledge base and constrain by visibility scope in
    // workspace mode: the top-level list is already scoped by `listVisibility`,
    // so all selected files share that scope and can only join KBs of the
    // matching visibility. Personal mode (no active workspace) skips the filter.
    const targetKbVisibility: 'private' | 'public' | null = activeWorkspaceId
      ? listVisibility === 'private'
        ? 'private'
        : 'public'
      : null;
    const availableKnowledgeBases = knowledgeBases.filter((kb) => {
      if (kb.id === libraryId) return false;
      if (targetKbVisibility) return kb.visibility === targetKbVisibility;
      return true;
    });

    const addToKnowledgeBaseSubmenu: DropdownItem[] = availableKnowledgeBases.map((kb) => ({
      disabled: selectCount === 0,
      icon: <RepoIcon />,
      key: `add-to-kb-${kb.id}`,
      label: <span style={{ marginLeft: 8 }}>{kb.name}</span>,
      onClick: async () => {
        try {
          const effectiveSelectedIds = await resolveSelectedResourceIds();
          await addFilesToKnowledgeBase(kb.id, effectiveSelectedIds);
          toast.success(
            t('addToKnowledgeBase.addSuccess', {
              count: selectAllState === 'all' ? effectiveSelectedIds.length : selectCount,
              ns: 'knowledgeBase',
            }),
          );
        } catch (e) {
          console.error(e);
          toast.error(t('addToKnowledgeBase.error', { ns: 'knowledgeBase' }));
        }
      },
    }));

    if (libraryId) {
      items.push({
        disabled: selectCount === 0,
        icon: <Icon icon={BookMinusIcon} />,
        key: 'removeFromKnowledgeBase',
        label: t('FileManager.actions.removeFromLibrary'),
        onClick: () => {
          confirmModal({
            cancelText: t('cancel', { ns: 'common' }),
            content: t('FileManager.actions.confirmRemoveFromLibrary', {
              count: selectCount,
            }),
            okButtonProps: {
              danger: true,
            },
            okText: t('FileManager.actions.removeFromLibrary'),
            onOk: async () => {
              await onActionClick('removeFromKnowledgeBase');
              toast.success(t('FileManager.actions.removeFromLibrarySuccess'));
            },
            title: t('FileManager.actions.removeFromLibrary'),
          });
        },
      });

      if (availableKnowledgeBases.length > 0) {
        items.push({
          children: addToKnowledgeBaseSubmenu as any,
          disabled: selectCount === 0,
          icon: <Icon icon={BookPlusIcon} />,
          key: 'moveToOtherKnowledgeBase',
          label: t('FileManager.actions.moveToOtherLibrary'),
        });
      }
    } else if (availableKnowledgeBases.length > 0) {
      items.push({
        children: addToKnowledgeBaseSubmenu as any,
        disabled: selectCount === 0,
        icon: <Icon icon={BookPlusIcon} />,
        key: 'addToKnowledgeBase',
        label: t('FileManager.actions.addToLibrary'),
      });
    }

    items.push(
      {
        disabled: selectCount === 0,
        icon: <Icon icon={FileBoxIcon} />,
        key: 'batchChunking',
        label: t('FileManager.actions.batchChunking'),
        onClick: async () => {
          await onActionClick('batchChunking');
        },
      },
      {
        type: 'divider',
      },
      {
        danger: true,
        disabled: selectCount === 0,
        icon: <Icon icon={Trash2Icon} />,
        key: 'delete',
        label: t(isWorkspaceDeleteAll ? 'FileManager.actions.deleteAll' : 'delete', {
          ns: isWorkspaceDeleteAll ? 'components' : 'common',
        }),
        onClick: async () => {
          const handleDelete = async () => {
            await onActionClick('delete');
            toast.success(t('FileManager.actions.deleteSuccess'));
          };

          if (isWorkspaceDeleteAll) {
            openWorkspaceDeleteAllModal({
              acknowledgeText: t('FileManager.actions.confirmDeleteAllWorkspaceAcknowledge'),
              cancelText: t('cancel', { ns: 'common' }),
              confirmText: t('FileManager.actions.deleteAll'),
              description: t('FileManager.actions.confirmDeleteAllWorkspaceFiles'),
              onConfirm: handleDelete,
              title: t('FileManager.actions.deleteAll'),
            });
            return;
          }

          confirmModal({
            cancelText: t('cancel', { ns: 'common' }),
            content: t(
              selectAllState === 'all'
                ? 'FileManager.actions.confirmDeleteAllFiles'
                : 'FileManager.actions.confirmDeleteMultiFiles',
              { count: selectCount },
            ),
            okButtonProps: {
              danger: true,
            },
            okText: t('delete', { ns: 'common' }),
            onOk: handleDelete,
            title: t('delete', { ns: 'common' }),
          });
        },
      },
    );

    return items;
  }, [
    libraryId,
    selectCount,
    selectAllState,
    onActionClick,
    addFilesToKnowledgeBase,
    resolveSelectedResourceIds,
    t,
    knowledgeBases,
    canEditResources,
    listVisibility,
    activeWorkspaceId,
    isWorkspaceDeleteAll,
  ]);

  const title = t('FileManager.actions.batchActions', 'Batch actions');

  // Without edit permission the menu has no items, so show the reason instead of a menu.
  // Keep the button as DropdownMenu's direct child: a Tooltip without a title returns its
  // children as-is and drops the trigger's onClick/ref, so the menu would never open.
  if (!canEditResources)
    return (
      <Tooltip title={reason}>
        <ActionIconWithChevron disabled icon={CircleEllipsisIcon} title={title} />
      </Tooltip>
    );

  return (
    <DropdownMenu items={menuItems} placement="bottomLeft">
      <ActionIconWithChevron icon={CircleEllipsisIcon} title={title} />
    </DropdownMenu>
  );
});

BatchActionsDropdown.displayName = 'BatchActionsDropdown';

export default BatchActionsDropdown;