SPB Git

Repository Public

Table.tsx 7.1 KB 145 lines tsx

1"use client";2import { useVirtualizer } from "@tanstack/react-virtual";3import { useMemo, useRef, useState, type ReactNode } from "react";4import { useI18n } from "@/i18n";5import { cx } from "./cx";6import { Icon } from "./Icon";78export interface Column<T> {9  id: string;10  header: string;11  cell: (row: T) => ReactNode;12  /** Enables client-side sorting on this column. Undefined values sort last. */13  sortValue?: (row: T) => string | number | undefined | null;14  /** Controlled (server-side) sorting: this column can be sorted by the server. */15  sortable?: boolean;16  align?: "right";17  shrink?: boolean;18  mono?: boolean;19  /** Hide below a breakpoint (the information must remain reachable in the detail view). */20  hide?: "sm" | "md";21  /** Header cell is announced but visually empty (actions column). */22  srOnlyHeader?: boolean;23}2425export interface SortState {26  id: string;27  dir: "asc" | "desc";28}2930interface Props<T> {31  caption: string;32  columns: Column<T>[];33  rows: readonly T[];34  rowKey: (row: T) => string;35  initialSort?: SortState;36  /** Controlled sort (server-side sorting): when set, rows are rendered as given. */37  sort?: SortState | undefined;38  onSortChange?: (s: SortState) => void;39  onRowClick?: (row: T) => void;40  selected?: ReadonlySet<string>;41  onSelectedChange?: (s: Set<string>) => void;42  selectLabel?: (row: T) => string;43  compact?: boolean;44  bare?: boolean;45  empty?: ReactNode;46  /** Rows above this count are virtualized (fixed row height, scroll container). */47  virtualizeOver?: number;48}4950const ROW_H = 38;5152export function DataTable<T>({ caption, columns, rows, rowKey, initialSort, sort: controlled, onSortChange, onRowClick, selected, onSelectedChange, selectLabel, compact, bare, empty, virtualizeOver = 200 }: Props<T>) {53  const { t } = useI18n();54  const [inner, setInner] = useState<SortState | undefined>(initialSort);55  const sort = controlled ?? inner;56  const sorted = useMemo(() => {57    if (controlled || !sort) return rows;58    const col = columns.find((c) => c.id === sort.id);59    if (!col?.sortValue) return rows;60    const get = col.sortValue;61    const dir = sort.dir === "asc" ? 1 : -1;62    return [...rows].sort((a, b) => {63      const x = get(a), y = get(b);64      if (x == null && y == null) return 0;65      if (x == null) return 1;66      if (y == null) return -1;67      if (typeof x === "number" && typeof y === "number") return (x - y) * dir;68      return String(x).localeCompare(String(y), undefined, { numeric: true, sensitivity: "base" }) * dir;69    });70  }, [rows, columns, sort, controlled]);7172  const virtual = sorted.length > virtualizeOver;73  const scroller = useRef<HTMLDivElement>(null);74  const rowH = compact ? 30 : ROW_H;75  // eslint-disable-next-line react-hooks/incompatible-library -- TanStack Virtual returns unstable functions by design76  const virt = useVirtualizer({ count: virtual ? sorted.length : 0, getScrollElement: () => scroller.current, estimateSize: () => rowH, overscan: 12 });77  const items = virtual ? virt.getVirtualItems() : null;78  const padTop = items?.[0]?.start ?? 0;79  const padBottom = items ? virt.getTotalSize() - (items[items.length - 1]?.end ?? 0) : 0;80  const visible = items ? items.map((v) => ({ row: sorted[v.index] as T, index: v.index })) : sorted.map((row, index) => ({ row, index }));8182  const toggleSort = (id: string) => {83    const next: SortState = sort?.id === id ? { id, dir: sort.dir === "asc" ? "desc" : "asc" } : { id, dir: "asc" };84    if (onSortChange) onSortChange(next);85    if (!controlled) setInner(next);86  };87  const allSelected = !!selected && sorted.length > 0 && sorted.every((r) => selected.has(rowKey(r)));88  const colCount = columns.length + (onSelectedChange ? 1 : 0);8990  return (91    <div className={cx("mcc-table-wrap", virtual && "virtual", bare && "bare")} ref={scroller} tabIndex={virtual ? 0 : undefined} role={virtual ? "group" : undefined} aria-label={virtual ? caption : undefined}>92      <table className={cx("mcc-table", compact && "compact")} aria-rowcount={virtual ? sorted.length + 1 : undefined}>93        <caption className="sr-only">{caption}</caption>94        <thead>95          <tr>96            {onSelectedChange ? (97              <th scope="col" className="shrink">98                <input type="checkbox" aria-label={t("ui.table.selectAll")} checked={allSelected}99                  onChange={(e) => onSelectedChange(e.target.checked ? new Set(sorted.map(rowKey)) : new Set())} />100              </th>101            ) : null}102            {columns.map((c) => {103              const active = sort?.id === c.id;104              const cls = cx(c.align, c.shrink && "shrink", c.hide && `hide-${c.hide}`);105              if (c.srOnlyHeader) return <th key={c.id} scope="col" className={cls}><span className="sr-only">{c.header}</span></th>;106              if (!(controlled ? c.sortable && onSortChange : c.sortValue)) return <th key={c.id} scope="col" className={cls}>{c.header}</th>;107              return (108                <th key={c.id} scope="col" className={cls} aria-sort={active ? (sort.dir === "asc" ? "ascending" : "descending") : "none"}>109                  <button type="button" className="mcc-th-btn" onClick={() => toggleSort(c.id)} title={t("ui.table.sortBy", { column: c.header })}>110                    {c.header}111                    <Icon name={active ? (sort.dir === "asc" ? "sort-asc" : "sort-desc") : "sort"} size={12} />112                  </button>113                </th>114              );115            })}116          </tr>117        </thead>118        <tbody>119          {sorted.length === 0 ? (120            <tr><td colSpan={colCount}>{empty ?? <span className="muted">{t("ui.table.empty")}</span>}</td></tr>121          ) : null}122          {virtual && padTop > 0 ? <tr aria-hidden="true"><td colSpan={colCount} ref={(el) => { if (el) { el.style.height = `${padTop}px`; el.style.padding = "0"; el.style.border = "0"; } }} /></tr> : null}123          {visible.map(({ row, index }) => {124            const key = rowKey(row);125            const isSel = selected?.has(key) ?? false;126            return (127              <tr key={key} aria-rowindex={virtual ? index + 2 : undefined} aria-selected={onSelectedChange ? isSel : undefined} className={onRowClick ? "clickable" : undefined}128                onClick={onRowClick ? (e) => { if (!(e.target as HTMLElement).closest("a,button,input,label")) onRowClick(row); } : undefined}>129                {onSelectedChange ? (130                  <td className="shrink">131                    <input type="checkbox" aria-label={selectLabel ? selectLabel(row) : t("ui.table.selectRow")} checked={isSel}132                      onChange={(e) => { const next = new Set(selected); if (e.target.checked) next.add(key); else next.delete(key); onSelectedChange(next); }} />133                  </td>134                ) : null}135                {columns.map((c) => <td key={c.id} className={cx(c.align, c.shrink && "shrink", c.mono && "mono", c.hide && `hide-${c.hide}`, c.align === "right" && "num")}>{c.cell(row)}</td>)}136              </tr>137            );138          })}139          {virtual && padBottom > 0 ? <tr aria-hidden="true"><td colSpan={colCount} ref={(el) => { if (el) { el.style.height = `${padBottom}px`; el.style.padding = "0"; el.style.border = "0"; } }} /></tr> : null}140        </tbody>141      </table>142    </div>143  );144}145
Files main
Menu

Theme