Skip to content
Shaken UI
Sign in

Artifact Preview

Save

A file an agent produced as a compact row. Hover, focus, or tap a ready file to open an animated preview shaped by its type: the image, a table for CSV and Excel, the opening lines of code or Markdown, a page sketch for PDF, or a plain fallback.

Category
Agent
Version
0.3.1
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Artifact Preview preview

Hover, focus, or tap a file to preview it.

Ready
Ready
Ready
Ready
Ready
Ready
Ready
Ready

Installation

npx @shakenui/cli add artifact-preview

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add artifact-preview --dry-run

Usage

artifact-preview-example.tsx
import { ArtifactPreview } from "@/components/shaken/agent/artifact-preview";

export default function ArtifactPreviewExample() {
  return (
    <ArtifactPreview
      className="w-full max-w-md"
      name="rate-limits.csv"
      type="text/csv"
      status="ready"
      path="/artifacts/rate-limits.csv"
      sizeBytes={58}
      content={"plan,requests_per_minute\nfree,60\npro,600"}
    />
  );
}

States

Every state, rendered from local fixture data.

Artifact Preview states
Writing the file
report.mdWriting…Markdown
Ready
Failed
report.mdFailed

The source page timed out.

API

PropTypeDefaultDescription
name / typestring—File name and MIME type. The extension and type choose the preview kind.
status"generating" | "ready" | "failed"—Generating shows a spinner and "Writing…"; failed shows the error under the row. Only ready files preview.
pathstring—Where to open or download the file. Images preview from this path unless previewSrc is set.
contentstring—Text for code, JSON, Markdown, and plain text previews (rendered as text, never HTML). CSV and TSV content is parsed into a table.
rows(string | number)[][]—Table data for spreadsheets such as xlsx, first row as the header. Takes precedence over parsing content.
previewSrcstring—A thumbnail to show instead of path, for large images or the first page of a PDF.
pagesnumber—Page count shown with the PDF page sketch.
kind"image" | "table" | "document" | "code" | "pdf" | "file"—Overrides the detected preview kind.
previewbooleantrueSet to false to show only the row.
previewSide"top" | "bottom" | "left" | "right""bottom"Side of the row the preview opens on; it flips when there is no room.
sizeBytes / errornumber / string—Optional size and failure message.

Accessibility

  • The row is a button: hover, keyboard focus, or a tap opens the preview, and Escape closes it with focus kept on the row.
  • Focus stays on the row when the preview opens; Tab moves into the preview (its Download link) and on to the row's own download link.
  • The preview is a labelled dialog ("Preview of name"). Tables use real table markup with a caption, images have alt text, and the PDF sketch is a labelled image.
  • Status is announced in a live region ("Writing the file", "Ready", "Failed") and also shown as text and a glyph.
  • With reduced motion the preview and its staggered content appear without transitions; the generating spinner holds still.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/agent/artifact-preview.tsxartifact-preview
  • Also installs agent-run@0.1.2registry dependency
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/artifact-preview/0.3.1.json.

agent/artifact-preview.tsxShow
agent/artifact-preview.tsx
"use client";

import { Popover as BasePopover } from "@base-ui/react/popover";
import { type ComponentProps, type CSSProperties, type FocusEvent, useState } from "react";
import type { ArtifactStatus } from "./agent-run";

/** How a file previews. Detected from the extension and MIME type unless you pass `kind`. */
export type ArtifactKind = "image" | "table" | "document" | "code" | "pdf" | "file";

export interface ArtifactPreviewProps extends Omit<ComponentProps<"article">, "children"> {
  name: string;
  /** MIME type, e.g. text/markdown, text/csv, application/json, image/png. */
  type: string;
  status: ArtifactStatus;
  /** Where to open or download the artifact once it is ready. Images preview from this path. */
  path?: string;
  /** Text content to preview for text-like types. Rendered as text, never HTML. */
  content?: string;
  sizeBytes?: number;
  error?: string;
  /** Overrides the detected preview kind. */
  kind?: ArtifactKind;
  /** Table data for spreadsheets (first row is the header). CSV and TSV content is parsed when this is unset. */
  rows?: (string | number)[][];
  /** A thumbnail to show instead of `path`, for large images or the first page of a PDF. */
  previewSrc?: string;
  /** Page count for documents such as PDFs. */
  pages?: number;
  /** Set to false to show only the row, without the hover preview. */
  preview?: boolean;
  /** Side of the row the preview opens on. Flips when there is not enough room. */
  previewSide?: "top" | "bottom" | "left" | "right";
}

const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";
/** Preview content settles in as the card opens: a 2px rise and a fade, staggered by `delay`. */
const rise = `transition-[opacity,translate] duration-300 ${ease} starting:opacity-0 motion-safe:starting:translate-y-0.5 motion-reduce:transition-none`;
const delay = (index: number): CSSProperties => ({ transitionDelay: `${40 + index * 28}ms` });

/**
 * A file an agent produced, as a compact row: name, type, size, and status. Hovering, focusing,
 * or tapping a ready file opens a preview shaped by its type: the image, the first rows of a
 * spreadsheet, the opening lines of code or a document, or a page sketch for a PDF.
 */
export function ArtifactPreview({
  name,
  type,
  status,
  path,
  content,
  sizeBytes,
  error,
  kind: kindProp,
  rows,
  previewSrc,
  pages,
  preview = true,
  previewSide = "bottom",
  className,
  ...props
}: ArtifactPreviewProps) {
  const [open, setOpen] = useState(false);
  const extension = extensionOf(name);
  const kind = kindProp ?? kindOf(extension, type);
  const label = typeLabel(extension, type, kind);
  const table = kind === "table" ? (rows ?? (content != null ? parseDelimited(content, extension === "tsv" || type.includes("tab-separated") ? "\t" : ",") : undefined)) : undefined;
  const ready = status === "ready";
  const canPreview = ready && preview;

  const row = (
    <>
      <FileTile extension={extension} kind={kind} status={status} />
      <span className="grid min-w-0 flex-1 text-left">
        <span className="truncate text-sm font-medium text-zinc-950 dark:text-white">{name}</span>
        <span className="flex min-w-0 items-center gap-1.5 text-xs text-zinc-500">
          {status === "generating" ? (
            <span key="generating" className={`text-sky-700 dark:text-sky-400 ${rise}`}>
              Writing…
            </span>
          ) : status === "failed" ? (
            <span key="failed" className={`text-red-700 dark:text-red-400 ${rise}`}>
              Failed
            </span>
          ) : null}
          {status === "failed" ? null : (
            <span className="truncate">
              {status === "generating" ? <span aria-hidden="true">· </span> : null}
              {label}
              {sizeBytes != null && ready ? <span className="font-mono tabular-nums"> · {formatSize(sizeBytes)}</span> : null}
            </span>
          )}
        </span>
      </span>
    </>
  );

  return (
    <article
      data-status={status}
      data-kind={kind}
      aria-busy={status === "generating" || undefined}
      aria-label={name}
      className={[
        "rounded-xl border border-zinc-950/10 bg-white text-zinc-950 shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
        "dark:border-white/10 dark:bg-black dark:text-white dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
        className,
      ]
        .filter(Boolean)
        .join(" ")}
      {...props}
    >
      <span role="status" className="sr-only">
        {status === "generating" ? "Writing the file" : status === "failed" ? "Failed" : "Ready"}
      </span>
      <div className="flex items-center gap-1 p-1.5">
        {canPreview ? (
          <BasePopover.Root open={open} onOpenChange={setOpen}>
            <BasePopover.Trigger
              openOnHover
              delay={140}
              closeDelay={120}
              // Keyboard focus opens the preview too; a mouse click is handled by the trigger itself.
              onFocus={(event: FocusEvent<HTMLButtonElement>) => {
                if (event.currentTarget.matches(":focus-visible")) setOpen(true);
              }}
              className={[
                "flex min-w-0 flex-1 items-center gap-3 rounded-lg p-1.5 text-left outline-none",
                "transition-colors duration-150 ease-out motion-reduce:transition-none",
                "hover:bg-zinc-950/[0.04] data-[popup-open]:bg-zinc-950/[0.04] dark:hover:bg-white/[0.06] dark:data-[popup-open]:bg-white/[0.06]",
                "focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
              ].join(" ")}
            >
              {row}
              <span className="sr-only">, show preview</span>
            </BasePopover.Trigger>
            <BasePopover.Portal>
              <BasePopover.Positioner side={previewSide} align="start" sideOffset={8} collisionPadding={12} className="z-50">
                <BasePopover.Popup
                  initialFocus={false}
                  className={[
                    "max-w-(--available-width) origin-(--transform-origin) overflow-hidden rounded-xl outline-none",
                    kind === "table" ? "w-[26rem]" : kind === "pdf" ? "w-64" : "w-80",
                    "border border-zinc-950/10 bg-white text-zinc-950 shadow-[0_12px_32px_-8px_rgb(0_0_0/0.18)]",
                    "dark:border-white/15 dark:bg-black dark:text-white dark:shadow-[0_16px_48px_-12px_rgb(0_0_0/1),inset_0_1px_0_rgb(255_255_255/0.08)]",
                    // Enter: 180ms from 96% at the row. Exit: 110ms, a fade with a smaller scale.
                    `transition-[opacity,scale] duration-180 ${ease} motion-reduce:transition-none`,
                    "data-[starting-style]:opacity-0 motion-safe:data-[starting-style]:scale-96",
                    "data-[ending-style]:opacity-0 data-[ending-style]:duration-110 data-[ending-style]:ease-out motion-safe:data-[ending-style]:scale-98",
                  ].join(" ")}
                >
                  <BasePopover.Title className="sr-only">Preview of {name}</BasePopover.Title>
                  <PreviewBody kind={kind} name={name} path={path} thumbnail={previewSrc} content={content} table={table} pages={pages} extension={extension} />
                  {path ? (
                    <div className="flex items-center justify-between gap-3 border-t border-zinc-950/[0.07] py-1.5 pr-1.5 pl-3 dark:border-white/[0.08]">
                      <code className="min-w-0 truncate font-mono text-[11px] text-zinc-500">{path}</code>
                      <DownloadLink path={path} name={name} withText />
                    </div>
                  ) : null}
                </BasePopover.Popup>
              </BasePopover.Positioner>
            </BasePopover.Portal>
          </BasePopover.Root>
        ) : (
          <div className="flex min-w-0 flex-1 items-center gap-3 p-1.5">{row}</div>
        )}
        {ready && path ? <DownloadLink path={path} name={name} /> : null}
      </div>
      {status === "failed" ? (
        <p key="error" className={`border-t border-zinc-950/[0.07] px-3 py-2.5 text-xs leading-relaxed text-zinc-600 dark:border-white/[0.08] dark:text-zinc-400 ${rise}`}>
          {error ?? "The artifact could not be generated."}
        </p>
      ) : null}
    </article>
  );
}

function PreviewBody({
  kind,
  name,
  path,
  thumbnail,
  content,
  table,
  pages,
  extension,
}: {
  kind: ArtifactKind;
  name: string;
  path?: string;
  thumbnail?: string;
  content?: string;
  table?: (string | number)[][];
  pages?: number;
  extension: string;
}) {
  if (kind === "image" && (thumbnail ?? path)) return <ImagePreview src={(thumbnail ?? path)!} name={name} />;
  if (kind === "table" && table && table.length > 0) return <TablePreview rows={table} name={name} />;
  if (kind === "pdf") return thumbnail ? <ImagePreview src={thumbnail} name={name} /> : <PagePreview pages={pages} name={name} />;
  if (kind === "document" && content != null) return <DocumentPreview content={content} markdown={extension === "md" || extension === "markdown"} />;
  if ((kind === "code" || kind === "document") && content != null) return <CodePreview content={content} json={extension === "json"} />;
  return <GenericPreview extension={extension} />;
}

function ImagePreview({ src, name }: { src: string; name: string }) {
  const [size, setSize] = useState<string | null>(null);
  return (
    <figure className="p-1.5">
      <div className="grid place-items-center overflow-hidden rounded-lg bg-zinc-950/[0.03] dark:bg-white/[0.04]">
        <img
          src={src}
          alt={`Preview of ${name}`}
          onLoad={(event) => setSize(`${event.currentTarget.naturalWidth} × ${event.currentTarget.naturalHeight}`)}
          className={`max-h-56 w-full object-contain transition-[opacity,scale,filter] duration-300 ${ease} starting:opacity-0 motion-safe:starting:scale-[1.04] motion-safe:starting:blur-[3px] motion-reduce:transition-none`}
        />
      </div>
      {size ? <figcaption className="px-1.5 pt-1.5 font-mono text-[11px] text-zinc-500 tabular-nums">{size}</figcaption> : null}
    </figure>
  );
}

const MAX_ROWS = 5;
const MAX_COLUMNS = 4;

function TablePreview({ rows, name }: { rows: (string | number)[][]; name: string }) {
  const [header = [], ...body] = rows;
  const shown = body.slice(0, MAX_ROWS);
  const columns = Math.max(header.length, ...shown.map((row) => row.length));
  const visibleColumns = Math.min(columns, MAX_COLUMNS);
  const numeric = Array.from({ length: visibleColumns }, (_, column) => shown.length > 0 && shown.every((row) => isNumeric(row[column])));
  const cell = "truncate px-2.5 py-1.5";

  return (
    <div className="p-1.5">
      <div className="overflow-hidden rounded-lg border border-zinc-950/[0.07] dark:border-white/[0.08]">
        <table className="w-full table-fixed border-collapse text-left text-xs">
          <caption className="sr-only">
            First {shown.length} of {body.length} rows of {name}
          </caption>
          <thead>
            <tr className={`bg-zinc-950/[0.03] dark:bg-white/[0.04] ${rise}`} style={delay(0)}>
              {Array.from({ length: visibleColumns }, (_, column) => (
                <th key={column} scope="col" className={`${cell} ${column === 0 && visibleColumns > 2 ? "w-[30%]" : ""} font-medium text-zinc-700 dark:text-zinc-300 ${numeric[column] ? "text-right" : ""}`}>
                  {header[column] ?? ""}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {shown.map((row, index) => (
              <tr key={index} className={`border-t border-zinc-950/[0.06] dark:border-white/[0.06] ${rise}`} style={delay(index + 1)}>
                {Array.from({ length: visibleColumns }, (_, column) => (
                  <td
                    key={column}
                    className={`${cell} text-zinc-600 dark:text-zinc-400 ${numeric[column] ? "text-right font-mono tabular-nums" : ""}`}
                  >
                    {row[column] ?? ""}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <p className="px-1.5 pt-1.5 text-[11px] text-zinc-500 tabular-nums">
        {shown.length < body.length ? `${shown.length} of ${body.length} rows` : `${body.length} ${body.length === 1 ? "row" : "rows"}`}
        {` · ${columns} ${columns === 1 ? "column" : "columns"}`}
      </p>
    </div>
  );
}

const MAX_LINES = 12;

function CodePreview({ content, json }: { content: string; json: boolean }) {
  const text = json ? prettyJson(content) : content;
  const lines = text.replace(/\n$/, "").split("\n");
  const shown = lines.slice(0, MAX_LINES);
  const more = lines.length - shown.length;

  return (
    <div className="p-1.5">
      <pre className="relative overflow-hidden rounded-lg border border-zinc-950/[0.07] bg-zinc-950/[0.02] py-2 font-mono text-[11px] leading-[1.6] text-zinc-800 dark:border-white/[0.08] dark:bg-white/[0.02] dark:text-zinc-300">
        {shown.map((line, index) => (
          <span key={index} className={`flex ${rise}`} style={delay(Math.min(index, 8))}>
            <span aria-hidden="true" className="w-8 shrink-0 pr-3 text-right text-zinc-400 tabular-nums select-none dark:text-zinc-600">
              {index + 1}
            </span>
            <span className="min-w-0 overflow-hidden pr-3 text-ellipsis whitespace-pre">{line || " "}</span>
          </span>
        ))}
        {more > 0 ? (
          <span aria-hidden="true" className="pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-linear-to-t from-white dark:from-black" />
        ) : null}
      </pre>
      {more > 0 ? <p className="px-1.5 pt-1.5 text-[11px] text-zinc-500 tabular-nums">{more} more {more === 1 ? "line" : "lines"}</p> : null}
    </div>
  );
}

/** Markdown and plain text read as a page: headings, list items, and paragraphs, never HTML. */
function DocumentPreview({ content, markdown }: { content: string; markdown: boolean }) {
  const blocks = content
    .split("\n")
    .map((line) => line.trim())
    .filter((line) => line && !line.startsWith("```"))
    .slice(0, 9);

  return (
    <div className="relative max-h-64 overflow-hidden px-4 pt-3.5 pb-4">
      <div className="grid gap-1.5">
        {blocks.map((line, index) => {
          const style = delay(index);
          if (markdown && /^#{1,6}\s/.test(line)) {
            const level = line.match(/^#+/)![0].length;
            return (
              <p key={index} style={style} className={`${level === 1 ? "text-sm" : "pt-1 text-xs"} font-semibold text-zinc-950 dark:text-white ${rise}`}>
                {inline(line.replace(/^#+\s*/, ""))}
              </p>
            );
          }
          if (markdown && /^([-*+]|\d+\.)\s/.test(line)) {
            return (
              <p key={index} style={style} className={`flex gap-2 text-xs leading-relaxed text-zinc-600 dark:text-zinc-400 ${rise}`}>
                <span aria-hidden="true" className="mt-[7px] size-1 shrink-0 rounded-full bg-current opacity-60" />
                <span className="min-w-0">{inline(line.replace(/^([-*+]|\d+\.)\s+/, ""))}</span>
              </p>
            );
          }
          return (
            <p key={index} style={style} className={`text-xs leading-relaxed text-zinc-600 dark:text-zinc-400 ${rise}`}>
              {markdown ? inline(line) : line}
            </p>
          );
        })}
      </div>
      <span aria-hidden="true" className="pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-linear-to-t from-white dark:from-black" />
    </div>
  );
}

/** A sketch of the first page: a title, text lines, and a figure, drawn in hairlines. */
function PagePreview({ pages, name }: { pages?: number; name: string }) {
  const lines = ["w-full", "w-11/12", "w-full", "w-3/4", "w-full", "w-5/6", "w-2/3"];
  const bar = "h-[3px] rounded-full bg-zinc-950/15 dark:bg-white/20";
  const grow = `origin-left transition-[opacity,scale] duration-300 ${ease} starting:opacity-0 motion-safe:starting:scale-x-50 motion-reduce:transition-none`;

  return (
    <div className="grid justify-items-center gap-2 px-4 pt-5 pb-3">
      <div role="img" aria-label={`First page of ${name}${pages ? `, ${pages} pages` : ""}`} className="relative">
        {pages && pages > 1 ? (
          <span
            aria-hidden="true"
            className={`absolute inset-0 translate-x-1.5 -translate-y-1.5 rounded-md border border-zinc-950/10 bg-white dark:border-white/10 dark:bg-black ${rise}`}
          />
        ) : null}
        <div className="relative grid aspect-[8.5/11] w-36 content-start gap-1.5 rounded-md border border-zinc-950/12 bg-white p-3.5 shadow-[0_6px_16px_-8px_rgb(0_0_0/0.2)] dark:border-white/15 dark:bg-black dark:shadow-none">
          <span className={`h-1.5 w-1/2 rounded-full bg-zinc-950/40 dark:bg-white/50 ${grow}`} style={delay(0)} />
          <span className={`mb-1 ${bar} w-1/3 ${grow}`} style={delay(1)} />
          {lines.slice(0, 3).map((width, index) => (
            <span key={`a${index}`} className={`${bar} ${width} ${grow}`} style={delay(index + 2)} />
          ))}
          <span className={`my-1 h-7 rounded-sm border border-zinc-950/10 bg-zinc-950/[0.03] dark:border-white/10 dark:bg-white/[0.04] ${rise}`} style={delay(5)} />
          {lines.slice(3).map((width, index) => (
            <span key={`b${index}`} className={`${bar} ${width} ${grow}`} style={delay(index + 6)} />
          ))}
        </div>
      </div>
      {pages ? <p className="text-[11px] text-zinc-500 tabular-nums">{pages === 1 ? "1 page" : `${pages} pages`}</p> : null}
    </div>
  );
}

function GenericPreview({ extension }: { extension: string }) {
  return (
    <div className="grid justify-items-center gap-2 px-4 py-6 text-center">
      <span
        aria-hidden="true"
        className={`grid size-12 place-items-center rounded-xl border border-zinc-950/10 font-mono text-xs font-medium text-zinc-600 dark:border-white/15 dark:text-zinc-400 ${rise}`}
      >
        {extension || <PageIcon />}
      </span>
      <p className={`text-xs text-zinc-500 ${rise}`} style={delay(1)}>
        No inline preview for this file type.
      </p>
    </div>
  );
}

function DownloadLink({ path, name, withText = false }: { path: string; name: string; withText?: boolean }) {
  return (
    <a
      href={path}
      download={name}
      aria-label={withText ? undefined : `Download ${name}`}
      className={[
        "inline-flex shrink-0 items-center justify-center gap-1.5 rounded-lg text-zinc-500",
        withText ? "h-7 px-2 text-xs font-medium" : "size-8",
        "transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none",
        "hover:bg-zinc-950/[0.05] hover:text-zinc-950 dark:hover:bg-white/[0.08] dark:hover:text-white",
        "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
      ].join(" ")}
    >
      <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-4">
        <path d="M8 2.75v7.5M4.75 7 8 10.25 11.25 7M3 13.25h10" />
      </svg>
      {withText ? (
        <>
          Download<span className="sr-only"> {name}</span>
        </>
      ) : null}
    </a>
  );
}

/** The file's tile: its extension in mono, with the running or failed glyph while it is not ready. */
function FileTile({ extension, kind, status }: { extension: string; kind: ArtifactKind; status: ArtifactStatus }) {
  return (
    <span
      aria-hidden="true"
      className={[
        "relative grid size-9 shrink-0 place-items-center rounded-lg border font-mono text-[10px] font-medium",
        "transition-colors duration-200 ease-out motion-reduce:transition-none",
        status === "failed"
          ? "border-red-500/35 text-red-600 dark:text-red-400"
          : status === "generating"
            ? "border-sky-500/35 text-sky-600 dark:text-sky-400"
            : "border-zinc-950/10 text-zinc-600 dark:border-white/10 dark:text-zinc-400",
      ].join(" ")}
    >
      {status === "generating" ? (
        <svg key="running" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="size-4">
          <circle cx="8" cy="8" r="6.25" strokeOpacity="0.2" />
          <path d="M8 1.75A6.25 6.25 0 1 1 1.75 8" className="origin-center motion-safe:animate-spin" />
        </svg>
      ) : status === "failed" ? (
        <svg key="failed" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className={`size-4 ${rise}`}>
          <circle cx="8" cy="8" r="6.25" />
          <path d="m6.1 6.1 3.8 3.8m0-3.8-3.8 3.8" />
        </svg>
      ) : kind === "image" ? (
        <svg key="image" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.25" strokeLinejoin="round" className="size-4">
          <rect x="2.25" y="3.25" width="11.5" height="9.5" rx="1.5" />
          <circle cx="5.75" cy="6.5" r="1" />
          <path d="m2.5 11.5 3.25-3 2.5 2.25 2-1.75 3.25 2.75" />
        </svg>
      ) : kind === "table" ? (
        <svg key="table" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.25" className="size-4">
          <rect x="2.25" y="3.25" width="11.5" height="9.5" rx="1.5" />
          <path d="M2.25 6.5h11.5M2.25 9.6h11.5M6.25 3.25v9.5" />
        </svg>
      ) : (
        extension || <PageIcon />
      )}
    </span>
  );
}

function PageIcon() {
  return (
    <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.25" strokeLinejoin="round" className="size-5">
      <path d="M5.5 2.75h6l3 3v11.5h-9z" />
      <path d="M11.5 2.75v3h3" />
    </svg>
  );
}

/** Renders `code` and **bold** spans as text; everything else stays plain. */
function inline(text: string) {
  return text.split(/(`[^`]+`|\*\*[^*]+\*\*)/g).map((part, index) =>
    part.startsWith("`") && part.endsWith("`") && part.length > 1 ? (
      <code key={index} className="font-mono text-[0.95em] text-zinc-800 dark:text-zinc-200">
        {part.slice(1, -1)}
      </code>
    ) : part.startsWith("**") && part.endsWith("**") && part.length > 3 ? (
      <strong key={index} className="font-semibold text-zinc-800 dark:text-zinc-200">
        {part.slice(2, -2)}
      </strong>
    ) : (
      part
    ),
  );
}

const imageExtensions = new Set(["png", "jpg", "jpeg", "webp", "gif", "svg", "avif", "bmp", "ico"]);
const tableExtensions = new Set(["csv", "tsv", "xlsx", "xls", "ods", "numbers"]);
const documentExtensions = new Set(["md", "markdown", "mdx", "txt", "rtf", "log"]);
const codeExtensions = new Set([
  "json", "ts", "tsx", "js", "jsx", "mjs", "cjs", "py", "rb", "go", "rs", "java", "kt", "swift", "c", "h", "cpp", "cs", "php",
  "html", "css", "scss", "vue", "svelte", "yaml", "yml", "toml", "xml", "sh", "sql", "graphql", "env",
]);

/** Picks a preview kind from the extension first, then the MIME type. */
export function kindOf(extension: string, type: string): ArtifactKind {
  if (imageExtensions.has(extension) || type.startsWith("image/")) return "image";
  if (tableExtensions.has(extension) || /csv|tab-separated|spreadsheet|excel/.test(type)) return "table";
  if (extension === "pdf" || type === "application/pdf") return "pdf";
  if (documentExtensions.has(extension) || type === "text/markdown" || type === "text/plain") return "document";
  if (codeExtensions.has(extension) || type.startsWith("text/") || /json|javascript|typescript|xml|yaml/.test(type)) return "code";
  return "file";
}

const labels: Record<string, string> = {
  csv: "CSV", tsv: "TSV", xlsx: "Excel spreadsheet", xls: "Excel spreadsheet", ods: "Spreadsheet", md: "Markdown", markdown: "Markdown",
  mdx: "MDX", txt: "Plain text", json: "JSON", ts: "TypeScript", tsx: "TypeScript", js: "JavaScript", jsx: "JavaScript",
  mjs: "JavaScript", py: "Python", pdf: "PDF", svg: "SVG image", gif: "GIF image", html: "HTML", css: "CSS", yaml: "YAML", yml: "YAML",
  sql: "SQL", zip: "ZIP archive",
};

function typeLabel(extension: string, type: string, kind: ArtifactKind) {
  if (labels[extension]) return labels[extension]!;
  if (kind === "image" && extension) return `${extension.toUpperCase()} image`;
  if (extension) return extension.toUpperCase();
  return type || "File";
}

function isNumeric(value: string | number | undefined) {
  if (typeof value === "number") return true;
  return value != null && value.trim() !== "" && /^[-+]?[$€£]?[\d,]*\.?\d+%?$/.test(value.trim());
}

function prettyJson(content: string) {
  try {
    return JSON.stringify(JSON.parse(content), null, 2);
  } catch {
    return content;
  }
}

/** A small CSV/TSV reader: quoted fields, escaped quotes, and newlines inside quotes. */
export function parseDelimited(text: string, separator = ","): string[][] {
  const rows: string[][] = [];
  let row: string[] = [];
  let field = "";
  let quoted = false;
  for (let i = 0; i < text.length; i++) {
    const char = text[i]!;
    if (quoted) {
      if (char === '"' && text[i + 1] === '"') {
        field += '"';
        i++;
      } else if (char === '"') quoted = false;
      else field += char;
    } else if (char === '"' && field === "") quoted = true;
    else if (char === separator) {
      row.push(field);
      field = "";
    } else if (char === "\n" || char === "\r") {
      if (char === "\r" && text[i + 1] === "\n") i++;
      row.push(field);
      rows.push(row);
      row = [];
      field = "";
    } else field += char;
  }
  if (field !== "" || row.length > 0) {
    row.push(field);
    rows.push(row);
  }
  return rows;
}

function extensionOf(name: string): string {
  const match = name.match(/\.([a-z0-9]{1,8})$/i);
  return match ? match[1]!.toLowerCase() : "";
}

function formatSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}