# Orders table

An orders admin view: an `Input` that searches by customer or order number, a status `Select`, sortable column headers, `Checkbox` selection with a select-all that goes indeterminate, a bulk action bar, status `Badge`s, a row `Menu` and a pagination footer, all inside a `TableContainer`.

**Example: Juniper & Rye orders** (`examples/recipes/orders-table.tsx`)

```tsx
'use client'

import {
  Badge,
  type BadgeTone,
  BodySmall,
  Button,
  Checkbox,
  Heading,
  Input,
  Label,
  Menu,
  Select,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableHeader,
  TableRow,
  Text,
  toastSuccess,
} from '@blocks/design-system'
import { ArrowDown, ArrowUp, ChevronLeft, ChevronRight, ChevronsUpDown, Download, MoreHorizontal, PackageCheck, Search } from 'lucide-react'
import { useId, useState } from 'react'
import styles from './orders-table.module.css'

type Status = 'pending' | 'paid' | 'fulfilled' | 'refunded'
type SortKey = 'id' | 'customer' | 'placed' | 'total'

interface Order {
  id: string
  customer: string
  /** Day of November 2026. */
  placed: number
  status: Status
  total: number
}

const statusTone: Record<Status, BadgeTone> = { pending: 'warning', paid: 'info', fulfilled: 'success', refunded: 'neutral' }
const statusLabel: Record<Status, string> = { pending: 'Pending', paid: 'Paid', fulfilled: 'Fulfilled', refunded: 'Refunded' }

const statusFilters = [
  { value: 'all', label: 'All statuses' },
  { value: 'pending', label: 'Pending' },
  { value: 'paid', label: 'Paid' },
  { value: 'fulfilled', label: 'Fulfilled' },
  { value: 'refunded', label: 'Refunded' },
]

const customers = [
  'Amara Okafor',
  'Bruno Castellano',
  'Chen Wei',
  'Delphine Moreau',
  'Elif Yıldız',
  'Farid Haddad',
  'Greta Lindqvist',
  'Hiro Tanaka',
  'Imogen Hale',
  'Jonas Becker',
  'Kalani Akana',
  'Lucía Ferrer',
  'Mateo Ruiz',
  'Nadia Rahman',
]
const statusCycle: Status[] = ['paid', 'fulfilled', 'pending', 'fulfilled', 'paid', 'fulfilled', 'refunded', 'fulfilled']

// Picks from a list by position, wrapping around at the end.
function cycle<T>(list: T[], index: number) {
  return list[index % list.length] as T
}

// 42 orders from fixed arithmetic, newest first.
const initialOrders: Order[] = Array.from({ length: 42 }, (_, index) => ({
  id: `#${3184 - index}`,
  customer: cycle(customers, index * 5),
  placed: 30 - Math.floor(index * 0.7),
  status: cycle(statusCycle, index),
  total: ((index * 7919) % 38_000) / 100 + 18,
}))

type Sort = { key: SortKey; direction: 'ascending' | 'descending' }

const pageSize = 8
const currency = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })

export default function OrdersTable() {
  const [orders, setOrders] = useState(initialOrders)
  const [query, setQuery] = useState('')
  const [status, setStatus] = useState('all')
  const [sort, setSort] = useState<Sort>({ key: 'placed', direction: 'descending' })
  const [selected, setSelected] = useState<string[]>([])
  const [page, setPage] = useState(0)
  const id = useId()

  const needle = query.trim().toLowerCase()
  const filtered = orders
    .filter((order) => status === 'all' || order.status === status)
    .filter((order) => !needle || order.customer.toLowerCase().includes(needle) || order.id.includes(needle.replace(/^#?/, '#')))
    .sort((a, b) => {
      const order = a[sort.key] < b[sort.key] ? -1 : a[sort.key] > b[sort.key] ? 1 : 0
      return sort.direction === 'ascending' ? order : -order
    })

  const pageCount = Math.max(1, Math.ceil(filtered.length / pageSize))
  const currentPage = Math.min(page, pageCount - 1)
  const rows = filtered.slice(currentPage * pageSize, (currentPage + 1) * pageSize)
  const first = filtered.length === 0 ? 0 : currentPage * pageSize + 1
  const last = currentPage * pageSize + rows.length

  const selectedOnPage = rows.filter((order) => selected.includes(order.id))
  const allOnPage = rows.length > 0 && selectedOnPage.length === rows.length

  function changeFilter(update: () => void) {
    update()
    setPage(0)
    setSelected([])
  }

  function sortBy(key: SortKey) {
    setSort((current) => ({
      key,
      direction: current.key === key && current.direction === 'ascending' ? 'descending' : 'ascending',
    }))
  }

  function toggleRow(orderId: string, checked: boolean) {
    setSelected((current) => (checked ? [...current, orderId] : current.filter((item) => item !== orderId)))
  }

  function toggleAll(checked: boolean) {
    const ids = rows.map((order) => order.id)
    setSelected((current) => (checked ? [...new Set([...current, ...ids])] : current.filter((item) => !ids.includes(item))))
  }

  function markFulfilled(ids: string[]) {
    setOrders((current) => current.map((order) => (ids.includes(order.id) && order.status === 'paid' ? { ...order, status: 'fulfilled' } : order)))
    setSelected([])
    toastSuccess(ids.length === 1 ? `Order ${ids[0]} marked fulfilled` : `${ids.length} orders marked fulfilled`)
  }

  function exportOrders(ids: string[]) {
    toastSuccess(`Exported ${ids.length} ${ids.length === 1 ? 'order' : 'orders'} to CSV`)
  }

  return (
    <Stack as="section" gap="lg" aria-labelledby={`${id}-title`} dangerouslySetClassName={styles.orders}>
      <Stack direction="row" justify="space-between" align="baseline" wrap="wrap" gap="sm">
        <Heading as="h2" id={`${id}-title`} fontSize="xl">
          Orders
        </Heading>
        <BodySmall color="text-muted" margin="none">
          Juniper &amp; Rye · November 2026
        </BodySmall>
      </Stack>

      <Stack direction="row" gap="md" align="end" wrap="wrap">
        <Stack gap="xxs" flexGrow={1} dangerouslySetClassName={styles.search}>
          <Label htmlFor={`${id}-search`} marginBottom="none">
            Search
          </Label>
          <div className={styles.searchField}>
            <Search aria-hidden size={16} className={styles.searchIcon} />
            <Input
              id={`${id}-search`}
              type="search"
              placeholder="Customer or order number"
              value={query}
              onChange={(event) => changeFilter(() => setQuery(event.target.value))}
              dangerouslySetClassName={styles.searchInput}
            />
          </div>
        </Stack>
        <Stack gap="xxs">
          <Select items={statusFilters} value={status} onValueChange={(value) => value && changeFilter(() => setStatus(value))}>
            <Select.Label>Status</Select.Label>
            <Select.Trigger dangerouslySetClassName={styles.statusTrigger} />
            <Select.Content>
              {statusFilters.map((item) => (
                <Select.Item key={item.value} value={item.value}>
                  {item.label}
                </Select.Item>
              ))}
            </Select.Content>
          </Select>
        </Stack>
      </Stack>

      {selected.length > 0 && (
        <div className={styles.bulkBar} role="toolbar" aria-label="Bulk actions">
          <Text fontSize="sm" fontWeight="semibold" aria-live="polite">
            {selected.length} selected
          </Text>
          <Stack direction="row" gap="sm" wrap="wrap">
            <Button type="button" size="sm" onClick={() => markFulfilled(selected)}>
              <PackageCheck aria-hidden size={14} />
              Mark fulfilled
            </Button>
            <Button type="button" size="sm" onClick={() => exportOrders(selected)}>
              <Download aria-hidden size={14} />
              Export
            </Button>
            <Button type="button" size="sm" variant="ghost" onClick={() => setSelected([])}>
              Clear
            </Button>
          </Stack>
        </div>
      )}

      <TableContainer tabIndex={0} role="region" dangerouslySetClassName={styles.scroller} aria-labelledby={`${id}-title`}>
        <Table dangerouslySetClassName={styles.table}>
          <TableHeader>
            <TableRow dangerouslySetClassName={styles.headRow}>
              <TableHead scope="col" dangerouslySetClassName={styles.checkCell}>
                <Checkbox
                  aria-label="Select all orders on this page"
                  checked={allOnPage}
                  indeterminate={selectedOnPage.length > 0 && !allOnPage}
                  onCheckedChange={toggleAll}
                  disabled={rows.length === 0}
                />
              </TableHead>
              <SortableHead column="id" label="Order" sort={sort} onSort={sortBy} />
              <SortableHead column="customer" label="Customer" sort={sort} onSort={sortBy} />
              <SortableHead column="placed" label="Placed" sort={sort} onSort={sortBy} />
              <TableHead scope="col" dangerouslySetClassName={styles.wideOnly}>
                Status
              </TableHead>
              <SortableHead column="total" label="Total" align="right" sort={sort} onSort={sortBy} />
              <TableHead scope="col" dangerouslySetClassName={styles.wideOnly}>
                <span className="visually-hidden">Actions</span>
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody dangerouslySetClassName={styles.body}>
            {rows.map((order) => (
              <TableRow key={order.id} data-selected={selected.includes(order.id) || undefined} dangerouslySetClassName={styles.row}>
                <TableCell dangerouslySetClassName={`${styles.checkCell} ${styles.cellCheck}`}>
                  <Checkbox
                    aria-label={`Select order ${order.id}`}
                    checked={selected.includes(order.id)}
                    onCheckedChange={(checked) => toggleRow(order.id, checked)}
                  />
                </TableCell>
                <TableHead scope="row" dangerouslySetClassName={`${styles.numeric} ${styles.cellId}`}>
                  {order.id}
                </TableHead>
                <TableCell dangerouslySetClassName={`${styles.nowrap} ${styles.cellCustomer}`}>{order.customer}</TableCell>
                <TableCell dangerouslySetClassName={`${styles.nowrap} ${styles.cellPlaced}`}>
                  <time dateTime={`2026-11-${String(order.placed).padStart(2, '0')}`}>Nov {order.placed}</time>
                </TableCell>
                <TableCell dangerouslySetClassName={styles.cellStatus}>
                  <Badge tone={statusTone[order.status]}>{statusLabel[order.status]}</Badge>
                </TableCell>
                <TableCell textAlign="right" dangerouslySetClassName={`${styles.numeric} ${styles.cellTotal}`}>
                  {currency.format(order.total)}
                </TableCell>
                <TableCell dangerouslySetClassName={styles.cellActions}>
                  <Menu>
                    <Menu.Trigger render={<Button type="button" size="sm" variant="ghost" aria-label={`Actions for order ${order.id}`} />}>
                      <MoreHorizontal aria-hidden size={16} />
                    </Menu.Trigger>
                    <Menu.Content align="end">
                      <Menu.LinkItem href={`#order-${order.id.slice(1)}`}>View order</Menu.LinkItem>
                      <Menu.Item disabled={order.status !== 'paid'} onClick={() => markFulfilled([order.id])}>
                        Mark fulfilled
                      </Menu.Item>
                      <Menu.Item onClick={() => exportOrders([order.id])}>Export</Menu.Item>
                    </Menu.Content>
                  </Menu>
                </TableCell>
              </TableRow>
            ))}
            {rows.length === 0 && (
              <TableRow>
                <TableCell colSpan={7} textAlign="center" paddingY="xl">
                  <Text color="text-muted">No orders match these filters.</Text>
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </TableContainer>

      <Stack as="nav" direction="row" justify="space-between" align="center" gap="md" aria-label="Orders pages">
        <Text fontSize="sm" color="text-muted" aria-live="polite" dangerouslySetClassName={styles.numeric}>
          {first}–{last} of {filtered.length}
        </Text>
        <Stack direction="row" gap="sm">
          <Button type="button" size="sm" aria-label="Previous page" disabled={currentPage === 0} onClick={() => setPage(currentPage - 1)}>
            <ChevronLeft aria-hidden size={16} />
          </Button>
          <Button
            type="button"
            size="sm"
            aria-label="Next page"
            disabled={currentPage >= pageCount - 1}
            onClick={() => setPage(currentPage + 1)}
          >
            <ChevronRight aria-hidden size={16} />
          </Button>
        </Stack>
      </Stack>
    </Stack>
  )
}

interface SortableHeadProps {
  column: SortKey
  label: string
  align?: 'right'
  sort: Sort
  onSort: (column: SortKey) => void
}

// The header cell carries aria-sort; the button inside it changes the order.
function SortableHead({ column, label, align, sort, onSort }: SortableHeadProps) {
  const active = sort.key === column
  const Icon = !active ? ChevronsUpDown : sort.direction === 'ascending' ? ArrowUp : ArrowDown
  return (
    <TableHead scope="col" aria-sort={active ? sort.direction : 'none'} textAlign={align}>
      <button type="button" className={styles.sortButton} data-align={align} onClick={() => onSort(column)}>
        {label}
        <Icon aria-hidden size={14} />
      </button>
    </TableHead>
  )
}
```

## How it works

- **Sorting is announced.** Each sortable `TableHead` carries `aria-sort`, and the control inside it is a real `<button>`, so a screen reader hears both the column’s current order and that it can be changed. The arrow icon only repeats what `aria-sort` already says.
- **Selection is per page.** The header checkbox selects or clears the rows you can see and shows `indeterminate` when only some are checked. Changing the search or status filter clears the selection and returns to the first page, so a bulk action never touches rows you can no longer see.
- **Bulk actions appear only when they apply.** The bar is a `role="toolbar"` with a live count. “Mark fulfilled” changes paid orders and confirms with a toast; the same action is in each row’s menu, disabled when the order isn’t paid.
- **Numbers line up.** Totals are right-aligned with tabular numerals, header included, and the range in the footer (“1–8 of 42”) is a polite live region.
- **Phones get a list, not a sliver of a table.** Below 34rem a container query turns each row into a two-line item: order number and customer on the left, status and total on the right, the menu at the end. The header row becomes a bar of select-all and sort buttons, so nothing important is ever scrolled out of view.

## App-owned CSS

The search icon, the sort buttons, the bulk bar, the selected-row tint and the narrow-screen row layout.

`examples/recipes/orders-table.module.css`:

```css
.search {
  min-width: min(100%, 14rem);
}

.searchField {
  position: relative;
}

.searchIcon {
  position: absolute;
  top: 50%;
  left: var(--ds-space-md);
  color: var(--ds-color-text-muted);
  transform: translateY(-50%);
  pointer-events: none;
}

.searchInput {
  width: 100%;
  padding-left: calc(var(--ds-space-md) + var(--ds-space-lg) + var(--ds-space-sm));
}

.statusTrigger {
  min-width: 10rem;
}

/* The bulk bar takes the accent's quiet tint so it reads as a mode, not a row. */
.bulkBar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: var(--ds-space-md);
  padding: var(--ds-space-md) var(--ds-space-lg);
  border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  border-radius: var(--ds-border-radius-md);
  background-color: var(--ds-color-accent-subtle);
}

.sortButton {
  display: inline-flex;
  align-items: center;
  gap: var(--ds-space-sm);
  margin: calc(var(--ds-space-xs) * -1);
  padding: var(--ds-space-xs);
  border: none;
  border-radius: var(--ds-border-radius-sm);
  background: none;
  color: inherit;
  font: inherit;
  cursor: pointer;

  &[data-align="right"] {
    flex-direction: row-reverse;
  }

  &:hover {
    color: var(--ds-color-text);
  }

  &:focus-visible {
    outline: var(--ds-border-width-md) solid var(--ds-color-focus-ring);
  }
}

.checkCell {
  width: var(--ds-space-xl);
  vertical-align: middle;

  /* A block-level box centres on the row instead of sitting on the text baseline. */
  & > :first-child {
    display: flex;
  }
}

.row[data-selected] {
  background-color: var(--ds-color-selected);
}

.numeric {
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
}

.nowrap {
  white-space: nowrap;
}

/* Positioned, so visually hidden text in the cells scrolls with the table instead of widening the page. */
.scroller {
  position: relative;
}

/* The table lays out by its own width. */
.orders {
  container-type: inline-size;
}

/*
 * On a narrow container each order becomes a two-line item: number and
 * customer on the left, status and total on the right, its menu at the end.
 * The header row turns into a bar of select-all and sort buttons.
 */
@container (max-width: 34rem) {
  .table,
  .table > thead,
  .body {
    display: block;
  }

  .headRow {
    display: flex;
    align-items: center;
    gap: var(--ds-space-md);
    padding: var(--ds-space-sm);

    & > th {
      padding: var(--ds-space-xs) 0;
    }

    /* The first right-aligned column's sort button goes to the end of the bar. */
    & > th:has(> [data-align="right"]) {
      margin-left: auto;
    }
  }

  .wideOnly,
  .cellPlaced {
    display: none;
  }

  .row {
    display: grid;
    grid-template-columns: auto minmax(0, 1fr) auto auto;
    align-items: center;
    gap: var(--ds-space-xxs) var(--ds-space-md);
    padding: var(--ds-space-md) var(--ds-space-sm);

    & > td,
    & > th {
      padding: 0;
    }
  }

  .cellCheck {
    grid-row: 1 / 3;
  }

  .cellId {
    grid-area: 1 / 2;
  }

  .cellCustomer {
    grid-area: 2 / 2;
    overflow: hidden;
    color: var(--ds-color-text-muted);
    text-overflow: ellipsis;
  }

  .cellStatus {
    grid-area: 1 / 3;
    justify-self: end;
  }

  .cellTotal {
    grid-area: 2 / 3;
    justify-self: end;
  }

  .cellActions {
    grid-row: 1 / 3;
    grid-column: 4;
  }
}
```
