@tangible/ui 0.2.9 → 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 { type SearchSelectProps, type SearchSelectTriggerProps, type SearchSelectContentProps, type SearchSelectOptionProps } from './types';
2
- declare function SearchSelectRoot({ value: controlledValue, defaultValue, onValueChange, open: controlledOpen, defaultOpen, onOpenChange, inputValue: controlledInputValue, onInputChange, filter, disabled, placeholder, size, id: triggerIdProp, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy, 'aria-invalid': ariaInvalid, 'aria-required': ariaRequired, labels: labelsProp, children, }: SearchSelectProps): import("react/jsx-runtime").JSX.Element;
2
+ declare function SearchSelectRoot({ value: controlledValue, defaultValue, onValueChange, open: controlledOpen, defaultOpen, onOpenChange, inputValue: controlledInputValue, onInputChange, filter, disabled, placeholder, size, anchorRef, restoreFocusRef, id: triggerIdProp, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy, 'aria-invalid': ariaInvalid, 'aria-required': ariaRequired, labels: labelsProp, children, }: SearchSelectProps): import("react/jsx-runtime").JSX.Element;
3
3
  declare namespace SearchSelectRoot {
4
4
  var displayName: string;
5
5
  }
@@ -14,7 +14,7 @@ const defaultFilter = (textValue, query) => textValue.toLowerCase().includes(que
14
14
  // =============================================================================
15
15
  // SearchSelect Root
16
16
  // =============================================================================
17
- function SearchSelectRoot({ value: controlledValue, defaultValue, onValueChange, open: controlledOpen, defaultOpen, onOpenChange, inputValue: controlledInputValue, onInputChange, filter = defaultFilter, disabled = false, placeholder = '', size = 'md', id: triggerIdProp, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy, 'aria-invalid': ariaInvalid, 'aria-required': ariaRequired, labels: labelsProp, children, }) {
17
+ function SearchSelectRoot({ value: controlledValue, defaultValue, onValueChange, open: controlledOpen, defaultOpen, onOpenChange, inputValue: controlledInputValue, onInputChange, filter = defaultFilter, disabled = false, placeholder = '', size = 'md', anchorRef, restoreFocusRef, id: triggerIdProp, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, 'aria-describedby': ariaDescribedBy, 'aria-invalid': ariaInvalid, 'aria-required': ariaRequired, labels: labelsProp, children, }) {
18
18
  const labels = { ...defaultSearchSelectLabels, ...labelsProp };
19
19
  // Controlled/uncontrolled value — lock decision at mount time (see the
20
20
  // controlled→uncontrolled gotcha in CLAUDE.md)
@@ -84,6 +84,10 @@ function SearchSelectRoot({ value: controlledValue, defaultValue, onValueChange,
84
84
  const listRef = useRef([]);
85
85
  // Active index for navigation (-1 means no active option)
86
86
  const [activeIndex, setActiveIndex] = useState(-1);
87
+ const returnFocus = useCallback(() => {
88
+ ;
89
+ (restoreFocusRef?.current ?? triggerElRef.current)?.focus();
90
+ }, [restoreFocusRef]);
87
91
  // Commit a value: capture label, close, reset the query, hand focus back
88
92
  const selectValue = useCallback((optionValue, textValue) => {
89
93
  knownLabelsRef.current.set(toKey(optionValue), textValue);
@@ -136,10 +140,21 @@ function SearchSelectRoot({ value: controlledValue, defaultValue, onValueChange,
136
140
  onNavigate: (index) => setActiveIndex(index ?? -1),
137
141
  disabledIndices,
138
142
  withClick: false,
139
- dismissOutsidePress: (event) => !(triggerElRef.current &&
140
- event.target instanceof Node &&
141
- triggerElRef.current.contains(event.target)),
143
+ dismissOutsidePress: (event) => {
144
+ const toggleEl = restoreFocusRef?.current ?? triggerElRef.current;
145
+ return !(toggleEl && event.target instanceof Node && toggleEl.contains(event.target));
146
+ },
142
147
  });
148
+ // EXTERNAL-TRIGGER MODE: anchor the panel to the provided element instead
149
+ // of the built-in Trigger (re-checked on every open — the anchor can mount
150
+ // late). Focus returns via restoreFocusRef (usually the opening button).
151
+ useEffect(() => {
152
+ if (anchorRef?.current) {
153
+ refs.setPositionReference(anchorRef.current);
154
+ }
155
+ // refs is stable; re-run on open so late-mounted anchors are picked up
156
+ // eslint-disable-next-line react-hooks/exhaustive-deps
157
+ }, [open, anchorRef]);
143
158
  // Active option ID for aria-activedescendant (hash-based — filtering shifts indices)
144
159
  const activeOptionId = activeIndex >= 0 && orderedOptions[activeIndex]
145
160
  ? optionIdForValue(listboxId, orderedOptions[activeIndex].value)
@@ -157,7 +172,7 @@ function SearchSelectRoot({ value: controlledValue, defaultValue, onValueChange,
157
172
  open,
158
173
  setOpen,
159
174
  floatingRef: refs.floating,
160
- extraContainerRef: triggerElRef,
175
+ extraContainerRef: restoreFocusRef ?? triggerElRef,
161
176
  });
162
177
  const handleInputKeyDown = useCallback((e) => {
163
178
  if (e.key === 'Enter') {
@@ -166,7 +181,7 @@ function SearchSelectRoot({ value: controlledValue, defaultValue, onValueChange,
166
181
  const option = orderedOptions[activeIndex];
167
182
  if (option && !option.disabled) {
168
183
  selectValue(option.value, option.textValue);
169
- triggerElRef.current?.focus();
184
+ returnFocus();
170
185
  }
171
186
  }
172
187
  return;
@@ -180,9 +195,9 @@ function SearchSelectRoot({ value: controlledValue, defaultValue, onValueChange,
180
195
  e.preventDefault();
181
196
  e.stopPropagation();
182
197
  setOpen(false);
183
- triggerElRef.current?.focus();
198
+ returnFocus();
184
199
  }
185
- }, [activeIndex, orderedOptions, selectValue, setOpen]);
200
+ }, [activeIndex, orderedOptions, selectValue, setOpen, returnFocus]);
186
201
  const contextValue = useMemo(() => ({
187
202
  disabled,
188
203
  placeholder,
@@ -202,10 +217,12 @@ function SearchSelectRoot({ value: controlledValue, defaultValue, onValueChange,
202
217
  registerOption,
203
218
  unregisterOption,
204
219
  labelFor,
220
+ returnFocus,
205
221
  handlePanelBlur,
206
222
  handleInputKeyDown,
207
223
  refs,
208
224
  triggerElRef,
225
+ anchorRef,
209
226
  inputRef,
210
227
  listRef,
211
228
  optionIndexMap,
@@ -244,6 +261,7 @@ function SearchSelectRoot({ value: controlledValue, defaultValue, onValueChange,
244
261
  registerOption,
245
262
  unregisterOption,
246
263
  labelFor,
264
+ returnFocus,
247
265
  handlePanelBlur,
248
266
  handleInputKeyDown,
249
267
  refs,
@@ -315,7 +333,7 @@ SearchSelectTriggerComponent.displayName = 'SearchSelect.Trigger';
315
333
  // SearchSelect.Content
316
334
  // =============================================================================
317
335
  function SearchSelectContentComponent({ className, children }) {
318
- const { labels, size, triggerId, listboxId, panelId, setInputValue, handlePanelBlur, handleInputKeyDown, refs, triggerElRef, inputRef, listRef, optionIndexMap, getReferenceProps, getFloatingProps, open, inputValue, activeOptionId, orderedOptions, floatingStyles, } = useSearchSelectContext();
336
+ const { labels, size, triggerId, listboxId, panelId, ariaLabel, setInputValue, handlePanelBlur, handleInputKeyDown, refs, triggerElRef, anchorRef, inputRef, listRef, optionIndexMap, getReferenceProps, getFloatingProps, open, inputValue, activeOptionId, orderedOptions, floatingStyles, } = useSearchSelectContext();
319
337
  // Move focus into the search field when the panel opens. Callback ref, not
320
338
  // an open-keyed effect: FloatingPortal can attach the subtree after the
321
339
  // parent's effects run, so an effect may fire while the input is still
@@ -350,13 +368,13 @@ function SearchSelectContentComponent({ className, children }) {
350
368
  }
351
369
  if (!open)
352
370
  return null;
353
- return (_jsx(FloatingPortal, { root: getPortalRootFor(triggerElRef.current), children: _jsxs("div", { ref: refs.setFloating, className: cx('tui-search-select__panel', className), style: floatingStyles, ...getFloatingProps(),
371
+ return (_jsx(FloatingPortal, { root: getPortalRootFor(triggerElRef.current ?? anchorRef?.current ?? null), children: _jsxs("div", { ref: refs.setFloating, className: cx('tui-search-select__panel', className), style: floatingStyles, ...getFloatingProps(),
354
372
  // AFTER the spread: useRole stamps role="listbox" and its own id on
355
373
  // the floating element — this panel is a NON-MODAL dialog (no focus
356
374
  // trap, no aria-modal; focus-out dismisses it via the blur guard
357
375
  // below, like a combobox popup) holding a combobox + listbox. The
358
376
  // trigger's aria-controls points at panelId.
359
- id: panelId, role: "dialog", "aria-labelledby": triggerId,
377
+ id: panelId, role: "dialog", "aria-labelledby": triggerElRef.current ? triggerId : undefined, "aria-label": triggerElRef.current ? undefined : ariaLabel,
360
378
  // Panel-level so blur from ANY descendant (input, search clear button,
361
379
  // future panel furniture) is evaluated — input-only wiring left the
362
380
  // panel orphaned open after Tab past the clear button.
@@ -367,14 +385,14 @@ function SearchSelectContentComponent({ className, children }) {
367
385
  // combobox-in-dialog shape. aria-haspopup is useRole's listbox
368
386
  // leftover — a combobox already conveys its popup via
369
387
  // aria-expanded/aria-controls.
370
- role: "combobox", "aria-haspopup": undefined, "aria-label": labels.search, "aria-expanded": "true", "aria-controls": listboxId, "aria-autocomplete": "list", "aria-activedescendant": activeOptionId }) }), _jsx("div", { id: listboxId, role: "listbox", "aria-labelledby": triggerId, className: "tui-search-select__listbox", tabIndex: -1, children: _jsx(SearchSelectContentContext.Provider, { value: contentContextValue, children: children }) }), orderedOptions.length === 0 && (_jsx("div", { role: "status", className: "tui-search-select__empty", children: labels.noResults }))] }) }));
388
+ role: "combobox", "aria-haspopup": undefined, "aria-label": labels.search, "aria-expanded": "true", "aria-controls": listboxId, "aria-autocomplete": "list", "aria-activedescendant": activeOptionId }) }), _jsx("div", { id: listboxId, role: "listbox", "aria-labelledby": triggerElRef.current ? triggerId : undefined, "aria-label": triggerElRef.current ? undefined : ariaLabel, className: "tui-search-select__listbox", tabIndex: -1, children: _jsx(SearchSelectContentContext.Provider, { value: contentContextValue, children: children }) }), orderedOptions.length === 0 && (_jsx("div", { role: "status", className: "tui-search-select__empty", children: labels.noResults }))] }) }));
371
389
  }
372
390
  SearchSelectContentComponent.displayName = 'SearchSelect.Content';
373
391
  // =============================================================================
374
392
  // SearchSelect.Option
375
393
  // =============================================================================
376
394
  function SearchSelectOptionComponent({ value: optionValue, disabled = false, textValue: explicitTextValue, className, children, }) {
377
- const { value: selectedValue, selectValue, listboxId, registerOption, unregisterOption, getItemProps, query, filter, triggerElRef, } = useSearchSelectContext();
395
+ const { value: selectedValue, selectValue, listboxId, registerOption, unregisterOption, getItemProps, query, filter, returnFocus, } = useSearchSelectContext();
378
396
  const { listRef, activeIndex, optionIndexMap } = useSearchSelectContentContext();
379
397
  const ref = useRef(null);
380
398
  // Built-in filtering: a non-matching option renders null AND leaves the
@@ -411,8 +429,8 @@ function SearchSelectOptionComponent({ value: optionValue, disabled = false, tex
411
429
  if (disabled)
412
430
  return;
413
431
  selectValue(optionValue, textValue);
414
- triggerElRef.current?.focus();
415
- }, [disabled, optionValue, textValue, selectValue, triggerElRef]);
432
+ returnFocus();
433
+ }, [disabled, optionValue, textValue, selectValue, returnFocus]);
416
434
  // Prevent the input losing focus when clicking an option
417
435
  const handlePointerDown = useCallback((e) => {
418
436
  e.preventDefault();
@@ -45,6 +45,21 @@ export type SearchSelectProps = {
45
45
  size?: SizeStandard;
46
46
  /** Trigger id — Field.Control injects this. */
47
47
  id?: string;
48
+ /**
49
+ * EXTERNAL-TRIGGER MODE: anchor the panel to this element instead of the
50
+ * built-in Trigger. Use with controlled `open`/`onOpenChange` and no
51
+ * `<SearchSelect.Trigger>` — e.g. an IconButton that opens a picker panel
52
+ * under its host field. Provide `aria-label` (the panel's name — the
53
+ * trigger-labelled path doesn't exist here) and wire the external button's
54
+ * own aria-haspopup/aria-expanded.
55
+ */
56
+ anchorRef?: React.RefObject<HTMLElement | null>;
57
+ /**
58
+ * External-trigger mode: where focus returns on commit/Escape (usually the
59
+ * button that opened the panel). Blur onto this element keeps the panel
60
+ * open, so the button's own click handler can toggle without flicker.
61
+ */
62
+ restoreFocusRef?: React.RefObject<HTMLElement | null>;
48
63
  'aria-label'?: string;
49
64
  'aria-labelledby'?: string;
50
65
  'aria-describedby'?: string;
@@ -99,6 +114,8 @@ export type SearchSelectContextValue = {
99
114
  registerOption: (option: RegisteredOption) => void;
100
115
  unregisterOption: (optionValue: OptionValue) => void;
101
116
  labelFor: (value: OptionValue) => string;
117
+ /** Focus the trigger (or restoreFocusRef in external-trigger mode). */
118
+ returnFocus: () => void;
102
119
  handlePanelBlur: (e: React.FocusEvent) => void;
103
120
  handleInputKeyDown: (e: React.KeyboardEvent) => void;
104
121
  refs: {
@@ -109,6 +126,8 @@ export type SearchSelectContextValue = {
109
126
  setFloating: (node: HTMLElement | null) => void;
110
127
  };
111
128
  triggerElRef: MutableRefObject<HTMLButtonElement | null>;
129
+ /** External-trigger mode anchor (see SearchSelectProps.anchorRef). */
130
+ anchorRef?: React.RefObject<HTMLElement | null>;
112
131
  inputRef: MutableRefObject<HTMLInputElement | null>;
113
132
  listRef: MutableRefObject<(HTMLElement | null)[]>;
114
133
  optionIndexMap: Map<string, number>;
@@ -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.9",
3
+ "version": "0.2.11",
4
4
  "description": "Tangible Design System",
5
5
  "type": "module",
6
6
  "main": "./components/index.js",