// Dashtreme's DataTables, in React: "Show N entries", search, Copy / CSV / Print, sortable striped rows, "Showing x to y // of z entries" and pagination. Columns render cells and give raw values for sorting, searching and export. import { useEffect, useMemo, useState, type ReactNode } from 'react' import { download, toCsv } from '../lib/csv' import { useStored } from '../lib/hooks' import { useFeedback } from './feedback' import { Help } from './ui' export type Col = { key: string label: string /** Render the cell (default: the value as text). */ render?: (row: R) => ReactNode /** The raw value for sorting, filtering and export (default: row[key]). */ value?: (row: R) => unknown num?: boolean wrap?: boolean help?: string width?: number } const SIZES = [10, 25, 50, 100, 0] as const // 0 = all function pages(cur: number, total: number): (number | '…')[] { if (total <= 7) return Array.from({ length: total }, (_, i) => i) const out: (number | '…')[] = [0] const lo = Math.max(1, cur - 1), hi = Math.min(total - 2, cur + 1) if (lo > 1) out.push('…') for (let i = lo; i <= hi; i++) out.push(i) if (hi < total - 2) out.push('…') out.push(total - 1) return out } /** ``compact`` fits a narrow card: header labels wrap onto two lines and the cells pad less. */ export function DataTable>({ rows, cols, height = 560, filename = 'table', onRowClick, empty = 'No rows.', search = true, initialSort, pageSize, compact = false }: { rows: R[]; cols: Col[]; height?: number; filename?: string; onRowClick?: (r: R) => void; empty?: ReactNode; search?: boolean initialSort?: { key: string; desc?: boolean }; pageSize?: number; compact?: boolean }) { const fb = useFeedback() const [sort, setSort] = useState<{ key: string; desc: boolean } | null>(initialSort ? { key: initialSort.key, desc: !!initialSort.desc } : null) const [filter, setFilter] = useState('') const [size, setSize] = useStored(`dt:${filename}:size`, pageSize ?? 10) const [page, setPage] = useState(0) const val = (c: Col, r: R) => (c.value ? c.value(r) : r[c.key]) const shown = useMemo(() => { let out = rows const f = filter.trim().toLowerCase() if (f) out = out.filter((r) => cols.some((c) => { const v = val(c, r); return v !== null && v !== undefined && String(v).toLowerCase().includes(f) })) if (sort) { const c = cols.find((x) => x.key === sort.key) if (c) { out = [...out].sort((a, b) => { const x = val(c, a), y = val(c, b) if (x === y) return 0 if (x === null || x === undefined) return 1 if (y === null || y === undefined) return -1 const r = typeof x === 'number' && typeof y === 'number' ? x - y : String(x).localeCompare(String(y), undefined, { numeric: true }) return sort.desc ? -r : r }) } } return out // eslint-disable-next-line react-hooks/exhaustive-deps }, [rows, cols, sort, filter]) const per = size > 0 ? size : Math.max(1, shown.length) const npages = Math.max(1, Math.ceil(shown.length / per)) useEffect(() => { if (page > npages - 1) setPage(npages - 1) }, [npages, page]) if (!rows.length) return
{empty}
const start = Math.min(page, npages - 1) * per const view = shown.slice(start, start + per) const click = (k: string) => setSort((s) => (!s || s.key !== k ? { key: k, desc: false } : !s.desc ? { key: k, desc: true } : null)) const exportRows = () => shown.map((r) => cols.map((c) => val(c, r))) const copy = async () => { const text = [cols.map((c) => c.label).join('\t'), ...exportRows().map((r) => r.map((v) => (v === null || v === undefined ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v))).join('\t'))].join('\n') try { await navigator.clipboard.writeText(text); fb.toast(`Copied ${shown.length} rows`, 'success', 2500) } catch { fb.toast('The browser refused the clipboard', 'error') } } const print = () => { const w = window.open('', '_blank'); if (!w) return const esc = (v: unknown) => String(v ?? '').replace(/[&<>]/g, (m) => ({ '&': '&', '<': '<', '>': '>' })[m]!) w.document.write(`${esc(filename)}` + `

${esc(filename)}

${cols.map((c) => ``).join('')}` + exportRows().map((r) => `${r.map((v) => ``).join('')}`).join('') + '
${esc(c.label)}
${esc(typeof v === 'object' && v !== null ? JSON.stringify(v) : v)}
') w.document.close(); w.focus(); w.print() } return (
{search && }
{cols.map((c) => ( ))} {view.map((r, i) => ( onRowClick(r) : undefined}> {cols.map((c) => { const v = c.render ? c.render(r) : (val(c, r) as ReactNode) return })} ))} {!view.length && }
click(c.key)}> {c.label}
{v === null || v === undefined || v === '' ? '—' : v}
No matching rows
Showing {shown.length ? start + 1 : 0} to {start + view.length} of {shown.length} entries{shown.length !== rows.length ? ` (filtered from ${rows.length})` : ''} {npages > 1 && ( )}
) } /** A 0..1 score as a bar with its number (Streamlit's ProgressColumn). */ export function BarCell({ value, max = 1, digits = 3 }: { value: number | null | undefined; max?: number; digits?: number }) { if (value === null || value === undefined) return <>— return ( {value.toFixed(digits)} ) } /** Dashtreme's status pill in a table cell. */ export function Pill({ children, color = 'gray' }: { children: ReactNode; color?: string }) { return {children} }