# Table

Rows ruled off by hand, three different lines so neighbours never match: striped, with ruled columns, sortable headings and an empty state.

Docs: https://ballpoint.st9wd.com/docs/table

```bash
npx shadcn@latest add @ballpoint/table
```

```tsx
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"

<Table variant="striped" columns>
  <TableHeader>
    <TableRow>
      <TableHead sort="asc" onSort={() => {}}>Invoice</TableHead>
      <TableHead>Amount</TableHead>
    </TableRow>
  </TableHeader>
  <TableBody>
    <TableRow>
      <TableCell>INV-001</TableCell>
      <TableCell>£12.50</TableCell>
    </TableRow>
  </TableBody>
</Table>
```

Props:

- `variant`: `"plain" | "striped"` (default `"plain"`). Plain rows, or every other row hatched with the pen.
- `columns`: `boolean` (default `false`). Rule the columns too: a different hand-drawn line for each, the way the rows are ruled.
- `size`: `"default" | "compact"` (default `"default"`). Row height.
- `TableHead sort`: `"asc" | "desc" | "none"`. Makes the heading a sort button. The chevron shows the direction, and the cell carries aria-sort.
- `TableHead onSort`: `() => void`. Called when the sort button is pressed.
- `TableRow`: `component`. Each row is ruled off underneath by hand, three different lines so neighbours never match. Hovered and selected rows (data-state=selected) are hatched.
- `TableEmpty`: `component`. A row that says there is nothing here, across colSpan columns.
- `TableFooter`: `component`. Totals, set in bold under the rows.
- `TableCaption`: `component`. A note under the table, in lighter ink.

## Example

```tsx
import { Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow } from "@/components/ui/table";

const orders = [
  ["INV-001", "Blue ballpoints, box of 50", "Paid", "£12.50"],
  ["INV-002", "Cream notebooks, A5", "Pending", "£24.00"],
  ["INV-003", "Fineliner set", "Paid", "£9.80"],
  ["INV-004", "Legal pads, pack of 6", "Refunded", "£15.00"],
];

export default function TableDemo() {
  return (
    <Table>
      <TableCaption>Recent orders.</TableCaption>
      <TableHeader>
        <TableRow>
          <TableHead>Invoice</TableHead>
          <TableHead>Item</TableHead>
          <TableHead>Status</TableHead>
          <TableHead className="text-right">Amount</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {orders.map(([invoice, item, status, amount]) => (
          <TableRow key={invoice}>
            <TableCell className="font-bold">{invoice}</TableCell>
            <TableCell>{item}</TableCell>
            <TableCell className="text-ink-2">{status}</TableCell>
            <TableCell className="text-right tabular-nums">{amount}</TableCell>
          </TableRow>
        ))}
      </TableBody>
      <TableFooter>
        <TableRow>
          <TableCell colSpan={3}>Total</TableCell>
          <TableCell className="text-right tabular-nums">£61.30</TableCell>
        </TableRow>
      </TableFooter>
    </Table>
  );
}
```

## Striped, ruled, compact

Every other row hatched, the columns ruled by hand, and the rows tightened.

```tsx
import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";

const pens = [
  ["Blue ballpoint", "14", "1,284", "Everyday"],
  ["Black fineliner", "9", "612", "Drawings"],
  ["Pencil", "21", "2,031", "Drafts"],
  ["Green ink", "3", "88", "Corrections"],
  ["Red pen", "2", "41", "Only when it matters"],
];

export default function TableStriped() {
  return (
    <Table variant="striped" columns size="compact">
      <TableCaption>Pens in use this year.</TableCaption>
      <TableHeader>
        <TableRow>
          <TableHead>Pen</TableHead>
          <TableHead className="text-right">Weeks</TableHead>
          <TableHead className="text-right">Pages</TableHead>
          <TableHead>Used for</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {pens.map(([pen, weeks, pages, use]) => (
          <TableRow key={pen}>
            <TableCell className="font-bold">{pen}</TableCell>
            <TableCell className="text-right tabular-nums">{weeks}</TableCell>
            <TableCell className="text-right tabular-nums">{pages}</TableCell>
            <TableCell className="text-ink-2">{use}</TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
}
```

## Sortable columns

A heading with sort is a button; its chevron points the way it is sorted.

```tsx
"use client";

import { useMemo, useState } from "react";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";

const rows = [
  { name: "Ada Lovelace", role: "Writer", pages: 412 },
  { name: "Grace Hopper", role: "Editor", pages: 268 },
  { name: "Katherine Johnson", role: "Illustrator", pages: 530 },
  { name: "Mary Jackson", role: "Writer", pages: 97 },
];

type Key = "name" | "role" | "pages";

export default function TableSortable() {
  const [sort, setSort] = useState<{ key: Key; dir: "asc" | "desc" }>({ key: "pages", dir: "desc" });
  const sorted = useMemo(() => {
    const out = [...rows].sort((a, b) => (a[sort.key] > b[sort.key] ? 1 : a[sort.key] < b[sort.key] ? -1 : 0));
    return sort.dir === "asc" ? out : out.reverse();
  }, [sort]);
  // A first press sorts a column one way, the next the other.
  const press = (key: Key) => setSort((s) => ({ key, dir: s.key === key && s.dir === "asc" ? "desc" : "asc" }));
  const state = (key: Key) => (sort.key === key ? sort.dir : "none");

  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead sort={state("name")} onSort={() => press("name")}>
            Name
          </TableHead>
          <TableHead sort={state("role")} onSort={() => press("role")}>
            Role
          </TableHead>
          <TableHead className="text-right" sort={state("pages")} onSort={() => press("pages")}>
            Pages
          </TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {sorted.map((row) => (
          <TableRow key={row.name}>
            <TableCell className="font-bold">{row.name}</TableCell>
            <TableCell className="text-ink-2">{row.role}</TableCell>
            <TableCell className="text-right tabular-nums">{row.pages}</TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
}
```

## Selectable rows

Checkboxes select rows; the header one is mixed when only some are picked.

```tsx
"use client";

import { useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";

const rows = [
  ["Ada Lovelace", "Writer", "Active"],
  ["Grace Hopper", "Editor", "Active"],
  ["Katherine Johnson", "Illustrator", "Away"],
] as const;

export default function TableSelectable() {
  const [picked, setPicked] = useState<string[]>(["Grace Hopper"]);
  const all = picked.length === rows.length;
  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead className="w-10">
            <Checkbox
              aria-label="Select all"
              checked={all}
              indeterminate={picked.length > 0 && !all}
              onCheckedChange={(on) => setPicked(on ? rows.map(([n]) => n) : [])}
              seed="ts-all"
            />
          </TableHead>
          <TableHead>Name</TableHead>
          <TableHead>Role</TableHead>
          <TableHead className="text-right">Status</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {rows.map(([name, role, status]) => (
          <TableRow key={name} data-state={picked.includes(name) ? "selected" : undefined}>
            <TableCell>
              <Checkbox
                aria-label={`Select ${name}`}
                checked={picked.includes(name)}
                onCheckedChange={(on) => setPicked((p) => (on ? [...p, name] : p.filter((x) => x !== name)))}
                seed={`ts-${name}`}
              />
            </TableCell>
            <TableCell className="font-bold">{name}</TableCell>
            <TableCell className="text-ink-2">{role}</TableCell>
            <TableCell className="text-right">
              <Badge variant={status === "Active" ? "default" : "outline"} seed={`ts-b-${name}`}>
                {status}
              </Badge>
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
}
```

## Nothing to show

TableEmpty says so across every column, when a filter leaves no rows.

```tsx
"use client";

import { useState } from "react";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableEmpty, TableHead, TableHeader, TableRow } from "@/components/ui/table";

const notebooks = [
  ["Cream A5", "Ruled", "96"],
  ["Legal pad", "Ruled", "50"],
  ["Sketchbook", "Plain", "120"],
  ["Graph pad", "Squared", "80"],
];

export default function TableEmptyExample() {
  const [query, setQuery] = useState("zzz");
  const shown = notebooks.filter(([name, kind]) => `${name} ${kind}`.toLowerCase().includes(query.trim().toLowerCase()));
  return (
    <div className="flex w-full flex-col gap-4">
      <Input aria-label="Filter notebooks" placeholder="Filter notebooks" value={query} onChange={(event) => setQuery(event.target.value)} className="max-w-xs" />
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Notebook</TableHead>
            <TableHead>Paper</TableHead>
            <TableHead className="text-right">Pages</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {shown.length ? (
            shown.map(([name, kind, pages]) => (
              <TableRow key={name}>
                <TableCell className="font-bold">{name}</TableCell>
                <TableCell className="text-ink-2">{kind}</TableCell>
                <TableCell className="text-right tabular-nums">{pages}</TableCell>
              </TableRow>
            ))
          ) : (
            <TableEmpty colSpan={3}>No notebook matches &quot;{query}&quot;. Try &quot;ruled&quot;.</TableEmpty>
          )}
        </TableBody>
      </Table>
    </div>
  );
}
```
