Skip to content

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

8.9 KB
Raw Blame
import * as React from "react";
import { useVirtualizer } from "@tanstack/react-virtual";

import { cn } from "@app/components/v3/utils";

import { rowLinkContainerClassName } from "../RowLink";
import { Skeleton } from "../Skeleton";

const Table = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<"table"> & { containerClassName?: string; hasAttachedFooter?: boolean }
>(({ className, containerClassName, hasAttachedFooter = false, ...props }, ref) => {
  return (
    <div
      ref={ref}
      data-slot="table-container"
      className={cn(
        "relative thin-scrollbar w-full min-w-0 overflow-x-auto rounded-md border border-border bg-container",
        hasAttachedFooter && "rounded-b-none",
        containerClassName
      )}
    >
      <table
        data-slot="table"
        className={cn("w-max min-w-full caption-bottom text-start text-sm", className)}
        {...props}
      />
    </div>
  );
});

Table.displayName = "Table";

function TableAttachedFooter({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="table-attached-footer"
      className={cn(
        "flex min-h-10 items-center justify-center overflow-hidden rounded-b-md border border-t-0 border-border bg-container",
        className
      )}
      {...props}
    />
  );
}

function TableHeader({
  className,
  sticky = false,
  ...props
}: React.ComponentProps<"thead"> & { sticky?: boolean }) {
  return (
    <thead
      data-slot="table-header"
      className={cn(
        "text-sm [&_tr]:border-b [&_tr]:hover:bg-transparent",
        // collapsed borders are painted by the table and scroll away under a sticky header,
        // so the header draws its bottom border as an inset shadow that moves with it
        sticky &&
          "sticky top-0 z-10 bg-container [&_th]:border-b-0 [&_th]:shadow-[inset_0_-1px_0_var(--color-border)] [&_tr]:border-b-0",
        className
      )}
      {...props}
    />
  );
}

const TableBody = React.forwardRef<HTMLTableSectionElement, React.ComponentProps<"tbody">>(
  ({ className, ...props }, ref) => {
    return (
      <tbody
        ref={ref}
        data-slot="table-body"
        className={cn(
          "[&>tr:last-of-type]:border-b-0 [&>tr:last-of-type>td]:border-b-0",
          className
        )}
        {...props}
      />
    );
  }
);

TableBody.displayName = "TableBody";

type TableVirtualRowProps = {
  ref: (element: HTMLTableRowElement | null) => void;
  "data-index": number;
  "aria-rowindex": number;
};

function TableVirtualBody({
  className,
  count,
  estimateRowHeight = 41,
  children
}: {
  className?: string;
  count: number;
  estimateRowHeight?: number;
  children: (index: number, rowProps: TableVirtualRowProps) => React.ReactNode;
}) {
  const bodyRef = React.useRef<HTMLTableSectionElement>(null);
  const virtualizer = useVirtualizer({
    count,
    getScrollElement: () => bodyRef.current?.closest("[data-slot=table-container]") ?? null,
    estimateSize: () => estimateRowHeight,
    overscan: 10
  });
  const [headerRowCount, setHeaderRowCount] = React.useState(1);
  React.useLayoutEffect(() => {
    const table = bodyRef.current?.closest("table");
    if (!table) return;
    const headerRows = Array.from(table.tHead?.rows ?? []);
    headerRows.forEach((row, index) => row.setAttribute("aria-rowindex", String(index + 1)));
    table.setAttribute("aria-rowcount", String(headerRows.length + count));
    setHeaderRowCount(headerRows.length);
  }, [count]);
  const virtualRows = virtualizer.getVirtualItems();
  const padTop = virtualRows[0]?.start ?? 0;
  const padBottom = virtualRows.length
    ? virtualizer.getTotalSize() - virtualRows[virtualRows.length - 1].end
    : 0;

  return (
    <TableBody ref={bodyRef} className={className}>
      {padTop > 0 && <tr aria-hidden style={{ height: padTop }} />}
      {virtualRows.map((virtualRow) =>
        children(virtualRow.index, {
          ref: virtualizer.measureElement,
          "data-index": virtualRow.index,
          "aria-rowindex": headerRowCount + virtualRow.index + 1
        })
      )}
      {padBottom > 0 && <tr aria-hidden style={{ height: padBottom }} />}
    </TableBody>
  );
}

function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
  return (
    <tfoot
      data-slot="table-footer"
      className={cn(
        "border-t border-border bg-foreground/[0.03] font-medium",
        "[&>tr:last-of-type]:border-b-0 [&>tr:last-of-type>td]:border-b-0",
        className
      )}
      {...props}
    />
  );
}

const TableRow = React.forwardRef<
  HTMLTableRowElement,
  React.ComponentProps<"tr"> & { linked?: boolean }
>(({ className, linked, ...props }, ref) => {
  return (
    <tr
      ref={ref}
      data-slot="table-row"
      className={cn(
        "border-b border-border transition-colors duration-75 hover:bg-container-hover data-[state=selected]:bg-container-hover",
        props.onClick && "cursor-pointer select-none",
        linked && rowLinkContainerClassName,
        className
      )}
      {...props}
    />
  );
});

TableRow.displayName = "TableRow";

type TableSortDirection = "ascending" | "descending" | "none";
type TableColumnVariant = "default" | "action";

const nextTableSortDirection: Record<TableSortDirection, TableSortDirection> = {
  none: "ascending",
  ascending: "descending",
  descending: "none"
};

function TableHead({
  className,
  children,
  isTruncatable,
  variant = "default",
  "aria-sort": ariaSort,
  onSortChange,
  sortDirection = "none",
  ...props
}: React.ComponentProps<"th"> & {
  isTruncatable?: boolean;
  onSortChange?: (direction: TableSortDirection) => void;
  sortDirection?: TableSortDirection;
  variant?: TableColumnVariant;
}) {
  return (
    <th
      data-slot="table-head"
      data-variant={variant}
      className={cn(
        "h-[30px] border-x-0 border-t-0 border-b border-border px-3 text-left align-middle text-xs whitespace-nowrap text-accent select-none [&:has([role=checkbox])]:pr-0",
        "has-[>svg]:cursor-pointer [&>svg]:ml-1 [&>svg]:inline-block [&>svg:not([class*='size-'])]:size-4",
        onSortChange && "p-0",
        isTruncatable && "truncate",
        variant === "action" && "min-w-12 pr-1.5 text-end",
        className
      )}
      aria-sort={onSortChange ? sortDirection : ariaSort}
      {...props}
    >
      {onSortChange ? (
        <button
          type="button"
          data-slot="table-head-sort-trigger"
          className="flex h-[30px] w-full cursor-pointer items-center gap-1 px-3 text-left text-xs text-accent outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset [&>svg]:shrink-0 [&>svg:not([class*='size-'])]:size-4"
          onClick={() => onSortChange(nextTableSortDirection[sortDirection])}
        >
          {children}
        </button>
      ) : (
        children
      )}
    </th>
  );
}

function TableHeadLabel({
  className,
  children,
  trailing,
  ...props
}: React.ComponentProps<"div"> & { trailing?: React.ReactNode }) {
  return (
    <div
      data-slot="table-head-label"
      className={cn("flex min-w-0 items-center gap-1", className)}
      {...props}
    >
      <span className="min-w-0 truncate">{children}</span>
      {trailing}
    </div>
  );
}

function TableCell({
  className,
  isTruncatable,
  isWrappable,
  isTopAligned,
  variant = "default",
  ...props
}: React.ComponentProps<"td"> & {
  isTruncatable?: boolean;
  isWrappable?: boolean;
  isTopAligned?: boolean;
  variant?: TableColumnVariant;
}) {
  return (
    <td
      data-slot="table-cell"
      data-variant={variant}
      className={cn(
        "h-10 border-b border-border px-3 py-1.5 align-middle whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>svg]:size-4",
        isTruncatable && "max-w-0 truncate",
        isWrappable && "max-w-md wrap-anywhere whitespace-normal",
        isTopAligned && "align-top",
        variant === "action" && "min-w-12 pr-1.5 text-end",
        className
      )}
      {...props}
    />
  );
}

function TableSkeletonRows({ columns, rows = 3 }: { columns: number; rows?: number }) {
  return (
    <>
      {Array.from({ length: rows }, (_, row) => (
        <TableRow key={row} data-slot="table-skeleton-row">
          {Array.from({ length: columns }, (__, column) => (
            <TableCell key={column}>
              <Skeleton className="h-4 w-full" />
            </TableCell>
          ))}
        </TableRow>
      ))}
    </>
  );
}

function TableCaption({ className, ...props }: React.ComponentProps<"caption">) {
  return (
    <caption
      data-slot="table-caption"
      className={cn(
        "border-t border-border bg-foreground/[0.03] px-3 py-2 text-left text-xs text-muted",
        className
      )}
      {...props}
    />
  );
}

export {
  Table,
  TableAttachedFooter,
  TableBody,
  TableCaption,
  TableCell,
  type TableColumnVariant,
  TableFooter,
  TableHead,
  TableHeader,
  TableHeadLabel,
  TableRow,
  TableSkeletonRows,
  type TableSortDirection,
  TableVirtualBody,
  type TableVirtualRowProps
};