# Filter Table

> Filter a table's rows with a row of chips that each show how many rows they match.

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

```tsx
"use client"

import { FilterTable } from "@/components/ai/filter-table"

type AgentTask = { id: string; task: string; owner: string; status: "todo" | "running" | "done" }

// Sample tasks.
const sampleTasks: AgentTask[] = [
  { id: "1", task: "Reconcile March invoices", owner: "Billing agent", status: "running" },
  { id: "2", task: "Draft supplier emails", owner: "Outreach agent", status: "todo" },
  { id: "3", task: "Update the runbook", owner: "Docs agent", status: "done" },
  { id: "4", task: "Triage new tickets", owner: "Support agent", status: "running" },
  { id: "5", task: "Archive stale threads", owner: "Support agent", status: "todo" },
]

const statusLabel = { todo: "To do", running: "In progress", done: "Completed" }
// Status is a small dot and a word; only the dot carries the tone, so the
// column stays calm. Status is not an interaction, so it stays off accent.
const statusDot = {
  todo: "bg-[var(--hui-color-foreground-base-tertiary)]",
  running: "bg-[var(--hui-color-foreground-attention-primary)]",
  done: "bg-[var(--hui-color-foreground-base-primary)]",
}

export function FilterTableDemo() {
  return (
    <div className="w-full max-w-lg min-w-0">
      <FilterTable
        label="Agent tasks"
        rows={sampleTasks}
        getRowId={(row) => row.id}
        columns={[
          { id: "task", header: "Task", cell: (row) => row.task },
          { id: "owner", header: "Owner", cell: (row) => row.owner },
          {
            id: "status",
            header: "Status",
            cell: (row) => (
              <span className="inline-flex items-center gap-[var(--hui-space-3)] text-[var(--hui-color-foreground-base-secondary)]">
                <span aria-hidden="true" className={`size-1.5 shrink-0 rounded-full ${statusDot[row.status]}`} />
                {statusLabel[row.status]}
              </span>
            ),
          },
        ]}
        filters={[
          { id: "todo", label: "To do", matches: (row) => row.status === "todo" },
          { id: "running", label: "In progress", matches: (row) => row.status === "running" },
          { id: "done", label: "Completed", matches: (row) => row.status === "done" },
          { id: "blocked", label: "Blocked", matches: () => false },
        ]}
      />
    </div>
  )
}

```

## Overview [#overview]

Filter Table puts a row of chips above a table. Each chip is one filter and shows how many rows it matches. Pressing a chip shows only those rows.

The counts are computed from the rows you pass, so a chip never disagrees with the table under it.

Use [Data Table](/docs/product/data-table) when people also need search, sorting, selection, or pagination.

## Anatomy [#anatomy]

<Anatomy title="FilterTable">
  <AnatomyItem name="Chips" description="All, then one chip for each filter, with its count" />

  <AnatomyItem name="Table" description="The matching rows" />

  <AnatomyItem name="Empty row" description="A message when the chosen filter matches nothing" />
</Anatomy>

Installing `filter-table` brings [Table](/docs/components/table) along as a registry dependency.

## Behavior [#behavior]

### Filters [#filters]

One filter is active at a time. All shows every row. A filter is a function, `matches`, so it can test anything on the row.

### Empty [#empty]

A chip that matches no rows shows 0 and can still be pressed. The table then shows `emptyMessage` in place of the rows.

## Accessibility [#accessibility]

The chips are a named group of toggle buttons in one segmented control, and the active one reports that it is pressed. On narrow screens the row scrolls sideways instead of wrapping above the table, a fade at the end edge shows more chips are out of view, and the chosen chip scrolls into view. The fade matches the page background; set `--filter-table-surface` when the table sits on another surface. The table uses native table markup with column headers, and is named by `label`.

When the filter changes, a polite status announces how many rows are shown, as "Showing 2 of 5 rows". Pass `countLabel` to word it differently or translate it.

| Key                                           | Action                         |
| --------------------------------------------- | ------------------------------ |
| <kbd>Tab</kbd>                                | Move into and out of the chips |
| <kbd>ArrowLeft</kbd> or <kbd>ArrowRight</kbd> | Move between the chips         |
| <kbd>Enter</kbd> or <kbd>Space</kbd>          | Apply the focused filter       |

## Installation [#installation]


  

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

  
    
      
        Add the components it is built from.
      

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

      
        Copy and paste this file into your project.
      

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

```tsx
"use client"

import * as React from "react"

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

// 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 filters sit in the plate's top bar, so they read as the table's own
// tabs; the header row sits on the plate, set apart by type and a hairline.
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 FilterTableColumn<Row> = {
  id: string
  header: string
  cell: (row: Row) => React.ReactNode
}

export type FilterTableFilter<Row> = {
  id: string
  label: string
  matches: (row: Row) => boolean
}

export type FilterTableProps<Row> = {
  /** Names the table for screen readers. */
  label: string
  columns: FilterTableColumn<Row>[]
  rows: Row[]
  getRowId: (row: Row) => string
  /** One chip each. A chip shows how many rows it matches. */
  filters: FilterTableFilter<Row>[]
  /** The chip that shows every row. */
  allLabel?: string
  /** The group name read before the chips. */
  filtersLabel?: string
  /** Shown when the chosen filter matches no rows. */
  emptyMessage?: string
  /** Announced when the filter changes. Defaults to "Showing 3 of 12 rows". */
  countLabel?: (shown: number, total: number) => string
  activeFilter?: string | null
  defaultActiveFilter?: string | null
  onActiveFilterChange?: (filterId: string | null) => void
  className?: string
}

/**
 * A table with a segmented row of filters above it. Counts are computed from the
 * rows you pass, so a chip never disagrees with what it shows.
 */
function FilterTable<Row>({
  label,
  columns,
  rows,
  getRowId,
  filters,
  allLabel = "All",
  filtersLabel = "Filter rows",
  emptyMessage = "No rows match this filter.",
  countLabel = (shown, total) => `Showing ${shown} of ${total} rows`,
  activeFilter: activeFilterProp,
  defaultActiveFilter = null,
  onActiveFilterChange,
  className,
}: FilterTableProps<Row>) {
  const [uncontrolledFilter, setUncontrolledFilter] = React.useState(defaultActiveFilter)
  const activeFilter = activeFilterProp !== undefined ? activeFilterProp : uncontrolledFilter
  const active = filters.find((filter) => filter.id === activeFilter)
  const visibleRows = active ? rows.filter(active.matches) : rows

  const select = (filterId: string | null) => {
    if (activeFilterProp === undefined) setUncontrolledFilter(filterId)
    onActiveFilterChange?.(filterId)
  }

  // Segments are keyed by position, so a filter id can never collide with All.
  const chips = [
    { id: null as string | null, label: allLabel, count: rows.length },
    ...filters.map((filter) => ({
      id: filter.id as string | null,
      label: filter.label,
      count: rows.filter(filter.matches).length,
    })),
  ].map((chip, index) => ({ ...chip, value: String(index) }))
  const activeValue = chips.find((chip) => chip.id === (active?.id ?? null))?.value ?? "0"

  // Keep the chosen segment in view when the strip scrolls. Only the strip
  // scrolls; the page never moves. Skipped on first render.
  const stripRef = React.useRef<HTMLDivElement>(null)
  const shownValue = React.useRef(activeValue)
  React.useEffect(() => {
    if (shownValue.current === activeValue) return
    shownValue.current = activeValue
    const strip = stripRef.current
    const segment = strip?.querySelector<HTMLElement>("[data-pressed]")
    if (!strip || !segment) return
    const stripBox = strip.getBoundingClientRect()
    const segmentBox = segment.getBoundingClientRect()
    const inset = 32
    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches
    const behavior: ScrollBehavior = reduced ? "auto" : "smooth"
    if (segmentBox.left < stripBox.left + inset) {
      strip.scrollBy({ left: segmentBox.left - stripBox.left - inset, behavior })
    } else if (segmentBox.right > stripBox.right - inset) {
      strip.scrollBy({ left: segmentBox.right - stripBox.right + inset, behavior })
    }
  }, [activeValue])

  return (
    <div data-slot="filter-table" className={cn("flex w-full min-w-0 flex-col", tableFrame, className)}>
      {/* Scrolls sideways on narrow screens instead of wrapping above the table.
          A fade at the end edge shows more filters are out of view; set
          --filter-table-surface when the table sits on another surface. It follows
          the scroll position and clears at the end; where scroll-driven
          animation is unsupported, or nothing overflows, it stays hidden. */}
      <div className="relative min-w-0 border-b-[0.5px] border-[var(--hui-color-border-base-primary)] [timeline-scope:--filter-table-scroll]">
        <div ref={stripRef} className="flex min-w-0 overflow-x-auto px-[var(--hui-space-3)] py-[var(--hui-space-3)] [scroll-timeline:--filter-table-scroll_inline] [scrollbar-width:none]">
          <ToggleGroup
            size="sm"
            aria-label={filtersLabel}
            value={[activeValue]}
            onValueChange={(next) => {
              // Pressing the active segment would clear it; one filter always stays chosen.
              const chosen = chips.find((chip) => chip.value === next[0])
              if (chosen) select(chosen.id)
            }}
            // Flat tabs on the plate: the chosen one is a quiet fill, not a raised key.
            className="shrink-0 bg-transparent p-0 shadow-none"
          >
            {chips.map((chip) => (
              <Toggle
                key={chip.value}
                value={chip.value}
                className="h-[var(--hui-space-8)] rounded-[var(--hui-radius-2)] px-[var(--hui-space-3)] whitespace-nowrap hover:bg-[var(--hui-color-background-base-primary-hover)] data-pressed:bg-[var(--hui-color-background-neutral-secondary)] data-pressed:shadow-none data-pressed:hover:bg-[var(--hui-color-background-neutral-secondary)]"
              >
                {chip.label}
                <span className="tabular-nums text-[var(--hui-color-foreground-base-secondary)] [font-weight:var(--hui-font-weight-regular)]">
                  {chip.count}
                </span>
              </Toggle>
            ))}
          </ToggleGroup>
        </div>
        <div
          aria-hidden="true"
          className="pointer-events-none absolute inset-y-0 end-0 w-[var(--hui-space-9)] bg-[linear-gradient(to_left,var(--filter-table-surface,var(--hui-color-background-base-primary)),transparent)] opacity-0 rtl:bg-[linear-gradient(to_right,var(--filter-table-surface,var(--hui-color-background-base-primary)),transparent)]"
          style={{ animation: "hui-scroll-cue linear both", animationTimeline: "--filter-table-scroll" }}
        />
      </div>

      {/* The first and last cells clear the card's rounded corner. */}
      <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) => (
                <TableHead key={column.id} scope="col">
                  {column.header}
                </TableHead>
              ))}
            </TableRow>
          </TableHeader>
          <TableBody>
            {visibleRows.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={columns.length}
                  className="h-24! text-center text-[var(--hui-color-foreground-base-secondary)]!"
                >
                  {emptyMessage}
                </TableCell>
              </TableRow>
            ) : (
              visibleRows.map((row) => (
                <TableRow key={getRowId(row)}>
                  {columns.map((column) => (
                    <TableCell key={column.id}>{column.cell(row)}</TableCell>
                  ))}
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>
      <p role="status" className="sr-only">
        {countLabel(visibleRows.length, rows.length)}
      </p>
    </div>
  )
}

export { FilterTable }

```

      
        Update the import paths to match your project setup.
      
    
  


## Usage [#usage]

```tsx
import { FilterTable } from "@/components/ai/filter-table"

<FilterTable
  label="Agent tasks"
  rows={tasks}
  getRowId={(task) => task.id}
  columns={[
    { id: "title", header: "Task", cell: (task) => task.title },
    { id: "owner", header: "Owner", cell: (task) => task.owner },
  ]}
  filters={[
    { id: "open", label: "Open", matches: (task) => !task.isDone },
    { id: "done", label: "Completed", matches: (task) => task.isDone },
  ]}
/>
```

## Examples [#examples]

### Controlled filter [#controlled-filter]

The active filter is held in state and starts on Failed.

```tsx
"use client"

import * as React from "react"

import { FilterTable } from "@/components/ai/filter-table"

type Run = { id: string; name: string; result: "passed" | "failed" }

// Sample runs.
const sampleRuns: Run[] = [
  { id: "r1", name: "Export totals", result: "passed" },
  { id: "r2", name: "Staging migration", result: "failed" },
  { id: "r3", name: "Ticket triage", result: "passed" },
]

export function FilterTableControlledExample() {
  const [filter, setFilter] = React.useState<string | null>("failed")

  return (
    <div className="w-full max-w-lg min-w-0">
      <FilterTable
        label="Agent runs"
        rows={sampleRuns}
        getRowId={(row) => row.id}
        activeFilter={filter}
        onActiveFilterChange={setFilter}
        columns={[
          { id: "name", header: "Run", cell: (row) => row.name },
          {
            id: "result",
            header: "Result",
            cell: (row) => (
              <span className="inline-flex items-center gap-[var(--hui-space-3)] text-[var(--hui-color-foreground-base-secondary)]">
                <span
                  aria-hidden="true"
                  className={
                    row.result === "passed"
                      ? "size-1.5 shrink-0 rounded-full bg-[var(--hui-color-foreground-base-primary)]"
                      : "size-1.5 shrink-0 rounded-full bg-[var(--hui-color-foreground-danger-primary)]"
                  }
                />
                {row.result === "passed" ? "Passed" : "Failed"}
              </span>
            ),
          },
        ]}
        filters={[
          { id: "passed", label: "Passed", matches: (row) => row.result === "passed" },
          { id: "failed", label: "Failed", matches: (row) => row.result === "failed" },
        ]}
      />
    </div>
  )
}

```

## API reference [#api-reference]

### FilterTable [#filtertable]

| Prop                   | Type                                       | Default  | Description                                    |
| ---------------------- | ------------------------------------------ | -------- | ---------------------------------------------- |
| `label`                | string                                     | Required | Names the table.                               |
| `columns`              | `FilterTableColumn<Row>[]`                 | Required | Each has `id`, `header`, and `cell`.           |
| `rows`                 | `Row[]`                                    | Required | The rows to show and count.                    |
| `getRowId`             | `(row: Row) => string`                     | Required | A stable id for each row.                      |
| `filters`              | `FilterTableFilter<Row>[]`                 | Required | Each has `id`, `label`, and `matches`.         |
| `allLabel`             | string                                     | `"All"`  | The chip that shows every row.                 |
| `filtersLabel`         | string                                     | English  | The group name read before the chips.          |
| `emptyMessage`         | string                                     | English  | Shown when the filter matches no rows.         |
| `countLabel`           | `(shown: number, total: number) => string` | English  | Announced when the filter changes.             |
| `activeFilter`         | `string \| null`                           | None     | The active filter's `id`, when you control it. |
| `defaultActiveFilter`  | `string \| null`                           | `null`   | The initially active filter.                   |
| `onActiveFilterChange` | `(filterId: string \| null) => void`       | None     | Runs when a chip is pressed.                   |
