@solexllc/usx-react 0.8.0 → 0.9.0

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.
Files changed (58) hide show
  1. package/README.md +15 -0
  2. package/dist/index.cjs +3173 -3238
  3. package/dist/index.js +3174 -3239
  4. package/package.json +4 -4
  5. package/src/components/checkbox/Checkbox.tsx +9 -4
  6. package/src/components/checkbox/checkbox.django.html +2 -2
  7. package/src/components/checkbox/config.json +9 -0
  8. package/src/components/data-table/DataTable.tsx +177 -0
  9. package/src/components/data-table/README.md +42 -0
  10. package/src/components/data-table/TableBody.tsx +123 -0
  11. package/src/components/{table → data-table}/TableCell.tsx +6 -3
  12. package/src/components/data-table/TableContext.tsx +49 -0
  13. package/src/components/{table → data-table}/TableFoot.tsx +8 -7
  14. package/src/components/data-table/TableGroup.tsx +62 -0
  15. package/src/components/data-table/TableHead.tsx +126 -0
  16. package/src/components/data-table/TableRow.tsx +24 -0
  17. package/src/components/data-table/cells.ts +49 -0
  18. package/src/components/data-table/columns.ts +15 -0
  19. package/src/components/data-table/config.json +375 -0
  20. package/src/components/data-table/data-table.django-snapshot.html +13560 -0
  21. package/src/components/data-table/data-table.django.html +13 -0
  22. package/src/components/data-table/data-table.html +34 -0
  23. package/src/components/data-table/data-table.react-snapshot.html +12033 -0
  24. package/src/components/{table → data-table}/table-body.django.html +12 -12
  25. package/src/components/{table → data-table}/table-foot.django.html +6 -6
  26. package/src/components/data-table/table-group.django.html +24 -0
  27. package/src/components/data-table/table-head.django.html +21 -0
  28. package/src/components/data-table/table-row.django.html +57 -0
  29. package/src/components/{table → data-table}/types.ts +48 -5
  30. package/src/components/pagination/Pagination.tsx +7 -1
  31. package/src/components/pagination/config.json +8 -0
  32. package/src/components/pagination/navigation/PaginationNavigation.tsx +10 -0
  33. package/src/components/pagination/step-options/PaginationStepOptions.tsx +3 -0
  34. package/src/components/radio-buttons/RadioButtons.tsx +37 -27
  35. package/src/components/radio-buttons/config.json +19 -1
  36. package/src/components/radio-buttons/radio-buttons.django-snapshot.html +28 -60
  37. package/src/components/radio-buttons/radio-buttons.django.html +16 -28
  38. package/src/components/table/Table.tsx +64 -334
  39. package/src/components/table/config.json +21 -339
  40. package/src/components/table/table.django-snapshot.html +712 -1482
  41. package/src/components/table/table.django.html +14 -59
  42. package/src/components/table/table.html +7 -2364
  43. package/src/components/table/table.react-snapshot.html +711 -2085
  44. package/src/index.js +1 -0
  45. package/src/components/table/TableBody.tsx +0 -256
  46. package/src/components/table/TableContext.tsx +0 -87
  47. package/src/components/table/TableGroup.tsx +0 -69
  48. package/src/components/table/TableHead.tsx +0 -139
  49. package/src/components/table/TableRow.tsx +0 -56
  50. package/src/components/table/hooks/useRowDetails.ts +0 -34
  51. package/src/components/table/hooks/useTableGroups.ts +0 -61
  52. package/src/components/table/hooks/useTableSelect.ts +0 -82
  53. package/src/components/table/hooks/useTableSort.ts +0 -60
  54. package/src/components/table/table-group.django.html +0 -40
  55. package/src/components/table/table-head.django.html +0 -85
  56. package/src/components/table/table-row.django.html +0 -98
  57. package/src/components/table/table_helper.py +0 -298
  58. /package/src/components/{table → data-table}/table-detail-row.django.html +0 -0
@@ -1,350 +1,80 @@
1
- import React, { useMemo, useState, useEffect, useId } from 'react';
1
+ import React from 'react';
2
2
  import classnames from 'classnames';
3
- import Pagination from '../pagination/Pagination';
4
3
 
5
- import { TableContext } from './TableContext';
6
- import type { TableContextValue } from './TableContext';
7
- import TableHead from './TableHead';
8
- import TableBody from './TableBody';
9
- import TableFoot from './TableFoot';
10
- import TableRow from './TableRow';
11
- import TableCell from './TableCell';
12
- import TableGroup from './TableGroup';
13
-
14
- import { useTableSort } from './hooks/useTableSort';
15
- import { useTableSelect } from './hooks/useTableSelect';
16
- import { useTableGroups } from './hooks/useTableGroups';
17
- import { useRowDetails } from './hooks/useRowDetails';
18
-
19
- import type {
20
- GroupBy,
21
- PaginateConfig,
22
- Responsive,
23
- RowDetails,
24
- RowKey,
25
- SelectionMode,
26
- SortState,
27
- TableColumn,
28
- TableRowData,
29
- } from './types';
30
-
31
- export type {
32
- Align,
33
- Aggregate,
34
- GroupBy,
35
- GroupByConfig,
36
- PaginateConfig,
37
- Responsive,
38
- RowDetails,
39
- RowDetailsConfig,
40
- RowKey,
41
- SelectionMode,
42
- SortDirection,
43
- SortState,
44
- TableColumn,
45
- TableRowData,
46
- } from './types';
47
-
48
- function countLeafCols(columns: TableColumn[]): number {
49
- return columns.reduce((sum, col) => {
50
- if (col.hidden) return sum;
51
- if (col.columns?.length) return sum + countLeafCols(col.columns);
52
- return sum + 1;
53
- }, 0);
54
- }
55
-
56
- function Caption({ className = '', children, ...rest }: React.HTMLAttributes<HTMLTableCaptionElement>) {
57
- return (
58
- <caption className={classnames('usx-table__caption', className)} {...rest}>
59
- {children}
60
- </caption>
61
- );
4
+ export interface TableColumn {
5
+ key: string;
6
+ header: React.ReactNode;
7
+ /** Render this column's cells as row headers. */
8
+ primary?: boolean;
9
+ /** Allow the USWDS table script to sort this column. */
10
+ sortable?: boolean;
62
11
  }
63
12
 
64
- // `placeholder`/`onSelect` exist on HTMLAttributes with DOM types; the table API redefines them.
65
- export interface TableProps extends Omit<React.TableHTMLAttributes<HTMLTableElement>, 'children' | 'placeholder' | 'onSelect'> {
66
- // Data
13
+ export interface TableProps extends Omit<React.TableHTMLAttributes<HTMLTableElement>, 'children'> {
67
14
  columns?: TableColumn[];
68
- data?: TableRowData[];
69
- /** Row field used as the unique key (default `id`). */
70
- primaryKey?: string;
71
-
72
- // USWDS variants
15
+ data?: Record<string, React.ReactNode>[];
16
+ caption?: React.ReactNode;
73
17
  striped?: boolean;
74
18
  borderless?: boolean;
75
19
  compact?: boolean;
76
-
77
- // Layout / responsive
78
20
  scrollable?: boolean;
79
- /** Max height (CSS value); implies a scroll wrapper. */
80
- height?: string;
81
- responsive?: Responsive;
21
+ /** Fixed height of the scroll container, when scrollable. */
22
+ scrollHeight?: string;
82
23
  stickyHeader?: boolean;
83
- stickyFirstColumn?: boolean;
84
- caption?: React.ReactNode;
85
-
86
- // Sorting
87
- /** Make every column sortable unless it sets `sortable: false`. */
88
- sortable?: boolean;
89
- /** Controlled sort state. */
90
- sort?: SortState | null;
91
- onSort?: (next: SortState) => void;
92
-
93
- // Selection
94
- selectionMode?: SelectionMode;
95
- selectionPosition?: 'left' | 'right';
96
- /** Controlled selected keys. */
97
- select?: RowKey[] | null;
98
- onSelect?: (selected: RowKey[]) => void;
99
- allowSelectAll?: boolean;
100
- /** Keys of rows that cannot be selected. */
101
- disabled?: RowKey[];
102
-
103
- // Row interaction
104
- onClickRow?: TableContextValue['onClickRow'];
105
-
106
- // Groups / details
107
- groupBy?: GroupBy;
108
- rowDetails?: RowDetails;
109
-
110
- showFooter?: boolean;
111
-
112
- // Pagination
113
- paginate?: boolean | PaginateConfig;
114
- /** Infinite scroll: called when the sentinel row scrolls into view. */
115
- onMore?: (() => void) | null;
116
- /** Show a loading row (e.g. while fetching the next page). */
117
- loading?: boolean;
118
-
119
- /** Content of the single row shown when `data` is empty. */
120
- placeholder?: React.ReactNode;
121
- /** Compound mode: render your own Table.Head / Table.Body / … */
24
+ responsive?: false | 'stack' | 'stack-header';
25
+ /** Use children for hand-authored USWDS table markup instead of columns and data. */
122
26
  children?: React.ReactNode;
123
27
  }
124
28
 
125
- /**
126
- * Table — USX design system table.
127
- * Primary API: data-driven via `columns` + `data`.
128
- * Escape hatch: compound mode via Table.Head / Table.Body / Table.Row / Table.Cell.
129
- */
130
- function Table({
131
- id: idProp,
132
- columns = [],
133
- data = [],
134
- primaryKey = 'id',
135
- striped = false,
136
- borderless = false,
137
- compact = false,
138
- scrollable = false,
139
- height,
140
- responsive = false,
141
- stickyHeader = false,
142
- stickyFirstColumn = false,
143
- caption,
144
- sortable: sortableAll = false,
145
- sort: sortProp,
146
- onSort,
147
- selectionMode = null,
148
- selectionPosition = 'left',
149
- select: selectProp,
150
- onSelect,
151
- allowSelectAll = true,
152
- disabled = [],
153
- onClickRow = null,
154
- groupBy,
155
- rowDetails,
156
- showFooter = false,
157
- paginate,
158
- onMore = null,
159
- loading = false,
160
- placeholder,
161
- className = '',
162
- children,
163
- ...props
29
+ /** A themeable USWDS table. Sorting is supplied by USWDS's table script. */
30
+ export default function Table({
31
+ columns = [], data = [], caption, striped = false, borderless = false,
32
+ compact = false, scrollable = false, scrollHeight, stickyHeader = false, responsive = false,
33
+ className, children, ...props
164
34
  }: TableProps) {
165
- const generatedId = useId();
166
- const id = idProp ?? `usx-table-${generatedId}`;
167
-
168
- const resolvedColumns = useMemo(() => {
169
- if (!sortableAll) return columns;
170
- return columns.map((col) => ({ ...col, sortable: col.sortable !== false }));
171
- }, [columns, sortableAll]);
172
-
173
- const { sortState, handleSort, sortedData } = useTableSort({ sortProp, onSort, columns: resolvedColumns, data });
174
-
175
- // ── Pagination ──────────────────────────────────────────────────────────────
176
- const isPaginated = !!paginate;
177
- const paginateConfig: PaginateConfig = paginate === true ? {} : paginate || {};
178
- const defaultPageSize = paginateConfig.pageSize || 10;
179
- const isServerSide = !!paginateConfig.totalCount;
180
-
181
- const [currentPage, setCurrentPage] = useState(1);
182
- const [pageSize, setPageSize] = useState(defaultPageSize);
183
-
184
- // Back to page 1 whenever sort changes so the user isn't stranded mid-table.
185
- useEffect(() => {
186
- if (isPaginated) setCurrentPage(1);
187
- }, [isPaginated, sortState.key, sortState.direction]);
188
-
189
- const totalItems = isServerSide ? paginateConfig.totalCount! : sortedData.length;
190
- const activeData =
191
- isPaginated && !isServerSide ? sortedData.slice((currentPage - 1) * pageSize, currentPage * pageSize) : sortedData;
192
-
193
- const { selectedKeys, handleSelect, handleSelectAll, isSelected, isAllSelected, isIndeterminate } = useTableSelect({
194
- selectionMode,
195
- selectProp,
196
- onSelect,
197
- data: activeData,
198
- primaryKey,
199
- disabled,
200
- allowSelectAll,
201
- });
202
-
203
- const { groups, expandedGroups, toggleGroup, isGroupExpanded } = useTableGroups({ groupBy, data: activeData });
204
- const { expandedRows, toggleRow, isRowExpanded } = useRowDetails({ rowDetails });
205
-
206
- const totalCols = useMemo(
207
- () => countLeafCols(resolvedColumns) + (selectionMode ? 1 : 0) + (rowDetails ? 1 : 0),
208
- [resolvedColumns, selectionMode, rowDetails]
209
- );
210
-
211
- const contextValue = useMemo<TableContextValue>(
212
- () => ({
213
- id,
214
- columns: resolvedColumns,
215
- data: activeData,
216
- primaryKey,
217
- sortState,
218
- handleSort,
219
- selectionMode,
220
- selectionPosition,
221
- selectedKeys,
222
- handleSelect,
223
- handleSelectAll,
224
- isSelected,
225
- isAllSelected,
226
- isIndeterminate,
227
- allowSelectAll,
228
- disabled,
229
- onClickRow,
230
- groupBy,
231
- groups,
232
- expandedGroups,
233
- toggleGroup,
234
- isGroupExpanded,
235
- expandedRows,
236
- toggleRow,
237
- isRowExpanded,
238
- rowDetails,
239
- responsive,
240
- stickyFirstColumn,
241
- totalCols,
242
- placeholder,
243
- onMore,
244
- loading,
245
- }),
246
- [
247
- id, resolvedColumns, activeData, primaryKey,
248
- sortState, handleSort,
249
- selectionMode, selectionPosition, selectedKeys, handleSelect, handleSelectAll,
250
- isSelected, isAllSelected, isIndeterminate, allowSelectAll, disabled,
251
- onClickRow,
252
- groupBy, groups, expandedGroups, toggleGroup, isGroupExpanded,
253
- expandedRows, toggleRow, isRowExpanded, rowDetails,
254
- responsive, stickyFirstColumn, totalCols,
255
- placeholder, onMore, loading,
256
- ]
257
- );
258
-
259
- const tableClasses = classnames(
260
- 'usa-table',
261
- striped && 'usa-table--striped',
262
- borderless && 'usa-table--borderless',
263
- compact && 'usa-table--compact',
264
- stickyHeader && 'usa-table--sticky-header',
265
- responsive === 'stack' && 'usa-table--stacked',
266
- responsive === 'stack-header' && 'usa-table--stacked-header',
267
- 'usx-table',
268
- stickyFirstColumn && 'usx-table--sticky-first-col',
269
- className
270
- );
271
-
272
- const tableEl = (
273
- <table id={idProp} className={tableClasses} {...props}>
274
- {caption && <Caption>{caption}</Caption>}
275
- {children || (
276
- <>
277
- <TableHead />
278
- <TableBody />
279
- {showFooter && <TableFoot />}
280
- </>
281
- )}
282
- </table>
283
- );
284
-
285
- const needsScrollWrapper = scrollable || !!height;
286
- const wrapped = needsScrollWrapper ? (
287
- <div
288
- className="usa-table-container--scrollable usx-table-container--scrollable"
289
- tabIndex={0}
290
- style={height ? { maxHeight: height, overflow: 'auto' } : undefined}
291
- >
292
- {tableEl}
293
- </div>
294
- ) : (
295
- tableEl
296
- );
297
-
298
- return (
299
- <TableContext.Provider value={contextValue}>
300
- {wrapped}
301
- {isPaginated && (
302
- <div
303
- onClick={(event) => {
304
- const link = (event.target as Element).closest<HTMLAnchorElement>('[data-usx-pagination-page]');
305
- if (!link || link.getAttribute('aria-disabled') === 'true') return;
306
- event.preventDefault();
307
- const page = Number(link.dataset.usxPaginationPage);
308
- if (!Number.isInteger(page) || page < 1 || page === currentPage) return;
309
- setCurrentPage(page);
310
- if (isServerSide) paginateConfig.onPageChange?.(page, pageSize);
311
- }}
312
- onChange={(event) => {
313
- const target: EventTarget = event.target;
314
- if (!(target instanceof HTMLSelectElement)) return;
315
- const select = target;
316
- if (!select.matches('.usx-pagination__step-options select')) return;
317
- const size = Number(select.value);
318
- if (!Number.isInteger(size) || size < 1) return;
319
- const page = Math.min(currentPage, Math.max(1, Math.ceil(totalItems / size)));
320
- setPageSize(size);
321
- setCurrentPage(page);
322
- if (isServerSide) paginateConfig.onPageChange?.(page, size);
323
- }}
324
- >
325
- <Pagination
326
- key={`${sortState.key}-${sortState.direction}`}
327
- currentPage={currentPage}
328
- pageSize={pageSize}
329
- totalItems={totalItems}
330
- {...(paginateConfig.pageSizeOptions ? { pageSizeOptions: paginateConfig.pageSizeOptions } : {})}
331
- {...(paginateConfig.showStepOptions !== undefined ? { showStepOptions: paginateConfig.showStepOptions } : {})}
332
- {...(paginateConfig.showSummary !== undefined ? { showSummary: paginateConfig.showSummary } : {})}
333
- />
334
- </div>
335
- )}
336
- </TableContext.Provider>
35
+ const hasSorting = !children && columns.some((column) => column.sortable);
36
+ const table = (
37
+ <>
38
+ <table
39
+ {...props}
40
+ className={classnames(
41
+ 'usa-table', 'usx-table',
42
+ striped && 'usa-table--striped',
43
+ borderless && 'usa-table--borderless',
44
+ compact && 'usa-table--compact',
45
+ stickyHeader && 'usa-table--sticky-header',
46
+ responsive === 'stack' && 'usa-table--stacked',
47
+ responsive === 'stack-header' && 'usa-table--stacked-header',
48
+ className
49
+ )}
50
+ >
51
+ {children ?? (
52
+ <>
53
+ <caption className="usx-table__caption">{caption || 'Data table'}</caption>
54
+ <thead><tr>{columns.map((column) => (
55
+ <th key={column.key} scope="col" data-sortable={column.sortable ? '' : undefined}>
56
+ {column.header}
57
+ </th>
58
+ ))}</tr></thead>
59
+ <tbody>{data.map((row, index) => (
60
+ <tr key={index}>{columns.map((column) => {
61
+ const Cell = column.primary ? 'th' : 'td';
62
+ const value = row[column.key];
63
+ return <Cell
64
+ key={column.key}
65
+ scope={column.primary ? 'row' : undefined}
66
+ data-label={responsive ? String(column.header) : undefined}
67
+ >{value ?? ''}</Cell>;
68
+ })}</tr>
69
+ ))}</tbody>
70
+ </>
71
+ )}
72
+ </table>
73
+ {hasSorting && <div className="usa-sr-only usa-table__announcement-region" aria-live="polite" />}
74
+ </>
337
75
  );
76
+ return scrollable
77
+ ? <div className="usa-table-container--scrollable" tabIndex={0}
78
+ style={scrollHeight ? { height: scrollHeight, overflow: 'auto' } : undefined}>{table}</div>
79
+ : table;
338
80
  }
339
-
340
- // ── Compound sub-components ───────────────────────────────────────────────────
341
-
342
- export default Object.assign(Table, {
343
- Head: TableHead,
344
- Body: TableBody,
345
- Foot: TableFoot,
346
- Row: TableRow,
347
- Cell: TableCell,
348
- Group: TableGroup,
349
- Caption,
350
- });