Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

4.9 KB
Raw Blame
/* eslint-disable no-nested-ternary, @typescript-eslint/no-use-before-define */
import React, { useMemo } from "react";
import { Lock, AlertCircle, ExternalLink, Sparkle } from "@langfuse/icons";
import { Button, type ButtonProps } from "@/src/components/ui/button";
import { HoverCard } from "@/src/components/design-system/HoverCard/HoverCard";
import Link from "next/link";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";

export type ActionButtonProps = Pick<
  ButtonProps,
  "disabled" | "onClick" | "size" | "title" | "type" | "variant"
> & {
  icon?: React.ReactNode;
  loading?: boolean;
  hasAccess?: boolean;
  hasEntitlement?: boolean;
  usageLimit?: {
    current: number | undefined;
    max: number;
  };
  children: React.ReactNode;
  href?: string;
} & (
    | {
        trackingEventName?: never;
        trackingProps?: never;
      }
    | {
        trackingEventName: Parameters<
          ReturnType<typeof usePostHogClientCapture>
        >[0];
        trackingProps?: Record<string, unknown>;
      }
  );

export const ActionButton = React.forwardRef<
  HTMLButtonElement,
  ActionButtonProps
>(function ActionButton(
  {
    loading = false,
    hasAccess = true,
    hasEntitlement = true,
    usageLimit,
    disabled = false,
    children,
    icon,
    href,
    trackingEventName,
    trackingProps,
    ...buttonProps
  },
  ref,
) {
  const capture = usePostHogClientCapture();

  const hasReachedLimit =
    usageLimit?.current !== undefined && usageLimit.current >= usageLimit.max;

  const isDisabled =
    disabled || !hasAccess || !hasEntitlement || hasReachedLimit;

  const usageLimitCurrent = usageLimit?.current ?? 0;
  const usageLimitMax = usageLimit?.max ?? 0;

  const disabledReason = useMemo(() => {
    if (!hasAccess) {
      return "You do not have access to this resource, please ask your admin to grant you access.";
    }
    if (!hasEntitlement) {
      return "This feature is not available in your current plan.";
    }
    if (hasReachedLimit) {
      return `You have reached the limit (${usageLimitCurrent}/${usageLimitMax}) for this resource at your current plan. Upgrade your plan to increase the limit.`;
    }

    return null;
  }, [
    hasAccess,
    hasEntitlement,
    hasReachedLimit,
    usageLimitCurrent,
    usageLimitMax,
  ]);

  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    if (trackingEventName) {
      capture(trackingEventName, trackingProps ?? null);
    }

    buttonProps.onClick?.(event);
  };

  const btnContent = (
    <ButtonContent
      ref={ref}
      icon={icon}
      isDisabled={isDisabled}
      loading={loading}
      hasAccess={hasAccess}
      hasEntitlement={hasEntitlement}
      hasReachedLimit={hasReachedLimit}
      href={href}
      {...buttonProps}
      onClick={handleClick}
    >
      {children}
    </ButtonContent>
  );

  if (isDisabled && disabledReason) {
    return (
      <HoverCard
        openDelay={200}
        content={<div className="w-80 p-3 text-sm">{disabledReason}</div>}
      >
        {({ getTriggerProps }) => (
          <span {...getTriggerProps()}>{btnContent}</span>
        )}
      </HoverCard>
    );
  }

  return btnContent;
});

const isExternalUrl = (url: string) => {
  return (
    url.startsWith("http://") ||
    url.startsWith("https://") ||
    url.startsWith("//")
  );
};

const ButtonContent = React.forwardRef<
  HTMLButtonElement,
  Pick<ButtonProps, "onClick" | "size" | "title" | "type" | "variant"> & {
    icon?: React.ReactNode;
    isDisabled: boolean;
    loading: boolean;
    hasAccess: boolean;
    hasEntitlement: boolean;
    hasReachedLimit: boolean;
    children: React.ReactNode;
    href?: string;
  }
>(function ButtonContent(
  {
    icon,
    isDisabled,
    loading,
    hasAccess,
    hasEntitlement,
    hasReachedLimit,
    children,
    href,
    ...buttonProps
  },
  ref,
) {
  const renderLink = href && !isDisabled;
  const isExternal = href && isExternalUrl(href);

  const content = (
    <>
      {!hasAccess ? (
        <Lock size="base" __rawClassName="mr-1" />
      ) : !hasEntitlement ? (
        <AlertCircle size="base" __rawClassName="mr-1" />
      ) : hasReachedLimit ? (
        <Sparkle size="base" __rawClassName="mr-1" />
      ) : icon ? (
        <div className="mr-1">{icon}</div>
      ) : null}
      {children}
      {renderLink && isExternal ? (
        <ExternalLink
          size="sm"
          aria-hidden
          __rawClassName="ml-1 -translate-y-px"
        />
      ) : null}
    </>
  );

  return (
    <Button
      ref={ref}
      disabled={isDisabled}
      loading={loading}
      {...buttonProps}
      asChild={renderLink ? true : undefined}
    >
      {renderLink ? (
        <Link
          href={href}
          target={isExternal ? "_blank" : undefined}
          rel={isExternal ? "noopener noreferrer" : undefined}
        >
          {content}
        </Link>
      ) : (
        content
      )}
    </Button>
  );
});