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.

2.6 KB
Raw Blame
'use client';

import { ActionIcon, Button, confirmModal, Icon, toast, Tooltip } from '@lobehub/ui';
import { Trash2Icon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useSearchParams } from 'react-router';

import { useUserMemoryStore } from '@/store/userMemory';
import { useHeaderActionSize } from '@/styles/density';

export const MEMORY_DETAIL_QUERY_KEYS = [
  'activityId',
  'contextId',
  'experienceId',
  'identityId',
  'preferenceId',
] as const;

interface Props {
  iconOnly?: boolean;
}

const PurgeButton = memo<Props>(({ iconOnly }) => {
  const { t } = useTranslation(['common', 'memory']);
  const translate = t as (key: string, options?: Record<string, unknown>) => string;
  const purgeAllMemories = useUserMemoryStore((s) => s.purgeAllMemories);
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParams] = useSearchParams();
  const headerActionSize = useHeaderActionSize();
  const headerActionSmallSize = useHeaderActionSize(true);

  const handleClick = () => {
    confirmModal({
      cancelText: translate('cancel', { ns: 'common' }),
      content: translate('purge.confirm', { ns: 'memory' }),
      okButtonProps: { danger: true },
      okText: translate('confirm', { ns: 'common' }),
      onOk: async () => {
        try {
          setLoading(true);
          await purgeAllMemories();
          const nextSearchParams = new URLSearchParams(searchParams);

          for (const key of MEMORY_DETAIL_QUERY_KEYS) {
            nextSearchParams.delete(key);
          }

          setSearchParams(nextSearchParams, { replace: true });
          toast.success(translate('purge.success', { ns: 'memory' }));
        } catch {
          toast.error(translate('purge.error', { ns: 'memory' }));
          throw new Error('Failed to purge memories');
        } finally {
          setLoading(false);
        }
      },
      title: translate('purge.title', { ns: 'memory' }),
    });
  };

  if (iconOnly) {
    return (
      <Tooltip title={translate('purge.action', { ns: 'memory' })}>
        <ActionIcon
          danger
          icon={Trash2Icon}
          loading={loading}
          size={headerActionSmallSize}
          tooltipProps={{ placement: 'bottom' }}
          onClick={handleClick}
        />
      </Tooltip>
    );
  }

  return (
    <Button
      danger
      icon={<Icon icon={Trash2Icon} size={headerActionSize} />}
      loading={loading}
      size={'small'}
      style={{ maxWidth: 300 }}
      type={'primary'}
      onClick={handleClick}
    >
      {translate('purge.action', { ns: 'memory' })}
    </Button>
  );
});

export default PurgeButton;