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.

4.8 KB
Raw Blame
'use client';

import { createStaticStyles, cx, Flexbox, Popover, Text } from '@lobehub/ui';
import type { AiModelForSelect } from 'model-bank';
import numeral from 'numeral';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';

import { ModelIcon } from '@/components/LobeIcons';
import NewModelBadge from '@/components/ModelSelect/NewModelBadge';
import { useIsDark } from '@/hooks/useIsDark';

const POPOVER_MAX_WIDTH = 320;

const styles = createStaticStyles(({ css, cssVar }) => ({
  descriptionText: css`
    color: ${cssVar.colorTextSecondary};
  `,
  descriptionText_dark: css`
    color: ${cssVar.colorText};
  `,
  priceText: css`
    font-weight: 500;
    color: ${cssVar.colorTextTertiary};
    word-break: keep-all;
    white-space: nowrap;
  `,
  priceText_dark: css`
    font-weight: 500;
    color: ${cssVar.colorTextLightSolid};
  `,
}));

interface GenerationPrice {
  /** USD amount with at least two decimals, without the `$` (the locale copy carries it). */
  amount: string;
  key: `GenerationModelItem.creditsPer${'Image' | 'Video'}${'Approximate' | 'Exact'}`;
}

/**
 * Pick which USD price a model shows: the exact one when the provider quotes it, otherwise the
 * approximate one. Image and video, on every deployment, share the same localized copy.
 */
export const resolveGenerationPrice = ({
  approxUsd,
  exactUsd,
  isVideo,
}: {
  approxUsd?: number;
  exactUsd?: number;
  isVideo: boolean;
}): GenerationPrice | undefined => {
  const kind = isVideo ? 'Video' : 'Image';

  if (typeof exactUsd === 'number') {
    return {
      amount: numeral(exactUsd).format('0,0.00[000]'),
      key: `GenerationModelItem.creditsPer${kind}Exact`,
    };
  }
  if (typeof approxUsd === 'number') {
    return {
      amount: numeral(approxUsd).format('0,0.00[000]'),
      key: `GenerationModelItem.creditsPer${kind}Approximate`,
    };
  }

  return undefined;
};

export interface GenerationModelItemProps extends AiModelForSelect {
  /**
   * Which USD price fields to use: image uses approximatePricePerImage / pricePerImage; video uses approximatePricePerVideo / pricePerVideo.
   * @default 'image'
   */
  priceKind?: 'image' | 'video';
  /**
   * @deprecated The price is shown the same way for every provider; kept so callers still type-check.
   */
  providerId?: string;
  /**
   * Whether to show new model badge
   * @default true
   */
  showBadge?: boolean;
  /**
   * Whether to show popover on hover
   * @default true
   */
  showPopover?: boolean;
  /**
   * Whether to show price in popover (e.g. true for image, false for video)
   * @default false
   */
  showPrice?: boolean;
}

const GenerationModelItem = memo<GenerationModelItemProps>(
  ({
    approximatePricePerImage,
    approximatePricePerVideo,
    description,
    pricePerImage,
    pricePerVideo,
    showPopover = true,
    showBadge = true,
    showPrice = false,
    priceKind = 'image',
    ...model
  }) => {
    const isDarkMode = useIsDark();
    const { t } = useTranslation('components');

    const priceLabel = useMemo(() => {
      if (!showPrice) return undefined;

      const isVideo = priceKind === 'video';
      const price = resolveGenerationPrice({
        approxUsd: isVideo ? approximatePricePerVideo : approximatePricePerImage,
        exactUsd: isVideo ? pricePerVideo : pricePerImage,
        isVideo,
      });

      return price ? t(price.key, { amount: price.amount }) : undefined;
    }, [
      showPrice,
      approximatePricePerImage,
      approximatePricePerVideo,
      pricePerImage,
      pricePerVideo,
      priceKind,
      t,
    ]);

    const popoverContent = useMemo(() => {
      if (!description && !priceLabel) return null;

      return (
        <Flexbox gap={8} style={{ maxWidth: POPOVER_MAX_WIDTH }}>
          {description && (
            <Text className={cx(styles.descriptionText, isDarkMode && styles.descriptionText_dark)}>
              {description}
            </Text>
          )}
          {priceLabel && (
            <Text className={cx(styles.priceText, isDarkMode && styles.priceText_dark)}>
              {priceLabel}
            </Text>
          )}
        </Flexbox>
      );
    }, [description, priceLabel, isDarkMode]);

    const content = (
      <Flexbox horizontal align={'center'} gap={8} style={{ overflow: 'hidden' }}>
        <ModelIcon model={model.id} size={20} />
        <Text ellipsis title={model.displayName || model.id}>
          {model.displayName || model.id}
        </Text>
        {showBadge && <NewModelBadge releasedAt={model.releasedAt} />}
      </Flexbox>
    );

    if (!showPopover || !popoverContent) return content;

    return (
      <Popover content={popoverContent} placement="rightTop">
        {content}
      </Popover>
    );
  },
);

GenerationModelItem.displayName = 'GenerationModelItem';

export default GenerationModelItem;