Skip to content

The platform for continuously improving AI agents.

17.0 KB
Raw Blame
import { Fragment, type KeyboardEvent, useRef, useState } from "react";

import { AnimatePresence, motion, useReducedMotion } from "motion/react";

import { FileTypeIcon } from "@/components/file-type-icon";
import { Button } from "@/components/ui/button";
import { Icon } from "@/components/ui/icons";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import type { DatasetUpload } from "@/hooks/use-uploads";
import { formatBytes } from "@/lib/formatters";
import { cn } from "@/lib/utils";
import type { DelimiterEnum, EncodingEnum, UploadReadOptionsRequest } from "@/openapi";

export const IMPORT_ACCEPT =
  ".csv,.tsv,.json,.jsonl,.ndjson,.parquet,.xlsx,.gz,.pdf,.docx,.md,.txt,.png,.jpg,.jpeg,.webp";

const SEPARATORS: { value: DelimiterEnum; label: string; mark: string }[] = [
  { label: "Comma", mark: ",", value: "comma" },
  { label: "Tab", mark: "Tab", value: "tab" },
  { label: "Semicolon", mark: ";", value: "semicolon" },
  { label: "Pipe", mark: "|", value: "pipe" },
];
const ENCODINGS: { value: EncodingEnum; label: string }[] = [
  { label: "UTF-8", value: "utf-8-sig" },
  { label: "UTF-16", value: "utf-16" },
  { label: "Windows-1252", value: "windows-1252" },
];
// Radix Select needs a non-empty value for the choice that sends no sheet.
const EVERY_SHEET = "*";

/** One file's review: its first rows as the options read them, how it is read, and Continue. */
export function FileImport({
  entry,
  busy = false,
  onRemove,
  onClose,
  onRetry,
  onContinue,
  onRead,
}: {
  entry: DatasetUpload;
  busy?: boolean;
  onRemove: () => void;
  onClose?: () => void;
  onRetry: () => void;
  onContinue: () => void;
  onRead: (options: UploadReadOptionsRequest) => void;
}) {
  const reduce = useReducedMotion();
  const inspection = entry.inspection;
  const options = entry.options ?? inspection?.options ?? {};
  const delimited = /\.(csv|tsv)(\.gz)?$/i.test(entry.file.name);
  const workbook = /\.xlsx$/i.test(entry.file.name);
  const working =
    entry.status === "queued" || entry.status === "uploading" || entry.status === "counting";
  const locked = busy || working;
  const columns = inspection?.columns ?? [];
  const rows = (inspection?.preview ?? []).slice(0, 5);
  const sheets = inspection?.sheets ?? [];
  const separator = SEPARATORS.find((item) => item.value === (options.delimiter ?? "comma"));
  const encoding = ENCODINGS.find((item) => item.value === (options.encoding ?? "utf-8-sig"));
  const reading = workbook
    ? (options.sheet ?? (sheets.length > 1 ? "All sheets" : (sheets[0] ?? "Excel")))
    : `${separator?.label ?? "Comma"} · ${encoding?.label ?? "UTF-8"}`;
  const read = (patch: UploadReadOptionsRequest) => onRead({ ...options, ...patch });

  return (
    <section
      aria-busy={working}
      aria-label={`Import ${entry.file.name}`}
      className="flex min-w-0 flex-col gap-3 text-foreground"
    >
      <header className="flex min-w-0 items-start gap-2">
        <span className="inline-flex size-6 flex-none items-center justify-center rounded-md bg-info/10 text-info">
          <FileTypeIcon className="size-3.5" filename={entry.file.name} />
        </span>
        <div className="flex min-w-0 flex-1 flex-col gap-0.5 pt-1">
          <p className="truncate text-sm leading-4 font-medium">{entry.file.name}</p>
          <p className="truncate text-xs leading-4 text-muted-foreground tabular-nums">
            {[
              entry.rows != null && `${entry.rows.toLocaleString()} rows`,
              columns.length > 0 && `${columns.length.toLocaleString()} columns shown`,
              formatBytes(entry.file.size),
            ]
              .filter(Boolean)
              .map((fact, index) => (
                <Fragment key={String(fact)}>
                  {index > 0 && ", "}
                  <span>{fact}</span>
                </Fragment>
              ))}
          </p>
        </div>
        <Button
          aria-label={onClose ? "Close" : `Remove ${entry.file.name}`}
          className="text-muted-foreground"
          disabled={busy}
          onClick={onClose ?? onRemove}
          size="icon-xs"
          type="button"
          variant="ghost"
        >
          <Icon.close className="size-3.5" />
        </Button>
      </header>
      <AnimatePresence initial={false} mode="wait">
        {columns.length > 0 ? (
          <motion.div
            animate={{ opacity: 1, y: 0 }}
            className={cn(
              "min-w-0 overflow-hidden rounded-sm bg-background",
              working && "opacity-50"
            )}
            initial={{ opacity: 0, y: reduce ? 0 : 4 }}
            key="preview"
          >
            <div className="overflow-x-auto overscroll-x-contain [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
              <table className="w-max min-w-full border-separate border-spacing-0 text-left text-xs leading-4">
                <caption className="sr-only">
                  The first {rows.length} rows of {entry.file.name}
                </caption>
                <thead>
                  <tr>
                    {columns.map((column) => (
                      <th
                        className="max-w-48 truncate px-2.5 pt-2 pb-1.5 font-medium whitespace-nowrap"
                        key={column}
                        scope="col"
                      >
                        {column}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {rows.map((row, index) => (
                    <tr key={index}>
                      {columns.map((column) => (
                        <td
                          className="max-w-48 truncate border-t border-border/60 px-2.5 py-1.5 whitespace-nowrap text-muted-foreground tabular-nums"
                          key={column}
                        >
                          {row[column] ?? ""}
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </motion.div>
        ) : working ? (
          <motion.div
            animate={{ opacity: 1 }}
            className="flex min-h-36 items-center justify-center gap-2 rounded-sm bg-background text-sm text-muted-foreground"
            initial={{ opacity: 0 }}
            key="working"
          >
            <Spinner size="sm" />
            {entry.status === "uploading"
              ? `Uploading ${entry.percent}%`
              : entry.status === "queued"
                ? "Queued"
                : "Reading file"}
          </motion.div>
        ) : entry.status === "error" ? null : (
          <p className="m-0 text-xs text-muted-foreground" key="later">
            Preview available after extraction.
          </p>
        )}
      </AnimatePresence>
      {entry.error && (
        <p className="m-0 px-0.5 text-xs leading-4 text-destructive" role="alert">
          {entry.error}
        </p>
      )}
      <footer className="-mt-0.5 flex min-h-6 min-w-0 items-center justify-between gap-2">
        {(delimited || workbook) && entry.uploadId ? (
          <Popover>
            <PopoverTrigger asChild>
              <button
                aria-label={`How the file is read: ${reading}`}
                className="inline-flex h-6 min-w-0 items-center gap-1.5 rounded-sm pr-1.5 pl-2 text-xs font-medium text-muted-foreground hover:bg-foreground/6 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
                type="button"
              >
                <span className="truncate">{reading}</span>
                <Icon.chevronDown className="size-3 shrink-0" />
              </button>
            </PopoverTrigger>
            <PopoverContent
              align="start"
              aria-label="File settings"
              className="flex w-72 flex-col gap-2.5 p-3"
              sideOffset={6}
            >
              {delimited && (
                <>
                  <Setting label="Separator">
                    <SeparatorPicker
                      disabled={locked}
                      onChange={(delimiter) => read({ delimiter })}
                      value={options.delimiter ?? "comma"}
                    />
                  </Setting>
                  <Setting label="Encoding">
                    <Select
                      disabled={locked}
                      onValueChange={(value) => read({ encoding: value as EncodingEnum })}
                      value={options.encoding ?? "utf-8-sig"}
                    >
                      <SelectTrigger aria-label="Encoding" size="xs">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {ENCODINGS.map((item) => (
                          <SelectItem key={item.value} value={item.value}>
                            {item.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </Setting>
                </>
              )}
              {workbook && sheets.length > 1 && (
                <Setting label="Sheet">
                  <Select
                    disabled={locked}
                    onValueChange={(value) => {
                      const { sheet: _, ...rest } = options;
                      onRead(value === EVERY_SHEET ? rest : { ...rest, sheet: value });
                    }}
                    value={options.sheet ?? EVERY_SHEET}
                  >
                    <SelectTrigger aria-label="Sheet" size="xs">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value={EVERY_SHEET}>All sheets</SelectItem>
                      {sheets.map((sheet) => (
                        <SelectItem key={sheet} value={sheet}>
                          {sheet}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </Setting>
              )}
              <Setting label="Headers">
                <span className="flex flex-1 items-center justify-between text-xs">
                  First row
                  <Switch
                    aria-label="First row is headers"
                    checked={options.header ?? true}
                    disabled={locked}
                    onCheckedChange={(header) => read({ header })}
                    size="sm"
                  />
                </span>
              </Setting>
            </PopoverContent>
          </Popover>
        ) : (
          <span />
        )}
        {entry.status === "error" ? (
          <Button disabled={busy} onClick={onRetry} size="xs" type="button">
            Retry
          </Button>
        ) : entry.reviewed ? (
          <span className="text-xs text-success">Ready</span>
        ) : (
          <Button disabled={locked} onClick={onContinue} size="xs" type="button">
            {working && <Spinner size="sm" />}
            Continue
          </Button>
        )}
      </footer>
    </section>
  );
}

function Setting({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="flex items-center gap-2">
      <span className="w-20 flex-none text-xs text-muted-foreground">{label}</span>
      {children}
    </div>
  );
}

/** A four-way segmented control; arrow keys move the choice like a radio group. */
function SeparatorPicker({
  value,
  disabled,
  onChange,
}: {
  value: DelimiterEnum;
  disabled: boolean;
  onChange: (value: DelimiterEnum) => void;
}) {
  const index = Math.max(
    0,
    SEPARATORS.findIndex((item) => item.value === value)
  );
  const step = (event: KeyboardEvent<HTMLButtonElement>) => {
    const move = { ArrowLeft: -1, ArrowRight: 1 }[event.key];
    if (!move) return;
    event.preventDefault();
    const next = (index + move + SEPARATORS.length) % SEPARATORS.length;
    onChange(SEPARATORS[next].value);
    event.currentTarget.parentElement?.querySelectorAll<HTMLElement>("[role=radio]")[next]?.focus();
  };
  return (
    <div
      aria-label="Separator"
      className="relative grid h-6 flex-1 grid-cols-4 rounded-sm bg-foreground/6 p-0.5"
      role="radiogroup"
    >
      <span
        aria-hidden
        className="absolute inset-y-0.5 left-0.5 w-[calc(25%-1px)] rounded-sm bg-card transition-transform duration-200 motion-reduce:transition-none"
        style={{ transform: `translateX(${index * 100}%)` }}
      />
      {SEPARATORS.map((item) => {
        const checked = item.value === value;
        return (
          <button
            aria-checked={checked}
            aria-label={item.label}
            className={cn(
              "relative rounded-sm leading-none font-medium focus-visible:ring-2 focus-visible:ring-ring",
              item.value === "tab" ? "text-xs" : "font-mono text-sm",
              checked ? "text-foreground" : "text-muted-foreground"
            )}
            disabled={disabled}
            key={item.value}
            onClick={() => onChange(item.value)}
            onKeyDown={step}
            role="radio"
            tabIndex={checked ? 0 : -1}
            type="button"
          >
            {item.mark}
          </button>
        );
      })}
    </div>
  );
}

/** The empty state: drop files, choose them, or paste cells as a table. */
export function FileImportPicker({
  disabled = false,
  onFiles,
  onError,
}: {
  disabled?: boolean;
  onFiles: (files: File[]) => void;
  onError: (message: string) => void;
}) {
  const input = useRef<HTMLInputElement>(null);
  // dragenter and dragleave fire for every child, so the hover state counts them.
  const depth = useRef(0);
  const [dragging, setDragging] = useState(false);
  return (
    <section
      aria-label="Import"
      className="flex min-w-0 flex-col gap-3"
      onDragEnter={(event) => {
        event.preventDefault();
        if (disabled) return;
        depth.current += 1;
        setDragging(true);
      }}
      onDragLeave={() => {
        depth.current = Math.max(0, depth.current - 1);
        if (depth.current === 0) setDragging(false);
      }}
      onDragOver={(event) => {
        event.preventDefault();
        event.stopPropagation();
      }}
      onDrop={(event) => {
        event.preventDefault();
        event.stopPropagation();
        depth.current = 0;
        setDragging(false);
        if (disabled) return;
        const folder = Array.from(event.dataTransfer.items).some(
          (item) => item.webkitGetAsEntry?.()?.isDirectory
        );
        if (folder) onError("Drop files, not folders.");
        else onFiles(Array.from(event.dataTransfer.files));
      }}
      onPaste={(event) => {
        if (
          disabled ||
          event.target instanceof HTMLInputElement ||
          event.target instanceof HTMLTextAreaElement
        )
          return;
        const text = event.clipboardData.getData("text/plain");
        if (!text.trim()) return;
        event.preventDefault();
        const name = text.includes("\t") ? "Pasted cells.tsv" : "Pasted cells.csv";
        onFiles([new File([text], name, { type: "text/plain" })]);
      }}
    >
      <div className="flex items-center gap-2">
        <span className="inline-flex size-6 items-center justify-center rounded-md bg-info/10 text-info">
          <Icon.upload className="size-3.5" />
        </span>
        <span className="text-sm font-medium">Import</span>
      </div>
      <input
        accept={IMPORT_ACCEPT}
        aria-label="Choose dataset files"
        className="hidden"
        disabled={disabled}
        multiple
        onChange={(event) => {
          onFiles(Array.from(event.target.files ?? []));
          event.target.value = "";
        }}
        ref={input}
        type="file"
      />
      <button
        className={cn(
          "group flex min-h-36 w-full cursor-pointer flex-col items-center justify-center gap-1 rounded-sm bg-background px-4 py-6 text-center outline-dashed outline-transparent transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",
          dragging && "bg-info/10 outline-info"
        )}
        disabled={disabled}
        onClick={() => input.current?.click()}
        type="button"
      >
        <span className="mb-2 inline-flex size-8 items-center justify-center rounded-sm border border-border bg-card text-muted-foreground">
          <Icon.upload className="size-4" />
        </span>
        <span className="text-sm font-medium">
          {dragging ? (
            "Drop to import"
          ) : (
            <>
              Drop data, or <span className="underline underline-offset-2">choose a file</span>
            </>
          )}
        </span>
        <span className="text-xs leading-4 text-muted-foreground">
          Tables, documents or images. You can paste cells too.
        </span>
      </button>
    </section>
  );
}