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

import { Button, Center, Flexbox, Icon, Text } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import { RotateCwIcon, TriangleAlertIcon } from 'lucide-react';
import { memo, type ReactNode, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { normalizeAsyncError } from '@/libs/swr/normalizeError';

/**
 * The error counterpart to the loading family (`Spin`,
 * `SkeletonLoading`, …). One reusable component, several `variant`s so different
 * surfaces express failure differently without each re-implementing the
 * icon + reason + retry plumbing. Pick the variant by where the failure lives;
 * the judgment (status β†’ copy, retryable β†’ show/hide Retry) stays here.
 *
 * - `page`   β€” full detail page / whole surface: centered hero + Reload.
 * - `block`  β€” a card / settings tab / widget: bordered block + Reload.
 * - `inline` β€” a list row / small slot: single line + retry link.
 * - `metric` β€” a stat / aggregate slot: a **failed** marker where a number
 *              would sit, so an errored fetch never reads as a confident `$0`.
 */
export type AsyncErrorVariant = 'page' | 'block' | 'inline' | 'metric';

export interface AsyncErrorProps {
  /**
   * Custom action rendered in the retry button's slot β€” for terminal errors
   * where retrying can never succeed but the user still needs a way out
   * (e.g. a Back button on a 403).
   */
  action?: ReactNode;
  /**
   * `inline` only: where the line sits. Centered by default, for a slot that
   * stands alone (a load-more footer); `start` when it replaces content that
   * reads left-aligned, such as a result card in a conversation.
   */
  align?: 'center' | 'start';
  /** Override the auto-derived description (status-based copy otherwise). */
  description?: ReactNode;
  /**
   * Raw technical detail (a stack, a response body). Folded behind a
   * "Show details" toggle so the failure stays one readable line, but the
   * evidence is still reachable without leaving the surface.
   */
  details?: ReactNode;
  /** The thrown error; normalized for status-specific copy + retryable gating. */
  error?: unknown;
  /** Retry the same request (SWR `mutate` / query refetch). Hidden if absent. */
  onRetry?: () => void;
  /** Whether an explicit Retry action is currently in flight. */
  retrying?: boolean;
  /** Override the default title copy. */
  title?: ReactNode;
  variant?: AsyncErrorVariant;
}

const styles = stylex.create({
  block: {
    width: '100%',
    minHeight: '180px',
    padding: '32px',
    borderWidth: '1px',
    borderStyle: 'solid',
    borderColor: cssVar.colorBorderSecondary,
    borderRadius: cssVar.borderRadiusLG,
    backgroundColor: cssVar.colorBgContainer,
    backgroundImage: 'none',
  },
  details: {
    overflow: 'auto',
    maxHeight: 160,
    margin: 0,
    fontFamily: cssVar.fontFamilyCode,
    fontSize: 12,
    color: cssVar.colorTextTertiary,
    wordBreak: 'break-word',
    whiteSpace: 'pre-wrap',
  },
  icon: { color: cssVar.colorTextTertiary },
  inline: { paddingBlock: '8px' },
  inlineIcon: { flex: 'none', marginBlockStart: 3, color: cssVar.colorTextTertiary },
  message: { flexBasis: 'auto', flexGrow: 0, flexShrink: 1, minWidth: 0 },
  metric: { color: cssVar.colorTextQuaternary },
  page: { flex: '1', width: '100%', minHeight: '320px', padding: '48px' },
});

const AsyncError = memo<AsyncErrorProps>(
  ({
    align = 'center',
    variant = 'block',
    error,
    onRetry,
    retrying = false,
    title,
    description,
    details,
    action,
  }) => {
    const { t } = useTranslation('error');
    const { status, retryable } = normalizeAsyncError(error);
    const [detailsOpen, setDetailsOpen] = useState(false);
    const hasDetails = details !== undefined && details !== null && details !== '';

    // Status-specific copy when we recovered a status, else the generic reason.
    const reason =
      description ??
      (status ? t(`response.${status}` as any, t('asyncState.desc')) : t('asyncState.desc'));
    const heading = title ?? t('asyncState.title');
    const showRetry = !!onRetry && retryable;

    // ─── metric: a failed marker where a number would render (never a fake $0) ───
    if (variant === 'metric') {
      return (
        <Flexbox
          horizontal
          align={'center'}
          className={stylex.props(styles.metric).className}
          gap={6}
        >
          <Icon icon={TriangleAlertIcon} size={14} />
          <Text color={cssVar.colorTextQuaternary} fontSize={13}>
            {t('asyncState.metricLabel')}
          </Text>
          {showRetry && (
            <Button
              disabled={retrying}
              loading={retrying}
              size={'small'}
              type={'text'}
              onClick={onRetry}
            >
              {t('error.retry')}
            </Button>
          )}
        </Flexbox>
      );
    }

    // ─── inline: single-line row failure with a retry link ───
    if (variant === 'inline') {
      return (
        <Flexbox className={stylex.props(styles.inline).className} gap={4}>
          <Flexbox
            horizontal
            align={'center'}
            gap={8}
            justify={align === 'start' ? 'flex-start' : 'center'}
            wrap={'wrap'}
          >
            {/* Icon and copy stay together; only the copy wraps in a narrow slot. */}
            <Flexbox
              horizontal
              align={'flex-start'}
              className={stylex.props(styles.message).className}
              gap={8}
            >
              <Icon
                className={stylex.props(styles.inlineIcon).className}
                icon={TriangleAlertIcon}
                size={14}
              />
              <Text color={cssVar.colorTextSecondary} fontSize={13}>
                {heading}
                {description && (
                  <Text as={'span'} color={cssVar.colorTextTertiary} fontSize={13}>
                    {' '}
                    {description}
                  </Text>
                )}
              </Text>
            </Flexbox>
            {action ??
              (showRetry && (
                <Button
                  disabled={retrying}
                  loading={retrying}
                  size={'small'}
                  type={'text'}
                  onClick={onRetry}
                >
                  {t('error.retry')}
                </Button>
              ))}
            {hasDetails && (
              <Button
                aria-expanded={detailsOpen}
                size={'small'}
                type={'text'}
                onClick={() => setDetailsOpen((value) => !value)}
              >
                {detailsOpen ? t('asyncState.hideDetails') : t('asyncState.showDetails')}
              </Button>
            )}
          </Flexbox>
          {hasDetails && detailsOpen && (
            <pre className={stylex.props(styles.details).className}>{details}</pre>
          )}
        </Flexbox>
      );
    }

    // ─── page / block: centered hero, sized by variant ───
    return (
      <Center
        className={stylex.props(variant === 'page' ? styles.page : styles.block).className}
        gap={12}
      >
        <Icon
          className={stylex.props(styles.icon).className}
          icon={TriangleAlertIcon}
          size={variant === 'page' ? 32 : 24}
        />
        <Flexbox align={'center'} gap={4}>
          <Text fontSize={variant === 'page' ? 16 : 15} weight={600}>
            {heading}
          </Text>
          <Text
            align={'center'}
            color={cssVar.colorTextTertiary}
            fontSize={13}
            style={{ maxWidth: 360 }}
          >
            {reason}
          </Text>
        </Flexbox>
        {action ??
          (showRetry && (
            <Button
              disabled={retrying}
              icon={<Icon icon={RotateCwIcon} />}
              loading={retrying}
              size={'small'}
              onClick={onRetry}
            >
              {t('error.retry')}
            </Button>
          ))}
        {hasDetails && (
          <Flexbox align={'center'} gap={4} width={'100%'}>
            <Button
              aria-expanded={detailsOpen}
              size={'small'}
              type={'text'}
              onClick={() => setDetailsOpen((value) => !value)}
            >
              {detailsOpen ? t('asyncState.hideDetails') : t('asyncState.showDetails')}
            </Button>
            {detailsOpen && <pre className={stylex.props(styles.details).className}>{details}</pre>}
          </Flexbox>
        )}
      </Center>
    );
  },
);

AsyncError.displayName = 'AsyncError';

export default AsyncError;