@tangible/ui 0.2.10 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import * as React from 'react';
2
- import type { ColumnDef, SortingState, Table as TanTable, RowSelectionState, Updater } from '@tanstack/react-table';
2
+ import type { ColumnDef, SortingState, Table as TanTable, Row as TanRow, RowSelectionState, Updater } from '@tanstack/react-table';
3
3
  import type { DataTableLabels } from './types';
4
4
  type RowId = string | number;
5
5
  type BulkSelectionRenderArgs<T> = {
@@ -20,12 +20,52 @@ export type DataTableProps<T> = {
20
20
  emptyMessage?: React.ReactNode;
21
21
  /** Override hardcoded English strings for i18n. Unset keys use English defaults. */
22
22
  labels?: DataTableLabels;
23
+ /**
24
+ * Extra props for each body `<tr>` — the escape hatch for row-level
25
+ * interaction: keyboard cursors, row click shortcuts, `data-*` hooks,
26
+ * context menus. Consumer `className` is merged after the built-in row
27
+ * classes; `data-selected` and the `is-selected` class always reflect
28
+ * actual selection state and cannot be overridden. `role`/`aria-*` are NOT
29
+ * guarded — overriding `role` on a `<tr>` removes it from the table's
30
+ * accessibility tree, so only do that as part of a deliberate pattern
31
+ * (e.g. rows in a `role="grid"` table keep `role="row"`). Loading/empty
32
+ * placeholder rows are not affected.
33
+ */
34
+ getRowProps?: (row: TanRow<T>) => Omit<React.ComponentProps<'tr'>, 'key' | 'children' | 'dangerouslySetInnerHTML'>;
23
35
  renderPagination?: (table: TanTable<T>) => React.ReactNode;
24
36
  paginationMode?: 'simple' | 'ends' | 'full' | 'smart';
25
37
  paginationMaxNumbers?: number;
26
38
  paginationNavStyle?: 'text' | 'icon';
27
39
  pageSizeOptions?: number[];
28
40
  initialPageSize?: number;
41
+ /**
42
+ * Controlled page index (0-based, matching TanStack). When set, the parent
43
+ * owns paging: the built-in pager requests changes via `onPageIndexChange`,
44
+ * but the page only moves when this prop updates. Page size stays internal
45
+ * either way. Controlled/uncontrolled is locked at mount.
46
+ */
47
+ pageIndex?: number;
48
+ /**
49
+ * Fires with the requested 0-based page index whenever anything asks for a
50
+ * page change — pager clicks, page-size changes (TanStack re-anchors to
51
+ * keep the top row visible), the auto page-0 reset (see
52
+ * `autoResetPageIndex`), or an out-of-range controlled `pageIndex` being
53
+ * clamped into range. Fires in both controlled and uncontrolled modes.
54
+ * Note: 0-based, unlike Pager's 1-based `onPageChange` (the built-in
55
+ * pager converts).
56
+ */
57
+ onPageIndexChange?: (pageIndex: number) => void;
58
+ /**
59
+ * TanStack's automatic page-0 reset when sorting or data identity change.
60
+ * Defaults to `true` when `pageIndex` is uncontrolled, `false` when
61
+ * controlled — a controlled parent owns the index, and the auto-reset
62
+ * would race it back to 0 on every re-render that recreates `data`
63
+ * (parent re-renders on page change → new array identity → reset).
64
+ * Uncontrolled consumers who `setState` inside `onPageIndexChange` while
65
+ * passing a derived (unmemoized) `data` array hit the same loop: pass
66
+ * `false` here or memoize `data`.
67
+ */
68
+ autoResetPageIndex?: boolean;
29
69
  enableRowSelection?: boolean;
30
70
  getRowId?: (row: T, index: number) => string | number;
31
71
  getRowLabelForSelection?: (row: T, index: number) => string;
@@ -33,6 +73,6 @@ export type DataTableProps<T> = {
33
73
  onRowSelectionChange?: (updater: Updater<RowSelectionState>) => void;
34
74
  onSelectionChange?: (selectedRows: T[], selectedIds: (string | number)[]) => void;
35
75
  renderBulkBar?: (args: BulkSelectionRenderArgs<T>) => React.ReactNode;
36
- };
37
- export declare function DataTable<T>({ data, columns, className, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, defaultSorting, loading, loadingMessage, emptyMessage, labels: labelsProp, renderPagination, paginationMode, paginationMaxNumbers, paginationNavStyle, pageSizeOptions, initialPageSize, enableRowSelection, getRowId, getRowLabelForSelection, onSelectionChange, renderBulkBar, rowSelection, onRowSelectionChange, }: DataTableProps<T>): import("react/jsx-runtime").JSX.Element;
76
+ } & Omit<React.TableHTMLAttributes<HTMLTableElement>, 'className' | 'id' | 'children'>;
77
+ export declare function DataTable<T>({ data, columns, className, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, defaultSorting, loading, loadingMessage, emptyMessage, labels: labelsProp, getRowProps, renderPagination, paginationMode, paginationMaxNumbers, paginationNavStyle, pageSizeOptions, initialPageSize, pageIndex: pageIndexProp, onPageIndexChange, autoResetPageIndex, enableRowSelection, getRowId, getRowLabelForSelection, onSelectionChange, renderBulkBar, rowSelection, onRowSelectionChange, ...rest }: DataTableProps<T>): import("react/jsx-runtime").JSX.Element;
38
78
  export {};
@@ -1,13 +1,18 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import * as React from 'react';
3
3
  import { cx } from '../../utils/cx.js';
4
+ import { isDev } from '../../utils/is-dev.js';
4
5
  import { useReactTable, getCoreRowModel, getSortedRowModel, getPaginationRowModel, flexRender } from '@tanstack/react-table';
5
6
  import { BulkActionsBar } from './BulkActionsBar.js';
6
7
  import { Pagination } from './Pagination.js';
7
8
  import { defaultDataTableLabels } from './types.js';
8
- export function DataTable({ data, columns, className, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, defaultSorting = [], loading = false, loadingMessage = 'Loading...', emptyMessage = 'No results', labels: labelsProp, renderPagination, paginationMode = 'smart', paginationMaxNumbers = 7, paginationNavStyle = 'text', pageSizeOptions = [10, 20, 50], initialPageSize,
9
+ // ^ Remaining props (role, data-*, handlers) spread onto the <table> element —
10
+ // enables role="grid" for consumer-owned row cursors and data-testid targeting.
11
+ // id/className/aria-label/aria-labelledby/aria-busy stay component-owned
12
+ // (declared after the spread; className styles the scroll container).
13
+ export function DataTable({ data, columns, className, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, defaultSorting = [], loading = false, loadingMessage = 'Loading...', emptyMessage = 'No results', labels: labelsProp, getRowProps, renderPagination, paginationMode = 'smart', paginationMaxNumbers = 7, paginationNavStyle = 'text', pageSizeOptions = [10, 20, 50], initialPageSize, pageIndex: pageIndexProp, onPageIndexChange, autoResetPageIndex,
9
14
  // selection
10
- enableRowSelection = false, getRowId, getRowLabelForSelection, onSelectionChange, renderBulkBar, rowSelection, onRowSelectionChange, }) {
15
+ enableRowSelection = false, getRowId, getRowLabelForSelection, onSelectionChange, renderBulkBar, rowSelection, onRowSelectionChange, ...rest }) {
11
16
  const labels = React.useMemo(() => ({ ...defaultDataTableLabels, ...labelsProp }), [labelsProp]);
12
17
  const tableId = React.useId();
13
18
  const [sorting, setSorting] = React.useState(defaultSorting);
@@ -23,6 +28,65 @@ enableRowSelection = false, getRowId, getRowLabelForSelection, onSelectionChange
23
28
  onRowSelectionChange?.(updater);
24
29
  }, [isSelectionControlled, onRowSelectionChange]);
25
30
  const defaultPageSize = initialPageSize ?? pageSizeOptions[0] ?? 10;
31
+ // Pagination state lives here (not in TanStack's internal store) so pageIndex
32
+ // can be controlled. Controlled/uncontrolled is locked at mount — see the
33
+ // "controlled→uncontrolled mode switch" gotcha; `pageIndex` flipping to
34
+ // undefined mid-flight must not silently hand control back. (Selection above
35
+ // checks per-render instead: `rowSelection` never legitimately becomes
36
+ // undefined the way a cleared value does.)
37
+ const isPageIndexControlled = React.useRef(pageIndexProp !== undefined).current;
38
+ const [internalPagination, setInternalPagination] = React.useState({
39
+ pageIndex: 0,
40
+ pageSize: defaultPageSize,
41
+ });
42
+ React.useEffect(() => {
43
+ if (isDev() && isPageIndexControlled !== (pageIndexProp !== undefined)) {
44
+ console.warn('DataTable: pageIndex switched between controlled and uncontrolled after mount. ' +
45
+ 'The mode is locked at mount; the switch is ignored.');
46
+ }
47
+ }, [isPageIndexControlled, pageIndexProp]);
48
+ // Clamp the index into range. An out-of-range controlled value (a persisted
49
+ // URL param against a shrunk dataset) would otherwise render a fake
50
+ // "No results" with no pager and no callback — an unrecoverable dead table.
51
+ // No filter row model exists, so the row count is data.length.
52
+ const pageSize = internalPagination.pageSize;
53
+ const maxPageIndex = Math.max(0, Math.ceil(data.length / pageSize) - 1);
54
+ const requestedPageIndex = isPageIndexControlled
55
+ ? (pageIndexProp ?? 0)
56
+ : internalPagination.pageIndex;
57
+ const effectivePageIndex = Math.min(requestedPageIndex, maxPageIndex);
58
+ const paginationState = {
59
+ pageIndex: effectivePageIndex,
60
+ pageSize,
61
+ };
62
+ const onPageIndexChangeRef = React.useRef(onPageIndexChange);
63
+ onPageIndexChangeRef.current = onPageIndexChange;
64
+ // Tell a controlled parent its index was clamped so its state can converge.
65
+ React.useEffect(() => {
66
+ if (isPageIndexControlled && effectivePageIndex !== requestedPageIndex) {
67
+ onPageIndexChangeRef.current?.(effectivePageIndex);
68
+ }
69
+ }, [isPageIndexControlled, effectivePageIndex, requestedPageIndex]);
70
+ // Resolve updaters against a ref, not the render closure: two updates in one
71
+ // React batch (nextPage ×2, or setPageSize + setPageIndex) must compose
72
+ // instead of both resolving against the same stale base — TanStack's own
73
+ // functional setState did this for free before the state was hoisted here.
74
+ // In controlled mode the in-tick composition tracks the *requested* index
75
+ // (optimistic); the per-render resync below snaps back to the prop.
76
+ const paginationRef = React.useRef(paginationState);
77
+ paginationRef.current = paginationState;
78
+ const handlePaginationChange = React.useCallback((updater) => {
79
+ const base = paginationRef.current;
80
+ const next = typeof updater === 'function'
81
+ ? updater(base)
82
+ : updater;
83
+ paginationRef.current = next;
84
+ // pageSize is always internal; pageIndex only when uncontrolled.
85
+ setInternalPagination((prev) => isPageIndexControlled ? { ...prev, pageSize: next.pageSize } : next);
86
+ if (next.pageIndex !== base.pageIndex) {
87
+ onPageIndexChangeRef.current?.(next.pageIndex);
88
+ }
89
+ }, [isPageIndexControlled]);
26
90
  // build columns, inject selection column only when enabled
27
91
  const selectionColumn = React.useMemo(() => ({
28
92
  id: '__select',
@@ -89,9 +153,11 @@ enableRowSelection = false, getRowId, getRowLabelForSelection, onSelectionChange
89
153
  state: {
90
154
  sorting,
91
155
  rowSelection: rowSelectionState,
156
+ pagination: paginationState,
92
157
  },
93
158
  onSortingChange: setSorting,
94
159
  onRowSelectionChange: handleRowSelectionChange,
160
+ onPaginationChange: handlePaginationChange,
95
161
  getCoreRowModel: getCoreRowModel(),
96
162
  getSortedRowModel: getSortedRowModel(),
97
163
  getPaginationRowModel: getPaginationRowModel(),
@@ -99,8 +165,14 @@ enableRowSelection = false, getRowId, getRowLabelForSelection, onSelectionChange
99
165
  ? (row, index) => String(getRowId(row, index))
100
166
  : undefined, // may be undefined, tanstack handles it
101
167
  enableRowSelection,
168
+ autoResetPageIndex: autoResetPageIndex ?? !isPageIndexControlled,
169
+ // initialState is NOT redundant with state.pagination: TanStack's reset
170
+ // helpers (resetPagination/resetPageSize/table.reset) read their defaults
171
+ // back from initialState — without it they'd snap pageSize to a hardcoded
172
+ // 10 that may not even be in pageSizeOptions.
102
173
  initialState: {
103
174
  pagination: {
175
+ pageIndex: 0,
104
176
  pageSize: defaultPageSize,
105
177
  },
106
178
  },
@@ -165,7 +237,7 @@ enableRowSelection = false, getRowId, getRowLabelForSelection, onSelectionChange
165
237
  selectedRowIds,
166
238
  clearSelection: () => table.resetRowSelection(),
167
239
  selectedCount
168
- })) : (_jsx(BulkActionsBar, { count: selectedCount, onClear: () => table.resetRowSelection(), "aria-controls": tableId }))), _jsxs("table", { id: tableId, className: "tui-table", "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, "aria-busy": loading || undefined, children: [_jsx("thead", { className: "tui-table__head", children: table.getHeaderGroups().map((headerGroup) => (_jsx("tr", { className: "tui-table__row tui-table__row--head", children: headerGroup.headers.map((header) => {
240
+ })) : (_jsx(BulkActionsBar, { count: selectedCount, onClear: () => table.resetRowSelection(), "aria-controls": tableId }))), _jsxs("table", { ...rest, id: tableId, className: "tui-table", "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, "aria-busy": loading || undefined, children: [_jsx("thead", { className: "tui-table__head", children: table.getHeaderGroups().map((headerGroup) => (_jsx("tr", { className: "tui-table__row tui-table__row--head", children: headerGroup.headers.map((header) => {
169
241
  const canSort = header.column.getCanSort();
170
242
  const sortDirection = header.column.getIsSorted();
171
243
  const headerDef = header.column.columnDef.header;
@@ -183,7 +255,14 @@ enableRowSelection = false, getRowId, getRowLabelForSelection, onSelectionChange
183
255
  : sortDirection === 'desc'
184
256
  ? '▼'
185
257
  : '' })] })) : (headerContent) }, header.id));
186
- }) }, headerGroup.id))) }), _jsx("tbody", { className: "tui-table__body", children: loading ? (_jsx("tr", { className: "tui-table__row tui-table__row--loading", children: _jsx("td", { className: "tui-table__cell tui-table__cell--body", colSpan: table.getAllLeafColumns().length, children: loadingMessage }) })) : isEmpty ? (_jsx("tr", { className: "tui-table__row tui-table__row--empty", children: _jsx("td", { className: "tui-table__cell tui-table__cell--body", colSpan: table.getAllLeafColumns().length, role: "status", children: emptyMessage }) })) : (rows.map((row) => (_jsx("tr", { className: cx('tui-table__row', 'tui-table__row--body', row.getIsSelected() && 'is-selected'), "data-selected": row.getIsSelected() ? 'true' : 'false', children: row.getVisibleCells().map((cell) => (_jsx("td", { className: "tui-table__cell tui-table__cell--body", children: flexRender(cell.column.columnDef.cell, cell.getContext()) }, cell.id))) }, row.id)))) })] }), renderPagination
258
+ }) }, headerGroup.id))) }), _jsx("tbody", { className: "tui-table__body", children: loading ? (_jsx("tr", { className: "tui-table__row tui-table__row--loading", children: _jsx("td", { className: "tui-table__cell tui-table__cell--body", colSpan: table.getAllLeafColumns().length, children: loadingMessage }) })) : isEmpty ? (_jsx("tr", { className: "tui-table__row tui-table__row--empty", children: _jsx("td", { className: "tui-table__cell tui-table__cell--body", colSpan: table.getAllLeafColumns().length, role: "status", children: emptyMessage }) })) : (rows.map((row) => {
259
+ const rowProps = getRowProps?.(row);
260
+ return (
261
+ // Consumer props spread first: className merges with the
262
+ // built-in classes, and the selection state markers stay
263
+ // authoritative (declared after the spread).
264
+ _jsx("tr", { ...rowProps, className: cx('tui-table__row', 'tui-table__row--body', row.getIsSelected() && 'is-selected', rowProps?.className), "data-selected": row.getIsSelected() ? 'true' : 'false', children: row.getVisibleCells().map((cell) => (_jsx("td", { className: "tui-table__cell tui-table__cell--body", children: flexRender(cell.column.columnDef.cell, cell.getContext()) }, cell.id))) }, row.id));
265
+ })) })] }), renderPagination
187
266
  ? renderPagination(table)
188
267
  : (_jsx(Pagination, { table: table, mode: paginationMode, showPager: showPager, maxNumbers: paginationMaxNumbers, navStyle: paginationNavStyle, pageSizeOptions: pageSizeOptions }))] }));
189
268
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangible/ui",
3
- "version": "0.2.10",
3
+ "version": "0.2.11",
4
4
  "description": "Tangible Design System",
5
5
  "type": "module",
6
6
  "main": "./components/index.js",