# Diff Table

> Review the rows an agent proposes to add or remove, clear the ones you do not want, and apply the rest.

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

```tsx
"use client"

import * as React from "react"

import { DiffTable, type DiffTableRow } from "@/components/ai/diff-table"

// Column names and types read as identifiers.
const mono = (value: string) => <code className="font-mono [font-size:13px]">{value}</code>

// Sample rows.
const sampleRows: DiffTableRow[] = [
  { id: "legacy", change: "removed", name: "legacy_region", cells: { column: mono("legacy_region"), type: mono("text") } },
  { id: "fax", change: "removed", name: "fax_number", cells: { column: mono("fax_number"), type: mono("text") } },
  { id: "email", change: "unchanged", name: "email", cells: { column: mono("email"), type: mono("text") } },
  { id: "region", change: "added", name: "region_id", cells: { column: mono("region_id"), type: mono("uuid") } },
]

/** This preview applies nothing. It shows the row ids your `onApply` receives. */
export function DiffTableDemo() {
  const [applied, setApplied] = React.useState<string[] | null>(null)

  return (
    <div className="flex w-full max-w-xl min-w-0 flex-col gap-[var(--hui-space-3)]">
      <DiffTable
        title="Proposed changes to the customers table"
        columns={[
          { id: "column", header: "Column" },
          { id: "type", header: "Type" },
        ]}
        rows={sampleRows}
        onApply={setApplied}
      />
      <p
        role="status"
        className="m-0 min-h-[1lh] text-[var(--hui-color-foreground-base-secondary)] [font-size:var(--hui-font-size-small)]"
      >
        {applied ? `onApply received: ${applied.join(", ")}` : ""}
      </p>
    </div>
  )
}

```

## Overview [#overview]

Diff Table shows edits an agent proposes to a table, one row for each addition and removal, with unchanged rows for context. Every change starts selected. The person clears the ones they do not want and applies the rest.

`onApply` receives the ids of the changes that stayed selected. Making the edits is your application's work.

Use [Change Review](/docs/product/change-review) for field-by-field changes to one object.

## Anatomy [#anatomy]

<Anatomy title="DiffTable">
  <AnatomyItem name="Title" description="What the edit is" />

  <AnatomyItem name="Change column" description="A checkbox and the word Add or Remove on each changed row" />

  <AnatomyItem name="Rows" description="Changed rows, tinted while selected, and unchanged rows" />

  <AnatomyItem name="Footer" description="A count of what is selected, and Apply" />
</Anatomy>

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

## Behavior [#behavior]

### Selecting changes [#selecting-changes]

A selected addition has a light green tint and a selected removal a light red one, with the row's name in the first column struck through. The other values stay readable, so you can review what is being removed. Clearing a change removes the tint, and the row is left as it is today. The footer counts what is selected, and Apply is disabled when nothing is.

### Applying [#applying]

If `onApply` returns a promise, Apply shows progress and the checkboxes lock until it settles. When it resolves, the footer confirms how many changes were applied and Apply goes away; if Apply had focus, the confirmation takes it. Apply stays focusable while it works. When it rejects, the footer shows an error and keeps the selection.

## Accessibility [#accessibility]

The table uses native markup with column headers and is named by its title. Each changed row has a real checkbox, named for what it does, such as "Include removing fax\_number". The word Add or Remove is in the row, so the tint is never the only cue.

The footer's count is a polite status, so it is announced as the selection changes. The error is an alert.

| Key                                  | Action                               |
| ------------------------------------ | ------------------------------------ |
| <kbd>Tab</kbd>                       | Move across the checkboxes and Apply |
| <kbd>Space</kbd>                     | Select or clear the focused change   |
| <kbd>Enter</kbd> or <kbd>Space</kbd> | Apply                                |

## Installation [#installation]


  

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

  
    
      
        Add the components it is built from.
      

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

      
        Copy and paste this file into your project.
      

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

```tsx
"use client"

import * as React from "react"
import {
  CircleAlert as CircleAlertIcon,
  CircleCheck as CircleCheckIcon,
  LoaderCircle as LoaderCircleIcon,
} from "honestui/icons"

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

export type DiffTableColumn = {
  id: string
  header: string
}

export type DiffTableRow = {
  id: string
  /** "added" and "removed" rows are proposed edits. "unchanged" rows give context. */
  change: "unchanged" | "added" | "removed"
  /** Names the row in its checkbox label, such as "Rocky Road". */
  name: string
  /** The cell for each column `id`. */
  cells: Record<string, React.ReactNode>
}

export type DiffTableLabels = {
  change: string
  added: string
  removed: string
  unchanged: string
  includeAdded: (name: string) => string
  includeRemoved: (name: string) => string
  summary: (additions: number, removals: number) => string
  apply: (count: number) => string
  applying: string
  applied: (count: number) => string
  error: string
}

export const defaultDiffTableLabels: DiffTableLabels = {
  change: "Change",
  added: "Add",
  removed: "Remove",
  unchanged: "No change",
  includeAdded: (name) => `Include adding ${name}`,
  includeRemoved: (name) => `Include removing ${name}`,
  summary: (additions, removals) =>
    `${additions} ${additions === 1 ? "addition" : "additions"}, ${removals} ${removals === 1 ? "removal" : "removals"} selected`,
  apply: (count) => (count === 1 ? "Apply 1 change" : `Apply ${count} changes`),
  applying: "Applying…",
  applied: (count) => (count === 1 ? "1 change applied." : `${count} changes applied.`),
  error: "The changes were not applied. Your selection is still here, so you can apply again.",
}

// Table's own header color is too light for small text, so these headers use the secondary foreground.
const headText = "text-[var(--hui-color-foreground-base-secondary)]!"

const regularText =
  "[font-size:var(--hui-font-size-regular)] [letter-spacing:var(--hui-letter-spacing-regular)] [line-height:var(--hui-line-height-regular)]"

// The title, footer, and the first and last cells keep clear of the card's
// rounded corners; inner cells keep the density's own padding.
const edgePadding = "px-[var(--hui-space-5)]"
const edgeCells = "[&_tr>*:first-child]:ps-[var(--hui-space-5)] [&_tr>*:last-child]:pe-[var(--hui-space-5)]"

// A change is marked by a hairline at the row's start edge and a glyph in its
// change cell, so the values themselves stay on the plain surface.
const rowEdge = {
  added: "[&>td:first-child]:shadow-[inset_2px_0_0_var(--hui-color-border-success-emphasis)]",
  removed: "[&>td:first-child]:shadow-[inset_2px_0_0_var(--hui-color-border-danger-emphasis)]",
} as const

const changeGlyph = {
  added: "text-[var(--hui-color-foreground-success-primary)]",
  removed: "text-[var(--hui-color-foreground-danger-primary)]",
} as const

export type DiffTableProps = Omit<React.ComponentProps<"div">, "children" | "title"> & {
  /** What the edit is, such as "Proposed menu cleanup". */
  title: string
  columns: DiffTableColumn[]
  rows: DiffTableRow[]
  /**
   * Receives the ids of the changed rows the person kept selected. Return a
   * promise to show progress; if it rejects, the selection is kept.
   */
  onApply: (includedRowIds: string[]) => void | Promise<void>
  labels?: Partial<DiffTableLabels>
}

/**
 * Row-level edits an agent proposes to a table. Every change starts selected;
 * the person clears the ones they do not want and then applies the rest.
 */
function DiffTable({
  title,
  columns,
  rows,
  onApply,
  labels: labelsProp,
  className,
  ...props
}: DiffTableProps) {
  const labels = React.useMemo(
    () => ({ ...defaultDiffTableLabels, ...labelsProp }),
    [labelsProp]
  )
  const [excluded, setExcluded] = React.useState<ReadonlySet<string>>(new Set())
  const [phase, setPhase] = React.useState<"editing" | "applying" | "applied" | "error">("editing")
  const titleId = React.useId()
  const statusRef = React.useRef<HTMLParagraphElement>(null)
  const applyRef = React.useRef<HTMLButtonElement>(null)
  // Apply goes away once the changes are in. If it had focus, hand focus to
  // the summary that replaces it rather than letting it fall to the page.
  const refocusStatus = React.useRef(false)
  React.useEffect(() => {
    if (phase !== "applied" || !refocusStatus.current) return
    refocusStatus.current = false
    statusRef.current?.focus()
  }, [phase])

  const changedRows = rows.filter((row) => row.change !== "unchanged")
  const included = changedRows.filter((row) => !excluded.has(row.id))
  const additions = included.filter((row) => row.change === "added").length
  const removals = included.length - additions
  const isLocked = phase === "applying" || phase === "applied"

  const apply = async () => {
    setPhase("applying")
    try {
      await onApply(included.map((row) => row.id))
      refocusStatus.current = document.activeElement === applyRef.current
      setPhase("applied")
    } catch {
      setPhase("error")
    }
  }

  return (
    <div
      data-slot="diff-table"
      data-phase={phase}
      className={cn(
        "@container/diff-table w-full min-w-0 overflow-hidden rounded-[var(--hui-radius-4)] border-[0.5px] border-[var(--hui-color-border-base-primary)] bg-[var(--hui-color-background-base-primary)] text-[var(--hui-color-foreground-base-primary)] shadow-[var(--hui-shadow-feather)]",
        regularText,
        edgeCells,
        className
      )}
      {...props}
    >
      <p
        id={titleId}
        className={cn(
          "m-0 py-[var(--hui-space-4)] [font-weight:var(--hui-font-weight-medium)]",
          edgePadding
        )}
      >
        {title}
      </p>
      {/* Short values such as "EMEA" wrap between words, never mid-word. */}
      <Table aria-labelledby={titleId} className="[&_td]:[overflow-wrap:break-word]">
        <TableHeader>
          <TableRow>
            <TableHead scope="col" className={headText}>{labels.change}</TableHead>
            {columns.map((column) => (
              <TableHead key={column.id} scope="col" className={headText}>
                {column.header}
              </TableHead>
            ))}
          </TableRow>
        </TableHeader>
        <TableBody>
          {rows.map((row) => {
            const isChange = row.change !== "unchanged"
            const isIncluded = isChange && !excluded.has(row.id)
            return (
              <TableRow
                key={row.id}
                data-change={row.change}
                data-included={isIncluded ? "" : undefined}
                className={cn(isIncluded && row.change !== "unchanged" && rowEdge[row.change])}
              >
                <TableCell>
                  {isChange ? (
                    <label className="flex cursor-pointer items-center gap-[var(--hui-space-3)]">
                      <Checkbox
                        size="small"
                        disabled={isLocked}
                        // Once applied, the checks read as a record, not as controls to change.
                        className="data-disabled:border-[var(--hui-color-border-base-secondary)]! data-disabled:bg-[var(--hui-color-background-neutral-secondary)]! data-disabled:shadow-none! data-disabled:[&_*]:text-[var(--hui-color-foreground-base-secondary)]!"
                        checked={isIncluded}
                        aria-label={
                          row.change === "added"
                            ? labels.includeAdded(row.name)
                            : labels.includeRemoved(row.name)
                        }
                        onCheckedChange={(checked) => {
                          setExcluded((current) => {
                            const next = new Set(current)
                            if (checked) next.delete(row.id)
                            else next.add(row.id)
                            return next
                          })
                          if (phase === "error") setPhase("editing")
                        }}
                      />
                      {/* The glyph and the word carry the change, so the edge color is never the only cue. */}
                      <span
                        aria-hidden="true"
                        className={cn(
                          "inline-flex items-center gap-[var(--hui-space-2)] whitespace-nowrap",
                          isIncluded ? "text-[var(--hui-color-foreground-base-primary)]" : "text-[var(--hui-color-foreground-base-secondary)]"
                        )}
                      >
                        <span
                          className={cn(
                            "inline-flex w-[1ch] justify-center font-mono [font-weight:var(--hui-font-weight-medium)]",
                            isIncluded ? changeGlyph[row.change as "added" | "removed"] : "text-[var(--hui-color-foreground-base-tertiary)]"
                          )}
                        >
                          {row.change === "added" ? "+" : "−"}
                        </span>
                        {row.change === "added" ? labels.added : labels.removed}
                      </span>
                    </label>
                  ) : (
                    // The spacer holds a checkbox's width, so every change word starts on one line.
                    <span className="flex items-center gap-[var(--hui-space-3)] whitespace-nowrap text-[var(--hui-color-foreground-base-secondary)]">
                      <span aria-hidden="true" className="size-[var(--hui-space-4)] shrink-0" />
                      <span className="inline-flex items-center gap-[var(--hui-space-2)]">
                        <span aria-hidden="true" className="inline-flex w-[1ch] justify-center font-mono text-[var(--hui-color-foreground-base-tertiary)]">·</span>
                        {labels.unchanged}
                      </span>
                    </span>
                  )}
                </TableCell>
                {columns.map((column, index) => (
                  <TableCell
                    key={column.id}
                    className={cn(
                      // The row's name is struck through; the other values stay readable for review.
                      isIncluded && row.change === "removed" && index === 0 && "line-through decoration-[var(--hui-color-foreground-danger-primary)] decoration-1",
                      row.change === "unchanged" ? "text-[var(--hui-color-foreground-base-secondary)]!" : "text-[var(--hui-color-foreground-base-primary)]"
                    )}
                  >
                    {row.cells[column.id]}
                  </TableCell>
                ))}
              </TableRow>
            )
          })}
        </TableBody>
      </Table>

      {/* On a narrow card the summary sits above the button, so neither clips. */}
      <div className={cn("flex flex-col items-start gap-[var(--hui-space-3)] border-t-[length:var(--hui-border-width-surface)] border-[var(--hui-color-border-base-primary)] py-[var(--hui-space-4)] @sm/diff-table:flex-row @sm/diff-table:items-center", edgePadding)}>
        <p
          ref={statusRef}
          tabIndex={-1}
          role={phase === "error" ? "alert" : "status"}
          className="m-0 flex min-w-0 items-start @sm/diff-table:me-auto gap-[var(--hui-space-3)] rounded-[var(--hui-radius-1)] text-[var(--hui-color-foreground-base-secondary)] tabular-nums outline-none focus-visible:[outline:var(--hui-focus-ring)]"
        >
          {phase === "applied" ? (
            <>
              <CircleCheckIcon
                aria-hidden="true"
                className="mt-[3px] size-3.5 shrink-0 text-[var(--hui-color-foreground-base-secondary)]"
              />
              <span className="text-[var(--hui-color-foreground-base-primary)]">
                {labels.applied(included.length)}
              </span>
            </>
          ) : phase === "error" ? (
            <>
              <CircleAlertIcon strokeWidth={1.5} strokeLinecap="round"
                aria-hidden="true"
                className="mt-[3px] size-3.5 shrink-0 text-[var(--hui-color-foreground-danger-primary)]"
              />
              <span className="min-w-0 text-[var(--hui-color-foreground-base-primary)]">{labels.error}</span>
            </>
          ) : (
            labels.summary(additions, removals)
          )}
        </p>
        {phase !== "applied" && (
          // aria-disabled while applying, so the pressed button keeps focus.
          <Button
            ref={applyRef}
            size="sm"
            disabled={included.length === 0}
            aria-disabled={phase === "applying" || undefined}
            className="aria-disabled:cursor-progress"
            onClick={() => {
              if (phase !== "applying") void apply()
            }}
          >
            {phase === "applying" && (
              <LoaderCircleIcon aria-hidden="true" className="size-3.5 motion-safe:animate-spin" />
            )}
            {phase === "applying" ? labels.applying : labels.apply(included.length)}
          </Button>
        )}
      </div>
    </div>
  )
}

export { DiffTable }

```

      
        Update the import paths to match your project setup.
      
    
  


## Usage [#usage]

```tsx
import { DiffTable } from "@/components/ai/diff-table"

<DiffTable
  title="Proposed changes to the customers table"
  columns={[
    { id: "column", header: "Column" },
    { id: "type", header: "Type" },
  ]}
  rows={proposal.rows}
  onApply={(rowIds) => agent.applyEdits(proposal.id, rowIds)}
/>
```

## Examples [#examples]

### An apply that fails [#an-apply-that-fails]

This preview rejects the first apply. The selection stays, and the second apply succeeds.

```tsx
"use client"

import * as React from "react"

import { DiffTable } from "@/components/ai/diff-table"

function wait(milliseconds: number) {
  return new Promise((resolve) => window.setTimeout(resolve, milliseconds))
}

/**
 * There is no server behind this preview. The first apply is rejected on
 * purpose to show the failure state; the next one resolves.
 */
export function DiffTableFailureExample() {
  const attempts = React.useRef(0)

  return (
    <div className="w-full max-w-lg min-w-0">
      <DiffTable
        title="Proposed tag cleanup"
        columns={[{ id: "tag", header: "Tag" }]}
        rows={[
          { id: "dup", change: "removed", name: "billing-old", cells: { tag: "billing-old" } },
          { id: "new", change: "added", name: "billing", cells: { tag: "billing" } },
        ]}
        onApply={async () => {
          attempts.current += 1
          await wait(900)
          if (attempts.current === 1) throw new Error("This preview rejects the first apply.")
        }}
      />
    </div>
  )
}

```

## API reference [#api-reference]

### DiffTable [#difftable]

Accepts native div props beyond those listed.

| Prop      | Type                                                  | Default  | Description                                                     |
| --------- | ----------------------------------------------------- | -------- | --------------------------------------------------------------- |
| `title`   | string                                                | Required | What the edit is.                                               |
| `columns` | `DiffTableColumn[]`                                   | Required | Each has `id` and `header`.                                     |
| `rows`    | `DiffTableRow[]`                                      | Required | Changed and unchanged rows, in order.                           |
| `onApply` | `(includedRowIds: string[]) => void \| Promise<void>` | Required | Receives the selected changes.                                  |
| `labels`  | `Partial<DiffTableLabels>`                            | English  | Column name, change words, checkbox names, and footer messages. |

### Types [#types]

| Export         | Shape                                                                                                |
| -------------- | ---------------------------------------------------------------------------------------------------- |
| `DiffTableRow` | `id`, `change` of `"unchanged"`, `"added"`, or `"removed"`, `name`, and `cells` keyed by column `id` |
