# Records Table

> Show records in a table where some columns are filled in by an agent, one cell at a time.

Source: https://www.honestui.com/docs/ai/records-table

```tsx
"use client"

import * as React from "react"

import {
  RecordsTable,
  type GeneratedCell,
  type RecordsTableRow,
} from "@/components/ai/records-table"
import { Button } from "@/components/honest-ui/ui/button"

// Sample records and the summary each row resolves to.
const sampleRecords = [
  { id: "a", name: "Northwind Dairy", region: "EMEA", summary: "Pays on time; two open invoices." },
  { id: "b", name: "Harbor Paper Co.", region: "APAC", summary: "One invoice 14 days late." },
  { id: "c", name: "Ridge Tooling", region: "AMER", summary: "No open invoices." },
]

const CELL_MILLISECONDS = 1100

/**
 * No model fills these cells. A timer completes one cell at a time, and the
 * second one fails on its first pass to show the error state and Try again.
 * The first cell starts done so the opening view shows a finished summary;
 * running the sample again replays every cell from the start.
 */
export function RecordsTableDemo() {
  const [completed, setCompleted] = React.useState(1)
  const [isRetried, setIsRetried] = React.useState(false)
  const isRunning = completed < sampleRecords.length

  React.useEffect(() => {
    if (!isRunning) return
    const timer = window.setTimeout(() => setCompleted((count) => count + 1), CELL_MILLISECONDS)
    return () => window.clearTimeout(timer)
  }, [completed, isRunning])

  const rows = sampleRecords.map((record, index): RecordsTableRow => {
    let cell: GeneratedCell = { status: "queued" }
    if (index < completed) {
      cell =
        record.id === "b" && !isRetried
          ? { status: "error", message: "Timed out" }
          : { status: "done", value: record.summary }
    } else if (index === completed) {
      cell = { status: "running" }
    }
    return {
      id: record.id,
      name: record.name,
      cells: { name: record.name, region: record.region },
      generated: { summary: cell },
    }
  })

  return (
    <div className="flex w-full max-w-xl min-w-0 flex-col items-start gap-[var(--hui-space-4)]">
      <RecordsTable
        label="Suppliers"
        columns={[
          { id: "name", header: "Supplier" },
          { id: "region", header: "Region" },
          { id: "summary", header: "Payment summary", isGenerated: true },
        ]}
        rows={rows}
        onRetry={() => setIsRetried(true)}
      />
      <Button
        variant="ghost"
        size="sm"
        className="text-[var(--hui-color-foreground-base-secondary)]"
        disabled={isRunning}
        onClick={() => {
          setIsRetried(false)
          setCompleted(0)
        }}
      >
        Run the sample again
      </Button>
    </div>
  )
}

```

## Overview [#overview]

Records Table is a table in which some columns are generated: an agent reads each record and fills in a summary, a category, a score. Each generated cell shows where it stands, and a line above the table counts how many are done.

It shows the state you pass for every cell. Running the agent, and deciding the order, are your application's work.

Use [Data Grid](/docs/product/data-grid) when people need to sort, resize, or edit columns. The Beautiful UI original also had column settings and resizing, which Data Grid already covers.

## Anatomy [#anatomy]

<Anatomy title="RecordsTable">
  <AnatomyItem name="Columns" description="Ordinary columns, and generated columns marked Generated in the header" />

  <AnatomyItem name="Generated cell" description="Queued, working, a value, or an error with Try again" />

  <AnatomyItem name="Progress" description="A count of generated cells that are done" />
</Anatomy>

Installing `records-table` brings [Button](/docs/components/button) and [Table](/docs/components/table) along as registry dependencies.

## Behavior [#behavior]

### Generated cells [#generated-cells]

A generated cell is `queued`, `running`, `done` with a value, or `error` with an optional message. A cell with no state reads as queued.

### Trying again [#trying-again]

Pass `onRetry` to show Try again in every failed cell. It calls your handler with the row and column ids. The button sits inside the line, so a failed cell does not make its row taller.

### Progress [#progress]

The line above the table counts done cells across every generated column. It is left out when the table has no generated columns.

## Accessibility [#accessibility]

The table uses native markup with column headers and is named by `label`. A generated column's header reads its name, then "Generated", set apart by a dot and a lighter weight. Queued, working, and failed are words in the cell, so no state depends on an icon or a color.

Try again is named with its column and row, such as "Try again: Payment summary for Harbor Paper Co.". The progress line is a polite status, so each completed cell is announced as a count, not as a re-reading of the table. With reduced motion, the working icon does not rotate.

| Key                                  | Action                            |
| ------------------------------------ | --------------------------------- |
| <kbd>Tab</kbd>                       | Move across the Try again buttons |
| <kbd>Enter</kbd> or <kbd>Space</kbd> | Try the focused cell again        |

## Installation [#installation]


  

  
    <CliBlock commands="[&#x22;@honestai/records-table&#x22;]" />
  

  
    
      
        Add the components it is built from.
      

      <CliBlock commands="[&#x22;button&#x22;, &#x22;table&#x22;]" />

      
        Copy and paste this file into your project.
      

      ### components/ai/records-table.tsx

```tsx
"use client"

import * as React from "react"
import {
  ArrowDown as ArrowDownIcon,
  ArrowUp as ArrowUpIcon,
  ChevronsUpDown as ChevronsUpDownIcon,
  CircleAlert as CircleAlertIcon,
  LoaderCircle as LoaderCircleIcon,
} from "honestui/icons"

import { cn } from "@/lib/utils"
import { Button } from "@/components/honest-ui/ui/button"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/honest-ui/ui/table"

// The frame is drawn here rather than by a Table variant, so the component
// keeps it when Table is installed from Honest UI. Cells wrap between words
// first, so short values such as "EMEA" do not split at narrow widths.
// The header sits on the plate itself, set apart by type and a hairline
// rather than a tinted band.
const tableFrame =
  "overflow-hidden rounded-[var(--hui-radius-4)] border-[0.5px] border-[var(--hui-color-border-base-primary)] bg-[var(--hui-color-background-base-primary)] shadow-[var(--hui-shadow-feather)] [&_th]:h-10 [&_th]:text-[var(--hui-color-foreground-base-secondary)]! [&_td]:h-11 [&_td]:text-[var(--hui-color-foreground-base-primary)] [&_td]:[overflow-wrap:break-word] [&_tbody>tr:last-child>td]:border-b-0"

export type RecordsTableColumn = {
  id: string
  header: string
  /** "end" right-aligns a numeric column, so place values line up. */
  align?: "start" | "end"
  /** False for a column of controls, such as row checkboxes, that sorting would not order. */
  sortable?: boolean
  /** Marks a column whose cells an agent fills in. */
  isGenerated?: boolean
  /** Shown in place of `header` in a column that doesn't sort, such as a select-all checkbox. */
  headerContent?: React.ReactNode
}

export type GeneratedCell =
  | { status: "queued" }
  | { status: "running" }
  | { status: "done"; value: React.ReactNode }
  | { status: "error"; message?: string }

export type RecordsTableRow = {
  id: string
  /** Names the row in button labels, such as the record's title. */
  name: string
  /** The cell for each ordinary column `id`. */
  cells: Record<string, React.ReactNode>
  /** The state of each generated column `id`. A missing entry reads as queued. */
  generated?: Record<string, GeneratedCell>
}

export type RecordsTableLabels = {
  generated: string
  queued: string
  running: string
  failed: string
  retry: string
  retryCell: (column: string, row: string) => string
  progress: (done: number, total: number) => string
}

export const defaultRecordsTableLabels: RecordsTableLabels = {
  generated: "Generated",
  queued: "Queued",
  running: "Working…",
  failed: "Failed",
  retry: "Try again",
  retryCell: (column, row) => `Try again: ${column} for ${row}`,
  progress: (done, total) => `${done} of ${total} generated cells done`,
}

export type RecordsTableSort = {
  columnId: string
  direction: "ascending" | "descending"
}

export type RecordsTableProps = {
  /** Names the table for screen readers. */
  label: string
  columns: RecordsTableColumn[]
  /** In display order; sorting them is the caller's. */
  rows: RecordsTableRow[]
  /** The column rows are ordered by, shown in its header. */
  sort?: RecordsTableSort | null
  /** Passing it makes each header a button that asks to sort by its column. */
  onSortChange?: (columnId: string) => void
  /** Passing it shows Try again in every failed cell. */
  onRetry?: (rowId: string, columnId: string) => void
  labels?: Partial<RecordsTableLabels>
  /** Controls for the whole table, such as a filter or export, in the card above the columns. */
  toolbar?: React.ReactNode
  className?: string
}

/**
 * A column's alignment. Text that follows a figure column gets extra room
 * at its start, so "15.7" and "1991" don't read as one value.
 */
function cellAlign(columns: RecordsTableColumn[], index: number) {
  const column = columns[index]
  if (column.align === "end") return "text-end"
  return columns[index - 1]?.align === "end" ? "ps-[var(--hui-space-6)]" : undefined
}

/**
 * A column header that sorts by its column. The arrow shows the current order;
 * an unsorted column shows a faint two-way arrow at rest, so sorting is
 * findable without hovering, and a stronger one on hover and focus.
 */
function SortButton({
  label,
  direction,
  end,
  onClick,
}: {
  label: string
  direction?: "ascending" | "descending"
  end: boolean
  onClick: () => void
}) {
  const Icon = direction === "ascending" ? ArrowUpIcon : direction === "descending" ? ArrowDownIcon : ChevronsUpDownIcon
  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(
        // Middle-aligned, so a header whose icon comes first (an end-aligned
        // column) sits on the same line as one whose label does.
        "group/sort -mx-[var(--hui-space-1)] inline-flex align-middle max-w-full cursor-pointer items-center gap-[var(--hui-space-1)] rounded-[var(--hui-radius-1)] px-[var(--hui-space-1)] text-inherit outline-none hover:text-[var(--hui-color-foreground-base-primary)] focus-visible:[outline:var(--hui-focus-ring)]",
        end && "flex-row-reverse"
      )}
    >
      <span>{label}</span>
      <Icon
        aria-hidden="true"
        className={cn(
          "size-3.5 shrink-0",
          !direction &&
            "opacity-30 group-hover/sort:opacity-70 group-focus-visible/sort:opacity-70"
        )}
      />
    </button>
  )
}

/**
 * A table of records where some columns are filled in by an agent, cell by
 * cell. Each generated cell shows the state you pass for it: queued, running,
 * done with a value, or failed.
 */
function RecordsTable({
  label,
  columns,
  rows,
  sort,
  onSortChange,
  onRetry,
  labels: labelsProp,
  toolbar,
  className,
}: RecordsTableProps) {
  const labels = { ...defaultRecordsTableLabels, ...labelsProp }
  const generatedColumns = columns.filter((column) => column.isGenerated)
  const total = generatedColumns.length * rows.length
  const done = rows.reduce(
    (count, row) =>
      count +
      generatedColumns.filter((column) => row.generated?.[column.id]?.status === "done").length,
    0
  )

  return (
    <div data-slot="records-table" className={cn("flex w-full min-w-0 flex-col gap-[var(--hui-space-3)]", className)}>
      {total > 0 && (
        // Above the table, next to the columns it counts, and announced as the
        // count changes so progress is heard without reading every cell. The
        // bar repeats the count for sighted readers, so it is hidden from
        // assistive technology.
        <div className="flex min-w-0 items-center gap-[var(--hui-space-4)]">
          <p
            role="status"
            className="m-0 min-w-0 tabular-nums text-[var(--hui-color-foreground-base-secondary)] [font-size:var(--hui-font-size-small)] [letter-spacing:var(--hui-letter-spacing-small)] [line-height:var(--hui-line-height-small)]"
          >
            {labels.progress(done, total)}
          </p>
          <span
            aria-hidden="true"
            className="relative h-1 w-16 shrink-0 overflow-hidden rounded-[var(--hui-radius-full)] bg-[var(--hui-color-background-neutral-primary)]"
          >
            <span
              className="absolute inset-y-0 start-0 rounded-[var(--hui-radius-full)] bg-[var(--hui-color-foreground-base-primary)] motion-safe:transition-[width] motion-safe:duration-300 motion-safe:ease-out"
              style={{ width: `${(done / total) * 100}%` }}
            />
          </span>
        </div>
      )}
      {/* The first and last cells clear the card's rounded corner, as the
          other cards inset their content. */}
      <div className={tableFrame}>
        {toolbar && (
          <div
            data-slot="records-table-toolbar"
            className="border-b-[length:var(--hui-border-width-surface)] border-[var(--hui-color-border-base-primary)] px-[var(--hui-space-5)] py-[var(--hui-space-3)]"
          >
            {toolbar}
          </div>
        )}
        <Table
          aria-label={label}
          className="[&_tr>*:first-child]:ps-[var(--hui-space-5)] [&_tr>*:last-child]:pe-[var(--hui-space-5)]"
        >
          <TableHeader>
            <TableRow>
              {columns.map((column, index) => (
                <TableHead
                  key={column.id}
                  scope="col"
                  aria-sort={
                    onSortChange && column.sortable !== false
                      ? sort?.columnId === column.id
                        ? sort.direction
                        : "none"
                      : undefined
                  }
                  className={cellAlign(columns, index)}
                >
                  {onSortChange && column.sortable !== false ? (
                    <SortButton
                      label={column.header}
                      direction={sort?.columnId === column.id ? sort.direction : undefined}
                      end={column.align === "end"}
                      onClick={() => onSortChange(column.id)}
                    />
                  ) : column.isGenerated ? (
                    // A separator and a lighter weight keep the marker from
                    // reading as part of the column name.
                    <span className="inline-flex flex-wrap items-baseline gap-x-[var(--hui-space-2)]">
                      <span>{column.header}</span>
                      <span className="inline-flex items-baseline gap-x-[var(--hui-space-2)] text-[var(--hui-color-foreground-base-secondary)] [font-weight:var(--hui-font-weight-regular)]">
                        <span aria-hidden="true">·</span>
                        {labels.generated}
                      </span>
                    </span>
                  ) : (
                    column.headerContent ?? column.header
                  )}
                </TableHead>
              ))}
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.map((row) => (
              <TableRow key={row.id}>
                {columns.map((column, index) => (
                  <TableCell
                    key={column.id}
                    data-generated={column.isGenerated ? "" : undefined}
                    className={cellAlign(columns, index)}
                  >
                    {column.isGenerated ? (
                      <GeneratedCellContent
                        cell={row.generated?.[column.id] ?? { status: "queued" }}
                        labels={labels}
                        retryLabel={labels.retryCell(column.header, row.name)}
                        onRetry={onRetry ? () => onRetry(row.id, column.id) : undefined}
                      />
                    ) : (
                      row.cells[column.id]
                    )}
                  </TableCell>
                ))}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </div>
  )
}

function GeneratedCellContent({
  cell,
  labels,
  retryLabel,
  onRetry,
}: {
  cell: GeneratedCell
  labels: RecordsTableLabels
  retryLabel: string
  onRetry?: () => void
}) {
  if (cell.status === "done") return <>{cell.value}</>

  if (cell.status === "error") {
    return (
      <span className="flex min-w-0 flex-wrap items-center gap-[var(--hui-space-2)]">
        <CircleAlertIcon strokeWidth={1.5} strokeLinecap="round"
          aria-hidden="true"
          className="size-3.5 shrink-0 text-[var(--hui-color-foreground-danger-primary)]"
        />
        <span className="min-w-0 break-words">{cell.message ?? labels.failed}</span>
        {onRetry && (
          // The negative block margin keeps the 24px button inside the 20px
          // line, so a failed cell does not make its row taller.
          <Button
            variant="outline"
            size="xs"
            aria-label={retryLabel}
            onClick={onRetry}
            className="-my-[var(--hui-space-1)] ms-[var(--hui-space-1)]"
          >
            {labels.retry}
          </Button>
        )}
      </span>
    )
  }

  // Working is louder than Queued, so the cell that is running stands out.
  return cell.status === "running" ? (
    <span className="flex items-center gap-[var(--hui-space-2)] text-[var(--hui-color-foreground-base-primary)]">
      <LoaderCircleIcon
        aria-hidden="true"
        className="size-3.5 shrink-0 text-[var(--hui-color-foreground-base-secondary)] motion-safe:animate-spin"
      />
      {labels.running}
    </span>
  ) : (
    <span className="text-[var(--hui-color-foreground-base-secondary)]">{labels.queued}</span>
  )
}

export { RecordsTable }

```

      
        Update the import paths to match your project setup.
      
    
  


## Usage [#usage]

```tsx
import { RecordsTable } from "@/components/ai/records-table"

<RecordsTable
  label="Suppliers"
  columns={[
    { id: "name", header: "Supplier" },
    { id: "summary", header: "Payment summary", isGenerated: true },
  ]}
  rows={suppliers.map((supplier) => ({
    id: supplier.id,
    name: supplier.name,
    cells: { name: supplier.name },
    generated: { summary: enrichment.cellFor(supplier.id) },
  }))}
  onRetry={(rowId, columnId) => enrichment.retry(rowId, columnId)}
/>
```

## Examples [#examples]

### All cells done [#all-cells-done]

A settled table. The progress line reads 2 of 2.

```tsx
import { RecordsTable } from "@/components/ai/records-table"

export function RecordsTableStaticExample() {
  return (
    <div className="w-full max-w-xl min-w-0">
      <RecordsTable
        label="Tickets"
        columns={[
          { id: "title", header: "Ticket" },
          { id: "category", header: "Category", isGenerated: true },
        ]}
        rows={[
          {
            id: "1",
            name: "Export totals are off",
            cells: { title: "Export totals are off" },
            generated: { category: { status: "done", value: "Billing" } },
          },
          {
            id: "2",
            name: "Cannot reset password",
            cells: { title: "Cannot reset password" },
            generated: { category: { status: "done", value: "Account" } },
          },
        ]}
      />
    </div>
  )
}

```

## API reference [#api-reference]

### RecordsTable [#recordstable]

| Prop        | Type                                        | Default  | Description                                             |
| ----------- | ------------------------------------------- | -------- | ------------------------------------------------------- |
| `label`     | string                                      | Required | Names the table.                                        |
| `columns`   | `RecordsTableColumn[]`                      | Required | Each has `id`, `header`, and an optional `isGenerated`. |
| `rows`      | `RecordsTableRow[]`                         | Required | The records.                                            |
| `onRetry`   | `(rowId: string, columnId: string) => void` | None     | Passing it shows Try again in failed cells.             |
| `labels`    | `Partial<RecordsTableLabels>`               | English  | State words, button names, and the progress text.       |
| `className` | string                                      | None     | Added to the root.                                      |

### Types [#types]

| Export            | Shape                                                                                                |
| ----------------- | ---------------------------------------------------------------------------------------------------- |
| `RecordsTableRow` | `id`, `name`, `cells` keyed by column `id`, and optional `generated` keyed by column `id`            |
| `GeneratedCell`   | `status` of `"queued"`, `"running"`, `"done"` (with `value`), or `"error"` (with optional `message`) |
