{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "elements-data-table",
  "type": "registry:component",
  "title": "Data table",
  "description": "A tool's rows and columns with formatting, sorting, and a card layout in narrow columns.",
  "registryDependencies": [
    "https://r.assistant-ui.com/base/elements-surfaces.json",
    "https://r.assistant-ui.com/base/elements-href.json",
    "https://r.assistant-ui.com/base/elements-range.json"
  ],
  "files": [
    {
      "type": "registry:component",
      "path": "components/assistant-ui/elements/data-table.tsx",
      "sourcePath": "packages/ui/src/components/react/assistant-ui/elements/data-table.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useState, type ComponentProps } from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport { safeHref } from \"../utils/href\";\nimport { clamp } from \"../utils/range\";\nimport { useIsomorphicLayoutEffect } from \"../utils/useIsomorphicLayoutEffect\";\nimport { field, mono, paper } from \"./surfaces\";\n\nexport type DataTableValue =\n  | string\n  | number\n  | boolean\n  | null\n  | undefined\n  | readonly (string | number)[];\n\nexport type DataTableRow = Readonly<Record<string, DataTableValue>>;\n\nexport type DataTableFormat =\n  | { kind: \"text\" }\n  | {\n      kind: \"number\";\n      decimals?: number | undefined;\n      compact?: boolean | undefined;\n      unit?: string | undefined;\n    }\n  | {\n      kind: \"currency\";\n      currency: string;\n      decimals?: number | undefined;\n      compact?: boolean | undefined;\n    }\n  | {\n      kind: \"percent\";\n      decimals?: number | undefined;\n      basis?: \"fraction\" | \"unit\" | undefined;\n    }\n  | {\n      kind: \"delta\";\n      decimals?: number | undefined;\n      unit?: string | undefined;\n      upIsGood?: boolean | undefined;\n    }\n  | { kind: \"date\"; style?: \"date\" | \"datetime\" | \"relative\" | undefined }\n  | {\n      kind: \"boolean\";\n      trueLabel?: string | undefined;\n      falseLabel?: string | undefined;\n    }\n  | { kind: \"link\"; hrefKey?: string | undefined }\n  | {\n      kind: \"badge\";\n      tones?:\n        | Readonly<Record<string, \"neutral\" | \"success\" | \"warning\" | \"danger\">>\n        | undefined;\n    }\n  | { kind: \"list\"; max?: number | undefined };\n\nexport interface DataTableColumn {\n  key: string;\n  label: string;\n  format?: DataTableFormat | undefined;\n  align?: \"start\" | \"end\" | undefined;\n  sortable?: boolean | undefined;\n  priority?: \"primary\" | \"secondary\" | undefined;\n  width?: string | undefined;\n}\n\nexport interface DataTableSort {\n  key: string;\n  direction: \"asc\" | \"desc\";\n}\n\nexport interface DataTableProps extends Omit<\n  ComponentProps<\"div\">,\n  \"children\"\n> {\n  columns: readonly DataTableColumn[];\n  rows: readonly DataTableRow[];\n  rowKey?: string | undefined;\n  caption?: string | undefined;\n  defaultSort?: DataTableSort | undefined;\n  sort?: DataTableSort | null | undefined;\n  onSortChange?: ((sort: DataTableSort | null) => void) | undefined;\n  locale?: string | undefined;\n  emptyMessage?: string | undefined;\n  relativeTo?: number | undefined;\n}\n\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}(?:T.*)?$/;\nconst DATE_ONLY = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nconst isEmpty = (value: DataTableValue) =>\n  value === null || value === undefined;\n\nconst textValue = (value: Exclude<DataTableValue, null | undefined>) =>\n  Array.isArray(value) ? value.join(\", \") : String(value);\n\nconst isCalendarDate = (value: string) => {\n  const [year, month, day] = value.slice(0, 10).split(\"-\").map(Number);\n  if (year === undefined || month === undefined || day === undefined) {\n    return false;\n  }\n  if (month < 1 || month > 12 || day < 1) return false;\n  const daysInMonth =\n    month === 2\n      ? year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)\n        ? 29\n        : 28\n      : [4, 6, 9, 11].includes(month)\n        ? 30\n        : 31;\n  return day <= daysInMonth;\n};\n\nconst asDate = (value: DataTableValue) => {\n  const timestamp =\n    typeof value === \"number\"\n      ? value\n      : typeof value === \"string\" &&\n          ISO_DATE.test(value) &&\n          isCalendarDate(value)\n        ? Date.parse(value)\n        : Number.NaN;\n  return Number.isNaN(timestamp) ? undefined : new Date(timestamp);\n};\n\nconst fractionDigits = (decimals: number | undefined) =>\n  decimals === undefined || !Number.isFinite(decimals)\n    ? {}\n    : {\n        minimumFractionDigits: Math.floor(clamp(decimals, 0, 20)),\n        maximumFractionDigits: Math.floor(clamp(decimals, 0, 20)),\n      };\n\nconst numberOptions = (decimals: number | undefined, compact: boolean) => ({\n  notation: compact ? (\"compact\" as const) : (\"standard\" as const),\n  ...fractionDigits(decimals),\n});\n\n/**\n * Formats with Intl, falling back to the raw value: a model can send a\n * currency code or locale that Intl rejects by throwing.\n */\nconst formatted = (\n  value: Exclude<DataTableValue, null | undefined>,\n  format: () => string,\n) => {\n  try {\n    return format();\n  } catch {\n    return textValue(value);\n  }\n};\n\nconst numericValue = (value: DataTableValue) =>\n  typeof value === \"number\" && !Number.isNaN(value) ? value : undefined;\n\nconst relativeDate = (date: Date, locale: string, relativeTo: number) => {\n  const seconds = Math.round((date.getTime() - relativeTo) / 1000);\n  const units: readonly [Intl.RelativeTimeFormatUnit, number][] = [\n    [\"year\", 31_536_000],\n    [\"month\", 2_592_000],\n    [\"week\", 604_800],\n    [\"day\", 86_400],\n    [\"hour\", 3_600],\n    [\"minute\", 60],\n    [\"second\", 1],\n  ];\n  const [unit, amount] = units.find(\n    ([, size]) => Math.abs(seconds) >= size,\n  ) ?? [\"second\", 1];\n  return new Intl.RelativeTimeFormat(locale, { numeric: \"auto\" }).format(\n    Math.round(seconds / amount),\n    unit,\n  );\n};\n\nconst relativeRefreshDelay = (\n  columns: readonly DataTableColumn[],\n  rows: readonly DataTableRow[],\n  now: number,\n) => {\n  const relativeKeys = columns\n    .filter(\n      (column) =>\n        column.format?.kind === \"date\" && column.format.style === \"relative\",\n    )\n    .map((column) => column.key);\n  const freshestAge = rows.reduce((minimum, row) => {\n    for (const key of relativeKeys) {\n      const date = asDate(row[key]);\n      if (date) minimum = Math.min(minimum, Math.abs(now - date.getTime()));\n    }\n    return minimum;\n  }, Number.POSITIVE_INFINITY);\n\n  if (freshestAge < 60_000) return 1_000;\n  if (freshestAge < 3_600_000) return 30_000;\n  if (freshestAge < 86_400_000) return 60_000;\n  if (freshestAge < 604_800_000) return 3_600_000;\n  return 86_400_000;\n};\n\nconst withUnit = (text: string, unit: string | undefined) =>\n  unit === undefined || unit === \"\"\n    ? text\n    : /^[%‰°]/.test(unit)\n      ? `${text}${unit}`\n      : `${text} ${unit}`;\n\nconst EmptyValue = () => <span className=\"text-muted-foreground\">none</span>;\n\nfunction Value({\n  column,\n  row,\n  locale,\n  relativeTo,\n}: {\n  column: DataTableColumn;\n  row: DataTableRow;\n  locale: string;\n  relativeTo: number | undefined;\n}) {\n  const value = row[column.key];\n  if (isEmpty(value)) return <EmptyValue />;\n\n  const format = column.format ?? { kind: \"text\" as const };\n  if (format.kind === \"number\") {\n    const number = numericValue(value);\n    if (number === undefined) return <>{textValue(value)}</>;\n    const content = formatted(value, () =>\n      new Intl.NumberFormat(\n        locale,\n        numberOptions(format.decimals, format.compact === true),\n      ).format(number),\n    );\n    return <>{withUnit(content, format.unit)}</>;\n  }\n\n  if (format.kind === \"currency\") {\n    const number = numericValue(value);\n    if (number === undefined) return <>{textValue(value)}</>;\n    return (\n      <>\n        {formatted(value, () =>\n          new Intl.NumberFormat(locale, {\n            style: \"currency\",\n            currency: format.currency,\n            ...numberOptions(format.decimals, format.compact === true),\n          }).format(number),\n        )}\n      </>\n    );\n  }\n\n  if (format.kind === \"percent\") {\n    const number = numericValue(value);\n    if (number === undefined) return <>{textValue(value)}</>;\n    return (\n      <>\n        {formatted(value, () =>\n          new Intl.NumberFormat(locale, {\n            style: \"percent\",\n            ...fractionDigits(format.decimals),\n          }).format(format.basis === \"unit\" ? number / 100 : number),\n        )}\n      </>\n    );\n  }\n\n  if (format.kind === \"delta\") {\n    const number = numericValue(value);\n    if (number === undefined) return <>{textValue(value)}</>;\n    const direction = number > 0 ? \"↑\" : number < 0 ? \"↓\" : \"→\";\n    const good = number === 0 || number > 0 === (format.upIsGood ?? true);\n    const content = formatted(value, () =>\n      new Intl.NumberFormat(locale, {\n        signDisplay: \"never\",\n        ...fractionDigits(format.decimals),\n      }).format(number),\n    );\n    return (\n      <span\n        className={cn(\n          number === 0\n            ? \"text-muted-foreground\"\n            : good\n              ? \"text-emerald-600 dark:text-emerald-400\"\n              : \"text-red-600 dark:text-red-400\",\n        )}\n      >\n        {direction} {withUnit(content, format.unit)}\n      </span>\n    );\n  }\n\n  if (format.kind === \"date\") {\n    const date = asDate(value);\n    if (!date) return <>{textValue(value)}</>;\n    const style = format.style ?? \"date\";\n    const content = formatted(value, () =>\n      style === \"relative\" && relativeTo !== undefined\n        ? relativeDate(date, locale, relativeTo)\n        : new Intl.DateTimeFormat(\n            locale,\n            style === \"datetime\"\n              ? { dateStyle: \"medium\", timeStyle: \"short\" }\n              : {\n                  dateStyle: \"medium\",\n                  ...((style === \"relative\" && relativeTo === undefined) ||\n                  (typeof value === \"string\" && DATE_ONLY.test(value))\n                    ? { timeZone: \"UTC\" }\n                    : {}),\n                },\n          ).format(date),\n    );\n    return <span title={date.toISOString()}>{content}</span>;\n  }\n\n  if (format.kind === \"boolean\") {\n    if (typeof value !== \"boolean\") return <>{textValue(value)}</>;\n    return (\n      <>{value ? (format.trueLabel ?? \"Yes\") : (format.falseLabel ?? \"No\")}</>\n    );\n  }\n\n  if (format.kind === \"link\") {\n    const hrefValue = format.hrefKey ? row[format.hrefKey] : value;\n    const href = safeHref(\n      typeof hrefValue === \"string\" ? hrefValue : undefined,\n    );\n    if (!href) return <>{textValue(value)}</>;\n    const external = /^https?:/.test(href);\n    return external ? (\n      <a\n        href={href}\n        target=\"_blank\"\n        rel=\"noopener noreferrer\"\n        className=\"underline underline-offset-2\"\n      >\n        {textValue(value)}\n        <span className=\"sr-only\"> (opens in a new tab)</span>\n      </a>\n    ) : (\n      <a href={href} className=\"underline underline-offset-2\">\n        {textValue(value)}\n      </a>\n    );\n  }\n\n  if (format.kind === \"badge\") {\n    const tone = format.tones?.[textValue(value)] ?? \"neutral\";\n    return (\n      <span\n        className={cn(\n          \"inline-flex rounded-full px-2 py-0.5 text-xs font-medium\",\n          tone === \"neutral\" && cn(field, \"text-foreground/60\"),\n          tone === \"success\" &&\n            \"bg-emerald-500/12 text-emerald-700 dark:text-emerald-300\",\n          tone === \"warning\" &&\n            \"bg-amber-500/12 text-amber-700 dark:text-amber-300\",\n          tone === \"danger\" && \"bg-red-500/12 text-red-700 dark:text-red-300\",\n        )}\n      >\n        {textValue(value)}\n      </span>\n    );\n  }\n\n  if (format.kind === \"list\" && Array.isArray(value)) {\n    const max = Math.max(0, Math.floor(format.max ?? value.length));\n    const shown = value.slice(0, max);\n    return (\n      <span className=\"flex flex-wrap gap-1\">\n        {shown.map((item, index) => (\n          <span\n            key={index}\n            className={cn(\n              field,\n              \"text-foreground/60 rounded-md px-1.5 py-0.5 text-xs\",\n            )}\n          >\n            {item}\n          </span>\n        ))}\n        {value.length > shown.length ? (\n          <span className=\"text-muted-foreground px-1.5 py-0.5 text-xs\">\n            +{value.length - shown.length}\n          </span>\n        ) : null}\n      </span>\n    );\n  }\n\n  return <>{textValue(value)}</>;\n}\n\nconst isNumeric = (format: DataTableFormat | undefined) =>\n  format?.kind === \"number\" ||\n  format?.kind === \"currency\" ||\n  format?.kind === \"percent\" ||\n  format?.kind === \"delta\";\n\nconst compareValues = (\n  a: DataTableValue,\n  b: DataTableValue,\n  column: DataTableColumn,\n  collator: Intl.Collator,\n) => {\n  if (isEmpty(a)) return isEmpty(b) ? 0 : 1;\n  if (isEmpty(b)) return -1;\n  if (column.format?.kind === \"date\") {\n    const first = asDate(a);\n    const second = asDate(b);\n    if (first && second) return first.getTime() - second.getTime();\n  }\n  if (typeof a === \"number\" && typeof b === \"number\") return a - b;\n  if (typeof a === \"boolean\" && typeof b === \"boolean\") {\n    return Number(a) - Number(b);\n  }\n  if (Array.isArray(a) && Array.isArray(b)) return a.length - b.length;\n  return collator.compare(textValue(a), textValue(b));\n};\n\nconst collatorFor = (locale: string) => {\n  try {\n    return new Intl.Collator(locale, { numeric: true, sensitivity: \"base\" });\n  } catch {\n    return new Intl.Collator(\"en-US\", { numeric: true, sensitivity: \"base\" });\n  }\n};\n\nconst rowIdentifier = (\n  row: DataTableRow,\n  key: string | undefined,\n  index: number,\n) => {\n  const value = key === undefined ? undefined : row[key];\n  return value === null || value === undefined ? index : textValue(value);\n};\n\nexport function DataTable({\n  columns,\n  rows,\n  rowKey,\n  caption,\n  defaultSort,\n  sort,\n  onSortChange,\n  locale = \"en-US\",\n  emptyMessage = \"No rows\",\n  relativeTo,\n  className,\n  ...props\n}: DataTableProps) {\n  const [internalSort, setInternalSort] = useState<DataTableSort | null>(\n    defaultSort ?? null,\n  );\n  const [announcement, setAnnouncement] = useState(\"\");\n  const activeSort = sort === undefined ? internalSort : sort;\n  const hasRelativeDates = columns.some(\n    (column) =>\n      column.format?.kind === \"date\" && column.format.style === \"relative\",\n  );\n  const [now, setNow] = useState<number>();\n  useIsomorphicLayoutEffect(() => {\n    if (relativeTo === undefined && hasRelativeDates) setNow(Date.now());\n  }, [columns, rows, relativeTo, hasRelativeDates]);\n  const relativeTime = relativeTo ?? now;\n  const refreshDelay =\n    relativeTo === undefined && hasRelativeDates && relativeTime !== undefined\n      ? relativeRefreshDelay(columns, rows, relativeTime)\n      : undefined;\n\n  useEffect(() => {\n    if (refreshDelay === undefined) return;\n    const timeout = window.setTimeout(() => setNow(Date.now()), refreshDelay);\n    return () => window.clearTimeout(timeout);\n  }, [refreshDelay, relativeTime]);\n  const sortColumn = columns.find((column) => column.key === activeSort?.key);\n  const collator = collatorFor(locale);\n  const indexedRows = rows.map((row, index) => ({ row, index }));\n  const sortedRows =\n    activeSort && sortColumn\n      ? indexedRows.sort((a, b) => {\n          const result = compareValues(\n            a.row[sortColumn.key],\n            b.row[sortColumn.key],\n            sortColumn,\n            collator,\n          );\n          if (result === 0) return a.index - b.index;\n          if (\n            isEmpty(a.row[sortColumn.key]) ||\n            isEmpty(b.row[sortColumn.key])\n          ) {\n            return result;\n          }\n          return activeSort.direction === \"asc\" ? result : -result;\n        })\n      : indexedRows;\n  const primaryColumn =\n    columns.find((column) => column.priority === \"primary\") ?? columns[0];\n\n  const changeSort = (column: DataTableColumn) => {\n    const next =\n      activeSort?.key !== column.key\n        ? { key: column.key, direction: \"asc\" as const }\n        : activeSort.direction === \"asc\"\n          ? { key: column.key, direction: \"desc\" as const }\n          : null;\n    if (sort === undefined) setInternalSort(next);\n    setAnnouncement(\n      next\n        ? `Sorted by ${column.label}, ${next.direction === \"asc\" ? \"ascending\" : \"descending\"}`\n        : \"Sorting cleared\",\n    );\n    onSortChange?.(next);\n  };\n\n  const cellClass = (column: DataTableColumn) =>\n    cn(\n      \"text-foreground/80 px-4 py-2.5 align-top text-[13px] leading-5\",\n      (column.align ?? (isNumeric(column.format) ? \"end\" : \"start\")) ===\n        \"end\" && \"text-end tabular-nums\",\n    );\n\n  return (\n    <div\n      data-slot=\"data-table\"\n      className={cn(\n        paper,\n        \"@container w-full overflow-hidden rounded-2xl\",\n        className,\n      )}\n      {...props}\n    >\n      <table className=\"hidden w-full border-collapse @md:table\">\n        {caption ? <caption className=\"sr-only\">{caption}</caption> : null}\n        <thead className=\"border-foreground/10 border-b\">\n          <tr>\n            {columns.map((column) => {\n              const direction =\n                activeSort?.key === column.key\n                  ? activeSort.direction\n                  : undefined;\n              const sortable = column.sortable !== false;\n              return (\n                <th\n                  key={column.key}\n                  scope=\"col\"\n                  {...(direction\n                    ? {\n                        \"aria-sort\":\n                          direction === \"asc\" ? \"ascending\" : \"descending\",\n                      }\n                    : {})}\n                  style={column.width ? { width: column.width } : undefined}\n                  className={cn(\n                    mono,\n                    \"text-muted-foreground px-4 py-3 font-medium\",\n                    (column.align ??\n                      (isNumeric(column.format) ? \"end\" : \"start\")) === \"end\"\n                      ? \"text-end\"\n                      : \"text-start\",\n                  )}\n                >\n                  {sortable ? (\n                    <button\n                      type=\"button\"\n                      onClick={() => changeSort(column)}\n                      aria-label={`Sort by ${column.label}`}\n                      className=\"focus-visible:ring-foreground/20 -mx-1 rounded px-1 outline-none focus-visible:ring-1\"\n                    >\n                      {column.label}\n                      {direction ? (\n                        <span aria-hidden className=\"ms-1\">\n                          {direction === \"asc\" ? \"↑\" : \"↓\"}\n                        </span>\n                      ) : null}\n                    </button>\n                  ) : (\n                    column.label\n                  )}\n                </th>\n              );\n            })}\n          </tr>\n        </thead>\n        <tbody>\n          {sortedRows.length === 0 ? (\n            <tr>\n              <td\n                colSpan={Math.max(columns.length, 1)}\n                className=\"text-muted-foreground px-4 py-6 text-center text-[13px]\"\n              >\n                <span role=\"status\">{emptyMessage}</span>\n              </td>\n            </tr>\n          ) : (\n            sortedRows.map(({ row, index }) => (\n              <tr\n                key={rowIdentifier(row, rowKey, index)}\n                className=\"hover:bg-foreground/[0.025] transition-colors motion-reduce:transition-none\"\n              >\n                {columns.map((column) => (\n                  <td key={column.key} className={cellClass(column)}>\n                    <Value\n                      column={column}\n                      row={row}\n                      locale={locale}\n                      relativeTo={relativeTime}\n                    />\n                  </td>\n                ))}\n              </tr>\n            ))\n          )}\n        </tbody>\n      </table>\n      <div role=\"list\" className=\"space-y-2 p-2.5 @md:hidden\">\n        {sortedRows.length === 0 ? (\n          <div\n            role=\"status\"\n            className=\"text-muted-foreground px-2 py-3 text-center text-[13px]\"\n          >\n            {emptyMessage}\n          </div>\n        ) : (\n          sortedRows.map(({ row, index }) => (\n            <div\n              key={rowIdentifier(row, rowKey, index)}\n              role=\"listitem\"\n              className=\"bg-foreground/[0.025] hover:bg-foreground/[0.04] rounded-xl px-3 py-2 transition-colors motion-reduce:transition-none\"\n            >\n              {primaryColumn ? (\n                <div className=\"text-foreground/90 text-[13px] leading-5 font-medium\">\n                  <Value\n                    column={primaryColumn}\n                    row={row}\n                    locale={locale}\n                    relativeTo={relativeTime}\n                  />\n                </div>\n              ) : null}\n              {columns.length > 1 ? (\n                <dl className=\"mt-1.5 grid grid-cols-1 gap-x-4 gap-y-1 text-[12px] leading-4 @xs:grid-cols-2\">\n                  {columns\n                    .filter((column) => column.key !== primaryColumn?.key)\n                    .map((column) => (\n                      <div\n                        key={column.key}\n                        className=\"flex min-w-0 items-baseline justify-between gap-2\"\n                      >\n                        <dt className=\"text-muted-foreground truncate\">\n                          {column.label}\n                        </dt>\n                        <dd className=\"text-foreground/75 shrink-0 text-end tabular-nums\">\n                          <Value\n                            column={column}\n                            row={row}\n                            locale={locale}\n                            relativeTo={relativeTime}\n                          />\n                        </dd>\n                      </div>\n                    ))}\n                </dl>\n              ) : null}\n            </div>\n          ))\n        )}\n      </div>\n      <p aria-live=\"polite\" className=\"sr-only\">\n        {announcement}\n      </p>\n    </div>\n  );\n}\n"
    }
  ]
}