Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

5.3 KB
Raw Blame
import { ComponentPropsWithoutRef, forwardRef, useMemo, useState } from "react";
import { GlobeIcon } from "lucide-react";

import { Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
import { ProviderIcon } from "@app/components/v3/platform/ProviderIcon";
import { cn } from "@app/components/v3/utils";
import { findAnyTemplateForHostPattern } from "@app/helpers/agentVaultTemplates";

type TServiceIcon = {
  label: string;
  image?: string;
};

const labelOf = (pattern: string) => {
  const trimmed = pattern.trim();
  // A bracketed IPv6 host is full of colons, so only the one after the bracket separates the port.
  const host = trimmed.startsWith("[")
    ? trimmed.slice(0, trimmed.indexOf("]") + 1)
    : trimmed.split(":")[0];
  return host || trimmed;
};

const iconFromHostPattern = (hostPattern: string): TServiceIcon => {
  const template = findAnyTemplateForHostPattern(hostPattern);
  return { label: template?.name ?? labelOf(hostPattern), image: template?.image };
};

const iconsFromHostPatterns = (hostPatterns: string[]): TServiceIcon[] => {
  const byLabel = new Map<string, TServiceIcon>();

  hostPatterns.forEach((pattern) => {
    const icon = iconFromHostPattern(pattern);
    if (icon.label && !byLabel.has(icon.label)) byLabel.set(icon.label, icon);
  });

  return [...byLabel.values()];
};

const chipClassName =
  "flex size-6 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-border text-foreground/60";

// The ring paints in the table surface color, following the row hover, so each overlapping chip
// reads as its own layer instead of a dark outline.
const stackedChipClassName =
  "ring-2 ring-container transition-shadow duration-75 [tr:hover_&]:ring-container-hover";

type TServiceChipProps = ComponentPropsWithoutRef<"div"> & { icon: TServiceIcon };

const ServiceChip = forwardRef<HTMLDivElement, TServiceChipProps>(
  ({ icon, className, ...props }, ref) => {
    const [hasImageError, setHasImageError] = useState(false);

    return (
      <div ref={ref} className={cn(chipClassName, className)} {...props}>
        {icon.image && !hasImageError ? (
          <ProviderIcon
            icon={icon.image}
            alt=""
            className="size-full object-contain p-1"
            onError={() => setHasImageError(true)}
          />
        ) : (
          <GlobeIcon className="size-3.5" />
        )}
      </div>
    );
  }
);

ServiceChip.displayName = "ServiceChip";

export const ServiceIcon = ({
  hostPattern,
  className
}: {
  hostPattern: string;
  className?: string;
}) => {
  const icon = useMemo(() => iconFromHostPattern(hostPattern), [hostPattern]);
  return <ServiceChip icon={icon} className={className} />;
};

// Host patterns collapse to one chip per provider.
type Props = {
  hostPatterns: string[];
  maxVisible?: number;
  className?: string;
};

export const ServiceIconStack = ({ hostPatterns, maxVisible = 4, className }: Props) => {
  const icons = useMemo(() => iconsFromHostPatterns(hostPatterns), [hostPatterns]);

  if (icons.length === 0) return <span className="text-muted">&mdash;</span>;

  const visible = icons.slice(0, maxVisible);
  const hidden = icons.slice(maxVisible);

  return (
    // The leftmost chip has to paint on top, and flex-row-reverse cannot do it: reversing the
    // direction moves a chip visually and its paint order follows, so the right edge wins either
    // way. `isolate` confines these depths to the stack, which also traps the chips below a linked
    // row's overlay, so the stack itself is marked interactive for RowLink to lift it. `w-fit` keeps the
    // lifted area to the chips, so the rest of the cell still opens the row.
    <div
      data-row-interactive
      className={cn("isolate flex w-fit items-center -space-x-1.5", className)}
    >
      {/* A screen reader never opens the hover tooltips, so it reads the names here. First, since the
          spacing puts a negative margin on every child but the last, and the last has to stay a chip. */}
      <span className="sr-only">{icons.map((icon) => icon.label).join(", ")}</span>
      {visible.map((icon, index) => (
        <Tooltip key={icon.label}>
          <TooltipTrigger asChild>
            <ServiceChip
              icon={icon}
              aria-hidden
              className={cn(stackedChipClassName, "relative")}
              style={{ zIndex: visible.length - index }}
            />
          </TooltipTrigger>
          <TooltipContent>{icon.label}</TooltipContent>
        </Tooltip>
      ))}
      {hidden.length > 0 && (
        <Tooltip>
          <TooltipTrigger asChild>
            {/* Inside a linked row, RowLink lifts every tooltip trigger to z-10, so the overflow chip
                needs its own depth to stay under the last icon like the rest of the stack. */}
            <div
              aria-hidden
              className={cn(
                chipClassName,
                stackedChipClassName,
                "relative text-[10px] font-medium"
              )}
              style={{ zIndex: 0 }}
            >
              +{hidden.length}
            </div>
          </TooltipTrigger>
          <TooltipContent>
            <div className="flex flex-col">
              {hidden.map((icon) => (
                <span key={icon.label}>{icon.label}</span>
              ))}
            </div>
          </TooltipContent>
        </Tooltip>
      )}
    </div>
  );
};