← ui

table

ui · paid

a table to read and edit: thousands of rows, sticky heads, a spreadsheet's keys

npx shadcn add @ag/table

A paid item: its source installs with a licence key, kept in .env.local as AG_LICENCE_KEY and sent from components.json. The source stays in your project and out of any public repository. The licence

components.json
{
  "registries": {
    "@ag": {
      "url": "https://ui.adriangalilea.com/r/{name}.json",
      "headers": { "Authorization": "Bearer ${AG_LICENCE_KEY}" }
    }
  }
}
Already installed? Preview an update
npx shadcn add @ag/table --dry-run

Your installed source stays unchanged until you update it. How updates work

Latest changes · 2026-11-16
  • Changed: a cell's note sets each code span in it in the cells' own face (codeSpans), the Cells engine's messages marking what they quote that way (` 5O.00 is not a number ); a staged cell's note quotes the value it was the same way (was 23.50 ). A note quoting with "…"` now reads as words.
Updated 2026-11-16 · release notes

also called data grid

shelf data & status

uses scrims, selection, keys, key-router, menu, scroll-area, scroll-thumb, shortcut, kbd, history, carry, cells, code-spans, tooltip

the demo above, verbatim

table.demo.tsx
"use client"

import "@/registry/base-nova/ui/edge-fade"
import { CircleCheck, CircleDashed, Copy, Trash2 } from "lucide-react"
import * as React from "react"
import { Sample } from "@/app/samples"
import { DataViewer } from "@/registry/base-nova/ui/data-view"
import { useHistory } from "@/registry/base-nova/ui/history"
import { Highlighted } from "@/registry/base-nova/ui/markdown-code"
import type { MenuEntry } from "@/registry/base-nova/ui/menu"
import { Switch } from "@/registry/base-nova/ui/switch"
import {
  type CellEdit,
  csv,
  Table,
  type TableCodec,
  type TableColumn,
  type TableDensity,
  type TableLines,
  useTableDocument,
} from "@/registry/base-nova/ui/table"
import { cells } from "@/registry/base-nova/ui/table-cells"
import {
  ToggleGroup,
  ToggleGroupItem,
} from "@/registry/base-nova/ui/toggle-group"

// ── The looks, a knob each: how rows and columns are told apart, the density, the
// columns' letters, the rows' numbers. Both examples wear them.

interface Look {
  lines: TableLines
  density: TableDensity
  letters: boolean
  numbers: boolean
}
const LOOK: Look = {
  lines: "rows",
  density: "comfortable",
  letters: false,
  numbers: true,
}

function Choice<T extends string>({
  label,
  value,
  options,
  onChange,
}: {
  label: string
  value: T
  options: readonly T[]
  onChange: (v: T) => void
}) {
  return (
    <ToggleGroup
      size="sm"
      aria-label={label}
      value={value}
      onValueChange={(v) => onChange(v as T)}
    >
      {options.map((o) => (
        <ToggleGroupItem key={o} value={o}>
          {o}
        </ToggleGroupItem>
      ))}
    </ToggleGroup>
  )
}

function LookKnobs({
  look,
  onChange,
}: {
  look: Look
  onChange: (look: Look) => void
}) {
  return (
    <>
      <Choice
        label="lines"
        value={look.lines}
        options={["rows", "grid", "bands"]}
        onChange={(lines) => onChange({ ...look, lines })}
      />
      <Choice
        label="density"
        value={look.density}
        options={["compact", "comfortable", "spacious"]}
        onChange={(density) => onChange({ ...look, density })}
      />
      <Switch
        size="sm"
        checked={look.letters}
        onCheckedChange={(letters) => onChange({ ...look, letters })}
      >
        letters
      </Switch>
      <Switch
        size="sm"
        checked={look.numbers}
        onCheckedChange={(numbers) => onChange({ ...look, numbers })}
      >
        numbers
      </Switch>
    </>
  )
}

/** A table and, beside it, the data it holds as the consumer holds it. */
function WithData({
  knobs,
  table,
  data,
}: {
  knobs: React.ReactNode
  table: React.ReactNode
  data: React.ReactNode
}) {
  return (
    <div className="w-full space-y-4">
      <div className="flex flex-wrap items-center gap-x-5 gap-y-3">{knobs}</div>
      <div className="grid w-full items-start gap-4 lg:grid-cols-[minmax(0,1fr)_20rem]">
        {table}
        {/* Bounds the data, never scrolls it: what is shown scrolls inside its own
            panes (the data viewer's, the CSV's), so nothing here clips their edges. */}
        <div className="flex max-h-96 min-h-0 flex-col">{data}</div>
      </div>
    </div>
  )
}

// #region file
// A document: text in, text out on every change. The same Table, its model a
// document's (useTableDocument): rows of text, columns that are data (add, name,
// move, delete them), its own verbs and history, written back through the codec.
const BUDGET = `item,category,cost,paid,on
fuel,travel,84.20,yes,2026-08-14
tolls,travel,23.50,yes,2026-08-14
cabin,stay,310.00,yes,2026-08-15
groceries,food,96.75,no,2026-08-15
ferry,travel,58.00,no,2026-08-17
sd cards,gear,42.99,yes,2026-08-12
`

// The same budget as a cell (github.com/adriangalilea/cells): each column's
// type in its header cell. `cost` is euros at least 0, so the ferry's 5O.00 (a letter
// O) is marked, never coerced, in red: it is wrong; the sd cards' date, not written
// yet, in yellow: it is absent. `paid` is a check written yes and no; `category` one
// of four, offered as a list. `spent` is computed, the running sum of the costs, its
// values stored in the file: edit a cost and every one below it follows in the same
// write; type a number over one and it is that row's override; type `=` and a formula,
// its names completed by the engine as they are typed.
const BUDGET_CELL = `---
type Category = travel|stay|food|gear
---
item: text!,category: Category,cost: EUR>=0,paid: yes/no,on: date,spent: EUR = SUM(cost[FIRST:THIS])
fuel,travel,84.20,yes,2026-08-14,84.20=
tolls,travel,23.50,yes,2026-08-14,107.70=
cabin,stay,310.00,yes,2026-08-15,417.70=
groceries,food,96.75,no,2026-08-15,514.45=
ferry,travel,5O.00,no,2026-08-17,514.45=
sd cards,gear,42.99,yes,,557.44=
`

function FileTable<Kept>({
  name,
  text,
  codec,
  look,
  onText,
}: {
  name: string
  text: string
  codec: TableCodec<Kept>
  look: Look
  onText: (text: string) => void
}) {
  const doc = useTableDocument({ text, codec, onChange: onText })
  return (
    <Table
      {...doc.props}
      {...look}
      label={name}
      className="max-h-96 rounded-lg border border-foreground/8"
    />
  )
}
// #endregion

// #region broken
// A Cells file whose header breaks: `on: dat`, a date's type misspelled. The column opens as
// text under the name it spells, its head marked with the engine's reason; every
// other column reads as typed.
const TRIP_CELL = `item: text!,cost: EUR>=0,on: dat
fuel,84.20,2026-08-14
cabin,310.00,2026-08-15
ferry,58.00,2026-08-17
`

function BrokenHeader() {
  const [text, setText] = React.useState(TRIP_CELL)
  return (
    <div className="grid w-full items-start gap-4 lg:grid-cols-[minmax(0,1fr)_20rem]">
      <FileTable
        name="trip.cells"
        text={TRIP_CELL}
        codec={cells}
        look={LOOK}
        onText={setText}
      />
      <div className="flex max-h-96 min-h-0 flex-col">
        <FileText name="trip.cells" text={text} lang="cells" />
      </div>
    </div>
  )
}
// #endregion

// #region looks
// How a Cells file's values look, said in the file and drawn by the table: each
// choice's word in its tint (`income#green`, a `#rrggbb` the same in every theme),
// money grouped with its negatives in parentheses and red, a balance red or green by
// a condition over the row, a score on a scale from red to green, a date in words,
// a paid row washed gray. The marks and the words are the browser's language; the
// text under each cell, what it edits, sorts and copies, is the file's.
const LEDGER_CELL = `---
type Kind = income#green|rent#red|food#orange|transfer#blue|gift#9b5de5|other
type Money = EUR
look Money: grouped, negative in parentheses, negative red
look balance: red when balance < budget, green when balance >= budget
look score: scale red..green
look on: as 'ddd D MMM YYYY'
look row: gray when paid
---
item: text!,kind: Kind,amount: Money,budget: Money,balance: Money,score: 0..10,on: date,paid: yes/no
salary,income,4200.00,4000.00,4200.00,9,2026-11-02,yes
rent,rent,-1350.00,-1400.00,2850.00,6,2026-11-03,yes
market,food,-86.40,-120.00,2763.60,7,2026-11-05,no
savings,transfer,-1000.00,-800.00,1763.60,4,2026-11-06,no
birthday,gift,-64.99,-50.00,1698.61,2,2026-11-08,no
refund,other,23.50,0.00,1722.11,10,2026-11-09,no
`

function Looks() {
  const [text, setText] = React.useState(LEDGER_CELL)
  return (
    <div className="grid w-full items-start gap-4 lg:grid-cols-[minmax(0,1fr)_20rem]">
      <FileTable
        name="ledger.cells"
        text={LEDGER_CELL}
        codec={cells}
        look={LOOK}
        onText={setText}
      />
      <div className="flex max-h-96 min-h-0 flex-col">
        <FileText name="ledger.cells" text={text} lang="cells" />
      </div>
    </div>
  )
}
// #endregion

/** The same budget, a million rows of it, invented as it is asked for and never kept
 *  as a file: every item its own (the key), every 1009th cost broken the ferry's way,
 *  so the problems are spread through the file. */
function millionRows(): string {
  const words = ["fuel", "tolls", "cabin", "groceries", "ferry", "sd cards"]
  const categories = ["travel", "travel", "stay", "food", "travel", "gear"]
  const lines = new Array<string>(1_000_001)
  lines[0] =
    "---\ntype Category = travel|stay|food|gear\n---\nitem: text!,category: Category,cost: EUR>=0,paid: yes/no,on: date"
  // mulberry32, seeded: the same file every time.
  let seed = 20260814
  const next = () => {
    seed = (seed + 0x6d2b79f5) | 0
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed)
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
    return (t ^ (t >>> 14)) >>> 0
  }
  for (let i = 0; i < 1_000_000; i++) {
    const k = next() % 6
    const cents = next() % 40000
    const cost =
      i % 1009 === 1008
        ? "5O.00"
        : `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`
    const day = 1 + (next() % 28)
    const month = 1 + (next() % 12)
    lines[i + 1] =
      `${words[k]} ${i + 1},${categories[k]},${cost},${next() % 3 === 0 ? "no" : "yes"},2026-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`
  }
  return `${lines.join("\n")}\n`
}

/** A file's text as the pane beside its table shows it: whole, or its first lines
 *  when it is too long to colour at once. */
function FileText({
  name,
  text,
  lang,
}: {
  name: string
  text: string
  lang: "csv" | "cells"
}) {
  const LINES = 60
  let cut = -1
  for (let n = 0; n < LINES && cut < text.length; n++) {
    cut = text.indexOf("\n", cut + 1)
    if (cut < 0) break
  }
  const whole = cut < 0 || cut === text.length - 1
  return (
    <>
      <Highlighted
        text={whole ? text : text.slice(0, cut)}
        lang={lang}
        filename={name}
        copy={whole}
        className="min-h-0 flex-1"
      />
      {!whole && (
        <p className="mt-2 text-xs text-muted-foreground">
          its first {LINES} lines, of {(text.length / 1_000_000).toFixed(1)} MB
        </p>
      )}
    </>
  )
}

// #region rows
// An app's own rows: typed values, never text. The table reads each column's text
// (what sorts, copies and is edited), the app keeps its numbers and booleans, and an
// edit comes back as text the app reads into its own types.
interface Expense {
  id: string
  item: string
  category: string
  cost: number
  paid: boolean
  on: string
}

const EXPENSES: Expense[] = [
  {
    id: "e1",
    item: "fuel",
    category: "travel",
    cost: 84.2,
    paid: true,
    on: "2026-08-14",
  },
  {
    id: "e2",
    item: "tolls",
    category: "travel",
    cost: 23.5,
    paid: true,
    on: "2026-08-14",
  },
  {
    id: "e3",
    item: "cabin",
    category: "stay",
    cost: 310,
    paid: true,
    on: "2026-08-15",
  },
  {
    id: "e4",
    item: "groceries",
    category: "food",
    cost: 96.75,
    paid: false,
    on: "2026-08-15",
  },
  {
    id: "e5",
    item: "ferry",
    category: "travel",
    cost: 58,
    paid: false,
    on: "2026-08-17",
  },
  {
    id: "e6",
    item: "sd cards",
    category: "gear",
    cost: 42.99,
    paid: true,
    on: "2026-08-12",
  },
]

/** Ten thousand of them: the table mounts only what the view shows. */
const ITEMS = [
  "fuel",
  "tolls",
  "cabin",
  "groceries",
  "ferry",
  "sd cards",
  "film",
]
const CATEGORIES = ["travel", "stay", "food", "gear"]
const MANY: Expense[] = Array.from({ length: 10_000 }, (_, i) => ({
  id: `m${i}`,
  item: `${ITEMS[i % ITEMS.length]} ${Math.floor(i / ITEMS.length) + 1}`,
  category: CATEGORIES[(i * 7) % CATEGORIES.length] as string,
  cost: ((i * 7919) % 40000) / 100,
  paid: (i * 31) % 3 !== 0,
  on: `2026-${String((i % 12) + 1).padStart(2, "0")}-${String((i % 28) + 1).padStart(2, "0")}`,
}))

const columnsOf = (rows: readonly Expense[]): TableColumn<Expense>[] => {
  const total = rows.reduce((sum, e) => sum + e.cost, 0)
  return [
    { id: "item", label: "item", text: (e) => e.item },
    // A few values repeated: read as choices, drawn as badges.
    { id: "category", label: "category", text: (e) => e.category },
    { id: "cost", label: "cost", text: (e) => e.cost.toFixed(2) },
    // A cell the app draws (`render`): text cannot say a share; it still sorts
    // and copies by its text.
    {
      id: "share",
      label: "share",
      width: "8rem",
      editable: false,
      text: (e) => `${((e.cost / total) * 100).toFixed(1)}%`,
      render: (e) => (
        <span className="h-1 w-full overflow-hidden rounded-full bg-foreground/10">
          <span
            className="block h-full w-(--share) rounded-full bg-foreground/55"
            style={
              { "--share": `${(e.cost / total) * 100}%` } as React.CSSProperties
            }
          />
        </span>
      ),
    },
    { id: "paid", label: "paid", text: (e) => (e.paid ? "yes" : "no") },
    { id: "on", label: "on", text: (e) => e.on },
  ]
}

/** An edit's text read back into the app's types. */
const applied = (rows: readonly Expense[], edits: readonly CellEdit[]) =>
  rows.map((e) => {
    const mine = edits.filter((x) => x.row === e.id)
    if (mine.length === 0) return e
    const typed = Object.fromEntries(
      mine.map(({ column, text }) => [
        column,
        column === "cost"
          ? Number(text) || 0
          : column === "paid"
            ? text === "yes"
            : text,
      ]),
    )
    return { ...e, ...typed } as Expense
  })

/** A server: answers after a moment, and refuses when told to. */
const server = (refuse: boolean) =>
  new Promise<void>((resolve, reject) =>
    setTimeout(
      () => (refuse ? reject(new Error("the server said no")) : resolve()),
      900,
    ),
  )

type Saving = "at once" | "a server" | "staged"
// #endregion

type Source = "your typed rows" | "a CSV file" | "a cell" | "a million rows"

/** One Table, its data from any source: an app's typed rows, or a document's text,
 *  plain or typed, a million rows of it too. Beside it, what is held, as the consumer
 *  holds it. */
function Budget() {
  const [source, setSource] = React.useState<Source>("your typed rows")
  const [csvText, setCsvText] = React.useState(BUDGET)
  const [cellText, setCellText] = React.useState(BUDGET_CELL)
  // Invented the first time it is chosen, then kept as it is edited.
  const [millionText, setMillionText] = React.useState<string | null>(null)
  const file = source !== "your typed rows"
  const text =
    source === "a cell"
      ? cellText
      : source === "a million rows"
        ? (millionText ?? "")
        : csvText
  const [look, setLook] = React.useState(LOOK)
  const [saving, setSaving] = React.useState<Saving>("at once")
  const [refuse, setRefuse] = React.useState(false)
  const [size, setSize] = React.useState<"6 rows" | "10 000 rows">("6 rows")
  const [rows, setRows] = React.useState(EXPENSES)
  const frame = React.useRef<HTMLDivElement>(null)
  const history = useHistory({ root: frame })
  // Every change a named step: the rows before and after.
  const change = (next: Expense[], label: string, offer = false) => {
    const before = rows
    setRows(next)
    history.record(
      { label, undo: () => setRows(before), redo: () => setRows(next) },
      { offer },
    )
  }
  const columns = React.useMemo(() => columnsOf(rows), [rows])
  const actions = (ids: readonly string[]): MenuEntry[] => {
    const chosen = rows.filter((e) => ids.includes(e.id))
    const them = ids.length === 1 ? "the row" : `${ids.length} rows`
    const allPaid = chosen.every((e) => e.paid)
    return [
      // The app's own verb, beside the ones every table has.
      {
        icon: allPaid ? <CircleDashed /> : <CircleCheck />,
        label: allPaid ? `mark ${them} unpaid` : `mark ${them} paid`,
        hint: "mod+shift+p",
        onSelect: () =>
          change(
            rows.map((e) =>
              ids.includes(e.id) ? { ...e, paid: !allPaid } : e,
            ),
            allPaid ? `mark ${them} unpaid` : `mark ${them} paid`,
          ),
      },
      {
        icon: <Copy />,
        label: `duplicate ${them}`,
        hint: "mod+shift+d",
        onSelect: () =>
          change(
            rows.flatMap((e) =>
              ids.includes(e.id)
                ? [e, { ...e, id: `${e.id}-copy-${Date.now()}` }]
                : [e],
            ),
            `duplicate ${them}`,
          ),
      },
      "separator",
      {
        icon: <Trash2 />,
        label: `delete ${them}`,
        hint: "mod+backspace",
        destructive: true,
        onSelect: () =>
          change(
            rows.filter((e) => !ids.includes(e.id)),
            `delete ${them}`,
            true,
          ),
      },
    ]
  }
  return (
    <WithData
      knobs={
        <>
          <Choice
            label="the data"
            value={source}
            options={[
              "your typed rows",
              "a CSV file",
              "a cell",
              "a million rows",
            ]}
            onChange={(s) => {
              if (s === "a million rows" && millionText === null)
                setMillionText(millionRows())
              setSource(s)
            }}
          />
          <LookKnobs look={look} onChange={setLook} />
          {/* How an app's rows are saved and how many: the app's. A document saves
              every change into its text. */}
          {source === "your typed rows" && (
            <>
              <Choice
                label="saving"
                value={saving}
                options={["at once", "a server", "staged"]}
                onChange={setSaving}
              />
              {saving === "a server" && (
                <Switch size="sm" checked={refuse} onCheckedChange={setRefuse}>
                  the server refuses
                </Switch>
              )}
              <Choice
                label="size"
                value={size}
                options={["6 rows", "10 000 rows"]}
                onChange={(s) => {
                  setSize(s)
                  setRows(s === "6 rows" ? EXPENSES : MANY)
                  history.clear()
                }}
              />
            </>
          )}
        </>
      }
      table={
        file ? (
          source === "a cell" ? (
            <FileTable
              // a document per file: each reads its own text once
              key="cells"
              name="budget.cells"
              text={BUDGET_CELL}
              codec={cells}
              look={look}
              onText={setCellText}
            />
          ) : source === "a million rows" ? (
            <FileTable
              key="million"
              name="budget-1m.cells"
              text={millionText ?? ""}
              codec={cells}
              look={look}
              onText={setMillionText}
            />
          ) : (
            <FileTable
              key="csv"
              name="budget.csv"
              text={BUDGET}
              codec={csv}
              look={look}
              onText={setCsvText}
            />
          )
        ) : (
          <Table
            // a new table for each way of saving: what was staged belongs to its mode
            key={saving}
            ref={frame}
            label="expenses"
            rows={rows}
            rowId={(e) => e.id}
            columns={columns}
            noun="expense"
            actions={actions}
            // Rows moved together, in their order: one named step.
            onMoveRows={(ids, to) => {
              const moving = new Set(ids)
              const rest = rows.filter((e) => !moving.has(e.id))
              const moved = rows.filter((e) => moving.has(e.id))
              change(
                [...rest.slice(0, to), ...moved, ...rest.slice(to)],
                ids.length === 1 ? "move the row" : `move ${ids.length} rows`,
              )
            }}
            staged={saving === "staged"}
            tint={(e) =>
              e.paid
                ? undefined
                : "color-mix(in oklab, var(--color-tone-warn) 8%, transparent)"
            }
            onEdit={
              saving === "at once"
                ? (edits) =>
                    change(
                      applied(rows, edits),
                      edits.length === 1
                        ? "edit a cell"
                        : `edit ${edits.length} cells`,
                    )
                : async (edits) => {
                    await server(saving === "a server" && refuse)
                    change(
                      applied(rows, edits),
                      edits.length === 1
                        ? "edit a cell"
                        : `edit ${edits.length} cells`,
                    )
                  }
            }
            onAddRow={() =>
              change(
                [
                  ...rows,
                  {
                    id: `e${Date.now()}`,
                    item: "",
                    category: "",
                    cost: 0,
                    paid: false,
                    on: "",
                  },
                ],
                "add a row",
              )
            }
            {...look}
            className="max-h-96 rounded-lg border border-foreground/8"
          />
        )
      }
      data={
        file ? (
          // A file holds text: shown as the file reads, what would be saved,
          // coloured by its own grammar (a cell's columns in rainbow, its types by
          // scope).
          <FileText
            name={
              source === "a CSV file"
                ? "budget.csv"
                : source === "a cell"
                  ? "budget.cells"
                  : "budget-1m.cells"
            }
            text={text}
            lang={source === "a CSV file" ? "csv" : "cells"}
          />
        ) : (
          // An app holds objects: shown open, each value in its own type, scrolled
          // in the viewer's own panes.
          <DataViewer
            value={rows}
            name="expenses"
            depth={2}
            itemName={(n) => (n.value as Expense).item}
            className="min-h-0 flex-1"
          />
        )
      }
    />
  )
}

export default function TableDemo() {
  return (
    <div className="space-y-8">
      <Sample
        name="budget"
        glance="wide"
        title="one table, any data"
        description="Switch the data: an app's typed rows (its numbers and booleans, its own verb and drawn cell, saved at once, through a server or staged), a CSV file's text (a document: its columns yours to add and rename), or a Cells file, whose header declares each column's type and formula, so the table edits by it and marks a cell that breaks it, read by the Cells engine as WebAssembly; or a million rows of it, invented as you choose them. Beside it, what the table holds, a file's text coloured by its own grammar."
        with="rows file"
      >
        <Budget />
      </Sample>
      <Sample
        name="broken-header"
        title="a header whose type breaks"
        with="file broken"
      >
        <BrokenHeader />
      </Sample>
      <Sample
        name="looks"
        title="how a file's values look"
        description="Tints and looks, written in the file and drawn by the table in your language; the text under each cell stays the file's."
        with="file looks"
      >
        <Looks />
      </Sample>
    </div>
  )
}