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.5 KB
Raw Blame
'use client';

import type { BuiltinRenderProps } from '@lobechat/types';
import { ActionIcon, Flexbox, Icon, Text } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import { CircleCheckIcon, CircleXIcon, DownloadIcon } from 'lucide-react';
import { memo, useCallback } from 'react';

import type { ExportFileState } from '../../../types';

const styles = stylex.create({
  container: { overflow: 'hidden', paddingInlineStart: '8px', paddingInlineEnd: '0' },
});

interface ExportFileParams {
  path: string;
}

const ExportFile = memo<BuiltinRenderProps<ExportFileParams, ExportFileState>>(
  ({ args, pluginState }) => {
    const isSuccess = pluginState?.success;

    const handleDownload = useCallback(async () => {
      if (!pluginState?.downloadUrl || !pluginState?.filename) return;

      try {
        // Fetch the file content to bypass cross-origin download restrictions
        const response = await fetch(pluginState.downloadUrl);
        const blob = await response.blob();

        // Create a blob URL and trigger download
        const blobUrl = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = blobUrl;
        link.download = pluginState.filename;
        document.body.append(link);
        link.click();
        link.remove();

        // Clean up the blob URL
        URL.revokeObjectURL(blobUrl);
      } catch {
        // Fallback: open in new tab if fetch fails
        window.open(pluginState.downloadUrl, '_blank');
      }
    }, [pluginState?.downloadUrl, pluginState?.filename]);

    return (
      <Flexbox className={stylex.props(styles.container).className} gap={8}>
        <Flexbox horizontal align={'center'} gap={8}>
          {pluginState === undefined ? null : isSuccess ? (
            <Icon color={cssVar.colorSuccess} icon={CircleCheckIcon} size={12} />
          ) : (
            <Icon color={cssVar.colorError} icon={CircleXIcon} size={12} />
          )}
          <Text code as={'span'} fontSize={12}>
            {isSuccess
              ? `Exported: ${pluginState?.filename || args.path}`
              : `Failed to export ${args.path}`}
          </Text>
          {isSuccess && pluginState?.downloadUrl && (
            <ActionIcon
              icon={DownloadIcon}
              size={'small'}
              title="Download"
              onClick={handleDownload}
            />
          )}
        </Flexbox>
      </Flexbox>
    );
  },
);

ExportFile.displayName = 'ExportFile';

export default ExportFile;