Components / DataStable

Table

Lists items that share the same fields in rows and columns, so people can scan and compare them.

View as Markdown

Playground

Tasks due this week
Write launch notesAna RibeiroIn reviewNov 19
Record the demoBen OkaforOn trackNov 20
Update pricing pageChen WeiBlockedNov 20
Brief supportDara NovakNot startedNov 22

Code

Table.tsx
'use client'
import { useEffect, useLayoutEffect, useRef, useState, type MouseEvent, type ReactNode } from 'react'
import { motionOk, tokenMs } from './Indicator'

// Nacre Table: rows of items compared by the same columns. React plus Tailwind classes only; needs nacre-theme.css and
// Indicator.tsx (for tokenMs and motionOk). Below 32rem of its own width (a container query, not the viewport) each row
// stacks into label and value pairs, so it never scrolls sideways; explicit ARIA roles keep table semantics when
// display changes. A rounded white wrapper with one 1 px ring; a sunken header row; one 1 px line above each row. End-aligned columns use tabular numbers.
// Sorting: a sortable column's header is a button; aria-sort on the header says the order. The caret turns with a
// base 240 spring. Rows that change place travel from where they were drawn (FLIP, base 240 out, retargeted from the
// drawn position when sorted again mid-flight); a keyboard press sorts at once.
// Hover: one fill glides between rows under a mouse (quick 160 out); the first row entered only fades in. Reduced
// motion or an ancestor with data-nacre-motion="off" keeps a plain per-row hover fill and instant sorting.

export type TableColumn = { key: string; header: string; align?: 'start' | 'end'; sortable?: boolean }
export type TableRow = { id: string; cells: Record<string, ReactNode>; values?: Record<string, string | number> }
export type TableDensity = 'comfortable' | 'compact'
export type TableSortDirection = 'ascending' | 'descending'
export type TableSort = { key: string; direction: TableSortDirection }

export type TableProps = {
  caption: string
  hideCaption?: boolean
  columns: TableColumn[]
  rows: TableRow[]
  density?: TableDensity
  defaultSort?: TableSort
  onSortChange?: (sort: TableSort) => void
  empty?: ReactNode
  className?: string
}

const heights: Record<TableDensity, string> = { comfortable: '@min-[32rem]:h-12', compact: '@min-[32rem]:h-9' }
// End-aligned columns hold figures, so they use tabular numbers and the digits line up down the column.
const aligns = { start: '@min-[32rem]:text-start', end: '@min-[32rem]:text-end tabular-nums' } as const
const headAligns = { start: 'justify-start', end: 'justify-end' } as const

/** The value a row sorts by: its `values` entry, else the cell when it is plain text or a number. */
function valueOf(row: TableRow, key: string): string | number {
  const v = row.values?.[key] ?? row.cells[key]
  return typeof v === 'number' || typeof v === 'string' ? v : ''
}

function sorted(rows: TableRow[], sort: TableSort | null): TableRow[] {
  if (!sort) return rows
  const sign = sort.direction === 'ascending' ? 1 : -1
  return [...rows].sort((a, b) => {
    const x = valueOf(a, sort.key)
    const y = valueOf(b, sort.key)
    const d = typeof x === 'number' && typeof y === 'number' ? x - y : String(x).localeCompare(String(y), undefined, { numeric: true, sensitivity: 'base' })
    return d * sign
  })
}

function Caret() {
  return (
    <svg viewBox="0 0 12 12" aria-hidden="true" className="size-3 shrink-0">
      <path d="M3 4.5 6 7.5l3-3" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  )
}

export function Table({ caption, hideCaption = false, columns, rows, density = 'comfortable', defaultSort, onSortChange, empty = 'Nothing here yet.', className = '' }: TableProps) {
  const [sort, setSort] = useState<TableSort | null>(defaultSort ?? null)
  const root = useRef<HTMLDivElement>(null)
  const glide = useRef<HTMLSpanElement>(null)
  const rowEls = useRef(new Map<string, HTMLTableRowElement>())
  // Where each row was drawn just before a sort, and whether the sort should travel (a pointer press, motion allowed).
  const before = useRef<Map<string, number> | null>(null)
  const shown = sorted(rows, sort)
  const order = shown.map((r) => r.id).join('|')

  const sortBy = (e: MouseEvent<HTMLButtonElement>, key: string) => {
    const next: TableSort = { key, direction: sort?.key === key && sort.direction === 'ascending' ? 'descending' : 'ascending' }
    const r = root.current
    // A click with detail 0 came from Enter or Space: sort at once.
    if (r && e.detail > 0 && motionOk(r)) {
      const tops = new Map<string, number>()
      rowEls.current.forEach((el, id) => tops.set(id, el.getBoundingClientRect().top))
      before.current = tops
    } else before.current = null
    setSort(next)
    onSortChange?.(next)
  }

  useLayoutEffect(() => {
    const tops = before.current
    before.current = null
    if (!tops || !root.current) return
    const duration = tokenMs(root.current, '--nx-dur-base', 240)
    const easing = getComputedStyle(root.current).getPropertyValue('--nx-ease-out').trim() || 'cubic-bezier(.23, 1, .32, 1)'
    rowEls.current.forEach((el, id) => {
      el.getAnimations().forEach((a) => a.cancel())
      const was = tops.get(id)
      if (was === undefined) return
      const dy = was - el.getBoundingClientRect().top
      if (Math.abs(dy) < 1) return
      el.animate([{ translate: `0 ${dy}px` }, { translate: '0 0' }], { duration, easing })
    })
  }, [order])

  // The gliding hover fill: one span behind the rows, laid out at the hovered row at once and carried there by a FLIP.
  useEffect(() => {
    const c = root.current
    const t = glide.current
    if (!c || !t) return
    let last: { x: number; y: number } | null = null
    let leave: ReturnType<typeof setTimeout> | undefined
    const hide = (ms: number) => {
      clearTimeout(leave)
      leave = setTimeout(() => {
        t.removeAttribute('data-shown')
        last = null
      }, ms)
    }
    const onOver = (e: PointerEvent) => {
      if (e.pointerType !== 'mouse') return
      const row = e.target instanceof Element ? e.target.closest<HTMLElement>('[data-part="row"]') : null
      if (!row || !c.contains(row) || !motionOk(c)) {
        c.removeAttribute('data-glide')
        return hide(row ? 0 : 80)
      }
      clearTimeout(leave)
      c.setAttribute('data-glide', '')
      const cr = c.getBoundingClientRect()
      const rr = row.getBoundingClientRect()
      const to = { x: rr.left - cr.left, y: rr.top - cr.top }
      const running = t.getAnimations()
      let from = last
      if (running.length) {
        const tr = t.getBoundingClientRect()
        from = { x: tr.left - cr.left, y: tr.top - cr.top }
        running.forEach((a) => a.cancel())
      }
      t.style.width = `${rr.width}px`
      t.style.height = `${rr.height}px`
      t.style.transform = `translate(${to.x}px, ${to.y}px)`
      if (from && t.hasAttribute('data-shown') && (from.x !== to.x || from.y !== to.y)) {
        const easing = getComputedStyle(c).getPropertyValue('--nx-ease-out').trim() || 'cubic-bezier(.23, 1, .32, 1)'
        t.animate([{ transform: `translate(${from.x}px, ${from.y}px)` }, { transform: `translate(${to.x}px, ${to.y}px)` }], {
          duration: tokenMs(c, '--nx-dur-base', 240),
          easing,
        })
      }
      last = to
      t.setAttribute('data-shown', '')
    }
    const onLeave = (e: PointerEvent) => { if (e.pointerType === 'mouse') hide(80) }
    c.addEventListener('pointerover', onOver)
    c.addEventListener('pointerleave', onLeave)
    return () => {
      clearTimeout(leave)
      c.removeEventListener('pointerover', onOver)
      c.removeEventListener('pointerleave', onLeave)
    }
  }, [])

  return (
    <div ref={root} data-part="root" className={`group/table relative @container overflow-hidden rounded-lg bg-surface ring-1 ring-line-subtle ${className}`}>
      <span
        ref={glide}
        aria-hidden="true"
        data-part="glide"
        className="pointer-events-none absolute top-0 left-0 bg-row-hover opacity-0 transition-opacity duration-(--nx-dur-base) ease-out data-shown:opacity-100"
      />
      <table role="table" className="relative block w-full border-collapse text-body text-fg @min-[32rem]:table">
        <caption data-part="caption" className={hideCaption ? 'sr-only' : 'block px-4 pt-3 pb-2 text-start text-label font-[600] text-fg-strong @min-[32rem]:table-caption'}>
          {caption}
        </caption>
        <thead role="rowgroup" className="hidden @min-[32rem]:table-header-group">
          <tr role="row" data-part="head-row" className="bg-sunken">
            {columns.map((c) => {
              const on = sort?.key === c.key
              const align = c.align ?? 'start'
              return (
                <th
                  key={c.key}
                  role="columnheader"
                  scope="col"
                  data-part="header"
                  aria-sort={c.sortable ? (on ? sort.direction : 'none') : undefined}
                  className={`h-10 px-3 align-middle text-caption font-[600] text-fg-muted ${aligns[align]}`}
                >
                  {c.sortable ? (
                    <button
                      type="button"
                      data-part="sort"
                      onClick={(e) => sortBy(e, c.key)}
                      className={`group/sort -mx-1.5 inline-flex h-7 items-center gap-1 rounded-sm px-1.5 font-[600] transition-[color,scale] duration-(--nx-dur-quick) ease-out hover:text-fg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus motion-safe:active:not-focus-visible:scale-[.97] ${headAligns[align]} ${on ? 'text-fg' : ''} ${align === 'end' ? 'flex-row-reverse' : ''}`}
                    >
                      <span>{c.header}</span>
                      <span
                        data-part="caret"
                        className={`inline-grid transition-[rotate,opacity] duration-(--nx-dur-base) ease-spring ${on ? 'opacity-100' : 'opacity-0 group-hover/sort:opacity-60 group-focus-visible/sort:opacity-60'} ${on && sort.direction === 'ascending' ? 'rotate-180' : ''}`}
                      >
                        <Caret />
                      </span>
                    </button>
                  ) : (
                    c.header
                  )}
                </th>
              )
            })}
          </tr>
        </thead>
        <tbody role="rowgroup" className="block @min-[32rem]:table-row-group">
          {shown.length === 0 ? (
            <tr role="row" className="block border-t border-line-subtle @min-[32rem]:table-row">
              <td role="cell" colSpan={columns.length} data-part="empty" className="block px-3 py-8 text-center text-fg-muted @min-[32rem]:table-cell">
                {empty}
              </td>
            </tr>
          ) : (
            shown.map((r) => (
              <tr
                key={r.id}
                ref={(el) => {
                  if (el) rowEls.current.set(r.id, el)
                  else rowEls.current.delete(r.id)
                }}
                role="row"
                data-part="row"
                className="block border-t border-line-subtle py-2 transition-colors duration-(--nx-dur-quick) ease-out hover:bg-row-hover group-data-glide/table:hover:bg-transparent @min-[32rem]:table-row @min-[32rem]:py-0"
              >
                {columns.map((c) => (
                  <td
                    key={c.key}
                    role="cell"
                    data-part="cell"
                    data-label={c.header}
                    className={`flex items-center justify-between gap-4 px-3 py-1 align-middle before:text-caption before:text-fg-muted before:content-[attr(data-label)] @min-[32rem]:table-cell @min-[32rem]:py-0 @min-[32rem]:before:content-none ${heights[density]} ${aligns[c.align ?? 'start']}`}
                  >
                    {r.cells[c.key]}
                  </td>
                ))}
              </tr>
            ))
          )}
        </tbody>
      </table>
    </div>
  )
}
Indicator.tsx
'use client'
import { useLayoutEffect, useRef, type RefObject } from 'react'

// Nacre gliding indicator: the one moving selection that Segmented control and Tabs share. React only; copy it next
// to SegmentedControl.tsx or Tabs.tsx. Motion: base 240 out (a line stretches across on the way), by transform only,
// retargeted from where it is drawn.

type Box = { x: number; y: number; w: number; h: number }
const same = (a: Box, b: Box) => a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h

/** A duration token in ms, read from CSS so a slowed-down parent slows this too. */
export function tokenMs(el: Element, name: string, fallback: number): number {
  const v = getComputedStyle(el).getPropertyValue(name).trim()
  const n = parseFloat(v)
  if (!Number.isFinite(n)) return fallback
  return v.endsWith('ms') ? n : v.endsWith('s') ? n * 1000 : n
}

/** Reduced motion, or an ancestor that switched motion off, means no movement. */
export function motionOk(el: Element): boolean {
  return !window.matchMedia('(prefers-reduced-motion: reduce)').matches && !el.closest('[data-nacre-motion="off"]')
}

/**
 * One thumb under the child of `list` marked data-state="on". The thumb is laid out at the new item at once (width and
 * height set, never animated) and a FLIP transform carries it from where it is drawn now, so a change in mid-flight
 * continues from there instead of jumping or restarting. First placement, resizes, keyboard changes (keyboard.current)
 * and reduced motion are instant. `line` draws a 2 px bar on the item's bottom edge instead of a fill; it reaches over
 * both items before it lets go of the old one. The list gets data-ready once the thumb is placed; until then the
 * selected item draws its own selection.
 */
export function useIndicator(list: RefObject<HTMLElement | null>, active: string | undefined, keyboard: RefObject<boolean>, line = false) {
  const thumb = useRef<HTMLSpanElement>(null)
  const last = useRef<Box | null>(null)
  useLayoutEffect(() => {
    const c = list.current
    const t = thumb.current
    if (!c || !t) return
    const place = (animate: boolean) => {
      const item = c.querySelector<HTMLElement>(':scope > [data-state="on"]')
      if (!item || !item.offsetWidth) {
        c.removeAttribute('data-ready')
        t.style.opacity = '0'
        last.current = null
        return
      }
      const box: Box = line
        ? { x: item.offsetLeft, y: item.offsetTop + item.offsetHeight - 1, w: item.offsetWidth, h: 2 }
        : { x: item.offsetLeft, y: item.offsetTop, w: item.offsetWidth, h: item.offsetHeight }
      if (!animate && last.current && same(last.current, box)) return
      const running = t.getAnimations()
      let from = last.current
      if (running.length) {
        const cr = c.getBoundingClientRect()
        const tr = t.getBoundingClientRect()
        from = { x: tr.left - cr.left - c.clientLeft, y: tr.top - cr.top - c.clientTop, w: tr.width, h: tr.height }
        running.forEach((a) => a.cancel())
      }
      t.style.width = `${box.w}px`
      t.style.height = `${box.h}px`
      t.style.transform = `translate(${box.x}px, ${box.y}px)`
      t.style.opacity = '1'
      c.setAttribute('data-ready', '')
      last.current = box
      if (!animate || !from || same(from, box) || keyboard.current || !motionOk(c)) return
      const easing = getComputedStyle(c).getPropertyValue('--nx-ease-out').trim() || 'cubic-bezier(.23, 1, .32, 1)'
      const at = (b: Box) => `translate(${b.x}px, ${b.y}px) scale(${b.w / box.w}, ${b.h / box.h})`
      // The line stretches over both tabs on the way (leading edge first), then lets go of the old one.
      const reach = { x: Math.min(from.x, box.x), y: box.y, w: Math.max(from.x + from.w, box.x + box.w) - Math.min(from.x, box.x), h: box.h }
      const frames = line && from.y === box.y ? [{ transform: at(from) }, { transform: at(reach), offset: 0.4 }, { transform: at(box) }] : [{ transform: at(from) }, { transform: at(box) }]
      t.animate(frames, { duration: tokenMs(c, '--nx-dur-base', 240), easing })
    }
    let cancelled = false
    place(true)
    const ro = new ResizeObserver(() => place(false))
    ro.observe(c)
    document.fonts?.ready.then(() => { if (!cancelled) place(false) })
    return () => {
      cancelled = true
      ro.disconnect()
    }
  }, [list, active, keyboard, line])
  return thumb
}

Usage

When to use

  • Tasks, members, invoices: many items with the same few fields.
  • Short reports where the exact numbers matter, with figures aligned to the end.

Choose something else when

  • Each item has a long text and little else: use a list of cards.
  • Opening an item needs more room than a row: use Drawer for its details.

In the Nacre workspace

Tasks due this week

The project page lists this week’s tasks in a Table: task, owner with avatar, status as a Badge, and the due date aligned to the end. On a phone each task becomes a small block of labelled lines.

Nothing due

When the week is clear, the same Table shows one calm line, Nothing due this week., instead of an empty grid.

Do and don't

  • DoKeep columns to what people compare: four or five.

    Don'tShow every field you have; put the rest in a Drawer.

  • DoAlign numbers and dates to the end.

    Don'tCentre text in cells.

Anatomy

Tasks due this week
Write launch notesAna RibeiroIn reviewNov 19
Record the demoBen OkaforOn trackNov 20
Update pricing pageChen WeiBlockedNov 20
Brief supportDara NovakNot startedNov 22
  1. Caption. Label 13/16 at weight 600 in fg-strong, inset 16 px inside the rounded wrapper.
  2. Column header. Caption 12/16 at weight 600 in fg-muted on a sunken row, 40 px tall, 12 px side padding. The 1 px line-subtle rule on top of the first row is the hairline under it.
  3. Row. A 1 px line-subtle rule on top; row-hover fill under a fine pointer, drawn with radius sm.
  4. Cell. Body text in fg, 48 px (comfortable) or 36 px (compact) tall, 12 px side padding. End-aligned columns use tabular numbers. Put a Badge in a status cell.
  5. Container. A size container: below 32rem wide, rows stack into label and value lines.

API

captionType stringDefault -Required. Names the table; hideCaption keeps it for assistive tech only.
hideCaptionType booleanDefault falseHides the caption visually.
columnsType { key: string; header: string; align?: 'start' | 'end'; sortable?: boolean }[]Default -Column headers in order. The header is also the label of each value when rows stack. A sortable column gets a header button.
rowsType { id: string; cells: Record<string, ReactNode>; values?: Record<string, string | number> }[]Default -One entry per row; cells are keyed by column key and can hold any element (an Avatar, a Badge). values gives the sort value of a cell that is not plain text, or of a date written for people.
defaultSortType { key: string; direction: 'ascending' | 'descending' }Default -The order the rows start in. Without it they keep the order given.
onSortChangeType (sort) => voidDefault -Called with the new key and direction after a header press.
densityType 'comfortable' | 'compact'Default 'comfortable'Row height 48 or 36 px.
emptyType ReactNodeDefault 'Nothing here yet.'Shown in one full-width row when there are no rows.
classNameType stringDefault -Extra classes for the container.

Motion

Row hoverProperty one fill glides between rows (transform, FLIP); the first row only fades inDuration quick 160Easing outKeyboard Rows are not focusable; links and buttons inside them show their own focus ring.
Sort pressProperty scale .97 on the header buttonDuration quick 160Easing outKeyboard No press scale.
Sort directionProperty caret rotate 180Duration base 240Easing springKeyboard Same.
Rows reorderProperty translate from where each row was drawn (FLIP), retargeted when sorted again mid-flightDuration base 240Easing outKeyboard Enter or Space on a header sorts at once.
Tasks due this week
Write launch notesAna RibeiroIn reviewNov 19
Record the demoBen OkaforOn trackNov 20
Update pricing pageChen WeiBlockedNov 20
Brief supportDara NovakNot startedNov 22

Accessibility

Keyboard

Tab
Moves through the sort buttons and the links and buttons in the cells. The table itself is not a tab stop.
Enter or Space
On a sort button: sorts by that column, ascending first, then flips the direction.

ARIA and semantics

  • A real table with a caption and column headers (scope="col"); explicit roles keep the semantics when rows stack.
  • Stacked rows show each column header as a visible label before its value.
  • Below 32rem the stacked layout hides the thead, so header-cell association relies on the visible ::before labels, which are text drawn from each cell, not on the column headers.
  • A sortable header holds a real button; the header carries aria-sort (ascending, descending or none), so screen readers announce the order.
  • Sorting is in the column headers, which the stacked layout hides; below 32rem rows keep the last order chosen.

Contrast

Cell textfg on pageLight 13.54:1Dark 13.19:1Needs 4.5:1
Headers and stacked labelsfg-muted on pageLight 5.07:1Dark 7.15:1Needs 4.5:1
Cell text on a hovered rowfg on row-hoverLight 13.79:1Dark 11.83:1Needs 4.5:1
Labels on a hovered rowfg-muted on row-hoverLight 5.16:1Dark 6.42:1Needs 4.5:1