Table
A responsive data table with sortable columns, per-column alignment, numeric formatting, and content-sized columns by default. Align by content type: text left, magnitudes right (numeric), identifier numbers (IDs/SKUs) left, row actions in a dedicated trailing Actions column, and icon-only data right or center. Defaults to auto-layout: columns size to their content, visual rhythm comes from consistent cell padding. Opt into layout="fixed" when you need predictable widths.
Installation
npx shadcn@latest add https://ui.mattdowney.com/r/table.jsonUsage
import {
Table, TableHeader, TableBody, TableHead, TableRow, TableCell,
} from "@/components/ui/table"Examples
Default
Columns size to their content out of the box. Mark magnitude columns numeric and they right-align with tabular figures; leave it off identifier numbers like IDs and SKUs, which read as text.
| Product | Price | Sales | Revenue |
|---|---|---|---|
| Super Life | $29 | 847 | $24,563 |
| Super Work | $29 | 623 | $18,067 |
| Super Budget | $19 | 1,204 | $22,876 |
| Super Goals | $19 | 956 | $18,164 |
Compact
One type step down with tightened cells. Use for dense reference and spec tables where scan speed matters more than reading comfort.
| Product | Price | Sales | Revenue |
|---|---|---|---|
| Super Life | $29 | 847 | $24,563 |
| Super Work | $29 | 623 | $18,067 |
| Super Budget | $19 | 1,204 | $22,876 |
| Super Goals | $19 | 956 | $18,164 |
Sortable
Click any column header to sort. Click again to reverse direction.
| Building AI-Powered Business Tools | Published | Mar 15, 2026 | 2,847 |
| The Case for Variable Fonts | Published | Mar 8, 2026 | 1,923 |
| Design Systems That Scale | Draft | Mar 1, 2026 | 0 |
| Typography on the Modern Web | Published | Feb 22, 2026 | 3,102 |
| From Figma to Code | Published | Feb 15, 2026 | 1,456 |
Stacked on a phone
The default, for a list of records read one at a time. Below 512px of the table's width each row becomes a title with labelled lines under it. The header row hides, so a sortable table needs another way to sort there.
| Invoice | Customer | Status | Due | Amount |
|---|---|---|---|---|
| INV-1042 | Priya Nair | Paid | Sep 30, 2026 | $1,240.00 |
| INV-1041 | Sam Okafor | Overdue | Sep 18, 2026 | $860.00 |
| INV-1040 | Alex Rivera | Paid | Sep 12, 2026 | $2,115.50 |
Row Actions
Keep the primary action and More trigger visible. Secondary state and destructive actions stay in the menu; deletion opens a confirmation dialog.
| Idea | Signal | Actions |
|---|---|---|
| Keep mandatory design rules in the agent’s instructions | High | |
| Make a knowledge base searchable and actionable | High | |
| Show intent through small hover-timing details | Medium |
Striped
Alternating row tints, for a wide table where the eye has to travel across a long row. Leave them off short or narrow tables, where the stripes are noise.
| Product | Status | Price | Sales | Revenue |
|---|---|---|---|---|
| Super Life | Active | $29 | 847 | $24,563 |
| Super Work | Active | $29 | 623 | $18,067 |
| Super Budget | Active | $19 | 1,204 | $22,876 |
| Super Goals | Draft | $19 | 0 | $0 |
| Super Reads | Active | $24 | 412 | $9,888 |
| Super Notes | Active | $19 | 738 | $14,022 |
With Selected Row
Paint the active row with selected. Which row that is stays yours to track; the table only paints it.
| Product | Price | Sales | Revenue |
|---|---|---|---|
| Super Life | $29 | 847 | $24,563 |
| Super Work | $29 | 623 | $18,067 |
| Super Budget | $19 | 1,204 | $22,876 |
| Super Goals | $19 | 956 | $18,164 |
Pick a row
A list beside a preview of the picked row. Give each row selected and onSelect: a click, Enter or Space picks it, and the arrow keys move the pick. Controls inside the row keep their own clicks.
| Day | Subject |
|---|---|
| 0 | Welcome to the newsletter |
| 2 | The three posts to start with |
| 5 | How I plan a week of work |
Thanks for subscribing. Here is what to expect each week.
API Reference
| Prop | Type | Default | Description |
|---|---|---|---|
| layoutTable | "auto" | "fixed" | "auto" | Column-sizing strategy: auto sizes columns to their content, fixed honors declared widths and fills the container. |
| firstColumnWidthTable | string | null | "17.5rem" | Width of the first column, only applied when layout="fixed"; pass null to disable. |
| lastColumnWidthTable | string | null | "10rem" | Width of the last column, only applied when layout="fixed"; pass null to disable. |
| columnCountTable | number | None | Overrides the auto-detected column count for fixed layout when children aren't a simple Header > Row > Head tree. |
| stripedTable | boolean | false | Applies an alternating background to body rows. |
| densityTable | "default" | "compact" | "default" | Row density. compact steps body type down one size and tightens cell padding for dense reference tables. |
| phoneTable | "stack" | "fit" | "grid" | "scroll" | "stack" (2 columns or fewer: "fit") | What the table does below 512px of its own width; above that nothing changes. stack turns each row into a title line plus one labelled line per cell, labelled from the header row, for record lists (a leading checkbox sits beside the title and the second cell is the title); a value too long to sit beside its label drops under it. fit keeps the columns with no sideways scroll: the first column takes the free width, each value column shrinks to its longest word, cells wrap; for comparisons of up to three value columns, like plans against features, and the default for two columns or fewer. grid sizes every column to its content and shares the spare width, for a short key against short values, like a size chart. scroll keeps full-width columns and scrolls sideways with the first column pinned; only for wide data with four or more value columns. Stacked cells your own component renders are labelled too; data-label on a cell overrides its label, and data-label="" drops it. |
| stackTable | boolean | None | Deprecated: use phone. stack is phone="stack", and stack={false} is phone="scroll". |
| stickyHeaderTable | boolean | false | Freezes the header row so it stays visible while the body scrolls. Needs a scrolling ancestor with a bounded height; pair with ScrollFade fade="bottom" so a top skim does not fade the frozen header. |
| surfaceTable | "card" | "bare" | "card" | Container chrome. card paints the table's own surface (radius, border, background, shadow). Use bare when the table already sits inside a Card, so you don't nest one card in another. |
| selectedTableRow | boolean | false | Paints the row selected. With onSelect, a screen reader hears it as selected too. |
| onSelectTableRow | () => void | None | Makes the row pickable by click, Enter, Space and the arrow keys, with one tab stop for the list. For a list beside a preview. |
| sortableTableHead | boolean | false | Renders the header content as a sort button with a direction glyph. |
| sortedTableHead | "asc" | "desc" | false | false | Current sort direction for the column; drives the glyph and aria-sort. |
| onSortTableHead | () => void | None | Called when a sortable header is clicked. |
| alignTableHead, TableCell | "left" | "center" | "right" | "left" | Column alignment; defaults to "right" when numeric is set. |
| numericTableHead, TableCell | boolean | false | Right-aligns with tabular-nums for magnitude columns (prices, counts); leave off for identifier numbers like IDs and SKUs. |
| widthTableHead | "label" | "value" | "fill" | "auto" | string | None | Column width strategy. "label" and "value" apply the proportional spec-table widths (a leading label column, a trailing metric column) under layout="fixed"; "fill" absorbs all remaining space, "auto" shrinks to content, or any explicit CSS width such as "120px" or "20%". |
layoutTable"auto" | "fixed" = "auto"Column-sizing strategy: auto sizes columns to their content, fixed honors declared widths and fills the container. |
firstColumnWidthTablestring | null = "17.5rem"Width of the first column, only applied when layout="fixed"; pass null to disable. |
lastColumnWidthTablestring | null = "10rem"Width of the last column, only applied when layout="fixed"; pass null to disable. |
| columnCountTablenumberOverrides the auto-detected column count for fixed layout when children aren't a simple Header > Row > Head tree. |
| stripedTableboolean = falseApplies an alternating background to body rows. |
densityTable"default" | "compact" = "default"Row density. compact steps body type down one size and tightens cell padding for dense reference tables. |
phoneTable"stack" | "fit" | "grid" | "scroll" = "stack" (2 columns or fewer: "fit")What the table does below 512px of its own width; above that nothing changes. stack turns each row into a title line plus one labelled line per cell, labelled from the header row, for record lists (a leading checkbox sits beside the title and the second cell is the title); a value too long to sit beside its label drops under it. fit keeps the columns with no sideways scroll: the first column takes the free width, each value column shrinks to its longest word, cells wrap; for comparisons of up to three value columns, like plans against features, and the default for two columns or fewer. grid sizes every column to its content and shares the spare width, for a short key against short values, like a size chart. scroll keeps full-width columns and scrolls sideways with the first column pinned; only for wide data with four or more value columns. Stacked cells your own component renders are labelled too; data-label on a cell overrides its label, and data-label="" drops it. |
stackTablebooleanDeprecated: use phone. stack is phone="stack", and stack={false} is phone="scroll". |
stickyHeaderTableboolean = falseFreezes the header row so it stays visible while the body scrolls. Needs a scrolling ancestor with a bounded height; pair with ScrollFade fade="bottom" so a top skim does not fade the frozen header. |
surfaceTable"card" | "bare" = "card"Container chrome. card paints the table's own surface (radius, border, background, shadow). Use bare when the table already sits inside a Card, so you don't nest one card in another. |
selectedTableRowboolean = falsePaints the row selected. With onSelect, a screen reader hears it as selected too. |
| onSelectTableRow() => voidMakes the row pickable by click, Enter, Space and the arrow keys, with one tab stop for the list. For a list beside a preview. |
| sortableTableHeadboolean = falseRenders the header content as a sort button with a direction glyph. |
sortedTableHead"asc" | "desc" | false = falseCurrent sort direction for the column; drives the glyph and aria-sort. |
| onSortTableHead() => voidCalled when a sortable header is clicked. |
alignTableHead, TableCell"left" | "center" | "right" = "left"Column alignment; defaults to "right" when numeric is set. |
| numericTableHead, TableCellboolean = falseRight-aligns with tabular-nums for magnitude columns (prices, counts); leave off for identifier numbers like IDs and SKUs. |
widthTableHead"label" | "value" | "fill" | "auto" | stringColumn width strategy. "label" and "value" apply the proportional spec-table widths (a leading label column, a trailing metric column) under layout="fixed"; "fill" absorbs all remaining space, "auto" shrinks to content, or any explicit CSS width such as "120px" or "20%". |
"use client"
import * as React from "react"
import { IconChevronDown as ChevronDown, IconChevronUp as ChevronUp, IconSelector as ChevronsUpDown } from "@tabler/icons-react"
import { cn } from "@/registry/lib/utils"
import { ScrollFade } from "@/registry/ui/scroll-fade"
/**
* Semantic column widths for "spec" tables (label · description · value), the
* recurring shape used across docs/reference tables. Declaring roles instead of
* raw rem values keeps every spec table proportioned consistently. These apply
* as MIN-widths (see TableHead): in the default auto layout each column holds its
* width as a floor but expands to fit long content, so a long label can never
* overflow into its neighbor. The description column (`width="fill"`) absorbs the
* remainder. Spec tables should use the default auto layout, not `layout="fixed"`.
*/
const COLUMN_WIDTHS = {
/** Leading label / name / token column. */
label: "10rem",
/** Trailing value / metric column (sizes, durations, token values). */
value: "8rem",
} as const
function isSpecWidth(w: string | undefined): w is keyof typeof COLUMN_WIDTHS {
return w === "label" || w === "value"
}
type TableDensity = "default" | "compact"
type TablePhone = "stack" | "fit" | "grid" | "scroll"
// Cell padding and body type live on TableHead/TableCell, so the root shares
// its density through context rather than fragile descendant selectors.
const TableDensityContext = React.createContext<TableDensity>("default")
// Whether the header row is frozen. Shared through context so a consumer flips
// it once on <Table> and TableHeader picks it up, without threading a prop
// through every header the consumer renders.
const TableStickyHeaderContext = React.createContext(false)
// The container surface, shared the same way. TableHeader reads it so a bare
// table's thead stops painting bg-muted: that fill was hardcoded regardless
// of `surface`, so a "bare" table sitting inside a Sheet still drew a muted
// band that belonged to the sheet surface it was supposed to have shed.
const TableSurfaceContext = React.createContext<"card" | "bare">("card")
// Match an element against one of this module's components by a stable marker
// rather than referential identity. Identity (`node.type === Component`) breaks
// under Fast Refresh / HMR and across bundler boundaries, which silently zeroes
// out the column detection below. A string `displayName` survives both (and
// minification, since it is an explicit literal), so the detection stays correct.
//
// A table written in a Server Component (an App Router page by default) hands
// this client module elements whose `type` is not the component at all but a
// lazy wrapper around the client reference, with no `displayName` of its own.
// Read without unwrapping, every check failed: no stacked-row labels and no
// colgroup on any server page, with a green build. `resolveType` reads through
// it the way React does when it renders the element. If the module has not
// loaded yet the wrapper throws, and the element is treated as unknown.
const LAZY = Symbol.for("react.lazy")
function resolveType(type: unknown): unknown {
const lazy = type as { $$typeof?: symbol; _payload?: unknown; _init?: (payload: unknown) => unknown } | null
if (!lazy || typeof lazy !== "object" || lazy.$$typeof !== LAZY || typeof lazy._init !== "function") return type
try {
return resolveType(lazy._init(lazy._payload))
} catch {
return undefined
}
}
function isElementOfType(
node: React.ReactNode,
component: { displayName?: string },
): node is React.ReactElement {
if (!React.isValidElement(node)) return false
const type = resolveType(node.type)
if (type === component) return true
if (!type || typeof type === "string") return false
return (type as { displayName?: string }).displayName === component.displayName
}
type TableProps = React.ComponentProps<"table"> & {
/**
* Column-sizing strategy.
*
* "auto" (default) - columns size to their content. Visual rhythm comes
* from consistent cell padding, not from width math.
* Best for most product tables. Matches what Linear,
* Stripe, Notion, GitHub, and shadcn/ui all do.
*
* "fixed" - columns honor their declared widths regardless of content.
* The table fills its container. Use when you need:
* predictable widths for streaming/virtualized data,
* user-resizable columns, sticky columns, or clean
* text-overflow ellipsis truncation.
*
* NOTE: in fixed mode, content wider than a column's
* width overflows into the next column unless you
* truncate it. For docs/reference "spec" tables with
* variable-length labels, prefer the default auto layout:
* the semantic `label`/`value` widths act as min-widths
* that expand to fit, so nothing ever overflows.
*/
layout?: "auto" | "fixed"
/**
* Width of the first column. Only applied when `layout="fixed"`.
* Pass null to disable. Defaults to 17.5rem (280px) in fixed mode.
*/
firstColumnWidth?: string | null
/**
* Width of the last column. Only applied when `layout="fixed"`.
* Pass null to disable. Defaults to 10rem (160px) in fixed mode.
*/
lastColumnWidth?: string | null
/** Override auto-detected column count when children aren't a simple Header > Row > Head tree. */
columnCount?: number
/** Apply alternating row background to body rows. */
striped?: boolean
/**
* Row density.
*
* "default" - reading-comfort tier: text-sm body, px-6 py-3 cells (px-4
* below 576px of the table's own width), h-11 header.
* "compact" - one type step down (text-xs body) with tightened cells
* (px-4 py-2, h-9 header). Use for dense reference and spec
* tables where scan speed matters more than reading comfort.
*/
density?: TableDensity
/**
* Freeze the header row so it stays visible while the body scrolls: the thead
* becomes `sticky top-0` at the sticky z-tier, carrying its opaque header
* background so rows pass beneath it. Needs a scrolling ancestor with a
* bounded height (a ScrollFade viewport, or an `overflow-y-auto` container
* with a height). Pair with ScrollFade `fade="bottom"` so a top skim does not
* fade the frozen header.
*/
stickyHeader?: boolean
/**
* The container surface.
*
* "card" (default) - the table paints its own card: rounded-lg, a real
* border, bg-card, shadow-xs. Correct when the table IS
* the surface on the screen.
*
* "bare" - no border, background, radius, or shadow. Use when the
* table already sits inside another surface that is NOT
* a Card - a Sheet, Drawer, or Dialog. A table never goes
* inside a Card, with or without `surface="bare"`: a Card
* is a surface too, so nesting them stacks two surfaces
* on one box (two edges, two radii, a shadow inside a
* shadow). Card-bound data uses CardRows/CardRow instead.
*
* Row rules, the header fill, and sticky-header behavior are identical in
* both: only the container chrome changes.
*/
surface?: "card" | "bare"
/**
* What the table does below 512px of its own width (a phone, a narrow pane).
* Above that nothing changes.
*
* "stack" (default from 3 columns) - each row becomes a short stack: the
* first cell as the row's title, then one line per
* remaining cell with its column header as the label.
* For a list of records read one at a time (orders,
* people, invoices), which is most tables. A value
* too long to sit beside its label (a sentence) wraps
* onto its own line under it, aligned to the start.
* "fit" - keeps the columns and fits them to the width, with no
* sideways scroll: the first column takes the free
* width and wraps, each value column shrinks to its
* longest word, every cell wraps. For a comparison of up to
* three value columns (plans against features), the
* shape phone paywalls use. The default for a table of
* two columns or fewer (a label and a price).
* "grid" - keeps the columns and fits them to the width, every
* column sized to its content and the spare width
* shared among them. For a short key against several
* short values (a size chart), where "fit" would give
* the one-letter key the room the values need.
* "scroll" - keeps the columns at full width and scrolls sideways
* with the first column pinned. Only for wide data
* with four or more value columns.
*
* Stacked: when the first cell holds a checkbox, the checkbox sits beside the
* title and the second cell becomes the title. Labels come from the header
* row's text and reach every cell, including a cell or a row your own
* component renders. A cell with its own `data-label` keeps it.
*/
phone?: TablePhone
/**
* @deprecated Use `phone`. `stack` is `phone="stack"`, and `stack={false}`
* is `phone="scroll"`, its old meaning. `phone` wins when both are set.
*/
stack?: boolean
children?: React.ReactNode
}
// A node's text, for a column label: a header reads "Customer" whether it is a
// string or a sort button wrapping one.
function textOf(node: React.ReactNode): string {
if (typeof node === "string" || typeof node === "number") return String(node)
if (Array.isArray(node)) return node.map(textOf).join("")
if (React.isValidElement(node)) return textOf((node.props as { children?: React.ReactNode }).children)
return ""
}
function withCellLabels(children: React.ReactNode, labels: string[]): React.ReactNode {
return React.Children.map(children, (section) => {
if (!isElementOfType(section, TableBody)) return section
const rows = React.Children.map((section.props as { children?: React.ReactNode }).children, (row) => {
if (!isElementOfType(row, TableRow)) return row
let i = 0
const cells = React.Children.map((row.props as { children?: React.ReactNode }).children, (cell) => {
if (!React.isValidElement(cell)) return cell
const label = labels[i++]
const own = (cell.props as { "data-label"?: string })["data-label"]
return own !== undefined || !label ? cell : React.cloneElement(cell as React.ReactElement<{ "data-label"?: string }>, { "data-label": label })
})
return React.cloneElement(row as React.ReactElement<{ children?: React.ReactNode }>, { children: cells })
})
return React.cloneElement(section as React.ReactElement<{ children?: React.ReactNode }>, { children: rows })
})
}
// The same labels, applied to the rendered table. withCellLabels can only see
// cells written straight into a TableRow; a cell the page wraps in its own
// component (a RateCell that returns a TableCell) receives the label as a prop
// and drops it, so on a phone that value showed with no label and nothing
// warned. This reads the header row and the body rows as rendered and fills
// in each cell still missing a label by its column, counting colSpan. A cell
// with its own `data-label` keeps it. It re-runs when rows are added or
// replaced, which is what filtering or paging does.
const AUTO_LABEL = "data-label-auto"
function labelRenderedCells(table: HTMLTableElement) {
const header = table.tHead?.rows[0]
if (!header) return
const labels: string[] = []
for (const th of Array.from(header.cells)) {
for (let n = 0; n < th.colSpan; n++) labels.push(th.textContent?.trim() ?? "")
}
for (const body of Array.from(table.tBodies)) {
for (const row of Array.from(body.rows)) {
let column = 0
for (const cell of Array.from(row.cells)) {
const label = labels[column]
column += cell.colSpan
const own = cell.hasAttribute("data-label") && !cell.hasAttribute(AUTO_LABEL)
if (own || !label || cell.getAttribute("data-label") === label) continue
cell.setAttribute("data-label", label)
cell.setAttribute(AUTO_LABEL, "")
}
}
}
}
// Pinned first column (see `pin` in Table). Sticky against the ScrollFade
// viewport, which is the scroller. Header cells take the header's own fill.
// A checkbox column is never the one pinned, since it names nothing.
const PIN_FIRST_COLUMN = cn(
"[&_tr>:first-child:not(:has([role=checkbox]))]:sticky [&_tr>:first-child:not(:has([role=checkbox]))]:start-0 [&_tr>:first-child:not(:has([role=checkbox]))]:z-10",
// The fill stops 1px short of the cell's top and bottom edges. A row's rule
// is the ROW's border, and depending on where the row lands on the pixel
// grid it paints in the bottom pixel of one row or the top pixel of the
// next; an opaque fill over either pixel erased it, so pinned columns lost
// their row lines on some tables and not others. Through the 1px strips
// shows whatever scrolls under the cell in the same row: the same rule, or
// the same row fill. The tint layer is the row's stripe or selection.
"[&_tbody_tr>td:first-child]:[background:linear-gradient(var(--row-tint,transparent),var(--row-tint,transparent))_0_1px/100%_calc(100%-2px)_no-repeat,linear-gradient(var(--card),var(--card))_0_1px/100%_calc(100%-2px)_no-repeat]",
"[&_thead_tr>th:first-child]:[background:linear-gradient(var(--muted),var(--muted))_0_1px/100%_calc(100%-2px)_no-repeat]",
"[&_tfoot_tr>td:first-child]:[background:linear-gradient(var(--muted),var(--muted))_0_1px/100%_calc(100%-2px)_no-repeat]",
// A hairline on its trailing edge, only while the rest is scrolled under
// it: ScrollFade publishes how far it has scrolled, and `min(1px, ...)`
// turns that into a 0 or 1px inset. At rest, and on a table that fits,
// there is no line. The bare `--border` token, as the sticky header uses.
"[&_tr>:first-child:not(:has([role=checkbox]))]:shadow-[inset_calc(-1*min(1px,var(--sf-scroll-left,0px)))_0_0_0_var(--border)]"
)
// Stacked rows (see `phone` in Table), below the `lg` container width (32rem).
// The table's parts drop their table display, the header row hides (its text
// rides on each value as a label), and every row becomes a title line plus
// label/value lines, spaced on the `lines` rung. Specificity beats the cells'
// own padding and alignment.
//
// A row wraps rather than stacking in a column, so a few cells can share the
// title line and every other cell takes a full line of its own, no taller
// than what it holds. `order` sets the title line: a leading checkbox, then
// the title, then the row's menu at the far end, the way a phone list puts a
// row's menu top-right. A checkbox column names nothing, so in a row that
// leads with one the second cell is the title. The menu cell is the one whose
// header reads "Actions", or that holds nothing but a menu button; it takes
// no label line of its own. A table with neither is untouched by those rules.
const STACK_ROWS = cn(
"@max-lg:block @max-lg:[&_thead]:hidden @max-lg:[&_tbody]:block @max-lg:[&_tfoot]:block",
"@max-lg:[&_tr]:flex @max-lg:[&_tr]:flex-row @max-lg:[&_tr]:flex-wrap @max-lg:[&_tr]:items-start @max-lg:[&_tr]:gap-x-3 @max-lg:[&_tr]:gap-y-(--spacing-rhythm-lines) @max-lg:[&_tr]:px-4 @max-lg:[&_tr]:py-3",
// A value line wraps: a short value sits at the end beside its label
// (justify-between), and one too long for that (a sentence) drops onto its
// own line under the label, aligned to the start. Right-aligned, a wrapped
// sentence sat ragged against the end edge.
"@max-lg:[&_td]:order-2 @max-lg:[&_td]:flex @max-lg:[&_td]:flex-wrap @max-lg:[&_td]:basis-full @max-lg:[&_td]:items-baseline @max-lg:[&_td]:justify-between @max-lg:[&_td]:gap-x-4 @max-lg:[&_td]:gap-y-1 @max-lg:[&_td]:p-0 @max-lg:[&_td]:text-start",
"@max-lg:[&_td]:before:shrink-0 @max-lg:[&_td]:before:text-start @max-lg:[&_td]:before:text-1xs @max-lg:[&_td]:before:text-subtle-foreground @max-lg:[&_td]:before:content-[attr(data-label)]",
"@max-lg:[&_td:first-child]:order-0 @max-lg:[&_td:first-child]:min-w-0 @max-lg:[&_td:first-child]:flex-1 @max-lg:[&_td:first-child]:text-start @max-lg:[&_td:first-child]:font-medium @max-lg:[&_td:first-child]:text-foreground @max-lg:[&_td:first-child]:before:hidden",
// The leading checkbox, beside the title on its first line.
"@max-lg:[&_tr:has(>td:first-child_[role=checkbox])>td:first-child]:flex-none @max-lg:[&_tr:has(>td:first-child_[role=checkbox])>td:first-child]:h-5 @max-lg:[&_tr:has(>td:first-child_[role=checkbox])>td:first-child]:items-center",
"@max-lg:[&_tr:has(>td:first-child_[role=checkbox])>td:nth-child(2)]:order-0 @max-lg:[&_tr:has(>td:first-child_[role=checkbox])>td:nth-child(2)]:min-w-0 @max-lg:[&_tr:has(>td:first-child_[role=checkbox])>td:nth-child(2)]:flex-1 @max-lg:[&_tr:has(>td:first-child_[role=checkbox])>td:nth-child(2)]:text-start @max-lg:[&_tr:has(>td:first-child_[role=checkbox])>td:nth-child(2)]:font-medium @max-lg:[&_tr:has(>td:first-child_[role=checkbox])>td:nth-child(2)]:text-foreground @max-lg:[&_tr:has(>td:first-child_[role=checkbox])>td:nth-child(2)]:before:hidden",
// The row's menu, at the end of the title line. The negative margin lets a
// 28px button sit on a 20px title line without pushing the lines below.
"@max-lg:[&_tr>td:is([data-label=Actions_i],:has(>[aria-haspopup]:only-child))]:order-1 @max-lg:[&_tr>td:is([data-label=Actions_i],:has(>[aria-haspopup]:only-child))]:flex-none @max-lg:[&_tr>td:is([data-label=Actions_i],:has(>[aria-haspopup]:only-child))]:-my-1 @max-lg:[&_tr>td:is([data-label=Actions_i],:has(>[aria-haspopup]:only-child))]:before:hidden",
// A stacked row is one box with no pinned column, so a pickable row's focus
// ring goes back on the row: drawn inside its cells it would rule a line
// between every stacked value.
"@max-lg:[&_tr[data-selectable]:focus-visible>td]:shadow-none! @max-lg:[&_tr[data-selectable]:focus-visible]:outline-solid @max-lg:[&_tr[data-selectable]:focus-visible]:outline-3 @max-lg:[&_tr[data-selectable]:focus-visible]:-outline-offset-3 @max-lg:[&_tr[data-selectable]:focus-visible]:outline-ring-focus"
)
// Fitted columns (see `phone="fit"` in Table), below the `lg` container width
// (32rem). The first column takes all the free width and every other column
// shrinks to its longest word, so the value columns sit narrow and alike
// while the table stays inside its box. A fixed layout with equal 5rem value
// columns was tried first: it broke "Unlimited" and "$24,563" mid-word on a
// phone and left a 52px name column in a 292px pane, because it cannot see
// the content. Every cell wraps; only the first column may break inside a
// word, as the last resort for a long name. Padding steps down a rung, and a
// value cell one more, since its words cannot wrap any narrower. The `!`
// marks beat a header's own `width`, a fixed table's colgroup and the text
// columns' minimums, which would otherwise widen the table past its box.
// Only the gaps BETWEEN columns step down on a narrow table. The table's own
// edges keep the 16px inset every other surface in the kit uses (a card's
// content, the wide table), or the first column hugs the border.
const EDGE_CELLS = "@max-lg:[&_tr>:first-child]:ps-4! @max-lg:[&_tr>:last-child]:pe-4!"
const FIT_COLUMNS = cn(
"@max-lg:table-auto @max-lg:[&_col]:w-auto!",
"@max-lg:[&_th]:min-w-0! @max-lg:[&_th]:whitespace-normal @max-lg:[&_td]:whitespace-normal",
"@max-lg:[&_tr>:first-child]:w-full! @max-lg:[&_tr>:first-child]:wrap-anywhere @max-lg:[&_tr>:not(:first-child)]:w-auto!",
"@max-lg:[&_th]:px-3 @max-lg:[&_td]:px-3 @max-lg:[&_tr>:not(:first-child)]:px-2",
EDGE_CELLS
)
// Grid columns (see `phone="grid"` in Table), below the `lg` container width.
// FIT_COLUMNS gives the first column all the free width, which is right for a
// plan name against short values and wrong for a one-letter size against
// three measurements: the key took the room and "19 5/8″" broke in two. Here
// every column sizes to its content and the auto layout shares what is left,
// so values only wrap when the table truly does not fit.
const GRID_COLUMNS = cn(
"@max-lg:table-auto @max-lg:[&_col]:w-auto!",
"@max-lg:[&_th]:min-w-0! @max-lg:[&_th]:whitespace-normal @max-lg:[&_td]:whitespace-normal @max-lg:[&_tr>*]:w-auto!",
"@max-lg:[&_th]:px-2 @max-lg:[&_td]:px-2",
EDGE_CELLS
)
// @use-when tabular data standing on the page by itself, including a list
// whose picked row shows in a preview beside it (TableRow `onSelect`). Never
// inside a Card.
function Table({
className,
layout = "auto",
firstColumnWidth = "17.5rem",
lastColumnWidth = "10rem",
columnCount: columnCountProp,
striped,
density = "default",
stickyHeader = false,
surface = "card",
phone: phoneProp,
stack,
children,
ref,
...props
}: TableProps) {
// `stack` is the old switch: on meant stacked rows, off meant scroll.
// Read before `phone`: a table of two columns or fewer (a label and a price)
// fits rather than stacking, since stacking it doubles every line.
const headerColumns = React.useMemo(() => {
let count = 0
let done = false
React.Children.forEach(children, (node) => {
if (done || !isElementOfType(node, TableHeader)) return
React.Children.forEach((node.props as { children?: React.ReactNode }).children, (rowNode) => {
if (done || !isElementOfType(rowNode, TableRow)) return
React.Children.forEach((rowNode.props as { children?: React.ReactNode }).children, (cell) => {
if (React.isValidElement(cell)) count++
})
done = true
})
})
return count
}, [children])
const phone: TablePhone =
phoneProp ??
(stack === false ? "scroll" : headerColumns > 0 && headerColumns <= 2 ? "fit" : "stack")
const stacked = phone === "stack"
const tableRef = React.useRef<HTMLTableElement | null>(null)
const setRef = React.useCallback(
(node: HTMLTableElement | null) => {
tableRef.current = node
if (typeof ref === "function") ref(node)
else if (ref) ref.current = node
},
[ref],
)
React.useLayoutEffect(() => {
const table = tableRef.current
if (!stacked || !table) return
labelRenderedCells(table)
const observer = new MutationObserver(() => labelRenderedCells(table))
observer.observe(table, { childList: true, subtree: true })
return () => observer.disconnect()
}, [stacked])
const isFixed = layout === "fixed"
// Read the first header row to learn the column count and each column's
// declared `width`, so a fixed table can build a colgroup that honors the
// per-column widths (semantic tokens, explicit values, or "fill"/"auto").
const { columnCount, columnWidths, columnLabels } = React.useMemo(() => {
const widths: (string | undefined)[] = []
const labels: string[] = []
let done = false
React.Children.forEach(children, (node) => {
if (done || !isElementOfType(node, TableHeader)) return
React.Children.forEach((node.props as { children?: React.ReactNode }).children, (rowNode) => {
if (done || !isElementOfType(rowNode, TableRow)) return
React.Children.forEach((rowNode.props as { children?: React.ReactNode }).children, (cell) => {
if (!React.isValidElement(cell)) return
const cellProps = cell.props as { width?: string; children?: React.ReactNode }
widths.push(cellProps.width)
labels.push(textOf(cellProps.children))
})
done = true
})
})
if (columnCountProp !== undefined) {
return { columnCount: columnCountProp, columnWidths: [] as (string | undefined)[], columnLabels: labels }
}
return { columnCount: widths.length, columnWidths: widths, columnLabels: labels }
}, [children, columnCountProp])
// Stacked rows label each value with its column header. A cell that already
// carries `data-label` keeps its own.
const body = stacked ? withCellLabels(children, columnLabels) : children
// The first column stays put while the rest scroll, so the row a value
// belongs to never leaves the screen. Only on the card surface, where the
// cell has a known opaque fill to cover what scrolls under it; a bare table
// sits on someone else's surface.
const pin = surface === "card" && !stickyHeader
// A column gets an explicit colgroup width when it's labelled (semantic token
// or raw value); "fill"/"auto"/undeclared columns are left to share the
// remaining space evenly (native table-fixed behavior). firstColumnWidth /
// lastColumnWidth remain the fallback for fixed tables that declare nothing.
const cols = isFixed && columnCount > 0 ? Array.from({ length: columnCount }, (_, i) => {
const declared = columnWidths[i]
const width =
declared === "fill" || declared === "auto" ? undefined :
isSpecWidth(declared) ? COLUMN_WIDTHS[declared] :
declared ? declared :
i === 0 && firstColumnWidth ? firstColumnWidth :
i === columnCount - 1 && lastColumnWidth ? lastColumnWidth :
undefined
return <col key={i} style={width ? { width } : undefined} />
}) : null
const table = (
<table
ref={setRef}
data-slot="table"
data-density={density}
className={cn(
"w-full caption-bottom",
density === "compact" ? "text-xs" : "text-sm",
isFixed && "table-fixed",
// The stripe excludes a selected row rather than out-ranking it. Both
// are backgrounds on the same `tr`, and the stripe's selector is the
// stronger one for free: it descends from this element, so it scores
// (0,2,2) against the row's own (0,2,0) and WON the cascade on every
// even row. A selection was invisible on half the table, and raising
// the row's specificity to beat it would only trade one collision for
// another. `:not()` makes the two mutually exclusive instead, so the
// stripe is simply absent where a selection is painted.
striped &&
"[&_tbody_tr:nth-child(even):not([data-state=selected])]:bg-neutral-400/[0.04] dark:[&_tbody_tr:nth-child(even):not([data-state=selected])]:bg-neutral-500/[0.04]",
// The pinned cell paints the card under the row's own tint (stripe
// or selection), read from `--row-tint`, so it matches the row while
// hiding what scrolls beneath it.
striped &&
"[&_tbody_tr:nth-child(even):not([data-state=selected])]:[--row-tint:color-mix(in_oklab,var(--color-neutral-400)_4%,transparent)] dark:[&_tbody_tr:nth-child(even):not([data-state=selected])]:[--row-tint:color-mix(in_oklab,var(--color-neutral-500)_4%,transparent)]",
pin && PIN_FIRST_COLUMN,
stacked && STACK_ROWS,
phone === "fit" && FIT_COLUMNS,
phone === "grid" && GRID_COLUMNS,
className,
)}
{...props}
>
{cols && <colgroup>{cols}</colgroup>}
<TableDensityContext.Provider value={density}>
<TableStickyHeaderContext.Provider value={stickyHeader}>
<TableSurfaceContext.Provider value={surface}>
{body}
</TableSurfaceContext.Provider>
</TableStickyHeaderContext.Provider>
</TableDensityContext.Provider>
</table>
)
return (
<div
data-slot="table-container"
data-surface={surface}
className={cn(
// A size container, so cell padding answers to the table's own width
// rather than the viewport's.
"@container relative w-full",
// Container tier, not form-control tier: this paints its own card
// surface, so it rounds like Card (`rounded-lg`) rather than like an
// Input. It keeps a real border instead of Card's ring because the
// header and row rules are borders too, and they have to line up.
// `surface="bare"` drops all of it for a table that already sits on a
// surface, so nothing nests a card inside a card.
surface === "card" && "rounded-lg border border-border bg-card shadow-xs",
// A frozen header needs an OUTER scroll container to own scrolling: the
// built-in overflow-x-auto is itself a scroll container and would trap
// the sticky thead (it would stick to this wrapper, not the ancestor,
// and scroll away). Drop it when stickyHeader is set so the sticky
// header resolves against the bounded-height ancestor. A frozen-header
// table is expected to fit horizontally in that ancestor.
//
// Otherwise the scrolling happens one level in, in a horizontal
// ScrollFade: on a phone a table is wider than the screen as a rule,
// and a bare overflow-x-auto cut the last column mid-number with
// nothing to say there was more. The fade at the cut edge says it.
// This box only clips the corners.
stickyHeader ? "overflow-visible" : "overflow-hidden",
)}
>
{/* With the first column pinned, the leading edge is the pinned column
itself, so only the trailing edge fades. */}
{stickyHeader ? table : <ScrollFade orientation="horizontal" fade={pin ? "end" : "both"}>{table}</ScrollFade>}
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
const sticky = React.useContext(TableStickyHeaderContext)
const surface = React.useContext(TableSurfaceContext)
// A "bare" table already sits inside another surface (a Card), so its
// header shouldn't paint a second one: the muted fill is card/table chrome,
// and two chromed bands stacked read as a bug. A frozen bare header is the
// one exception: body rows scroll UNDER it, so it still needs an opaque
// background or their content shows through the "transparent" header.
const paintFill = surface === "card" || sticky
return (
<thead
data-slot="table-header"
className={cn(
paintFill && "bg-muted",
sticky
// Frozen header: the opaque bg-muted travels with the sticky thead, so
// body rows scroll underneath it (z-20 is the sticky-header z-tier).
// The divider is an INSET box-shadow on the header CELLS, not a border
// and not an outset shadow. A collapsed border is shared with the
// first body row and scrolls away under the sticky header; an outset
// shadow paints below the cell, into the first row, where the body
// cells (later in the DOM) paint over it. An inset shadow draws the
// 1px line at the bottom edge INSIDE the header cell, so it can't be
// covered or scroll away.
// border-b-0 suppresses TableRow's own baked-in bottom border on the
// header row, so the inset shadow is the SOLE divider (otherwise the
// row border and the shadow stack into a double 1px line at rest).
// The bare token, NOT the `--color-border` alias. That alias is an
// `@theme inline` entry declared once at `:root`, and a custom
// property resolves where it is declared, so it froze against the
// root palette: the stuck hairline painted a different grey from
// every real border beside it under any scope with its own palette.
? "sticky top-0 z-20 [&_tr]:border-b-0 [&_th]:shadow-[inset_0_-1px_0_0_var(--border)]"
: "[&_tr]:border-b [&_tr]:border-border",
className,
)}
{...props}
/>
)
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn("border-t border-border bg-muted font-medium [&>tr]:last:border-b-0", className)}
{...props}
/>
)
}
// A click that lands on a control inside the row belongs to that control, not
// to the row: a checkbox in the first cell toggles, it does not also pick.
const ROW_CONTROL = "a, button, input, select, textarea, label, [role=checkbox], [role=switch]"
/** The selectable rows of the body a row sits in, top to bottom. */
const selectableRows = (row: HTMLTableRowElement) =>
[...(row.closest("tbody")?.querySelectorAll<HTMLTableRowElement>("tr[data-selectable]") ?? [])]
function TableRow({
className,
selected,
onSelect,
onClick,
onKeyDown,
...props
}: React.ComponentProps<"tr"> & {
/** Paints the row selected. With `onSelect`, also tells a screen reader. */
selected?: boolean
/** Makes the row pickable: a click, Enter or Space picks it, and the arrow
* keys (plus Home and End) move to a neighbouring row and pick that. For a
* list beside a preview of the picked row. */
onSelect?: () => void
}) {
const ref = React.useRef<HTMLTableRowElement>(null)
const selectable = !!onSelect
// One tab stop for the whole list: the picked row, or the first row while
// nothing is picked. Set on the DOM after every render because it depends on
// the rows around this one, which a row's own props cannot see.
React.useEffect(() => {
const row = ref.current
if (!row || !selectable) return
const rows = selectableRows(row)
const picked = rows.find((r) => r.getAttribute("aria-selected") === "true")
row.tabIndex = row === (picked ?? rows[0]) ? 0 : -1
})
const pick = (row: HTMLTableRowElement | undefined) => {
if (!row) return
row.focus()
row.click()
}
return (
<tr
ref={ref}
data-slot="table-row"
data-state={selected ? "selected" : undefined}
data-selectable={selectable ? "" : undefined}
aria-selected={selectable ? !!selected : undefined}
onClick={(event) => {
onClick?.(event)
if (!selectable || event.defaultPrevented) return
const control = (event.target as HTMLElement).closest(ROW_CONTROL)
if (control && event.currentTarget.contains(control)) return
onSelect()
}}
onKeyDown={(event) => {
onKeyDown?.(event)
if (!selectable || event.defaultPrevented || event.target !== event.currentTarget) return
const rows = selectableRows(event.currentTarget)
const at = rows.indexOf(event.currentTarget)
const next = {
ArrowDown: rows[at + 1],
ArrowUp: rows[at - 1],
Home: rows[0],
End: rows[rows.length - 1],
}[event.key]
if (next) {
event.preventDefault()
pick(next)
} else if (event.key === "Enter" || event.key === " ") {
event.preventDefault()
onSelect()
}
}}
className={cn(
"border-b border-border",
// A pickable row takes a pointer and the kit's 3px focus ring, drawn
// inside its cells: each paints its top and bottom, the end cells their
// outer side. An outline on the row was the first try, and the pinned
// first column paints over it. `!` beats the pinned cell's own hairline
// shadow. `outline-hidden` keeps a ring in forced-colours mode.
selectable && [
"cursor-pointer outline-hidden",
"focus-visible:*:shadow-[inset_0_3px_0_0_var(--ring-focus),inset_0_-3px_0_0_var(--ring-focus)]!",
"focus-visible:*:first:shadow-[inset_3px_0_0_0_var(--ring-focus),inset_0_3px_0_0_var(--ring-focus),inset_0_-3px_0_0_var(--ring-focus)]!",
"focus-visible:*:last:shadow-[inset_-3px_0_0_0_var(--ring-focus),inset_0_3px_0_0_var(--ring-focus),inset_0_-3px_0_0_var(--ring-focus)]!",
],
// Selection is a STATE, not an emphasis, so it is a fill and nothing
// else. The old menu-row recipe (`accent-100` + `text-accent` on every
// child) is tuned for one transient highlighted row inside a popup; at
// table scale it is a different picture, because a table row is
// full-width, persistent, and multi-select.
//
// The fill is NEUTRAL in both modes, and that is the part to keep. The
// accent ramp has no rung quiet enough for this: its floor still reads
// as accent colour once a whole table is selected. Dark `accent-950` is
// C 0.0753, and a select-all across 39 rows of it is a slab of navy
// rather than a selection. A neutral tint (C 0.0017 light, 0.0024 dark)
// cannot do that at any row count.
//
// The values are picked against `bg-card`, the ground here: Table
// paints it, and `surface="bare"` exists for a table already sitting on
// a surface, where an alpha tint composites correctly and a solid step
// would not. An alpha tint also because no solid neutral rung is free:
// in light, card (L 0.9886) and `bg-muted` (0.9725) are adjacent rungs
// with nothing between them, and in dark, card (0.1651) and `bg-muted`
// (0.2242) are too.
//
// Light `neutral-900/5` composites to L 0.9531: 0.0355 under card,
// 0.0194 under `bg-muted`. Dark `neutral-100/[3.5%]` composites to
// L 0.2019: 0.0368 over card, 0.0223 under `bg-muted`. The dark half
// is off the opacity scale on purpose: at 4% it closes to 0.0172 of
// `bg-muted`, and at 3% it closes to 0.0143 of the stripe. 3.5% is the
// one value that clears both by roughly the same margin. `bg-muted` is
// the header and the footer, so a selected row landing on it reads as
// chrome, and the accent pair cleared it by hue alone: in light,
// `accent-50` sat 0.0025 of lightness from muted.
//
// The stripe is the third ground. Table excludes selected rows from it,
// but a selected row still sits BESIDE striped ones, at L 0.9776 light
// and 0.1824 dark. Both fills clear the stripe by ~0.02 as well, which
// the accent pair did not in dark: `accent-950` was 0.0026 off it and
// told apart by hue only.
//
// A row picked with `onSelect` is the other case: one row at a time,
// picked to show its details beside the list, which is what Nav and a
// menu's current item mark in the accent. It cannot become a slab,
// since only one row is ever picked, and the neutral tint sat too
// close to the lighter `bg-muted` header to read as picked. So a
// pick-one row takes a light accent tint; selection by checkbox keeps
// the neutral one.
selectable
? "data-[state=selected]:bg-accent-500/6 dark:data-[state=selected]:bg-accent-500/10 data-[state=selected]:[--row-tint:color-mix(in_oklab,var(--color-accent-500)_6%,transparent)] dark:data-[state=selected]:[--row-tint:color-mix(in_oklab,var(--color-accent-500)_10%,transparent)]"
: [
"data-[state=selected]:bg-neutral-900/5 dark:data-[state=selected]:bg-neutral-100/[3.5%]",
// The same tint as a variable, for Table's pinned first cell.
"data-[state=selected]:[--row-tint:color-mix(in_oklab,var(--color-neutral-900)_5%,transparent)] dark:data-[state=selected]:[--row-tint:color-mix(in_oklab,var(--color-neutral-100)_3.5%,transparent)]",
],
className
)}
{...props}
/>
)
}
type SortDirection = "asc" | "desc" | false
type Align = "left" | "center" | "right"
function alignToTextClass(align: Align) {
return align === "right" ? "text-end" : align === "center" ? "text-center" : "text-start"
}
function alignToJustifyClass(align: Align) {
return align === "right" ? "justify-end" : align === "center" ? "justify-center" : "justify-start"
}
function SortGlyph({ sorted }: { sorted: SortDirection }) {
if (sorted === "asc") {
return <ChevronUp aria-hidden="true" className="size-3.5 shrink-0 text-foreground" />
}
if (sorted === "desc") {
return <ChevronDown aria-hidden="true" className="size-3.5 shrink-0 text-foreground" />
}
return <ChevronsUpDown aria-hidden="true" className="size-3.5 shrink-0" />
}
type TableHeadProps = React.ComponentProps<"th"> & {
sortable?: boolean
sorted?: SortDirection
onSort?: () => void
/**
* Column alignment. Defaults to "left", or "right" when `numeric` is set.
*
* Align by content type:
* - Text, names, descriptions, dates, status badges → "left"
* - Magnitudes (prices, counts, %) → "right" + tabular-nums (use `numeric`)
* - Identifier numbers (IDs, SKUs, ports) → "left" - they're labels, not values
* - Row actions → a dedicated trailing "Actions" column, right-aligned.
* Keep one frequent, labelled action visible and put every secondary
* state or destructive action in an always-available More menu.
* - Icon-only / boolean-only (single ✓, star, avatar) → "center"
*/
align?: Align
/** Right-align with tabular-nums. Use for magnitude columns. For identifier numbers (IDs/SKUs), leave default. */
numeric?: boolean
/**
* Column width strategy. For "spec" tables (label · description · value),
* prefer the semantic tokens with `layout="fixed"` so every such table is
* proportioned identically:
* "label" - leading label/name column (a shared min-width floor that expands to fit).
* "value" - trailing value/metric column (a shared min-width floor that expands to fit).
* "fill" - absorb the remaining horizontal space (the description column).
* In a fixed table, multiple fill/undeclared columns split it evenly.
* "auto" - shrink to content width. Pair with whitespace-nowrap (auto layout).
* string - explicit CSS width (e.g. "120px", "20%").
*/
width?: "label" | "value" | "fill" | "auto" | string
}
function TableHead({ className, sortable, sorted, onSort, align, numeric, width, style, children, ...props }: TableHeadProps) {
const resolvedAlign: Align = align ?? (numeric ? "right" : "left")
const density = React.useContext(TableDensityContext)
const textColumn =
resolvedAlign === "left" && !numeric && children != null && (width == null || width === "fill")
// Spec widths are min-widths, not hard widths: in a spec table (auto layout)
// the column holds this as a proportional floor but expands to fit long
// content instead of overflowing into its neighbor. In a true fixed table the
// colgroup carries the exact width, so this min is a harmless floor.
const widthStyle: React.CSSProperties | undefined =
width === "fill" ? { width: "100%" }
: width === "auto" ? { width: "1px" }
: isSpecWidth(width) ? { minWidth: COLUMN_WIDTHS[width] }
: width ? { width }
: undefined
return (
<th
data-slot="table-head"
scope="col"
style={{ ...widthStyle, ...style }}
className={cn(
"align-middle font-semibold text-2xs text-muted-foreground uppercase tracking-wide whitespace-nowrap select-none",
density === "compact" ? "h-9 px-4" : "h-11 px-4 @xl:px-6",
// Two rungs. From the `xl` container width (42rem) up, 160 / 128px.
// Below it, 112 / 80px: the wide floors added up to more than a phone,
// so a three-column table of short values scrolled when it fit, while
// no floor at all let a name wrap a word per line in a table that was
// going to scroll anyway. A table that stacks or fits on a phone drops
// these floors there (see `phone` in Table).
// A text column holds a floor, so a narrow screen scrolls the table
// sideways instead of squeezing a name to one word per line: auto
// layout shrinks every column to its longest word before it overflows.
// The floor only bites when space runs out, since a wide container
// hands columns more than this anyway. Not on numbers, which never
// wrap, or on centred icon columns, an empty actions header, a
// checkbox column, or a column that declares its own width.
// The leading column names the row, so it takes the `label` floor.
// Both skip a checkbox column, written as one selector each so neither
// depends on the other's place in the stylesheet.
textColumn &&
"[&:not(:has([role=checkbox]))]:min-w-20 [&:first-child:not(:has([role=checkbox]))]:min-w-28 @xl:[&:not(:has([role=checkbox]))]:min-w-32 @xl:[&:first-child:not(:has([role=checkbox]))]:min-w-40",
alignToTextClass(resolvedAlign),
numeric && "tabular-nums",
"[&:has([role=checkbox])]:pe-0",
sortable && "cursor-pointer hover:text-foreground transition-colors duration-small ease-small",
className
)}
aria-sort={sorted === "asc" ? "ascending" : sorted === "desc" ? "descending" : sortable ? "none" : undefined}
{...props}
>
{sortable ? (
<button
type="button"
onClick={onSort}
// Buttons inherit font/letter-spacing/color via preflight, but NOT
// text-transform - re-apply uppercase so sortable headers match plain ones.
className={cn(
"inline-flex items-center gap-1.5 w-full h-full cursor-pointer rounded-sm uppercase outline-none focus-visible:ring-ring-focus focus-visible:ring-[3px]",
alignToJustifyClass(resolvedAlign)
)}
>
{children}
<SortGlyph sorted={sorted ?? false} />
</button>
) : (
children
)}
</th>
)
}
type TableCellProps = React.ComponentProps<"td"> & {
align?: Align
numeric?: boolean
}
function TableCell({ className, align, numeric, ...props }: TableCellProps) {
const resolvedAlign: Align = align ?? (numeric ? "right" : "left")
const density = React.useContext(TableDensityContext)
return (
<td
data-slot="table-cell"
className={cn(
"align-middle text-muted-foreground",
// 16px a side below 576px of the table's own width (a phone, a narrow
// sheet), where 24 left the text column too little room.
density === "compact" ? "px-4 py-2" : "px-4 py-3 @xl:px-6",
alignToTextClass(resolvedAlign),
numeric && "tabular-nums",
"[&:has([role=checkbox])]:pe-0",
className
)}
{...props}
/>
)
}
function TableCaption({ className, ...props }: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("text-subtle-foreground py-2 px-3 text-xs text-start", className)}
{...props}
/>
)
}
// Stable markers so column detection (isElementOfType) survives HMR, bundler
// boundaries, and minification, where referential identity is not guaranteed.
Table.displayName = "Table"
TableHeader.displayName = "TableHeader"
TableBody.displayName = "TableBody"
TableFooter.displayName = "TableFooter"
TableRow.displayName = "TableRow"
TableHead.displayName = "TableHead"
TableCell.displayName = "TableCell"
TableCaption.displayName = "TableCaption"
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}