Data table
A shadcn/ui data table on TanStack Table: sortable columns, search and faceted filters, pagination, row selection with bulk actions, column visibility, expandable rows, inline editing, a sticky header and pinned columns.
npx shadcn@latest add https://dresscodeui.com/r/dresscode/data-table.json6 examples below; each installs the component with it. They wear whichever DressCode theme you install.
Sorting and pagination
Sort menus on every header, money right-aligned with totals, page size and page controls, and loading rows.
npx shadcn@latest add https://dresscodeui.com/r/dresscode/data-table-sorting-pagination.json// Invoices with sortable columns: each header opens a sort menu, money is right-aligned, the footer
// totals every invoice, and the pagination picks the page size. Refresh shows the loading rows.
"use client"
import * as React from "react"
import type { ColumnDef } from "@tanstack/react-table"
import { CircleAlertIcon, CircleCheckIcon, ClockIcon, FilePenLineIcon, PlusIcon, RefreshCwIcon } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { DataTable } from "@/components/ui/data-table"
import { DataTableColumnHeader } from "@/components/ui/data-table-column-header"
type Status = "Paid" | "Due" | "Overdue" | "Draft"
type Invoice = {
id: string
client: string
email: string
/** ISO dates sort as text; the cells format them. */
issued: string
due: string
status: Status
amount: number
balance: number
}
const CLIENTS = [
["Fernwood Studio", "mara@fernwood.studio"],
["Kato & Lee", "ken@katolee.com"],
["Juniper Labs", "theo@juniperlabs.dev"],
["Ola Bakery", "hello@olabakery.com"],
["Pellucid Health", "accounts@pellucid.health"],
["Alder Coffee", "sam@aldercoffee.com"],
["Mossgrove Architects", "paul@mossgrove.co.uk"],
["Saltmarsh Films", "nadia@saltmarsh.film"],
["Tidewater Co.", "hana@tidewater.co"],
["Quill & Ink", "bea@quillandink.co"],
] as const
const DAY = 86_400_000
const TODAY = Date.UTC(2026, 10, 24)
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
const iso = (t: number) => new Date(t).toISOString().slice(0, 10)
const formatDate = (d: string) => `${MONTHS[Number(d.slice(5, 7)) - 1]} ${Number(d.slice(8, 10))}, ${d.slice(0, 4)}`
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })
// 48 invoices over the last six months: drafts this week, a few late, the rest paid or not due yet.
const INVOICES: Invoice[] = Array.from({ length: 48 }, (_, i) => {
const [client, email] = CLIENTS[(i * 7 + 3) % CLIENTS.length]
const issuedAt = TODAY - (i * 4 + (i % 3)) * DAY
const dueAt = issuedAt + [14, 30, 30, 7][i % 4] * DAY
const amount = 480 + ((i * 37) % 23) * 185 + (i % 4) * 25
const status: Status = i < 3 ? "Draft" : dueAt >= TODAY ? "Due" : i % 6 === 1 && i < 34 ? "Overdue" : "Paid"
const balance = status === "Paid" ? 0 : status === "Overdue" && i % 4 === 1 ? Math.round(amount / 2) : amount
return { id: `INV-${1048 - i}`, client, email, issued: iso(issuedAt), due: iso(dueAt), status, amount, balance }
})
const STATUS: Record<Status, { icon: React.ComponentType<{ className?: string }>; variant: "secondary" | "outline" | "destructive"; rank: number }> = {
Overdue: { icon: CircleAlertIcon, variant: "destructive", rank: 0 },
Due: { icon: ClockIcon, variant: "outline", rank: 1 },
Draft: { icon: FilePenLineIcon, variant: "outline", rank: 2 },
Paid: { icon: CircleCheckIcon, variant: "secondary", rank: 3 },
}
function StatusBadge({ status }: { status: Status }) {
const { icon: Icon, variant } = STATUS[status]
return (
<Badge variant={variant} className={status === "Draft" ? "text-muted-foreground" : undefined}>
<Icon aria-hidden="true" />
{status}
</Badge>
)
}
const sumOf = (rows: { original: Invoice }[], key: "amount" | "balance") => rows.reduce((s, r) => s + r.original[key], 0)
const columns: ColumnDef<Invoice>[] = [
{
accessorKey: "id",
meta: { label: "Invoice" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Invoice" />,
cell: ({ row }) => <span className="font-medium tabular-nums">{row.original.id}</span>,
footer: "Total",
},
{
accessorKey: "client",
meta: { label: "Client" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Client" sortLabels={{ asc: "A to Z", desc: "Z to A" }} />,
cell: ({ row }) => (
<div className="flex min-w-40 flex-col">
<span className="font-medium">{row.original.client}</span>
<span className="text-xs text-muted-foreground">{row.original.email}</span>
</div>
),
},
{
accessorKey: "issued",
meta: { label: "Issued" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Issued" sortLabels={{ asc: "Oldest first", desc: "Newest first" }} />,
cell: ({ row }) => <span className="text-muted-foreground tabular-nums">{formatDate(row.original.issued)}</span>,
},
{
accessorKey: "due",
meta: { label: "Due" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Due" sortLabels={{ asc: "Soonest first", desc: "Latest first" }} />,
cell: ({ row }) => {
const { due, status } = row.original
const days = Math.round((TODAY - Date.parse(due)) / DAY)
return (
<div className="flex flex-col tabular-nums">
<span>{formatDate(due)}</span>
{status === "Overdue" ? (
<span className="text-xs text-destructive">{days} days late</span>
) : status === "Due" ? (
<span className="text-xs text-muted-foreground">{-days === 0 ? "Due today" : `In ${-days} ${-days === 1 ? "day" : "days"}`}</span>
) : null}
</div>
)
},
},
{
accessorKey: "status",
meta: { label: "Status" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Status" sortLabels={{ asc: "Overdue first", desc: "Paid first" }} />,
sortingFn: (a, b) => STATUS[a.original.status].rank - STATUS[b.original.status].rank,
cell: ({ row }) => <StatusBadge status={row.original.status} />,
},
{
accessorKey: "amount",
meta: { label: "Amount", align: "right" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Amount" sortLabels={{ asc: "Low to high", desc: "High to low" }} />,
cell: ({ row }) => <span className="font-medium tabular-nums">{usd.format(row.original.amount)}</span>,
footer: ({ table }) => <span className="tabular-nums">{usd.format(sumOf(table.getFilteredRowModel().rows, "amount"))}</span>,
},
{
accessorKey: "balance",
meta: { label: "Balance due", align: "right" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Balance due" sortLabels={{ asc: "Low to high", desc: "High to low" }} />,
cell: ({ row }) => (
<span className={row.original.balance ? "tabular-nums" : "text-muted-foreground tabular-nums"}>{usd.format(row.original.balance)}</span>
),
footer: ({ table }) => <span className="tabular-nums">{usd.format(sumOf(table.getFilteredRowModel().rows, "balance"))}</span>,
},
]
export default function DataTableSortingPagination() {
const [loading, setLoading] = React.useState(false)
const timer = React.useRef<ReturnType<typeof setTimeout>>(undefined)
React.useEffect(() => () => clearTimeout(timer.current), [])
const outstanding = INVOICES.reduce((s, i) => s + i.balance, 0)
const refresh = () => {
setLoading(true)
clearTimeout(timer.current)
timer.current = setTimeout(() => setLoading(false), 1200)
}
return (
<div className="mx-auto w-full max-w-5xl">
<div className="mb-4 flex flex-wrap items-end justify-between gap-3">
<div>
<h2 className="text-lg font-semibold">Invoices</h2>
<p className="text-sm text-muted-foreground">
{INVOICES.length} invoices, <span className="tabular-nums">{usd.format(outstanding)}</span> outstanding
</p>
</div>
<div className="flex gap-2">
<Button variant="outline" onClick={refresh} disabled={loading}>
<RefreshCwIcon className={loading ? "motion-safe:animate-spin" : undefined} />
{loading ? "Refreshing" : "Refresh"}
</Button>
<Button>
<PlusIcon />
New invoice
</Button>
</div>
</div>
<DataTable
caption="Invoices"
columns={columns}
data={INVOICES}
getRowId={(row) => row.id}
loading={loading}
initialState={{ sorting: [{ id: "issued", desc: true }] }}
rowLabel={{ singular: "invoice", plural: "invoices" }}
/>
</div>
)
}Search and filters
Search across columns, faceted status and client filters with counts, a reset button and a column visibility menu.
npx shadcn@latest add https://dresscodeui.com/r/dresscode/data-table-filters.json// Invoices you can narrow down: search across invoice numbers, clients and emails, faceted filters
// for status and client with live counts, a reset button, and a menu to show or hide columns.
"use client"
import type { ColumnDef } from "@tanstack/react-table"
import { CircleAlertIcon, CircleCheckIcon, ClockIcon, FilePenLineIcon, SearchIcon, SearchXIcon, XIcon } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group"
import { DataTable } from "@/components/ui/data-table"
import { DataTableColumnHeader } from "@/components/ui/data-table-column-header"
import { DataTableFacetedFilter, facetedFilterFn } from "@/components/ui/data-table-faceted-filter"
import { DataTableViewOptions } from "@/components/ui/data-table-view-options"
type Status = "Paid" | "Due" | "Overdue" | "Draft"
type Invoice = {
id: string
client: string
email: string
issued: string
due: string
status: Status
amount: number
}
const CLIENTS = [
["Fernwood Studio", "mara@fernwood.studio"],
["Kato & Lee", "ken@katolee.com"],
["Juniper Labs", "theo@juniperlabs.dev"],
["Ola Bakery", "hello@olabakery.com"],
["Pellucid Health", "accounts@pellucid.health"],
["Alder Coffee", "sam@aldercoffee.com"],
["Mossgrove Architects", "paul@mossgrove.co.uk"],
["Saltmarsh Films", "nadia@saltmarsh.film"],
["Tidewater Co.", "hana@tidewater.co"],
["Quill & Ink", "bea@quillandink.co"],
] as const
const DAY = 86_400_000
const TODAY = Date.UTC(2026, 10, 24)
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
const iso = (t: number) => new Date(t).toISOString().slice(0, 10)
const formatDate = (d: string) => `${MONTHS[Number(d.slice(5, 7)) - 1]} ${Number(d.slice(8, 10))}, ${d.slice(0, 4)}`
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })
const INVOICES: Invoice[] = Array.from({ length: 52 }, (_, i) => {
const [client, email] = CLIENTS[(i * 7 + 3) % CLIENTS.length]
const issuedAt = TODAY - (i * 4 + (i % 3)) * DAY
const dueAt = issuedAt + [14, 30, 30, 7][i % 4] * DAY
const amount = 480 + ((i * 37) % 23) * 185 + (i % 4) * 25
const status: Status = i < 3 ? "Draft" : dueAt >= TODAY ? "Due" : i % 6 === 1 && i < 34 ? "Overdue" : "Paid"
return { id: `INV-${1052 - i}`, client, email, issued: iso(issuedAt), due: iso(dueAt), status, amount }
})
const STATUS_OPTIONS = [
{ value: "Draft", label: "Draft", icon: FilePenLineIcon },
{ value: "Due", label: "Due", icon: ClockIcon },
{ value: "Overdue", label: "Overdue", icon: CircleAlertIcon },
{ value: "Paid", label: "Paid", icon: CircleCheckIcon },
]
const CLIENT_OPTIONS = CLIENTS.map(([name]) => ({ value: name, label: name })).sort((a, b) => a.label.localeCompare(b.label))
const BADGE: Record<Status, "secondary" | "outline" | "destructive"> = { Paid: "secondary", Due: "outline", Overdue: "destructive", Draft: "outline" }
const columns: ColumnDef<Invoice>[] = [
{
accessorKey: "id",
meta: { label: "Invoice" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Invoice" />,
cell: ({ row }) => <span className="font-medium tabular-nums">{row.original.id}</span>,
},
{
accessorKey: "client",
meta: { label: "Client" },
filterFn: facetedFilterFn,
header: ({ column }) => <DataTableColumnHeader column={column} title="Client" sortLabels={{ asc: "A to Z", desc: "Z to A" }} />,
cell: ({ row }) => <span className="font-medium">{row.original.client}</span>,
},
{
accessorKey: "email",
meta: { label: "Billing email" },
enableSorting: false,
header: ({ column }) => <DataTableColumnHeader column={column} title="Billing email" />,
cell: ({ row }) => <span className="text-muted-foreground">{row.original.email}</span>,
},
{
accessorKey: "issued",
meta: { label: "Issued" },
enableGlobalFilter: false,
header: ({ column }) => <DataTableColumnHeader column={column} title="Issued" sortLabels={{ asc: "Oldest first", desc: "Newest first" }} />,
cell: ({ row }) => <span className="text-muted-foreground tabular-nums">{formatDate(row.original.issued)}</span>,
},
{
accessorKey: "due",
meta: { label: "Due" },
enableGlobalFilter: false,
header: ({ column }) => <DataTableColumnHeader column={column} title="Due" sortLabels={{ asc: "Soonest first", desc: "Latest first" }} />,
cell: ({ row }) => <span className="tabular-nums">{formatDate(row.original.due)}</span>,
},
{
accessorKey: "status",
meta: { label: "Status" },
filterFn: facetedFilterFn,
enableGlobalFilter: false,
header: ({ column }) => <DataTableColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const option = STATUS_OPTIONS.find((o) => o.value === row.original.status)!
return (
<Badge variant={BADGE[row.original.status]} className={row.original.status === "Draft" ? "text-muted-foreground" : undefined}>
<option.icon aria-hidden="true" />
{option.label}
</Badge>
)
},
},
{
accessorKey: "amount",
meta: { label: "Amount", align: "right" },
enableGlobalFilter: false,
header: ({ column }) => <DataTableColumnHeader column={column} title="Amount" sortLabels={{ asc: "Low to high", desc: "High to low" }} />,
cell: ({ row }) => <span className="font-medium tabular-nums">{usd.format(row.original.amount)}</span>,
},
]
export default function DataTableFilters() {
return (
<div className="mx-auto w-full max-w-5xl">
<DataTable
caption="Invoices"
columns={columns}
data={INVOICES}
getRowId={(row) => row.id}
initialState={{ sorting: [{ id: "issued", desc: true }], columnFilters: [{ id: "status", value: ["Draft", "Due", "Overdue"] }] }}
rowLabel={{ singular: "invoice", plural: "invoices" }}
empty={(table) => (
<div className="flex flex-col items-center gap-1.5 py-4">
<SearchXIcon aria-hidden="true" className="mb-1 size-6 text-muted-foreground" />
<p className="font-medium text-foreground">No invoices match</p>
<p>Try another search, or clear the filters to see all {INVOICES.length} invoices.</p>
<Button
variant="outline"
size="sm"
className="mt-2"
onClick={() => {
table.resetColumnFilters(true)
table.setGlobalFilter("")
}}
>
Clear filters
</Button>
</div>
)}
toolbar={(table) => {
const query = (table.getState().globalFilter as string | undefined) ?? ""
const filtered = query !== "" || table.getState().columnFilters.length > 0
return (
<div className="flex flex-wrap items-center gap-2">
<InputGroup className="w-full sm:w-72">
<InputGroupAddon>
<SearchIcon />
</InputGroupAddon>
<InputGroupInput
type="search"
value={query}
onChange={(e) => table.setGlobalFilter(e.target.value)}
onKeyDown={(e) => e.key === "Escape" && table.setGlobalFilter("")}
placeholder="Search invoices, clients, emails"
aria-label="Search invoices"
className="[&::-webkit-search-cancel-button]:hidden"
/>
{query ? (
<InputGroupAddon align="inline-end">
<InputGroupButton size="icon-xs" onClick={() => table.setGlobalFilter("")} aria-label="Clear search">
<XIcon />
</InputGroupButton>
</InputGroupAddon>
) : null}
</InputGroup>
<DataTableFacetedFilter column={table.getColumn("status")} title="Status" options={STATUS_OPTIONS} />
<DataTableFacetedFilter column={table.getColumn("client")} title="Client" options={CLIENT_OPTIONS} />
{filtered ? (
<Button
variant="ghost"
size="sm"
onClick={() => {
table.resetColumnFilters(true)
table.setGlobalFilter("")
}}
>
Reset
<XIcon />
</Button>
) : null}
<DataTableViewOptions table={table} className="ml-auto" />
</div>
)
}}
/>
</div>
)
}Row selection and bulk actions
Checkboxes with select all and shift-click ranges, a bulk bar to remind, export or delete, and a menu on each row.
npx shadcn@latest add https://dresscodeui.com/r/dresscode/data-table-row-selection.json// Pick invoices with checkboxes (the header picks the page, shift-click picks a range) and act on
// them at once: send reminders for the unpaid ones, export a CSV, or delete after a confirm. Each
// row also has its own actions menu. What happened shows above the table, with an undo for deletes.
"use client"
import * as React from "react"
import type { ColumnDef, Table } from "@tanstack/react-table"
import {
CircleAlertIcon,
CircleCheckIcon,
ClockIcon,
CopyIcon,
DownloadIcon,
EyeIcon,
FilePenLineIcon,
MoreHorizontalIcon,
SearchIcon,
SendIcon,
Trash2Icon,
XIcon,
} from "lucide-react"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group"
import { DataTable, selectColumn } from "@/components/ui/data-table"
import { DataTableColumnHeader } from "@/components/ui/data-table-column-header"
type Status = "Paid" | "Due" | "Overdue" | "Draft"
type Invoice = {
id: string
client: string
email: string
due: string
status: Status
amount: number
}
const CLIENTS = [
["Fernwood Studio", "mara@fernwood.studio"],
["Kato & Lee", "ken@katolee.com"],
["Juniper Labs", "theo@juniperlabs.dev"],
["Ola Bakery", "hello@olabakery.com"],
["Pellucid Health", "accounts@pellucid.health"],
["Alder Coffee", "sam@aldercoffee.com"],
["Mossgrove Architects", "paul@mossgrove.co.uk"],
["Saltmarsh Films", "nadia@saltmarsh.film"],
["Tidewater Co.", "hana@tidewater.co"],
["Quill & Ink", "bea@quillandink.co"],
] as const
const DAY = 86_400_000
const TODAY = Date.UTC(2026, 10, 24)
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
const iso = (t: number) => new Date(t).toISOString().slice(0, 10)
const formatDate = (d: string) => `${MONTHS[Number(d.slice(5, 7)) - 1]} ${Number(d.slice(8, 10))}, ${d.slice(0, 4)}`
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })
const INVOICES: Invoice[] = Array.from({ length: 40 }, (_, i) => {
const [client, email] = CLIENTS[(i * 7 + 3) % CLIENTS.length]
const issuedAt = TODAY - (i * 4 + (i % 3)) * DAY
const dueAt = issuedAt + [14, 30, 30, 7][i % 4] * DAY
const amount = 480 + ((i * 37) % 23) * 185 + (i % 4) * 25
const status: Status = i < 3 ? "Draft" : dueAt >= TODAY ? "Due" : i % 6 === 1 && i < 34 ? "Overdue" : "Paid"
return { id: `INV-${1040 - i}`, client, email, due: iso(dueAt), status, amount }
})
const STATUS: Record<Status, { icon: React.ComponentType<{ className?: string }>; variant: "secondary" | "outline" | "destructive" }> = {
Overdue: { icon: CircleAlertIcon, variant: "destructive" },
Due: { icon: ClockIcon, variant: "outline" },
Draft: { icon: FilePenLineIcon, variant: "outline" },
Paid: { icon: CircleCheckIcon, variant: "secondary" },
}
const unpaid = (i: Invoice) => i.status === "Due" || i.status === "Overdue"
const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
function toCsv(rows: Invoice[]) {
const quote = (v: string | number) => (/[",\n]/.test(String(v)) ? `"${String(v).replace(/"/g, '""')}"` : String(v))
const head = ["Invoice", "Client", "Email", "Due", "Status", "Amount"]
return [head, ...rows.map((r) => [r.id, r.client, r.email, r.due, r.status, r.amount.toFixed(2)])].map((line) => line.map(quote).join(",")).join("\n")
}
type Notice = { text: string; undo?: Invoice[] }
export default function DataTableRowSelection() {
const [data, setData] = React.useState(INVOICES)
const [notice, setNotice] = React.useState<Notice | null>(null)
// Ids waiting for the delete confirm, and the table whose selection to clear afterwards.
const [confirm, setConfirm] = React.useState<{ ids: string[]; table?: Table<Invoice> } | null>(null)
const remind = React.useCallback((rows: Invoice[]) => {
const due = rows.filter(unpaid)
const clients = new Set(due.map((r) => r.client))
setNotice({ text: `Sent ${plural(due.length, "reminder")} to ${clients.size === 1 ? [...clients][0] : plural(clients.size, "client")}.` })
}, [])
const markPaid = React.useCallback((id: string) => {
setData((rows) => rows.map((r) => (r.id === id ? { ...r, status: "Paid" } : r)))
setNotice({ text: `${id} marked as paid.` })
}, [])
const duplicate = React.useCallback((invoice: Invoice) => {
setData((rows) => {
const next = Math.max(...rows.map((r) => Number(r.id.slice(4)))) + 1
return [{ ...invoice, id: `INV-${next}`, status: "Draft" }, ...rows]
})
setNotice({ text: `Copied ${invoice.id} to a new draft.` })
}, [])
const exportCsv = (rows: Invoice[]) => {
const name = "invoices-2026-11-24.csv"
const url = URL.createObjectURL(new Blob([toCsv(rows)], { type: "text/csv" }))
const a = Object.assign(document.createElement("a"), { href: url, download: name })
a.click()
URL.revokeObjectURL(url)
setNotice({ text: `Exported ${plural(rows.length, "invoice")} to ${name}.` })
}
const remove = () => {
if (!confirm) return
const gone = data.filter((r) => confirm.ids.includes(r.id))
setData((rows) => rows.filter((r) => !confirm.ids.includes(r.id)))
confirm.table?.setRowSelection((selected) => Object.fromEntries(Object.entries(selected).filter(([id]) => !confirm.ids.includes(id))))
setNotice({ text: `Deleted ${gone.length === 1 ? gone[0].id : plural(gone.length, "invoice")}.`, undo: gone })
setConfirm(null)
}
const undo = (rows: Invoice[]) => {
setData((current) => [...current, ...rows].sort((a, b) => Number(b.id.slice(4)) - Number(a.id.slice(4))))
setNotice({ text: `Restored ${rows.length === 1 ? rows[0].id : plural(rows.length, "invoice")}.` })
}
const columns = React.useMemo<ColumnDef<Invoice>[]>(
() => [
selectColumn<Invoice>({ label: (row) => row.original.id }),
{
accessorKey: "id",
meta: { label: "Invoice" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Invoice" />,
cell: ({ row }) => <span className="font-medium tabular-nums">{row.original.id}</span>,
},
{
accessorKey: "client",
meta: { label: "Client" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Client" sortLabels={{ asc: "A to Z", desc: "Z to A" }} />,
cell: ({ row }) => (
<div className="flex min-w-40 flex-col">
<span className="font-medium">{row.original.client}</span>
<span className="text-xs text-muted-foreground">{row.original.email}</span>
</div>
),
},
{
accessorKey: "due",
meta: { label: "Due" },
enableGlobalFilter: false,
header: ({ column }) => <DataTableColumnHeader column={column} title="Due" sortLabels={{ asc: "Soonest first", desc: "Latest first" }} />,
cell: ({ row }) => <span className="text-muted-foreground tabular-nums">{formatDate(row.original.due)}</span>,
},
{
accessorKey: "status",
meta: { label: "Status" },
enableGlobalFilter: false,
header: ({ column }) => <DataTableColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const { icon: Icon, variant } = STATUS[row.original.status]
return (
<Badge variant={variant} className={row.original.status === "Draft" ? "text-muted-foreground" : undefined}>
<Icon aria-hidden="true" />
{row.original.status}
</Badge>
)
},
},
{
accessorKey: "amount",
meta: { label: "Amount", align: "right" },
enableGlobalFilter: false,
header: ({ column }) => <DataTableColumnHeader column={column} title="Amount" sortLabels={{ asc: "Low to high", desc: "High to low" }} />,
cell: ({ row }) => <span className="font-medium tabular-nums">{usd.format(row.original.amount)}</span>,
},
{
id: "actions",
enableHiding: false,
meta: { headerClassName: "w-14", cellClassName: "w-14 text-right" },
header: () => <span className="sr-only">Actions</span>,
cell: ({ row, table }) => {
const invoice = row.original
return (
<DropdownMenu>
<DropdownMenuTrigger render={<Button variant="ghost" size="icon-sm" className="-mr-1.5 data-popup-open:bg-muted" aria-label={`Actions for ${invoice.id}`} />}>
<MoreHorizontalIcon />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuGroup>
<DropdownMenuItem onClick={() => setNotice({ text: `Opening ${invoice.id}…` })}>
<EyeIcon />
View invoice
</DropdownMenuItem>
<DropdownMenuItem onClick={() => duplicate(invoice)}>
<CopyIcon />
Duplicate
</DropdownMenuItem>
<DropdownMenuItem disabled={!unpaid(invoice)} onClick={() => remind([invoice])}>
<SendIcon />
Send reminder
</DropdownMenuItem>
<DropdownMenuItem disabled={invoice.status === "Paid"} onClick={() => markPaid(invoice.id)}>
<CircleCheckIcon />
Mark as paid
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onClick={() => setConfirm({ ids: [invoice.id], table })}>
<Trash2Icon />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
},
},
],
[duplicate, markPaid, remind],
)
return (
<div className="mx-auto w-full max-w-5xl">
<DataTable
caption="Invoices"
columns={columns}
data={data}
getRowId={(row) => row.id}
initialState={{ rowSelection: { "INV-1035": true, "INV-1034": true, "INV-1033": true } }}
rowLabel={{ singular: "invoice", plural: "invoices" }}
toolbar={(table) => {
const selected = table.getSelectedRowModel().rows.map((r) => r.original)
const total = table.getFilteredRowModel().rows.length
const toRemind = selected.filter(unpaid).length
return (
<div className="flex flex-col gap-3">
{selected.length ? (
<div role="toolbar" aria-label="Selected invoices" className="flex min-h-10 flex-wrap items-center gap-x-2 gap-y-2 rounded-lg border bg-muted/50 py-1 pr-1 pl-3">
<span className="text-sm font-medium tabular-nums">{selected.length} selected</span>
{table.getIsAllPageRowsSelected() && selected.length < total ? (
<Button variant="link" size="sm" className="h-7 px-1" onClick={() => table.toggleAllRowsSelected(true)}>
Select all {total}
</Button>
) : null}
<Button variant="ghost" size="sm" className="h-7 text-muted-foreground" onClick={() => table.resetRowSelection(true)}>
Clear
</Button>
<div className="flex flex-wrap gap-1.5 sm:ml-auto">
<Button variant="outline" size="sm" disabled={!toRemind} onClick={() => remind(selected)}>
<SendIcon />
{toRemind ? `Send ${plural(toRemind, "reminder")}` : "Nothing to remind"}
</Button>
<Button variant="outline" size="sm" onClick={() => exportCsv(selected)}>
<DownloadIcon />
Export CSV
</Button>
<Button variant="destructive" size="sm" onClick={() => setConfirm({ ids: selected.map((r) => r.id), table })}>
<Trash2Icon />
Delete
</Button>
</div>
</div>
) : (
<div className="flex min-h-10 flex-wrap items-center gap-2">
<InputGroup className="w-full sm:w-72">
<InputGroupAddon>
<SearchIcon />
</InputGroupAddon>
<InputGroupInput
type="search"
value={(table.getState().globalFilter as string | undefined) ?? ""}
onChange={(e) => table.setGlobalFilter(e.target.value)}
placeholder="Search invoices or clients"
aria-label="Search invoices"
/>
</InputGroup>
<p className="text-sm text-muted-foreground sm:ml-auto">Tip: shift-click a checkbox to select a range.</p>
</div>
)}
<div aria-live="polite" className="empty:hidden">
{notice ? (
<div className="flex items-center gap-2 rounded-lg border bg-card py-1 pr-1 pl-3 text-sm text-card-foreground">
<CircleCheckIcon aria-hidden="true" className="size-4 shrink-0 text-primary" />
<span className="min-w-0 flex-1">{notice.text}</span>
{notice.undo ? (
<Button variant="ghost" size="sm" onClick={() => undo(notice.undo!)}>
Undo
</Button>
) : null}
<Button variant="ghost" size="icon-sm" onClick={() => setNotice(null)} aria-label="Dismiss">
<XIcon />
</Button>
</div>
) : null}
</div>
</div>
)
}}
/>
<AlertDialog open={confirm !== null} onOpenChange={(open) => !open && setConfirm(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
Delete {confirm?.ids.length === 1 ? confirm.ids[0] : plural(confirm?.ids.length ?? 0, "invoice")}?
</AlertDialogTitle>
<AlertDialogDescription>
{confirm?.ids.length === 1 ? "It leaves" : "They leave"} your invoice list and reports. Clients keep the copies already sent to them.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={remove}>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}npx shadcn@latest add https://dresscodeui.com/r/dresscode/data-table-expandable-rows.json// Invoices that open in place: the chevron shows an invoice's line items, totals and payment details
// under its row, without leaving the list. The header chevron (or Expand all) opens every row on the page.
"use client"
import type { ColumnDef, Row } from "@tanstack/react-table"
import { ChevronsDownUpIcon, ChevronsUpDownIcon, CircleAlertIcon, CircleCheckIcon, ClockIcon, DownloadIcon, ExternalLinkIcon, FilePenLineIcon } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Table, TableBody, TableCell, TableFooter, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { DataTable, expandColumn } from "@/components/ui/data-table"
import { DataTableColumnHeader } from "@/components/ui/data-table-column-header"
type Status = "Paid" | "Due" | "Overdue" | "Draft"
type LineItem = { description: string; qty: number; unit: string; rate: number }
type Invoice = {
id: string
client: string
email: string
issued: string
due: string
status: Status
items: LineItem[]
subtotal: number
tax: number
total: number
paidOn?: string
}
const CLIENTS = [
["Fernwood Studio", "mara@fernwood.studio"],
["Kato & Lee", "ken@katolee.com"],
["Juniper Labs", "theo@juniperlabs.dev"],
["Ola Bakery", "hello@olabakery.com"],
["Pellucid Health", "accounts@pellucid.health"],
["Alder Coffee", "sam@aldercoffee.com"],
["Mossgrove Architects", "paul@mossgrove.co.uk"],
["Saltmarsh Films", "nadia@saltmarsh.film"],
["Tidewater Co.", "hana@tidewater.co"],
["Quill & Ink", "bea@quillandink.co"],
] as const
// What the studio sells: [description, unit, rate, how many of the unit an invoice usually has].
const SERVICES: [string, string, number, number[]][] = [
["Brand strategy workshop", "day", 1200, [1, 2]],
["Logo and identity system", "project", 3800, [1]],
["Website design", "hour", 110, [12, 18, 24]],
["Front-end build", "hour", 95, [16, 20, 32]],
["Copywriting", "hour", 85, [4, 6, 10]],
["Product photography", "half day", 650, [1, 2]],
["Monthly design retainer", "month", 1500, [1]],
["Hosting and maintenance", "month", 120, [1, 3]],
["Illustration set", "set", 480, [1, 2]],
["Print production", "batch", 340, [1, 2]],
]
const DAY = 86_400_000
const TODAY = Date.UTC(2026, 10, 24)
const TAX_RATE = 0.08
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
const iso = (t: number) => new Date(t).toISOString().slice(0, 10)
const formatDate = (d: string) => `${MONTHS[Number(d.slice(5, 7)) - 1]} ${Number(d.slice(8, 10))}, ${d.slice(0, 4)}`
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })
const INVOICES: Invoice[] = Array.from({ length: 30 }, (_, i) => {
const [client, email] = CLIENTS[(i * 7 + 3) % CLIENTS.length]
const issuedAt = TODAY - (i * 4 + (i % 3)) * DAY
const dueAt = issuedAt + [14, 30, 30, 7][i % 4] * DAY
const status: Status = i < 2 ? "Draft" : dueAt >= TODAY ? "Due" : i % 6 === 1 ? "Overdue" : "Paid"
const items = Array.from({ length: 1 + ((i * 5 + 1) % 4) }, (_, k): LineItem => {
const [description, unit, rate, qtys] = SERVICES[(i * 3 + k * 7) % SERVICES.length]
return { description, unit, rate, qty: qtys[(i + k) % qtys.length] }
})
const subtotal = items.reduce((s, it) => s + it.qty * it.rate, 0)
const tax = Math.round(subtotal * TAX_RATE * 100) / 100
const paidOn = status === "Paid" ? iso(dueAt - ((i * 3) % 9) * DAY) : undefined
return { id: `INV-${1030 - i}`, client, email, issued: iso(issuedAt), due: iso(dueAt), status, items, subtotal, tax, total: subtotal + tax, paidOn }
})
const quantity = (item: LineItem) =>
`${item.qty} ${item.qty === 1 ? item.unit : item.unit === "half day" ? "half days" : `${item.unit}s`}`
const STATUS: Record<Status, { icon: React.ComponentType<{ className?: string }>; variant: "secondary" | "outline" | "destructive" }> = {
Overdue: { icon: CircleAlertIcon, variant: "destructive" },
Due: { icon: ClockIcon, variant: "outline" },
Draft: { icon: FilePenLineIcon, variant: "outline" },
Paid: { icon: CircleCheckIcon, variant: "secondary" },
}
const columns: ColumnDef<Invoice>[] = [
expandColumn<Invoice>({ label: (row) => row.original.id }),
{
accessorKey: "id",
meta: { label: "Invoice" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Invoice" />,
cell: ({ row }) => <span className="font-medium tabular-nums">{row.original.id}</span>,
},
{
accessorKey: "client",
meta: { label: "Client" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Client" sortLabels={{ asc: "A to Z", desc: "Z to A" }} />,
cell: ({ row }) => <span className="font-medium">{row.original.client}</span>,
},
{
accessorKey: "issued",
meta: { label: "Issued" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Issued" sortLabels={{ asc: "Oldest first", desc: "Newest first" }} />,
cell: ({ row }) => <span className="text-muted-foreground tabular-nums">{formatDate(row.original.issued)}</span>,
},
{
accessorKey: "status",
meta: { label: "Status" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const { icon: Icon, variant } = STATUS[row.original.status]
return (
<Badge variant={variant} className={row.original.status === "Draft" ? "text-muted-foreground" : undefined}>
<Icon aria-hidden="true" />
{row.original.status}
</Badge>
)
},
},
{
id: "items",
accessorFn: (row) => row.items.length,
meta: { label: "Line items", align: "right" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Items" sortLabels={{ asc: "Fewest first", desc: "Most first" }} />,
cell: ({ row }) => <span className="text-muted-foreground tabular-nums">{row.original.items.length}</span>,
},
{
accessorKey: "total",
meta: { label: "Total", align: "right" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Total" sortLabels={{ asc: "Low to high", desc: "High to low" }} />,
cell: ({ row }) => <span className="font-medium tabular-nums">{usd.format(row.original.total)}</span>,
},
]
function InvoiceDetails({ row }: { row: Row<Invoice> }) {
const invoice = row.original
const payment =
invoice.status === "Paid"
? `Paid ${formatDate(invoice.paidOn!)} by bank transfer`
: invoice.status === "Overdue"
? `${Math.round((TODAY - Date.parse(invoice.due)) / DAY)} days late, reminder sent Nov 20`
: invoice.status === "Draft"
? "Not sent yet"
: `Due ${formatDate(invoice.due)}`
// A size container: the details take the table's width instead of stretching it.
return (
<div className="@container">
<div className="grid gap-x-8 gap-y-5 px-4 py-4 @2xl:grid-cols-[minmax(0,1fr)_15rem] @2xl:pl-14">
<div className="min-w-0 overflow-hidden rounded-lg border bg-background">
<Table aria-label={`Line items on ${invoice.id}`} className="text-[13px]">
<TableHeader>
<TableRow className="hover:bg-transparent">
<TableHead className="h-9 px-3 text-muted-foreground">Description</TableHead>
<TableHead className="hidden h-9 px-3 text-right text-muted-foreground @lg:table-cell">Qty</TableHead>
<TableHead className="hidden h-9 px-3 text-right text-muted-foreground @lg:table-cell">Rate</TableHead>
<TableHead className="h-9 px-3 text-right text-muted-foreground">Amount</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{invoice.items.map((item) => (
<TableRow key={item.description} className="hover:bg-transparent">
<TableCell className="px-3">
{item.description}
{/* Narrow details: quantity and rate under the description instead of in columns. */}
<span className="block text-xs text-muted-foreground tabular-nums @lg:hidden">
{quantity(item)} × {usd.format(item.rate)}
</span>
</TableCell>
<TableCell className="hidden px-3 text-right text-muted-foreground tabular-nums @lg:table-cell">{quantity(item)}</TableCell>
<TableCell className="hidden px-3 text-right text-muted-foreground tabular-nums @lg:table-cell">{usd.format(item.rate)}</TableCell>
<TableCell className="px-3 text-right tabular-nums">{usd.format(item.qty * item.rate)}</TableCell>
</TableRow>
))}
</TableBody>
<TableFooter className="bg-transparent font-normal">
<TableRow className="hover:bg-transparent">
<TableCell colSpan={2} className="hidden pt-2.5 pb-0 @lg:table-cell" />
<TableCell className="px-3 pt-2.5 pb-0 text-right text-muted-foreground">
Subtotal
</TableCell>
<TableCell className="px-3 pt-2.5 pb-0 text-right tabular-nums">{usd.format(invoice.subtotal)}</TableCell>
</TableRow>
<TableRow className="border-0 hover:bg-transparent">
<TableCell colSpan={2} className="hidden py-1 @lg:table-cell" />
<TableCell className="px-3 py-1 text-right text-muted-foreground">
Sales tax ({TAX_RATE * 100}%)
</TableCell>
<TableCell className="px-3 py-1 text-right tabular-nums">{usd.format(invoice.tax)}</TableCell>
</TableRow>
<TableRow className="border-0 hover:bg-transparent">
<TableCell colSpan={2} className="hidden pt-0 pb-2.5 @lg:table-cell" />
<TableCell className="px-3 pt-0 pb-2.5 text-right font-medium">
Total
</TableCell>
<TableCell className="px-3 pt-0 pb-2.5 text-right font-semibold tabular-nums">{usd.format(invoice.total)}</TableCell>
</TableRow>
</TableFooter>
</Table>
</div>
<div className="flex flex-col gap-4 text-sm">
<dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-2">
<dt className="text-muted-foreground">Billed to</dt>
<dd className="min-w-0">
<span className="block font-medium">{invoice.client}</span>
<span className="block truncate text-muted-foreground">{invoice.email}</span>
</dd>
<dt className="text-muted-foreground">Issued</dt>
<dd className="tabular-nums">{formatDate(invoice.issued)}</dd>
<dt className="text-muted-foreground">Payment</dt>
<dd className={invoice.status === "Overdue" ? "text-destructive" : undefined}>{payment}</dd>
</dl>
<div className="flex flex-wrap gap-2">
<Button variant="outline" size="sm">
<ExternalLinkIcon />
Open invoice
</Button>
<Button variant="ghost" size="sm">
<DownloadIcon />
PDF
</Button>
</div>
</div>
</div>
</div>
)
}
export default function DataTableExpandableRows() {
return (
<div className="mx-auto w-full max-w-5xl">
<DataTable
caption="Invoices with their line items"
columns={columns}
data={INVOICES}
getRowId={(row) => row.id}
renderSubRow={(row) => <InvoiceDetails row={row} />}
initialState={{ expanded: { "INV-1028": true } }}
pageSizeOptions={[8, 16, 30]}
rowLabel={{ singular: "invoice", plural: "invoices" }}
toolbar={(table) => {
const all = table.getIsAllRowsExpanded()
return (
<div className="flex flex-wrap items-end justify-between gap-3">
<div>
<h2 className="text-lg font-semibold">Invoices</h2>
<p className="text-sm text-muted-foreground">Open a row to see what was billed.</p>
</div>
<Button variant="outline" size="sm" onClick={() => table.toggleAllRowsExpanded(!all)}>
{all ? <ChevronsDownUpIcon /> : <ChevronsUpDownIcon />}
{all ? "Collapse all" : "Expand all"}
</Button>
</div>
)
}}
/>
</div>
)
}Editable cells
Edit an email, terms or rate in place, with save and cancel, validation messages and undo.
npx shadcn@latest add https://dresscodeui.com/r/dresscode/data-table-editable-cells.json// Clients with cells you can edit in place: billing email, payment terms and hourly rate. Click a
// cell (or focus it and press Enter), change it, then save with Enter or the check, or cancel with
// Escape. Values are checked before saving and the error is read out; each save can be undone.
"use client"
import * as React from "react"
import type { ColumnDef } from "@tanstack/react-table"
import { CheckIcon, CircleCheckIcon, PencilIcon, XIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Spinner } from "@/components/ui/spinner"
import { cn } from "@/lib/utils"
import { DataTable } from "@/components/ui/data-table"
import { DataTableColumnHeader } from "@/components/ui/data-table-column-header"
const TERMS = ["Due on receipt", "Net 7", "Net 14", "Net 30", "Net 60"] as const
type Client = {
id: string
name: string
city: string
email: string
terms: (typeof TERMS)[number]
rate: number
open: number
outstanding: number
}
type Field = "email" | "terms" | "rate"
const NAMES = [
"Fernwood Studio", "Kato & Lee", "Juniper Labs", "Ola Bakery", "Pellucid Health", "Alder Coffee",
"Mossgrove Architects", "Saltmarsh Films", "Tidewater Co.", "Quill & Ink", "Verity Legal", "Arbor Supply",
"Beacon Media", "Cinder Works", "Harbor & Pine", "Ember Goods", "Fable Collective", "Granite Dental",
"Hollow Labs", "Indigo Studio", "Jasper & Co.", "Kestrel Media", "Lumen Partners", "Meridian Goods",
"Nimbus Works", "Orchard Collective", "Pine Street Books", "Rook Studio", "Sable Labs", "Thistle Health",
]
const CITIES = ["Portland, OR", "Vancouver, BC", "Denver, CO", "Brooklyn, NY", "Boston, MA", "Oakland, CA", "London, UK", "Los Angeles, CA", "Charleston, SC", "Berlin, DE"]
const domain = (name: string) => name.toLowerCase().replace(/&/g, "and").replace(/[^a-z0-9]+/g, "") + ".com"
const CLIENTS: Client[] = NAMES.map((name, i) => {
const open = (i * 7) % 5
return {
id: domain(name),
name,
city: CITIES[i % CITIES.length],
email: `${["billing", "accounts", "finance", "ap", "hello"][i % 5]}@${domain(name)}`,
terms: TERMS[[3, 2, 3, 1, 4, 3, 0, 2][i % 8]],
rate: [95, 110, 120, 135, 150, 85, 175, 140][i % 8] + (i % 3) * 5,
open,
outstanding: open * (420 + ((i * 53) % 17) * 95),
}
})
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })
const FIELD_NAME: Record<Field, string> = { email: "billing email", terms: "payment terms", rate: "hourly rate" }
const show = (field: Field, value: string | number) => (field === "rate" ? `${usd.format(Number(value))}/h` : String(value))
/** Returns an error message, or null when the value can be saved. */
function validate(field: Field, raw: string, client: Client, all: Client[]): string | null {
const value = raw.trim()
if (field === "email") {
if (!value) return "Enter a billing email."
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(value)) return "Enter an email like name@company.com."
const taken = all.find((c) => c.id !== client.id && c.email.toLowerCase() === value.toLowerCase())
if (taken) return `${taken.name} already uses this email.`
}
if (field === "rate") {
if (!value) return "Enter an hourly rate."
const n = Number(value.replace(/[$,]/g, ""))
if (Number.isNaN(n)) return "Use numbers only, like 120."
if (!/^\d+(\.\d{1,2})?$/.test(value.replace(/[$,]/g, ""))) return "Use at most two decimals."
if (n < 25 || n > 1000) return "Rates go from $25 to $1,000 an hour."
}
return null
}
type Editing = {
/** "<client id>:<field>" of the open editor, if any. */
cell: string | null
/** Focus the editor when it opens (not for the one the demo opens on load). */
focus: boolean
/** A starting draft for the open editor instead of the saved value. */
draft?: string
open: (cell: string | null) => void
save: (client: Client, field: Field, value: string) => Promise<void>
clients: Client[]
}
const EditingContext = React.createContext<Editing | null>(null)
function EditableCell({ client, field }: { client: Client; field: Field }) {
const editing = React.useContext(EditingContext)!
const key = `${client.id}:${field}`
const isOpen = editing.cell === key
const buttonRef = React.useRef<HTMLButtonElement>(null)
const refocus = React.useRef(false)
React.useEffect(() => {
if (!isOpen && refocus.current) {
refocus.current = false
buttonRef.current?.focus()
}
}, [isOpen])
const close = () => {
refocus.current = true
editing.open(null)
}
const value = client[field]
const align = field === "rate" ? "right" : "left"
if (isOpen) return <CellEditor client={client} field={field} onClose={close} />
return (
<button
ref={buttonRef}
type="button"
onClick={() => editing.open(key)}
aria-label={`Edit ${FIELD_NAME[field]} for ${client.name}: ${show(field, value)}`}
className={cn(
"group/edit -mx-2 flex h-8 w-[calc(100%+1rem)] items-center gap-2 rounded-md px-2 text-left outline-none hover:bg-muted focus-visible:ring-3 focus-visible:ring-ring/50",
align === "right" && "flex-row-reverse text-right",
)}
>
<span className={cn("truncate", field === "rate" && "tabular-nums")}>{show(field, value)}</span>
<PencilIcon aria-hidden="true" className="size-3.5 shrink-0 text-muted-foreground opacity-0 group-hover/edit:opacity-100 group-focus-visible/edit:opacity-100" />
</button>
)
}
function CellEditor({ client, field, onClose }: { client: Client; field: Field; onClose: () => void }) {
const editing = React.useContext(EditingContext)!
const [draft, setDraft] = React.useState(editing.draft ?? String(client[field]))
const [tried, setTried] = React.useState(editing.draft !== undefined)
const [saving, setSaving] = React.useState(false)
const errorId = React.useId()
const error = tried ? validate(field, draft, client, editing.clients) : null
const label = `${FIELD_NAME[field][0].toUpperCase()}${FIELD_NAME[field].slice(1)} for ${client.name}`
const submit = async (event: React.FormEvent) => {
event.preventDefault()
setTried(true)
if (validate(field, draft, client, editing.clients)) return
const clean = field === "rate" ? draft.replace(/[$,]/g, "").trim() : draft.trim()
if (clean === String(client[field])) return onClose()
setSaving(true)
await editing.save(client, field, clean)
onClose()
}
return (
<form
noValidate
onSubmit={submit}
onKeyDown={(e) => {
// Escape inside the select's own popup closes the popup, not the editor.
if (e.key === "Escape" && e.currentTarget.contains(e.target as Node)) {
e.preventDefault()
onClose()
}
}}
className="flex w-full items-start gap-1"
>
<div className="min-w-0 flex-1">
{field === "terms" ? (
<Select
items={TERMS.map((t) => ({ label: t, value: t }))}
value={draft}
onValueChange={(v) => v != null && setDraft(v)}
disabled={saving}
>
<SelectTrigger size="sm" autoFocus={editing.focus} aria-label={label} className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
{TERMS.map((t) => (
<SelectItem key={t} value={t}>
{t}
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<InputGroup className="h-7">
{field === "rate" ? <InputGroupAddon className="pr-0">$</InputGroupAddon> : null}
<InputGroupInput
autoFocus={editing.focus}
onFocus={(e) => e.currentTarget.select()}
value={draft}
onChange={(e) => setDraft(e.target.value)}
disabled={saving}
type={field === "email" ? "email" : "text"}
inputMode={field === "rate" ? "decimal" : "email"}
aria-label={label}
aria-invalid={error ? true : undefined}
aria-describedby={error ? errorId : undefined}
className={cn("h-7 text-sm", field === "rate" && "text-right tabular-nums")}
/>
</InputGroup>
)}
{error ? (
<p id={errorId} role="alert" className="mt-1 text-left text-xs whitespace-normal text-destructive">
{error}
</p>
) : null}
</div>
<Button type="submit" size="icon-sm" className="size-7" disabled={saving} aria-label="Save">
{saving ? <Spinner /> : <CheckIcon />}
</Button>
<Button type="button" variant="ghost" size="icon-sm" className="size-7" disabled={saving} onClick={onClose} aria-label="Cancel">
<XIcon />
</Button>
</form>
)
}
const columns: ColumnDef<Client>[] = [
{
accessorKey: "name",
meta: { label: "Client" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Client" sortLabels={{ asc: "A to Z", desc: "Z to A" }} />,
cell: ({ row }) => (
<div className="flex min-w-40 flex-col">
<span className="font-medium">{row.original.name}</span>
<span className="text-xs text-muted-foreground">{row.original.city}</span>
</div>
),
},
{
accessorKey: "email",
meta: { label: "Billing email", cellClassName: "min-w-[17.5rem]" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Billing email" sortLabels={{ asc: "A to Z", desc: "Z to A" }} />,
cell: ({ row }) => <EditableCell client={row.original} field="email" />,
},
{
accessorKey: "terms",
meta: { label: "Payment terms", cellClassName: "min-w-[13.5rem]" },
sortingFn: (a, b) => TERMS.indexOf(a.original.terms) - TERMS.indexOf(b.original.terms),
header: ({ column }) => <DataTableColumnHeader column={column} title="Payment terms" sortLabels={{ asc: "Shortest first", desc: "Longest first" }} />,
cell: ({ row }) => <EditableCell client={row.original} field="terms" />,
},
{
accessorKey: "rate",
meta: { label: "Hourly rate", align: "right", cellClassName: "min-w-48" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Hourly rate" sortLabels={{ asc: "Low to high", desc: "High to low" }} />,
cell: ({ row }) => <EditableCell client={row.original} field="rate" />,
},
{
accessorKey: "outstanding",
meta: { label: "Outstanding", align: "right" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Outstanding" sortLabels={{ asc: "Low to high", desc: "High to low" }} />,
cell: ({ row }) => (
<div className="flex flex-col items-end">
<span className={cn("tabular-nums", row.original.outstanding ? "font-medium" : "text-muted-foreground")}>{usd.format(row.original.outstanding)}</span>
<span className="text-xs text-muted-foreground">
{row.original.open ? `${row.original.open} open ${row.original.open === 1 ? "invoice" : "invoices"}` : "All paid"}
</span>
</div>
),
},
]
type Notice = { client: Client; field: Field; before: Client[Field]; after: Client[Field] }
export default function DataTableEditableCells() {
const [data, setData] = React.useState(CLIENTS)
// The demo opens Kato & Lee's rate with a draft that is too high, to show the error. Start with
// { cell: null, focus: true } in your app.
const [open, setOpen] = React.useState<{ cell: string | null; focus: boolean; draft?: string }>({ cell: "katoandlee.com:rate", focus: false, draft: "1,500" })
const [notice, setNotice] = React.useState<Notice | null>(null)
const apply = (id: string, field: Field, value: Client[Field]) => setData((rows) => rows.map((r) => (r.id === id ? { ...r, [field]: value } : r)))
const editing: Editing = {
...open,
open: (cell) => setOpen({ cell, focus: true }),
clients: data,
// Stands in for a request to your API.
save: (client, field, raw) =>
new Promise((resolve) =>
setTimeout(() => {
const value = field === "rate" ? Number(raw) : raw
apply(client.id, field, value as Client[Field])
setNotice({ client, field, before: client[field], after: value as Client[Field] })
resolve()
}, 500),
),
}
return (
<EditingContext.Provider value={editing}>
<div className="mx-auto w-full max-w-6xl">
<DataTable
caption="Clients"
columns={columns}
data={data}
getRowId={(row) => row.id}
rowLabel={{ singular: "client", plural: "clients" }}
toolbar={() => (
<div className="flex flex-col gap-3">
<div>
<h2 className="text-lg font-semibold">Clients</h2>
<p className="text-sm text-muted-foreground">Click an email, terms or rate to change it. New invoices use the new values.</p>
</div>
<div aria-live="polite" className="empty:hidden">
{notice ? (
<div className="flex items-center gap-2 rounded-lg border bg-card py-1 pr-1 pl-3 text-sm text-card-foreground">
<CircleCheckIcon aria-hidden="true" className="size-4 shrink-0 text-primary" />
<span className="min-w-0 flex-1">
Saved {notice.client.name}’s {FIELD_NAME[notice.field]}: <span className="font-medium">{show(notice.field, notice.after)}</span>
</span>
<Button
variant="ghost"
size="sm"
onClick={() => {
apply(notice.client.id, notice.field, notice.before)
setNotice(null)
}}
>
Undo
</Button>
<Button variant="ghost" size="icon-sm" onClick={() => setNotice(null)} aria-label="Dismiss">
<XIcon />
</Button>
</div>
) : null}
</div>
</div>
)}
/>
</div>
</EditingContext.Provider>
)
}Sticky header and pinned columns
Twenty-one columns that scroll both ways inside the table, with the header, first column and actions held in place.
npx shadcn@latest add https://dresscodeui.com/r/dresscode/data-table-sticky-columns.json// Every field of every invoice: 21 columns in a box that scrolls both ways. The header row sticks to
// the top, the invoice number stays pinned on the left and the actions on the right; the switches
// unpin them. Totals sit in the footer.
"use client"
import type { ColumnDef } from "@tanstack/react-table"
import { CircleAlertIcon, CircleCheckIcon, ClockIcon, DownloadIcon, EyeIcon, FilePenLineIcon, MoreHorizontalIcon, SendIcon } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { DataTable } from "@/components/ui/data-table"
import { DataTableColumnHeader } from "@/components/ui/data-table-column-header"
type Status = "Paid" | "Due" | "Overdue" | "Draft"
type Invoice = {
id: string
client: string
contact: string
email: string
project: string
owner: string
issued: string
due: string
terms: string
status: Status
subtotal: number
discount: number
tax: number
total: number
paid: number
balance: number
daysLate: number
method: string
reminders: number
lastReminder?: string
}
const CLIENTS = [
["Fernwood Studio", "Mara Lind", "mara@fernwood.studio"],
["Kato & Lee", "Ken Kato", "ken@katolee.com"],
["Juniper Labs", "Theo Grant", "theo@juniperlabs.dev"],
["Ola Bakery", "Ola Bergstrom", "hello@olabakery.com"],
["Pellucid Health", "Ravi Shah", "accounts@pellucid.health"],
["Alder Coffee", "Sam Alder", "sam@aldercoffee.com"],
["Mossgrove Architects", "Paul Moss", "paul@mossgrove.co.uk"],
["Saltmarsh Films", "Nadia Cole", "nadia@saltmarsh.film"],
["Tidewater Co.", "Hana Ito", "hana@tidewater.co"],
["Quill & Ink", "Bea Marsh", "bea@quillandink.co"],
] as const
const PROJECTS = ["Website refresh", "Spring campaign", "Packaging redesign", "Product shoot", "Monthly retainer", "Annual report", "App onboarding", "Brand guidelines"]
const OWNERS = ["Ada Ruiz", "Tom Okafor", "Maya Lindqvist", "Leo Brandt"]
const METHODS = ["Bank transfer", "Card", "ACH debit", "Bank transfer", "Card"]
const DAY = 86_400_000
const TODAY = Date.UTC(2026, 10, 24)
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
const iso = (t: number) => new Date(t).toISOString().slice(0, 10)
const formatDate = (d?: string) => (d ? `${MONTHS[Number(d.slice(5, 7)) - 1]} ${Number(d.slice(8, 10))}, ${d.slice(0, 4)}` : "—")
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })
const INVOICES: Invoice[] = Array.from({ length: 40 }, (_, i) => {
const [client, contact, email] = CLIENTS[(i * 7 + 3) % CLIENTS.length]
const issuedAt = TODAY - (i * 4 + (i % 3)) * DAY
const termDays = [14, 30, 30, 7][i % 4]
const dueAt = issuedAt + termDays * DAY
const status: Status = i < 3 ? "Draft" : dueAt >= TODAY ? "Due" : i % 6 === 1 && i < 34 ? "Overdue" : "Paid"
const subtotal = 480 + ((i * 37) % 23) * 185 + (i % 4) * 25
const discount = i % 5 === 0 ? Math.round(subtotal * 0.1) : 0
const tax = Math.round((subtotal - discount) * 8) / 100
const total = subtotal - discount + tax
const paid = status === "Paid" ? total : status === "Overdue" && i % 4 === 1 ? Math.round(total / 2) : 0
const daysLate = status === "Overdue" ? Math.round((TODAY - dueAt) / DAY) : 0
const reminders = status === "Overdue" ? 1 + (daysLate > 20 ? 1 : 0) : status === "Due" && i % 3 === 0 ? 1 : 0
return {
id: `INV-${1040 - i}`,
client,
contact,
email,
project: PROJECTS[(i * 5) % PROJECTS.length],
owner: OWNERS[i % OWNERS.length],
issued: iso(issuedAt),
due: iso(dueAt),
terms: termDays === 7 ? "Net 7" : `Net ${termDays}`,
status,
subtotal,
discount,
tax,
total,
paid,
balance: total - paid,
daysLate,
method: status === "Draft" ? "—" : METHODS[i % METHODS.length],
reminders,
lastReminder: reminders ? iso(TODAY - ((i % 5) + 1) * DAY) : undefined,
}
})
const STATUS: Record<Status, { icon: React.ComponentType<{ className?: string }>; variant: "secondary" | "outline" | "destructive" }> = {
Overdue: { icon: CircleAlertIcon, variant: "destructive" },
Due: { icon: ClockIcon, variant: "outline" },
Draft: { icon: FilePenLineIcon, variant: "outline" },
Paid: { icon: CircleCheckIcon, variant: "secondary" },
}
type MoneyKey = "subtotal" | "discount" | "tax" | "total" | "paid" | "balance"
const money = (key: MoneyKey, title: string): ColumnDef<Invoice> => ({
accessorKey: key,
meta: { label: title, align: "right" },
header: ({ column }) => <DataTableColumnHeader column={column} title={title} sortLabels={{ asc: "Low to high", desc: "High to low" }} />,
cell: ({ row }) => {
const v = row.original[key]
return <span className={v ? "tabular-nums" : "text-muted-foreground tabular-nums"}>{usd.format(key === "discount" && v ? -v : v)}</span>
},
footer: ({ table }) => {
const sum = table.getFilteredRowModel().rows.reduce((s, r) => s + r.original[key], 0)
return <span className="tabular-nums">{usd.format(key === "discount" && sum ? -sum : sum)}</span>
},
})
const text = (key: "client" | "contact" | "email" | "project" | "owner" | "terms" | "method", title: string, muted = false): ColumnDef<Invoice> => ({
accessorKey: key,
meta: { label: title },
header: ({ column }) => <DataTableColumnHeader column={column} title={title} sortLabels={{ asc: "A to Z", desc: "Z to A" }} />,
cell: ({ row }) => <span className={muted ? "text-muted-foreground" : key === "client" ? "font-medium" : undefined}>{row.original[key]}</span>,
})
const date = (key: "issued" | "due" | "lastReminder", title: string): ColumnDef<Invoice> => ({
id: key,
accessorFn: (row) => row[key] ?? "",
meta: { label: title },
header: ({ column }) => <DataTableColumnHeader column={column} title={title} sortLabels={{ asc: "Oldest first", desc: "Newest first" }} />,
cell: ({ row }) => <span className="text-muted-foreground tabular-nums">{formatDate(row.original[key])}</span>,
})
const columns: ColumnDef<Invoice>[] = [
{
accessorKey: "id",
size: 128,
enableHiding: false,
meta: { label: "Invoice" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Invoice" />,
cell: ({ row }) => <span className="font-medium tabular-nums">{row.original.id}</span>,
footer: "Total",
},
text("client", "Client"),
text("contact", "Contact"),
text("email", "Email", true),
text("project", "Project"),
text("owner", "Owner"),
date("issued", "Issued"),
date("due", "Due"),
text("terms", "Terms", true),
{
accessorKey: "status",
meta: { label: "Status" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Status" />,
cell: ({ row }) => {
const { icon: Icon, variant } = STATUS[row.original.status]
return (
<Badge variant={variant} className={row.original.status === "Draft" ? "text-muted-foreground" : undefined}>
<Icon aria-hidden="true" />
{row.original.status}
</Badge>
)
},
},
money("subtotal", "Subtotal"),
money("discount", "Discount"),
money("tax", "Tax"),
money("total", "Total"),
money("paid", "Paid"),
money("balance", "Balance"),
{
accessorKey: "daysLate",
meta: { label: "Days late", align: "right" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Days late" sortLabels={{ asc: "Low to high", desc: "High to low" }} />,
cell: ({ row }) =>
row.original.daysLate ? <span className="text-destructive tabular-nums">{row.original.daysLate}</span> : <span className="text-muted-foreground">—</span>,
},
text("method", "Paid by", true),
{
accessorKey: "reminders",
meta: { label: "Reminders", align: "right" },
header: ({ column }) => <DataTableColumnHeader column={column} title="Reminders" sortLabels={{ asc: "Fewest first", desc: "Most first" }} />,
cell: ({ row }) => <span className="text-muted-foreground tabular-nums">{row.original.reminders}</span>,
},
date("lastReminder", "Last reminder"),
{
id: "actions",
size: 56,
enableHiding: false,
header: () => <span className="sr-only">Actions</span>,
cell: ({ row }) => (
<DropdownMenu>
<DropdownMenuTrigger render={<Button variant="ghost" size="icon-sm" className="data-popup-open:bg-muted" aria-label={`Actions for ${row.original.id}`} />}>
<MoreHorizontalIcon />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-44">
<DropdownMenuItem>
<EyeIcon />
View invoice
</DropdownMenuItem>
<DropdownMenuItem>
<DownloadIcon />
Download PDF
</DropdownMenuItem>
<DropdownMenuItem disabled={row.original.status === "Paid" || row.original.status === "Draft"}>
<SendIcon />
Send reminder
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
),
},
]
export default function DataTableStickyColumns() {
return (
<div className="mx-auto w-full max-w-5xl">
<DataTable
caption="Invoices, every field"
columns={columns}
data={INVOICES}
getRowId={(row) => row.id}
pagination={false}
maxHeight={440}
initialState={{ columnPinning: { left: ["id"], right: ["actions"] }, sorting: [{ id: "issued", desc: true }] }}
toolbar={(table) => {
const invoice = table.getColumn("id")
const actions = table.getColumn("actions")
return (
<div className="flex flex-wrap items-end justify-between gap-x-6 gap-y-3">
<div>
<h2 className="text-lg font-semibold">All invoices</h2>
<p className="text-sm text-muted-foreground">
{INVOICES.length} invoices, {table.getVisibleLeafColumns().length - 1} fields. Scroll inside the table.
</p>
</div>
<div className="flex flex-wrap gap-x-5 gap-y-2">
<Label className="font-normal">
<Switch size="sm" checked={invoice?.getIsPinned() === "left"} onCheckedChange={(on) => invoice?.pin(on ? "left" : false)} />
Pin invoice number
</Label>
<Label className="font-normal">
<Switch size="sm" checked={actions?.getIsPinned() === "right"} onCheckedChange={(on) => actions?.pin(on ? "right" : false)} />
Pin actions
</Label>
</div>
</div>
)
}}
/>
</div>
)
}The component
What shadcn@latest add https://dresscodeui.com/r/dresscode/data-table.json writes. It uses only shadcn/ui's variables, so it follows the theme.
// Data table column header: the column's title as a menu button to sort it ascending or descending,
// clear the sort, or hide the column. The arrow shows the current sort; the header cell carries
// aria-sort (DataTable sets it). Right-aligned columns (meta.align) open the menu from the right.
// Built for shadcn/ui; reads only the theme's variables.
"use client"
import * as React from "react"
import type { Column } from "@tanstack/react-table"
import { ArrowDownIcon, ArrowUpIcon, ChevronsUpDownIcon, EyeOffIcon, XIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { cn } from "@/lib/utils"
type DataTableColumnHeaderProps<TData, TValue> = React.ComponentProps<"div"> & {
column: Column<TData, TValue>
title: string
/** Words for the two directions, e.g. { asc: "Oldest first", desc: "Newest first" }. */
sortLabels?: { asc: string; desc: string }
}
function DataTableColumnHeader<TData, TValue>({
column,
title,
sortLabels = { asc: "Ascending", desc: "Descending" },
className,
...props
}: DataTableColumnHeaderProps<TData, TValue>) {
const align = column.columnDef.meta?.align
const canSort = column.getCanSort()
const canHide = column.getCanHide()
const sorted = column.getIsSorted()
const justify = align === "right" ? "justify-end" : align === "center" ? "justify-center" : undefined
if (!canSort && !canHide) {
return (
<div data-slot="data-table-column-header" className={cn("flex items-center", justify, className)} {...props}>
{title}
</div>
)
}
return (
<div data-slot="data-table-column-header" className={cn("flex items-center", justify, className)} {...props}>
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button
variant="ghost"
size="sm"
className={cn(
"h-7 gap-1 px-2 font-medium text-muted-foreground hover:text-foreground data-popup-open:text-foreground",
sorted && "text-foreground",
align === "right" ? "-mr-2 flex-row-reverse" : "-ml-2",
)}
/>
}
>
<span>{title}</span>
{sorted === "desc" ? (
<ArrowDownIcon aria-hidden="true" />
) : sorted === "asc" ? (
<ArrowUpIcon aria-hidden="true" />
) : (
<ChevronsUpDownIcon aria-hidden="true" className="opacity-60" />
)}
<span className="sr-only">
{sorted ? `, sorted ${(sorted === "asc" ? sortLabels.asc : sortLabels.desc).toLowerCase()}. ` : ". "}Column options
</span>
</DropdownMenuTrigger>
<DropdownMenuContent align={align === "right" ? "end" : "start"} className="w-auto min-w-40">
{canSort ? (
<DropdownMenuGroup>
<DropdownMenuRadioGroup
value={sorted || ""}
onValueChange={(value) => (value === "asc" || value === "desc" ? column.toggleSorting(value === "desc") : column.clearSorting())}
>
<DropdownMenuRadioItem value="asc" closeOnClick>
<ArrowUpIcon className="text-muted-foreground" />
{sortLabels.asc}
</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="desc" closeOnClick>
<ArrowDownIcon className="text-muted-foreground" />
{sortLabels.desc}
</DropdownMenuRadioItem>
</DropdownMenuRadioGroup>
{sorted ? (
<DropdownMenuItem onClick={() => column.clearSorting()}>
<XIcon className="text-muted-foreground" />
Clear sort
</DropdownMenuItem>
) : null}
</DropdownMenuGroup>
) : null}
{canSort && canHide ? <DropdownMenuSeparator /> : null}
{canHide ? (
<DropdownMenuItem onClick={() => column.toggleVisibility(false)}>
<EyeOffIcon className="text-muted-foreground" />
Hide column
</DropdownMenuItem>
) : null}
</DropdownMenuContent>
</DropdownMenu>
</div>
)
}
export { DataTableColumnHeader }
export type { DataTableColumnHeaderProps }// Data table faceted filter: a dashed button that opens a searchable list of a column's values, each
// with a checkbox and how many rows have it (counted with the other filters applied). Pick several;
// the button shows what is picked. Give the column `filterFn: facetedFilterFn`.
// Built for shadcn/ui; reads only the theme's variables.
"use client"
import * as React from "react"
import type { Column, Row } from "@tanstack/react-table"
import { CheckIcon, PlusCircleIcon } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from "@/components/ui/command"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { cn } from "@/lib/utils"
type FacetOption = {
label: string
value: string
icon?: React.ComponentType<{ className?: string }>
}
type DataTableFacetedFilterProps<TData, TValue> = {
column?: Column<TData, TValue>
title: string
options: FacetOption[]
/** Show the search box at the top of the list. On by default when there are more than 6 options. */
searchable?: boolean
className?: string
}
/** Keeps rows whose value is one of the picked values. Use as the column's filterFn. */
function facetedFilterFn<TData>(row: Row<TData>, columnId: string, value: string[] | undefined) {
return !value?.length || value.includes(String(row.getValue(columnId)))
}
facetedFilterFn.autoRemove = (value: unknown) => !Array.isArray(value) || value.length === 0
function DataTableFacetedFilter<TData, TValue>({ column, title, options, searchable, className }: DataTableFacetedFilterProps<TData, TValue>) {
const facets = column?.getFacetedUniqueValues()
const selected = new Set((column?.getFilterValue() as string[] | undefined) ?? [])
const picked = options.filter((o) => selected.has(o.value))
const withSearch = searchable ?? options.length > 6
const toggle = (value: string) => {
const next = new Set(selected)
if (next.has(value)) next.delete(value)
else next.add(value)
column?.setFilterValue(next.size ? options.map((o) => o.value).filter((v) => next.has(v)) : undefined)
}
return (
<Popover>
<PopoverTrigger
render={<Button variant="outline" size="sm" className={cn("border-dashed data-popup-open:bg-muted", selected.size > 0 && "border-solid", className)} />}
>
<PlusCircleIcon className="text-muted-foreground" />
{title}
{picked.length > 0 ? (
<>
<span aria-hidden="true" className="mx-0.5 h-4 w-px bg-border" />
<Badge variant="secondary" className="rounded-sm px-1.5 font-normal tabular-nums lg:hidden">
{picked.length}
<span className="sr-only"> selected</span>
</Badge>
<span className="hidden gap-1 lg:flex">
{picked.length > 2 ? (
<Badge variant="secondary" className="rounded-sm px-1.5 font-normal">
{picked.length} selected
</Badge>
) : (
picked.map((o) => (
<Badge key={o.value} variant="secondary" className="max-w-32 rounded-sm px-1.5 font-normal">
<span className="truncate">{o.label}</span>
</Badge>
))
)}
</span>
</>
) : null}
</PopoverTrigger>
<PopoverContent align="start" className="w-60 gap-0 p-0">
<Command>
{withSearch ? <CommandInput placeholder={`Search ${title.toLowerCase()}`} aria-label={`Search ${title.toLowerCase()}`} /> : null}
<CommandList aria-label={title}>
<CommandEmpty>No matches.</CommandEmpty>
<CommandGroup>
{options.map((option) => {
const isSelected = selected.has(option.value)
const count = facets?.get(option.value) ?? 0
return (
<CommandItem
key={option.value}
value={option.label}
onSelect={() => toggle(option.value)}
aria-checked={isSelected}
className="[&>svg:last-child]:hidden"
>
<span
aria-hidden="true"
className={cn(
"flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-input",
isSelected && "border-primary bg-primary text-primary-foreground",
)}
>
{isSelected ? <CheckIcon className="size-3" /> : null}
</span>
{option.icon ? <option.icon className="text-muted-foreground" /> : null}
<span className="truncate">{option.label}</span>
<span className={cn("ml-auto text-xs tabular-nums text-muted-foreground", count === 0 && "opacity-60")}>
{count}
<span className="sr-only"> {count === 1 ? "row" : "rows"}</span>
</span>
</CommandItem>
)
})}
</CommandGroup>
{selected.size > 0 ? (
<>
<CommandSeparator />
<CommandGroup>
<CommandItem value="__clear" onSelect={() => column?.setFilterValue(undefined)} className="justify-center [&>svg:last-child]:hidden">
Clear filter
</CommandItem>
</CommandGroup>
</>
) : null}
</CommandList>
</Command>
</PopoverContent>
</Popover>
)
}
export { DataTableFacetedFilter, facetedFilterFn }
export type { DataTableFacetedFilterProps, FacetOption }// Data table pagination: which rows are showing (or how many are selected), rows per page, page n of m
// and first / previous / next / last. On phones the first and last buttons and the label fold away.
// Built for shadcn/ui; reads only the theme's variables.
"use client"
import * as React from "react"
import type { Table } from "@tanstack/react-table"
import { ChevronLeftIcon, ChevronRightIcon, ChevronsLeftIcon, ChevronsRightIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { cn } from "@/lib/utils"
type DataTablePaginationProps<TData> = React.ComponentProps<"div"> & {
table: Table<TData>
pageSizeOptions?: number[]
/** What a row is called: "Showing 1–10 of 48 invoices". */
rowLabel?: { singular: string; plural: string }
}
function DataTablePagination<TData>({
table,
pageSizeOptions = [10, 20, 50],
rowLabel = { singular: "row", plural: "rows" },
className,
...props
}: DataTablePaginationProps<TData>) {
const labelId = React.useId()
const { pageIndex, pageSize } = table.getState().pagination
const total = table.getFilteredRowModel().rows.length
const pageCount = Math.max(table.getPageCount(), 1)
const selectable = Boolean(table.options.enableRowSelection)
const selected = selectable ? table.getFilteredSelectedRowModel().rows.length : 0
const from = total ? pageIndex * pageSize + 1 : 0
const to = Math.min(total, (pageIndex + 1) * pageSize)
const noun = total === 1 ? rowLabel.singular : rowLabel.plural
const sizes = pageSizeOptions.includes(pageSize) ? pageSizeOptions : [...pageSizeOptions, pageSize].sort((a, b) => a - b)
const items = sizes.map((s) => ({ label: String(s), value: String(s) }))
return (
<div
data-slot="data-table-pagination"
className={cn("flex flex-wrap items-center justify-between gap-x-6 gap-y-3 px-1 text-sm", className)}
{...props}
>
<p className="text-muted-foreground tabular-nums" aria-live="polite">
{selected > 0 ? (
<>
<span className="font-medium text-foreground">{selected}</span> of {total} {noun} selected
</>
) : total ? (
<>
Showing {from}–{to} of {total} {noun}
</>
) : (
<>No {rowLabel.plural}</>
)}
</p>
<div className="flex items-center gap-3 sm:gap-6">
<div className="flex items-center gap-2">
<span id={labelId} className="hidden font-medium sm:inline">
Rows per page
</span>
<Select items={items} value={String(pageSize)} onValueChange={(value) => value != null && table.setPageSize(Number(value))}>
<SelectTrigger size="sm" aria-labelledby={labelId} className="w-[4.5rem] tabular-nums">
<SelectValue />
</SelectTrigger>
<SelectContent side="top">
{items.map((item) => (
<SelectItem key={item.value} value={item.value} className="tabular-nums">
{item.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<span className="font-medium whitespace-nowrap tabular-nums">
Page {Math.min(pageIndex + 1, pageCount)} of {pageCount}
</span>
<div className="flex items-center gap-1">
<Button
variant="outline"
size="icon-sm"
className="hidden sm:inline-flex"
onClick={() => table.firstPage()}
disabled={!table.getCanPreviousPage()}
aria-label="Go to first page"
>
<ChevronsLeftIcon />
</Button>
<Button variant="outline" size="icon-sm" onClick={() => table.previousPage()} disabled={!table.getCanPreviousPage()} aria-label="Go to previous page">
<ChevronLeftIcon />
</Button>
<Button variant="outline" size="icon-sm" onClick={() => table.nextPage()} disabled={!table.getCanNextPage()} aria-label="Go to next page">
<ChevronRightIcon />
</Button>
<Button
variant="outline"
size="icon-sm"
className="hidden sm:inline-flex"
onClick={() => table.lastPage()}
disabled={!table.getCanNextPage()}
aria-label="Go to last page"
>
<ChevronsRightIcon />
</Button>
</div>
</div>
</div>
)
}
export { DataTablePagination }
export type { DataTablePaginationProps }// Data table view options: a menu of checkboxes to show and hide columns, named by each column's
// meta.label. The last visible column cannot be hidden; "Reset columns" brings back the defaults.
// Built for shadcn/ui; reads only the theme's variables.
"use client"
import type { Table } from "@tanstack/react-table"
import { RotateCcwIcon, Settings2Icon } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { cn } from "@/lib/utils"
type DataTableViewOptionsProps<TData> = {
table: Table<TData>
className?: string
}
function DataTableViewOptions<TData>({ table, className }: DataTableViewOptionsProps<TData>) {
const columns = table.getAllLeafColumns().filter((c) => c.accessorFn !== undefined && c.getCanHide())
const visible = columns.filter((c) => c.getIsVisible())
const initial = table.initialState.columnVisibility ?? {}
const isDefault = columns.every((c) => c.getIsVisible() === (initial[c.id] ?? true))
return (
<DropdownMenu>
<DropdownMenuTrigger render={<Button variant="outline" size="sm" className={cn("data-popup-open:bg-muted", className)} />}>
<Settings2Icon />
<span className="max-sm:sr-only">View</span>
{visible.length < columns.length ? (
<span className="text-muted-foreground tabular-nums max-sm:hidden">
{visible.length}/{columns.length}
</span>
) : null}
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-52">
<DropdownMenuGroup>
<DropdownMenuLabel>Show columns</DropdownMenuLabel>
{columns.map((column) => {
const only = column.getIsVisible() && visible.length === 1
return (
<DropdownMenuCheckboxItem
key={column.id}
checked={column.getIsVisible()}
disabled={only}
onCheckedChange={(value) => column.toggleVisibility(value)}
>
{column.columnDef.meta?.label ?? column.id}
</DropdownMenuCheckboxItem>
)
})}
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem disabled={isDefault} onClick={() => table.resetColumnVisibility()}>
<RotateCcwIcon className="text-muted-foreground" />
Reset columns
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
export { DataTableViewOptions }
export type { DataTableViewOptionsProps }// Data table: rows of records on @tanstack/react-table and the stock shadcn/ui Table. Sorting,
// search and column filters, pagination, row selection (shift-click selects a range), column
// visibility, expandable rows, a totals footer, a sticky header and pinned columns.
// Pass columns and data; the toolbar slot gets the table instance for search, filters and bulk
// actions. Column meta (label, align, classes) is typed below. Built for shadcn/ui; reads only the
// theme's variables. The frame's background is var(--data-table-bg), the page background by default:
// set it to var(--card) when the table sits in a card, so pinned cells match.
"use client"
import * as React from "react"
import {
flexRender,
getCoreRowModel,
getExpandedRowModel,
getFacetedRowModel,
getFacetedUniqueValues,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
type Column,
type ColumnDef,
type FilterFnOption,
type InitialTableState,
type Row,
type RowData,
type Table as TanstackTable,
type TableOptions,
} from "@tanstack/react-table"
import { ChevronDownIcon, ChevronRightIcon, ChevronsDownUpIcon, ChevronsUpDownIcon, MinusIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { cn } from "@/lib/utils"
import { DataTablePagination } from "@/components/ui/data-table-pagination"
declare module "@tanstack/react-table" {
// TData and TValue must stay: the declaration merges with TanStack's own.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface ColumnMeta<TData extends RowData, TValue> {
/** The column's name in the view menu and in screen-reader labels. Defaults to its id. */
label?: string
/** Right-align numbers and money; the header follows. */
align?: "left" | "center" | "right"
/** Extra classes for this column's header cell. */
headerClassName?: string
/** Extra classes for this column's body and footer cells. */
cellClassName?: string
}
}
type RowLabel = { singular: string; plural: string }
type DataTableProps<TData, TValue> = {
columns: ColumnDef<TData, TValue>[]
data: TData[]
/** Rendered above the table with the table instance: search, filters, view options, bulk actions. */
toolbar?: (table: TanstackTable<TData>) => React.ReactNode
/** A caption for screen readers, e.g. "Invoices". */
caption?: string
/** A stable id per row (an invoice number), so selection and expansion survive sorting and edits. */
getRowId?: (row: TData, index: number) => string
/** Lets rows be selected; on by default when the columns include selectColumn(). A function decides per row. */
enableRowSelection?: boolean | ((row: Row<TData>) => boolean)
/** What an expanded row shows under itself; pair it with expandColumn(). */
renderSubRow?: (row: Row<TData>) => React.ReactNode
/** Which rows can expand. Defaults to every row when renderSubRow is set. */
getRowCanExpand?: (row: Row<TData>) => boolean
/** Starting sort, filters, page size, hidden and pinned columns, selection. */
initialState?: InitialTableState
/** Pages of rows with a footer to move between them. Off shows every row. */
pagination?: boolean
pageSizeOptions?: number[]
/** What the pagination footer calls a row: "Showing 1–10 of 48 invoices". */
rowLabel?: RowLabel
/** Shows skeleton rows instead of data. */
loading?: boolean
/** Shown in place of rows when there are none (or none match the filters); a function gets the table. */
empty?: React.ReactNode | ((table: TanstackTable<TData>) => React.ReactNode)
/** Scroll the rows inside a box this tall; the header row sticks to its top. */
maxHeight?: number | string
/**
* Go back to page 1 when the rows change. By default the table does so when the search, filters or
* sort change, but stays on its page when the data does (an edit, a delete, a status change).
*/
autoResetPageIndex?: boolean
/** How the search box (table.setGlobalFilter) matches a row. Defaults to "contains" on text and number columns. */
globalFilterFn?: FilterFnOption<TData>
/** Anything else TanStack Table takes (meta, onRowSelectionChange, manual pagination...). */
options?: Partial<TableOptions<TData>>
className?: string
}
function DataTable<TData, TValue>({
columns,
data,
toolbar,
caption,
getRowId,
enableRowSelection,
renderSubRow,
getRowCanExpand,
initialState,
pagination = true,
pageSizeOptions = [10, 20, 50],
rowLabel,
loading = false,
empty,
maxHeight,
autoResetPageIndex,
globalFilterFn = "auto",
options,
className,
}: DataTableProps<TData, TValue>) {
"use no memo" // TanStack Table mutates its instance; keep the React Compiler from caching renders.
// A render with new data skips TanStack's page reset, so editing a row on page 3 stays on page 3.
const [seenData, setSeenData] = React.useState(data)
const dataChanged = seenData !== data
if (dataChanged) setSeenData(data)
// eslint-disable-next-line react-hooks/incompatible-library -- opted out of the compiler above
const table = useReactTable<TData>({
data,
columns,
getRowId,
enableRowSelection: enableRowSelection ?? columns.some((c) => c.id === "select"),
getRowCanExpand: getRowCanExpand ?? (renderSubRow ? () => true : undefined),
globalFilterFn,
autoResetPageIndex: autoResetPageIndex ?? !dataChanged,
initialState: {
...initialState,
pagination: { pageIndex: 0, pageSize: pageSizeOptions[0] ?? 10, ...initialState?.pagination },
},
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getFacetedRowModel: getFacetedRowModel(),
getFacetedUniqueValues: getFacetedUniqueValues(),
getExpandedRowModel: getExpandedRowModel(),
...(pagination ? { getPaginationRowModel: getPaginationRowModel() } : {}),
...options,
})
// After a delete the current page can be past the end: step back to the last page.
const { pageIndex } = table.getState().pagination
const pageCount = table.getPageCount()
React.useEffect(() => {
if (pagination && pageIndex > 0 && pageIndex >= pageCount) table.setPageIndex(Math.max(pageCount - 1, 0))
}, [pagination, pageIndex, pageCount, table])
const sticky = maxHeight !== undefined
const rows = table.getRowModel().rows
const columnCount = table.getVisibleLeafColumns().length
const footerGroups = table.getFooterGroups()
const hasFooter = footerGroups.some((g) => g.headers.some((h) => h.column.columnDef.footer !== undefined))
const skeletonRows = Math.min(table.getState().pagination.pageSize, 8)
return (
<div data-slot="data-table" className={cn("flex min-w-0 flex-col gap-3", className)}>
{toolbar?.(table)}
<div
data-slot="data-table-frame"
className={cn(
"@container/data-table overflow-hidden rounded-lg border bg-(--data-table-bg,var(--background))",
sticky && "*:data-[slot=table-container]:max-h-(--data-table-max-h) *:data-[slot=table-container]:overscroll-x-contain",
)}
style={sticky ? ({ "--data-table-max-h": typeof maxHeight === "number" ? `${maxHeight}px` : maxHeight } as React.CSSProperties) : undefined}
>
<Table aria-busy={loading || undefined}>
{caption ? <TableCaption className="sr-only">{caption}</TableCaption> : null}
<TableHeader className={cn(sticky && "[&_tr]:border-b-0")}>
{table.getHeaderGroups().map((group) => (
<TableRow key={group.id} className="hover:bg-transparent">
{group.headers.map((header) => (
<TableHead
key={header.id}
colSpan={header.colSpan}
aria-sort={ariaSort(header.column)}
style={columnStyle(header.column)}
className={cn(
"px-3 text-muted-foreground first:pl-4 last:pr-4",
alignClass(header.column),
edgeClasses(header.column, sticky ? "sticky-head" : "head"),
header.column.columnDef.meta?.headerClassName,
)}
>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{loading ? (
Array.from({ length: skeletonRows }, (_, i) => (
<TableRow key={i} className="hover:bg-transparent">
{table.getVisibleLeafColumns().map((column) => (
<TableCell key={column.id} style={columnStyle(column)} className={cn("h-12 px-3 first:pl-4 last:pr-4", edgeClasses(column, "cell"))}>
<Skeleton className={cn("h-4", column.id === "select" || column.id === "expand" ? "w-4" : "w-full max-w-32", column.columnDef.meta?.align === "right" && "ml-auto")} />
</TableCell>
))}
</TableRow>
))
) : rows.length ? (
rows.map((row) => (
<React.Fragment key={row.id}>
<TableRow data-state={row.getIsSelected() ? "selected" : undefined} data-expanded={row.getIsExpanded() || undefined}>
{row.getVisibleCells().map((cell) => (
<TableCell
key={cell.id}
style={columnStyle(cell.column)}
className={cn("h-12 px-3 first:pl-4 last:pr-4", alignClass(cell.column), edgeClasses(cell.column, "cell"), cell.column.columnDef.meta?.cellClassName)}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
{renderSubRow && row.getIsExpanded() ? (
<TableRow data-slot="data-table-sub-row" className="bg-muted/30 hover:bg-muted/30">
<TableCell colSpan={columnCount} className="p-0 whitespace-normal">
{/* As wide as the visible frame and held at its left edge, so on a narrow screen the
details stay in view while the wide row above scrolls sideways. */}
<div className="sticky left-0 w-[100cqw]">{renderSubRow(row)}</div>
</TableCell>
</TableRow>
) : null}
</React.Fragment>
))
) : (
<TableRow className="hover:bg-transparent">
<TableCell colSpan={columnCount} className="h-40 px-4 text-center whitespace-normal text-muted-foreground">
{(typeof empty === "function" ? empty(table) : empty) ?? "No results."}
</TableCell>
</TableRow>
)}
</TableBody>
{hasFooter && !loading && rows.length ? (
<TableFooter>
{footerGroups.slice(0, 1).map((group) => (
<TableRow key={group.id} className="hover:bg-transparent">
{group.headers.map((header) => (
<TableCell
key={header.id}
colSpan={header.colSpan}
style={columnStyle(header.column)}
className={cn("h-11 px-3 first:pl-4 last:pr-4", alignClass(header.column), edgeClasses(header.column, "foot"), header.column.columnDef.meta?.cellClassName)}
>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.footer, header.getContext())}
</TableCell>
))}
</TableRow>
))}
</TableFooter>
) : null}
</Table>
</div>
{pagination ? <DataTablePagination table={table} pageSizeOptions={pageSizeOptions} rowLabel={rowLabel} /> : null}
</div>
)
}
function ariaSort<TData>(column: Column<TData, unknown>): React.AriaAttributes["aria-sort"] {
if (!column.getCanSort()) return undefined
const sorted = column.getIsSorted()
return sorted === "asc" ? "ascending" : sorted === "desc" ? "descending" : "none"
}
function alignClass<TData>(column: Column<TData, unknown>) {
const align = column.columnDef.meta?.align
return align === "right" ? "text-right" : align === "center" ? "text-center" : undefined
}
/**
* Pinned columns get a fixed width (the column's `size`, 150px unless set) and their offset, so
* several can stick side by side. Other columns size to their content.
*/
function columnStyle<TData>(column: Column<TData, unknown>): React.CSSProperties | undefined {
const pinned = column.getIsPinned()
if (!pinned) return undefined
const size = column.getSize()
return {
width: size,
minWidth: size,
maxWidth: size,
...(pinned === "left" ? { left: column.getStart("left") } : { right: column.getAfter("right") }),
}
}
/**
* Sticky header cells and pinned columns need an opaque background (the frame's) and draw their
* borders as inset shadows, because collapsed table borders do not travel with sticky cells.
*/
function edgeClasses<TData>(column: Column<TData, unknown>, part: "head" | "sticky-head" | "cell" | "foot") {
const pinned = column.getIsPinned()
const lastLeft = pinned === "left" && column.getIsLastColumn("left")
const firstRight = pinned === "right" && column.getIsFirstColumn("right")
const bg = "bg-(--data-table-bg,var(--background))"
if (part === "sticky-head") {
return cn(
"sticky top-0",
bg,
pinned ? "z-30" : "z-20",
lastLeft ? "shadow-[inset_-1px_-1px_0_var(--border)]" : firstRight ? "shadow-[inset_1px_-1px_0_var(--border)]" : "shadow-[inset_0_-1px_0_var(--border)]",
)
}
if (!pinned) return undefined
return cn(
"sticky z-10",
part === "foot" ? "bg-[color-mix(in_srgb,var(--muted)_50%,var(--data-table-bg,var(--background)))]" : bg,
part === "cell" &&
"[tr:hover>&]:bg-[color-mix(in_srgb,var(--muted)_50%,var(--data-table-bg,var(--background)))] [tr[data-state=selected]>&]:bg-muted",
lastLeft && "shadow-[inset_-1px_0_0_var(--border)]",
firstRight && "shadow-[inset_1px_0_0_var(--border)]",
)
}
// ---------------------------------------------------------------------------------------------
// Column helpers: a checkbox column for selection and a chevron column for expandable rows.
/** The row last clicked in each table, and whether shift is down, for shift-click range selection. */
const selectionAnchors = new WeakMap<object, string>()
const shiftHeld = new WeakMap<object, boolean>()
/**
* A checkbox column: the header checkbox selects every row on the page (and shows a dash when only
* some are), each row's checkbox selects that row, and shift-click selects the rows in between.
* (The dash fill is bg-primary! so it also beats the stock checkbox's dark-mode background.)
*/
function selectColumn<TData>({ label }: { label?: (row: Row<TData>) => string } = {}): ColumnDef<TData> {
return {
id: "select",
size: 44,
enableSorting: false,
enableHiding: false,
enableGlobalFilter: false,
meta: { label: "Select", headerClassName: "w-11 pr-0", cellClassName: "w-11 pr-0" },
header: ({ table }) => {
const some = table.getIsSomePageRowsSelected()
return (
<span className="relative flex w-fit">
<Checkbox
checked={table.getIsAllPageRowsSelected()}
indeterminate={some}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(value)}
aria-label="Select all rows on this page"
className="data-indeterminate:border-primary data-indeterminate:bg-primary! data-indeterminate:[&_[data-slot=checkbox-indicator]]:hidden"
/>
{some ? <MinusIcon aria-hidden="true" className="pointer-events-none absolute inset-0 m-auto size-3 text-primary-foreground" /> : null}
</span>
)
},
cell: ({ row, table }) => (
<Checkbox
checked={row.getIsSelected()}
disabled={!row.getCanSelect()}
aria-label={`Select ${label ? label(row) : `row ${row.index + 1}`}`}
// The change event comes from a hidden input, so read shift from the press itself.
onPointerDown={(event) => shiftHeld.set(table, event.shiftKey)}
onKeyDown={(event) => shiftHeld.set(table, event.shiftKey)}
onCheckedChange={(value) => {
const anchor = selectionAnchors.get(table)
const shift = shiftHeld.get(table) ?? false
selectionAnchors.set(table, row.id)
shiftHeld.delete(table)
if (!shift || !anchor || anchor === row.id) return row.toggleSelected(value)
const pageRows = table.getRowModel().rows
const a = pageRows.findIndex((r) => r.id === anchor)
const b = pageRows.findIndex((r) => r.id === row.id)
if (a === -1) return row.toggleSelected(value)
const range = pageRows.slice(Math.min(a, b), Math.max(a, b) + 1).filter((r) => r.getCanSelect())
table.setRowSelection((prev) => {
const next = { ...prev }
for (const r of range) {
if (value) next[r.id] = true
else delete next[r.id]
}
return next
})
}}
/>
),
}
}
/**
* A chevron column for rows that expand (DataTable's renderSubRow). The header button opens or
* closes every row at once.
*/
function expandColumn<TData>({ label }: { label?: (row: Row<TData>) => string } = {}): ColumnDef<TData> {
return {
id: "expand",
size: 48,
enableSorting: false,
enableHiding: false,
enableGlobalFilter: false,
meta: { label: "Details", headerClassName: "w-12 pr-0", cellClassName: "w-12 pr-0" },
header: ({ table }) => {
const all = table.getIsAllRowsExpanded()
return (
<Button
variant="ghost"
size="icon-sm"
className="-ml-1.5 text-muted-foreground"
onClick={() => table.toggleAllRowsExpanded(!all)}
aria-label={all ? "Collapse all rows" : "Expand all rows"}
>
{all ? <ChevronsDownUpIcon /> : <ChevronsUpDownIcon />}
</Button>
)
},
cell: ({ row }) =>
row.getCanExpand() ? (
<Button
variant="ghost"
size="icon-sm"
className="-ml-1.5"
onClick={row.getToggleExpandedHandler()}
aria-expanded={row.getIsExpanded()}
aria-label={`${row.getIsExpanded() ? "Hide" : "Show"} details for ${label ? label(row) : `row ${row.index + 1}`}`}
>
{row.getIsExpanded() ? <ChevronDownIcon /> : <ChevronRightIcon />}
</Button>
) : null,
}
}
export { DataTable, expandColumn, selectColumn }
export type { DataTableProps }