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.5 KB
Raw Blame
import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';
import type { ChatTopicStatus } from '@lobechat/types';
import type { DropdownItem } from '@lobehub/ui';
import { Icon, toast } from '@lobehub/ui';
import {
  Archive,
  ArchiveRestore,
  ExternalLink,
  Hash,
  Link2,
  LucideCopy,
  PanelTop,
  PencilLine,
  Pin,
  PinOff,
  Share,
  Trash,
  Wand2,
} from 'lucide-react';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';

import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { openRenameModal } from '@/components/RenameModal';
import { isDesktop } from '@/const/version';
import { confirmRemoveTopic } from '@/features/DeleteTopicConfirm';
import { usePrivateAgentLinkNotice } from '@/features/PrivateAgentLinkNotice';
import { openShareModal } from '@/features/ShareModal';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useAppOrigin } from '@/hooks/useAppOrigin';
import { usePermission } from '@/hooks/usePermission';
import { useChatStore } from '@/store/chat';
import { useElectronStore } from '@/store/electron';
import { useGlobalStore } from '@/store/global';

interface UseDropdownMenuProps {
  agentId?: string;
  fav?: boolean;
  onClose: () => void;
  onDelete?: (topicId: string) => void;
  status?: ChatTopicStatus | null;
  topicId: string;
  topicTitle: string;
}

export const useDropdownMenu = ({
  agentId,
  fav,
  onClose,
  onDelete,
  status,
  topicId,
  topicTitle,
}: UseDropdownMenuProps): (() => DropdownItem[]) => {
  const { t } = useTranslation(['common', 'topic', 'chat']);
  const notifyPrivateAgentLink = usePrivateAgentLinkNotice();

  const appOrigin = useAppOrigin();
  const navigate = useWorkspaceAwareNavigate();
  const activeWorkspaceSlug = useActiveWorkspaceSlug();
  const { allowed: canCreateTopic } = usePermission('create_content');
  const { allowed: canEditTopic } = usePermission('edit_own_content');

  const addTab = useElectronStore((s) => s.addTab);
  const openTopicInNewWindow = useGlobalStore((s) => s.openTopicInNewWindow);

  const [
    autoRenameTopicTitle,
    duplicateTopic,
    favoriteTopic,
    markTopicCompleted,
    removeTopic,
    unmarkTopicCompleted,
    updateTopicTitle,
  ] = useChatStore((s) => [
    s.autoRenameTopicTitle,
    s.duplicateTopic,
    s.favoriteTopic,
    s.markTopicCompleted,
    s.removeTopic,
    s.unmarkTopicCompleted,
    s.updateTopicTitle,
  ]);

  const isCompleted = status === 'completed';
  const handleOpenShareModal = useCallback(() => {
    void openShareModal({ context: { threadId: null, topicId } });
  }, [topicId]);

  return useCallback(
    () =>
      [
        {
          disabled: !canEditTopic,
          icon: <Icon icon={isCompleted ? ArchiveRestore : Archive} />,
          key: 'markCompleted',
          label: isCompleted
            ? t('actions.unmarkCompleted', { ns: 'topic' })
            : t('actions.markCompleted', { ns: 'topic' }),
          onClick: () => {
            if (isCompleted) {
              unmarkTopicCompleted(topicId);
            } else {
              markTopicCompleted(topicId);
            }
          },
          sfSymbol: isCompleted ? 'tray.and.arrow.up' : 'archivebox',
        },
        {
          type: 'divider' as const,
        },
        {
          disabled: !canEditTopic,
          icon: <Icon icon={fav ? PinOff : Pin} />,
          key: 'favorite',
          label: fav ? t('actions.unpin', { ns: 'topic' }) : t('actions.pin', { ns: 'topic' }),
          onClick: () => {
            favoriteTopic(topicId, !fav);
          },
          sfSymbol: fav ? 'pin.slash' : 'pin',
        },
        {
          type: 'divider' as const,
        },
        {
          disabled: !canEditTopic,
          icon: <Icon icon={Wand2} />,
          key: 'autoRename',
          label: t('actions.autoRename', { ns: 'topic' }),
          onClick: () => {
            autoRenameTopicTitle(topicId);
          },
          sfSymbol: 'wand.and.stars',
        },
        {
          disabled: !canEditTopic,
          icon: <Icon icon={PencilLine} />,
          key: 'rename',
          label: t('rename'),
          onClick: () => {
            openRenameModal({
              defaultValue: topicTitle,
              description: t('renameModal.description', { ns: 'topic' }),
              onSave: async (newTitle) => {
                await updateTopicTitle(topicId, newTitle);
              },
              title: t('renameModal.title', { ns: 'topic' }),
            });
          },
          sfSymbol: 'pencil',
        },
        {
          type: 'divider' as const,
        },
        ...(isDesktop
          ? [
              {
                disabled: !agentId,
                icon: <Icon icon={PanelTop} />,
                key: 'openInNewTab',
                label: t('actions.openInNewTab', { ns: 'topic' }),
                onClick: () => {
                  if (!agentId) return;
                  const url = buildWorkspaceAwarePath(
                    AGENT_CHAT_TOPIC_URL(agentId, topicId),
                    activeWorkspaceSlug,
                  );
                  addTab(url);
                  navigate(url, { escape: true });
                  onClose();
                },
              },
              {
                disabled: !agentId,
                icon: <Icon icon={ExternalLink} />,
                key: 'openInNewWindow',
                label: t('actions.openInNewWindow', { ns: 'topic' }),
                onClick: () => {
                  if (!agentId) return;
                  openTopicInNewWindow(agentId, topicId);
                  onClose();
                },
              },
              {
                type: 'divider' as const,
              },
            ]
          : []),
        {
          icon: <Icon icon={Hash} />,
          key: 'copySessionId',
          label: t('actions.copySessionId', { ns: 'topic' }),
          onClick: () => {
            void navigator.clipboard.writeText(topicId);
            toast.success(t('actions.copySessionIdSuccess', { ns: 'topic' }));
          },
        },
        {
          disabled: !agentId,
          icon: <Icon icon={Link2} />,
          key: 'copyLink',
          label: t('actions.copyLink', { ns: 'topic' }),
          onClick: async () => {
            if (!agentId) return;
            const url = `${appOrigin}${buildWorkspaceAwarePath(
              AGENT_CHAT_TOPIC_URL(agentId, topicId),
              activeWorkspaceSlug,
            )}`;
            void navigator.clipboard.writeText(url);
            // A private agent's topic link opens for nobody else in the workspace.
            if (!(await notifyPrivateAgentLink(agentId)))
              toast.success(t('actions.copyLinkSuccess', { ns: 'topic' }));
          },
        },
        {
          disabled: !canCreateTopic,
          icon: <Icon icon={LucideCopy} />,
          key: 'duplicate',
          label: t('actions.duplicate', { ns: 'topic' }),
          onClick: () => {
            duplicateTopic(topicId);
          },
        },
        {
          type: 'divider' as const,
        },
        {
          disabled: !canEditTopic,
          icon: <Icon icon={Share} />,
          key: 'share',
          label: t('shareModal.title', { ns: 'chat' }),
          onClick: handleOpenShareModal,
          sfSymbol: 'square.and.arrow.up',
        },
        {
          type: 'divider' as const,
        },
        {
          danger: true,
          disabled: !canEditTopic,
          icon: <Icon icon={Trash} />,
          key: 'delete',
          label: t('delete'),
          onClick: () => {
            void confirmRemoveTopic({
              onConfirm: async (removeFiles) => {
                await removeTopic(topicId, removeFiles);
                onDelete?.(topicId);
                onClose();
              },
              topicIds: [topicId],
            });
          },
          sfSymbol: 'trash',
        },
      ].filter(Boolean) as DropdownItem[],
    [
      addTab,
      activeWorkspaceSlug,
      agentId,
      appOrigin,
      autoRenameTopicTitle,
      canCreateTopic,
      canEditTopic,
      duplicateTopic,
      favoriteTopic,
      fav,
      handleOpenShareModal,
      isCompleted,
      markTopicCompleted,
      navigate,
      notifyPrivateAgentLink,
      onClose,
      onDelete,
      openTopicInNewWindow,
      removeTopic,
      t,
      topicId,
      topicTitle,
      unmarkTopicCompleted,
      updateTopicTitle,
    ],
  );
};