Components

Data table

A table people filter, sort and page through: a dropdown per filter, heads in capitals that sort, 40px rows on neutral hairlines that take the #262626 fill under the pointer, numbers in tabular figures, Previous and Next under it. It scrolls sideways with fading edges inside the frame.

Install

React apps get the React files; every other stack gets the web component.

npx spyglass-ds add data-table
<script type="module" src="/spyglass-ds/elements/data-table.js"></script>
A board's creatives
FormatStatus
Acme summer UGCVideoActive3$1,80086,000
Acme serum launchCarouselActive20$9,719190,729
Acme founder storyImageActive37$17,638295,458
Acme bundle offerVideoPaused54$25,557400,187
Acme before and afterCarouselActive71$33,476504,916
1 to 5 of 17

Usage

A board's creatives, a brand's ads, a team's searches: rows of one kind of thing that people narrow and order.

Never

  • Zebra stripes or a shadow: hairlines separate rows
  • Bold heads: DM Sans Medium capitals at 6%
  • A spectrum color for a sorted column or a picked filter
  • A table wider than the page without its own scroll

Adds with it: button, dropdown-menu packages lucide-react

Props

The web component takes the same as attributes or properties (<spyglass-data-table>); title is heading there.

<DataTable>

PropTypeDefault
columnsDataColumn[]

The columns: key, label, align, sortable, muted.

rowsRow[]
rowKeystring

The field that tells rows apart.

labelstring

The table's name for assistive tech.

filtersDataFilter[]

A dropdown per filter: key, label, options, and what "any" reads as.

[]
pageSizenumber

Rows per page.

5
cellPartial<Record<string, (slot: { row: Row, value: unknown }) => ReactNode>>

How a column's cells render, by key.

{}
emptyReactNode

In place of the line shown when nothing matches.

classNamestring

Examples

The same example in React and as web components; both render identically.

react/examples/data-table/Creatives.tsx
'use client'
import { DataTable } from '@/react/components/ui/DataTable'
// A board's creatives on sample data: filter by format and status, sort by days running, spend or impressions, five
// to a page.
const formats = ['Video', 'Carousel', 'Image']
const statuses = ['Active', 'Paused']
const names = ['summer UGC', 'serum launch', 'founder story', 'bundle offer', 'before and after', 'unboxing', 'routine in 30 seconds', 'holiday gift set']
const rows = Array.from({ length: 17 }, (_, i) => ({
  id: `cr-${i + 1}`,
  name: `Acme ${names[i % names.length]!}${i >= names.length ? ` ${Math.floor(i / names.length) + 1}` : ''}`,
  format: formats[i % 3]!,
  status: statuses[i % 4 === 3 ? 1 : 0]!,
  days: ((i * 17) % 80) + 3,
  spend: ((i * 7919) % 42000) + 1800,
  impressions: ((i * 104729) % 2400000) + 86000,
}))
const columns = [
  { key: 'name', label: 'Creative', sortable: true },
  { key: 'format', label: 'Format' },
  { key: 'status', label: 'Status', muted: true },
  { key: 'days', label: 'Days running', align: 'right' as const, sortable: true },
  { key: 'spend', label: 'Spend', align: 'right' as const, sortable: true },
  { key: 'impressions', label: 'Impressions', align: 'right' as const, sortable: true },
]
const filters = [{ key: 'format', label: 'Format', options: formats }, { key: 'status', label: 'Status', options: statuses }]

export default function Creatives() {
  return (
    <div className="min-h-110 w-full">
      <DataTable columns={columns} rows={rows} rowKey="id" label="Board creatives" filters={filters} cell={{ spend: ({ value }) => `$${Number(value).toLocaleString('en-US')}` }} />
    </div>
  )
}
elements/examples/data-table/Creatives.html
<!-- A board's creatives on sample data: filter by format and status, sort by days running, spend or impressions, five
     to a page. -->
<div class="min-h-110 w-full">
  <spyglass-data-table id="board-creatives" row-key="id" label="Board creatives"></spyglass-data-table>
</div>
<script type="module">
  const formats = ['Video', 'Carousel', 'Image']
  const statuses = ['Active', 'Paused']
  const names = ['summer UGC', 'serum launch', 'founder story', 'bundle offer', 'before and after', 'unboxing', 'routine in 30 seconds', 'holiday gift set']
  const table = document.getElementById('board-creatives')
  table.rows = Array.from({ length: 17 }, (_, i) => ({
    id: `cr-${i + 1}`,
    name: `Acme ${names[i % names.length]}${i >= names.length ? ` ${Math.floor(i / names.length) + 1}` : ''}`,
    format: formats[i % 3],
    status: statuses[i % 4 === 3 ? 1 : 0],
    days: ((i * 17) % 80) + 3,
    spend: ((i * 7919) % 42000) + 1800,
    impressions: ((i * 104729) % 2400000) + 86000,
  }))
  table.columns = [
    { key: 'name', label: 'Creative', sortable: true },
    { key: 'format', label: 'Format' },
    { key: 'status', label: 'Status', muted: true },
    { key: 'days', label: 'Days running', align: 'right', sortable: true },
    { key: 'spend', label: 'Spend', align: 'right', sortable: true },
    { key: 'impressions', label: 'Impressions', align: 'right', sortable: true },
  ]
  table.filters = [{ key: 'format', label: 'Format', options: formats }, { key: 'status', label: 'Status', options: statuses }]
  table.cells = { spend: ({ value }) => `$${Number(value).toLocaleString('en-US')}` }
</script>

Source

react/components/ui/DataTable.tsx
'use client'
import { useState, type ReactNode } from 'react'
import { ArrowDown, ArrowUp, ArrowUpDown, Check, ChevronDown } from 'lucide-react'
import { Button } from '@/react/components/ui/Button'
import { DropdownMenu } from '@/react/components/ui/DropdownMenu'
import { MenuItem } from '@/react/components/ui/MenuItem'
import { cn } from '@/react/lib/cn'

// shadcn's data table in the brand: a table people filter, sort and page through. Over it, a dropdown per filter
// (radio rows, the trigger saying what is picked) and a way to clear them; heads in DM Sans Medium capitals, muted,
// that sort when they can (aria-sort; the arrow shows the order, a faint pair where it could); 40px rows on hairlines
// that take the #262626 fill under the pointer; numbers right-aligned in tabular figures; the whole in a hairline box
// with the 8px corner that scrolls sideways on its own, so a phone never scrolls the page. Under it, where the page is
// and Previous and Next. Filters and sort go back to the first page. Cells render the value (numbers in en-US), or
// `cell[key]({ row, value })`. Nothing matching shows one line with a way to clear the filters (`empty` replaces it).
export type DataColumn = { key: string, label: string, align?: 'left' | 'right', sortable?: boolean, muted?: boolean }
export type DataFilter = { key: string, label: string, options: string[], any?: string }
export interface DataTableProps<Row extends Record<string, unknown>> {
  /** The columns: key, label, align, sortable, muted. */
  columns: DataColumn[]
  rows: Row[]
  /** The field that tells rows apart. */
  rowKey: string
  /** The table's name for assistive tech. */
  label: string
  /** A dropdown per filter: key, label, options, and what "any" reads as. */
  filters?: DataFilter[]
  /** Rows per page. */
  pageSize?: number
  /** How a column's cells render, by key. */
  cell?: Partial<Record<string, (slot: { row: Row, value: unknown }) => ReactNode>>
  /** In place of the line shown when nothing matches. */
  empty?: ReactNode
  className?: string
}

const display = (v: unknown) => (typeof v === 'number' ? v.toLocaleString('en-US') : String(v ?? ''))
export const FILTER = 'inline-flex h-control-sm cursor-pointer items-center gap-1.5 rounded-control border border-edge-strong bg-surface-subtle px-3 type-ui text-fg transition-[border-color] duration-160 ease-standard hover:border-action-secondary-edge-hover aria-expanded:border-edge-focus max-md:h-control-touch'
export const SORT = '-mx-1 inline-flex cursor-pointer items-center gap-1 rounded-ds-sm px-1 align-middle uppercase transition-[color] duration-160 ease-standard hover:text-fg'

export function DataTable<Row extends Record<string, unknown>>({ columns, rows, rowKey, label, filters = [], pageSize = 5, cell = {}, empty, className }: DataTableProps<Row>) {
  const [picked, setPicked] = useState<Record<string, string>>({})
  const [sort, setSort] = useState<{ key: string, dir: 'ascending' | 'descending' } | null>(null)
  const [page, setPage] = useState(0)

  const filtered = rows.filter(r => filters.every(f => !picked[f.key] || String(r[f.key]) === picked[f.key]))
  const sorted = (() => {
    if (!sort) return filtered
    const sign = sort.dir === 'ascending' ? 1 : -1
    return [...filtered].sort((a, b) => {
      const x = a[sort.key]
      const y = b[sort.key]
      return sign * (typeof x === 'number' && typeof y === 'number' ? x - y : String(x).localeCompare(String(y)))
    })
  })()
  const pages = Math.max(1, Math.ceil(sorted.length / pageSize))
  const at = Math.min(page, pages - 1)
  const visible = sorted.slice(at * pageSize, at * pageSize + pageSize)
  const anyOn = Object.values(picked).some(Boolean)

  function pick(next: Record<string, string>) {
    setPicked(next)
    setPage(0)
  }
  function toggleSort(key: string) {
    setSort(s => (s?.key !== key ? { key, dir: 'ascending' } : s.dir === 'ascending' ? { key, dir: 'descending' } : null))
    setPage(0)
  }

  return (
    <div data-ds="data-table" className={cn('flex min-w-0 flex-col gap-3', className)}>
      {filters.length > 0 && (
        <div className="flex flex-wrap items-center gap-2">
          {filters.map(f => (
            <DropdownMenu key={f.key} label={f.label} width="200px" triggerClass={FILTER} trigger={<><span>{`${f.label}: ${picked[f.key] || (f.any ?? 'Any')}`}</span><ChevronDown size={16} strokeWidth={1.5} className="text-fg-muted" aria-hidden="true" /></>}>
              {['', ...f.options].map(o => (
                <MenuItem key={o || 'any'} role="menuitemradio" aria-checked={(picked[f.key] ?? '') === o} onSelect={() => pick({ ...picked, [f.key]: o })}>
                  <span className="min-w-0 flex-1 truncate">{o || (f.any ?? 'Any')}</span>
                  {(picked[f.key] ?? '') === o && <Check size={16} strokeWidth={1.5} className="shrink-0" aria-hidden="true" />}
                </MenuItem>
              ))}
            </DropdownMenu>
          ))}
          {anyOn && <Button variant="ghost" size="sm" onClick={() => pick({})}>Clear filters</Button>}
        </div>
      )}
      <div className="overflow-hidden rounded-container border border-edge">
        <div className="overflow-x-auto -outline-offset-2 fade-x" role="region" aria-label={label} tabIndex={0}>
          <table className="w-full border-collapse type-ui">
            <thead>
              <tr>
                {columns.map(c => (
                  <th key={c.key} scope="col" className={cn('h-10 border-b border-edge px-3 align-middle type-label whitespace-nowrap text-fg-muted', c.align === 'right' ? 'text-right' : 'text-left')} aria-sort={sort?.key === c.key ? sort.dir : c.sortable ? 'none' : undefined}>
                    {c.sortable
                      ? (
                          <button type="button" className={cn(SORT, c.align === 'right' && 'flex-row-reverse')} onClick={() => toggleSort(c.key)}>
                            {c.label}
                            {sort?.key === c.key && sort.dir === 'ascending'
                              ? <ArrowUp size={14} strokeWidth={1.5} className="text-fg" aria-hidden="true" />
                              : sort?.key === c.key
                                ? <ArrowDown size={14} strokeWidth={1.5} className="text-fg" aria-hidden="true" />
                                : <ArrowUpDown size={14} strokeWidth={1.5} className="text-fg-faint" aria-hidden="true" />}
                          </button>
                        )
                      : c.label}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {visible.map(r => (
                <tr key={String(r[rowKey])} className="transition-[background-color] duration-160 ease-standard hover:bg-surface-raised">
                  {columns.map(c => (
                    <td key={c.key} className={cn('h-row border-b border-edge px-3 py-1 whitespace-nowrap [tr:last-child>&]:border-b-0', c.align === 'right' && 'text-right tabular-nums', c.muted && 'text-fg-muted')}>
                      {cell[c.key] ? cell[c.key]!({ row: r, value: r[c.key] }) : display(r[c.key])}
                    </td>
                  ))}
                </tr>
              ))}
              {!visible.length && (
                <tr>
                  <td colSpan={columns.length} className="px-3 py-6 text-center text-fg-muted">
                    {empty ?? <>Nothing matches these filters. <button type="button" className="cursor-pointer font-medium text-fg underline-offset-4 hover:underline" onClick={() => pick({})}>Clear filters</button></>}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
      {sorted.length > pageSize && (
        <div className="flex items-center justify-between gap-3">
          <span className="type-caption text-fg-muted tabular-nums" aria-live="polite">{`${at * pageSize + 1} to ${at * pageSize + visible.length} of ${sorted.length}`}</span>
          <div className="flex gap-2">
            <Button variant="secondary" size="sm" disabled={at === 0} onClick={() => setPage(at - 1)}>Previous</Button>
            <Button variant="secondary" size="sm" disabled={at >= pages - 1} onClick={() => setPage(at + 1)}>Next</Button>
          </div>
        </div>
      )}
    </div>
  )
}

export default DataTable
react/lib/cn.ts
// Joins class names, skipping falsy ones: cn('a', on && 'b', ['c', undefined]). It does not merge conflicting
// utilities (no tailwind-merge), as Vue's class binding does not: the library's classes are written not to compete,
// and a className from the caller is appended after them, as Vue appends a fallthrough class.
export type ClassValue = string | false | null | undefined | 0 | ClassValue[]

export function cn(...values: ClassValue[]): string {
	const out: string[] = []
	for (const v of values) {
		if (!v) continue
		if (Array.isArray(v)) {
			const s = cn(...v)
			if (s) out.push(s)
		}
		else out.push(v)
	}
	return out.join(' ')
}
elements/components/ui/data-table.ts
import { html, nothing } from 'lit'
import { ArrowDown, ArrowUp, ArrowUpDown, Check, ChevronDown } from 'lucide'
import { ifDefined } from 'lit/directives/if-defined.js'
import { repeat } from 'lit/directives/repeat.js'
import { DsElement, define } from '@/elements/lib/element'
import { icon } from '@/elements/lib/icon'
import '@/elements/components/ui/button'
import '@/elements/components/ui/dropdown-menu'
import '@/elements/components/ui/menu-item'
import styles from 'virtual:tw'

// DataTable.tsx as <spyglass-data-table>: a table people filter, sort and page through. Over it, a dropdown per filter
// (radio rows, the trigger saying what is picked) and a way to clear them; heads in DM Sans Medium capitals, muted,
// that sort when they can (aria-sort; the arrow shows the order, a faint pair where it could); 40px rows on hairlines
// that take the #262626 fill under the pointer; numbers right-aligned in tabular figures; the whole in a hairline box
// with the 8px corner that scrolls sideways on its own. Under it, where the page is and Previous and Next. Filters and
// sort go back to the first page. Cells render the value (numbers in en-US), or what `cells[key]({ row, value })`
// returns (a node or text: React's `cell`). Nothing matching shows one line with a way to clear the filters, or the
// `empty` slot. `columns`, `rows` and `filters` are JSON attributes or properties.

export type DataColumn = { key: string, label: string, align?: 'left' | 'right', sortable?: boolean, muted?: boolean }
export type DataFilter = { key: string, label: string, options: string[], any?: string }
export type DataRow = Record<string, unknown>
export type DataCell = (slot: { row: DataRow, value: unknown }) => unknown

const display = (v: unknown) => (typeof v === 'number' ? v.toLocaleString('en-US') : String(v ?? ''))
const FILTER = 'inline-flex h-control-sm cursor-pointer items-center gap-1.5 rounded-control border border-edge-strong bg-surface-subtle px-3 type-ui text-fg transition-[border-color] duration-160 ease-standard hover:border-action-secondary-edge-hover aria-expanded:border-edge-focus max-md:h-control-touch'
const SORT = '-mx-1 inline-flex cursor-pointer items-center gap-1 rounded-ds-sm px-1 align-middle uppercase transition-[color] duration-160 ease-standard hover:text-fg'

/**
 * @summary A table people filter, sort and page through.
 * @slot empty - In place of the line shown when nothing matches the filters.
 */
export class DataTable extends DsElement {
	static styles = [DsElement.styles, styles]
	static properties = {
		columns: { type: Array },
		rows: { type: Array },
		rowKey: { attribute: 'row-key' },
		label: {},
		filters: { type: Array },
		pageSize: { type: Number, attribute: 'page-size' },
		cells: { attribute: false },
		picked: { state: true },
		sort: { state: true },
		page: { state: true },
	}

	/** The columns: key, label, align, sortable, muted. */
	columns: DataColumn[] = []
	rows: DataRow[] = []
	/** The field that tells rows apart. */
	rowKey = 'id'
	/** The table's name for assistive tech. */
	label = ''
	/** A dropdown per filter: key, label, options, and what "any" reads as. */
	filters: DataFilter[] = []
	/** Rows per page. */
	pageSize = 5
	/** How a column's cells render, by key (a property): table.cells = { spend: ({ value }) => text }. */
	cells: Partial<Record<string, DataCell>> = {}
	private picked: Record<string, string> = {}
	private sort: { key: string, dir: 'ascending' | 'descending' } | null = null
	private page = 0

	private get sorted() {
		const filtered = (this.rows ?? []).filter((r) => (this.filters ?? []).every((f) => !this.picked[f.key] || String(r[f.key]) === this.picked[f.key]))
		const s = this.sort
		if (!s) return filtered
		const sign = s.dir === 'ascending' ? 1 : -1
		return [...filtered].sort((a, b) => {
			const x = a[s.key]
			const y = b[s.key]
			return sign * (typeof x === 'number' && typeof y === 'number' ? x - y : String(x).localeCompare(String(y)))
		})
	}
	private pick(next: Record<string, string>) {
		this.picked = next
		this.page = 0
	}
	private toggleSort(key: string) {
		const s = this.sort
		this.sort = s?.key !== key ? { key, dir: 'ascending' } : s.dir === 'ascending' ? { key, dir: 'descending' } : null
		this.page = 0
	}

	render() {
		const filters = this.filters ?? []
		const columns = this.columns ?? []
		const sorted = this.sorted
		const size = this.pageSize
		const pages = Math.max(1, Math.ceil(sorted.length / size))
		const at = Math.min(this.page, pages - 1)
		const visible = sorted.slice(at * size, at * size + size)
		const anyOn = Object.values(this.picked).some(Boolean)
		const sort = this.sort
		const arrow = (c: DataColumn) => sort?.key === c.key && sort.dir === 'ascending'
			? icon(ArrowUp, 'arrow-up', { size: 14, strokeWidth: 1.5, class: 'text-fg', attrs: { 'aria-hidden': 'true' } })
			: sort?.key === c.key
				? icon(ArrowDown, 'arrow-down', { size: 14, strokeWidth: 1.5, class: 'text-fg', attrs: { 'aria-hidden': 'true' } })
				: icon(ArrowUpDown, 'arrow-up-down', { size: 14, strokeWidth: 1.5, class: 'text-fg-faint', attrs: { 'aria-hidden': 'true' } })
		const filterBar = filters.length
			? html`<div class="flex flex-wrap items-center gap-2">${filters.map((f) => {
				const any = f.any ?? 'Any'
				const now = this.picked[f.key] ?? ''
				return html`<spyglass-dropdown-menu label=${f.label} width="200px"><button slot="trigger" type="button" class=${FILTER}><span>${`${f.label}: ${now || any}`}</span>${icon(ChevronDown, 'chevron-down', { size: 16, strokeWidth: 1.5, class: 'text-fg-muted', attrs: { 'aria-hidden': 'true' } })}</button>${['', ...f.options].map((o) => html`<spyglass-menu-item role="menuitemradio" aria-checked=${String(now === o)} @select=${() => this.pick({ ...this.picked, [f.key]: o })}><span class="min-w-0 flex-1 truncate">${o || any}</span>${now === o ? icon(Check, 'check', { size: 16, strokeWidth: 1.5, class: 'shrink-0', attrs: { 'aria-hidden': 'true' } }) : nothing}</spyglass-menu-item>`)}</spyglass-dropdown-menu>`
			})}${anyOn ? html`<spyglass-button variant="ghost" size="sm" @click=${() => this.pick({})}>Clear filters</spyglass-button>` : nothing}</div>`
			: nothing
		return html`<div data-ds="data-table" class="flex min-w-0 flex-col gap-3">${filterBar}<div class="overflow-hidden rounded-container border border-edge"><div class="overflow-x-auto -outline-offset-2 fade-x" role="region" aria-label=${this.label} tabindex="0"><table class="w-full border-collapse type-ui">
			<thead><tr>${columns.map((c) => html`<th scope="col" class=${['h-10 border-b border-edge px-3 align-middle type-label whitespace-nowrap text-fg-muted', c.align === 'right' ? 'text-right' : 'text-left'].join(' ')} aria-sort=${ifDefined(sort?.key === c.key ? sort.dir : c.sortable ? 'none' : undefined)}>${c.sortable ? html`<button type="button" class=${[SORT, c.align === 'right' ? 'flex-row-reverse' : ''].filter(Boolean).join(' ')} @click=${() => this.toggleSort(c.key)}>${c.label}${arrow(c)}</button>` : c.label}</th>`)}</tr></thead>
			<tbody>${repeat(visible, (r) => String(r[this.rowKey]), (r) => html`<tr class="transition-[background-color] duration-160 ease-standard hover:bg-surface-raised">${columns.map((c) => html`<td class=${['h-row border-b border-edge px-3 py-1 whitespace-nowrap [tr:last-child>&]:border-b-0', c.align === 'right' ? 'text-right tabular-nums' : '', c.muted ? 'text-fg-muted' : ''].filter(Boolean).join(' ')}>${this.cells?.[c.key] ? this.cells[c.key]!({ row: r, value: r[c.key] }) : display(r[c.key])}</td>`)}</tr>`)}${!visible.length ? html`<tr><td colspan=${columns.length} class="px-3 py-6 text-center text-fg-muted"><slot name="empty">Nothing matches these filters. <button type="button" class="cursor-pointer font-medium text-fg underline-offset-4 hover:underline" @click=${() => this.pick({})}>Clear filters</button></slot></td></tr>` : nothing}</tbody>
		</table></div></div>${sorted.length > size ? html`<div class="flex items-center justify-between gap-3"><span class="type-caption text-fg-muted tabular-nums" aria-live="polite">${`${at * size + 1} to ${at * size + visible.length} of ${sorted.length}`}</span><div class="flex gap-2"><spyglass-button variant="secondary" size="sm" ?disabled=${at === 0} @click=${() => { this.page = at - 1 }}>Previous</spyglass-button><spyglass-button variant="secondary" size="sm" ?disabled=${at >= pages - 1} @click=${() => { this.page = at + 1 }}>Next</spyglass-button></div></div>` : nothing}</div>`
	}
}

define('data-table', DataTable)

Reference: Derived from the guidelines: DM Sans for cells and capital labels for heads, neutral hairlines, the #262626 card fill for the hovered row and the filter menus, the 10px canvas corner (8px here). shadcn's data table (filters, sortable heads, pagination) for anatomy and ARIA..