@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solexllc/usx-react",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "React component library for USX.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -25,9 +25,9 @@
25
25
  "dist"
26
26
  ],
27
27
  "dependencies": {
28
- "@solexllc/usx": "0.10.0",
29
- "@solexllc/usx-theme": "0.10.0",
30
- "@solexllc/usx-uswds-fixes": "0.1.14",
28
+ "@solexllc/usx": "0.11.0",
29
+ "@solexllc/usx-theme": "0.11.0",
30
+ "@solexllc/usx-uswds-fixes": "0.1.15",
31
31
  "classnames": "^2.5.1",
32
32
  "prop-types": "^15.8.1"
33
33
  },
@@ -1,4 +1,4 @@
1
- import React from 'react';
1
+ import React, { useEffect, useRef } from 'react';
2
2
  import ClassNames from 'classnames';
3
3
  import Label from '../label/Label';
4
4
  import ErrorMessage from '../error-message/ErrorMessage';
@@ -11,6 +11,7 @@ export interface CheckboxProps extends React.InputHTMLAttributes<HTMLInputElemen
11
11
  label?: string;
12
12
  ariaLabel?: string;
13
13
  checked?: boolean;
14
+ indeterminate?: boolean;
14
15
  disabled?: boolean;
15
16
  description?: string;
16
17
  tile?: boolean;
@@ -29,9 +30,10 @@ export default function Checkbox({
29
30
  value,
30
31
  label = '',
31
32
  ariaLabel = '',
32
- checked = false,
33
+ checked,
34
+ indeterminate = false,
33
35
  disabled = false,
34
- description = null,
36
+ description = '',
35
37
  tile = false,
36
38
  small = false,
37
39
  error,
@@ -42,6 +44,8 @@ export default function Checkbox({
42
44
  formGroup = true,
43
45
  ...props
44
46
  }: CheckboxProps) {
47
+ const inputRef = useRef<HTMLInputElement>(null);
48
+ useEffect(() => { if (inputRef.current) inputRef.current.indeterminate = indeterminate; }, [indeterminate]);
45
49
  const hasError = !!error;
46
50
  const hasSuccess = !!success;
47
51
 
@@ -61,13 +65,14 @@ export default function Checkbox({
61
65
  <>
62
66
  <div className={divClasses} {...props}>
63
67
  <input
68
+ ref={inputRef}
64
69
  className={inputClasses}
65
70
  id={id}
66
71
  type="checkbox"
67
72
  name={name}
68
73
  value={value}
69
74
  aria-label={ariaLabel || undefined}
70
- defaultChecked={checked}
75
+ {...(checked !== undefined && onChange ? { checked } : { defaultChecked: checked })}
71
76
  disabled={disabled}
72
77
  required={required}
73
78
  {...(onChange ? { onChange } : {})}
@@ -4,7 +4,7 @@
4
4
  {% if wrap_group %}
5
5
  {% form_group error=error %}
6
6
  <div class="usa-checkbox usx-checkbox{% if small %} usx-checkbox--small{% endif %}{% if className %} {{ className }}{% endif %}">
7
- <input class="usa-checkbox__input{% if tile %} usa-checkbox__input--tile{% endif %}" id="{{ id }}" type="checkbox" name="{{ name }}" value="{{ value }}"{% if checked %} checked{% endif %}{% if disabled %} disabled{% endif %}{% if required %} required{% endif %}{% if onChange %} onchange="{{ onChange }}"{% endif %}>
7
+ <input class="usa-checkbox__input{% if tile %} usa-checkbox__input--tile{% endif %}" id="{{ id }}" type="checkbox"{% if name %} name="{{ name }}"{% endif %} value="{{ value }}"{% if ariaLabel %} aria-label="{{ ariaLabel }}"{% endif %}{% if checked %} checked{% endif %}{% if disabled %} disabled{% endif %}{% if required %} required{% endif %}{% if onChange %} onchange="{{ onChange }}"{% endif %}>
8
8
  {% label htmlFor=id className="usa-checkbox__label" classOverride=True required=required %}{{ label }}
9
9
  {% if description %}
10
10
  <span class="usa-checkbox__label-description">{{ description }}</span>
@@ -19,7 +19,7 @@
19
19
  {% endform_group %}
20
20
  {% else %}
21
21
  <div class="usa-checkbox usx-checkbox{% if small %} usx-checkbox--small{% endif %}{% if className %} {{ className }}{% endif %}">
22
- <input class="usa-checkbox__input{% if tile %} usa-checkbox__input--tile{% endif %}" id="{{ id }}" type="checkbox" name="{{ name }}" value="{{ value }}"{% if checked %} checked{% endif %}{% if disabled %} disabled{% endif %}{% if required %} required{% endif %}{% if onChange %} onchange="{{ onChange }}"{% endif %}>
22
+ <input class="usa-checkbox__input{% if tile %} usa-checkbox__input--tile{% endif %}" id="{{ id }}" type="checkbox"{% if name %} name="{{ name }}"{% endif %} value="{{ value }}"{% if ariaLabel %} aria-label="{{ ariaLabel }}"{% endif %}{% if checked %} checked{% endif %}{% if disabled %} disabled{% endif %}{% if required %} required{% endif %}{% if onChange %} onchange="{{ onChange }}"{% endif %}>
23
23
  {% label htmlFor=id className="usa-checkbox__label" classOverride=True required=required %}{{ label }}
24
24
  {% if description %}
25
25
  <span class="usa-checkbox__label-description">{{ description }}</span>
@@ -30,6 +30,15 @@
30
30
  "default": false,
31
31
  "description": "Whether the checkbox is checked"
32
32
  },
33
+ "indeterminate": {
34
+ "type": "boolean",
35
+ "default": false,
36
+ "description": "React-only mixed state for a select-all checkbox."
37
+ },
38
+ "ariaLabel": {
39
+ "type": "string",
40
+ "description": "Accessible name when a visible label is unsuitable."
41
+ },
33
42
  "disabled": {
34
43
  "type": "boolean",
35
44
  "default": false,
@@ -0,0 +1,177 @@
1
+ import React, { useId } from 'react';
2
+ import classnames from 'classnames';
3
+ import { TableContext } from './TableContext';
4
+ import type { TableContextValue } from './TableContext';
5
+ import TableHead from './TableHead';
6
+ import TableBody from './TableBody';
7
+ import TableFoot from './TableFoot';
8
+ import TableRow from './TableRow';
9
+ import TableCell from './TableCell';
10
+ import TableGroup from './TableGroup';
11
+ import { leafColumns } from './columns';
12
+ import Input from '../input/Input';
13
+ import Pagination from '../pagination/Pagination';
14
+ import type {
15
+ GroupBy, PaginateConfig, Responsive, RowDetails, RowKey, SelectionMode,
16
+ SortState, TableColumn, TableRowData, VerticalAlign,
17
+ } from './types';
18
+
19
+ export type {
20
+ Align, Aggregate, CellOptions, GroupBy, GroupColumn, GroupByConfig,
21
+ PaginateConfig, Responsive, RowOptions, RowDetails, RowDetailsConfig,
22
+ RowKey, SelectionMode, SortDirection, SortState, TableColumn, TableRowData,
23
+ VerticalAlign,
24
+ } from './types';
25
+
26
+ function Caption({ className = '', children, ...rest }: React.HTMLAttributes<HTMLTableCaptionElement>) {
27
+ return <caption className={classnames('usx-data-table__caption', className)} {...rest}>{children}</caption>;
28
+ }
29
+
30
+ // DataTable renders the complete initial DOM. @solexllc/usx/js/data-table owns every interaction.
31
+ export interface TableProps extends Omit<React.TableHTMLAttributes<HTMLTableElement>, 'children' | 'placeholder' | 'onSelect'> {
32
+ columns?: TableColumn[];
33
+ data?: TableRowData[];
34
+ primaryKey?: string;
35
+ striped?: boolean;
36
+ borderless?: boolean;
37
+ compact?: boolean;
38
+ scrollable?: boolean;
39
+ height?: string;
40
+ responsive?: Responsive;
41
+ stickyHeader?: boolean;
42
+ stickyFirstColumn?: boolean;
43
+ caption?: React.ReactNode;
44
+ searchable?: boolean;
45
+ searchPlaceholder?: string;
46
+ sortable?: boolean;
47
+ /** Initial sort state. Subsequent changes are emitted as usx:data-table:sort events. */
48
+ sort?: SortState | null;
49
+ selectionMode?: SelectionMode;
50
+ selectionPosition?: 'left' | 'right';
51
+ selectionVerticalAlign?: VerticalAlign;
52
+ /** Initially selected keys. */
53
+ select?: RowKey[] | null;
54
+ allowSelectAll?: boolean;
55
+ disabled?: RowKey[];
56
+ /** Emit usx:data-table:row-activate for clicks and Enter/Space on rows. */
57
+ clickableRows?: boolean;
58
+ groupBy?: GroupBy;
59
+ rowDetails?: RowDetails;
60
+ showFooter?: boolean;
61
+ paginate?: boolean | PaginateConfig;
62
+ /** Emit usx:data-table:more when the sentinel enters the viewport. */
63
+ infinite?: boolean;
64
+ loading?: boolean;
65
+ placeholder?: React.ReactNode;
66
+ children?: React.ReactNode;
67
+ }
68
+
69
+ /** Data-driven table with a compound markup escape hatch. */
70
+ function DataTable({
71
+ id: idProp,
72
+ columns = [],
73
+ data = [],
74
+ primaryKey = 'id',
75
+ striped = false,
76
+ borderless = false,
77
+ compact = false,
78
+ scrollable = false,
79
+ height,
80
+ responsive = false,
81
+ stickyHeader = false,
82
+ stickyFirstColumn = false,
83
+ caption,
84
+ searchable = false,
85
+ searchPlaceholder = 'Search table',
86
+ sortable: sortableAll = false,
87
+ sort: initialSort,
88
+ selectionMode = null,
89
+ selectionPosition = 'left',
90
+ selectionVerticalAlign = 'middle',
91
+ select: initialSelection,
92
+ allowSelectAll = true,
93
+ disabled = [],
94
+ clickableRows = false,
95
+ groupBy,
96
+ rowDetails,
97
+ showFooter = false,
98
+ paginate,
99
+ infinite = false,
100
+ loading = false,
101
+ placeholder = 'No rows to display',
102
+ className = '',
103
+ children,
104
+ ...props
105
+ }: TableProps) {
106
+ const generatedId = useId();
107
+ const id = idProp ?? `usx-data-table-${generatedId}`;
108
+ const resolveColumns = (items: TableColumn[]): TableColumn[] => items.map((column) => ({
109
+ ...column,
110
+ ...(column.columns?.length
111
+ ? { columns: resolveColumns(column.columns) }
112
+ : sortableAll ? { sortable: column.sortable !== false } : {}),
113
+ }));
114
+ const resolvedColumns = sortableAll ? resolveColumns(columns) : columns;
115
+ const groupConfig = typeof groupBy === 'object' && groupBy !== null ? groupBy : null;
116
+ const groupKey = typeof groupBy === 'string' ? groupBy : groupConfig?.property;
117
+ const groups = groupKey ? [...data.reduce((map, row) => {
118
+ const key = String(row[groupKey] ?? '__ungrouped__');
119
+ if (!map.has(key)) map.set(key, []);
120
+ map.get(key)!.push(row);
121
+ return map;
122
+ }, new Map<string, TableRowData[]>())].map(([key, rows]) => ({ key, rows })) : null;
123
+ const expandedGroups = new Set<string>(groupConfig?.expand
124
+ ? groupConfig.expand.map(String)
125
+ : groupConfig?.defaultExpanded === false ? [] : groups?.map(({ key }) => key) || []);
126
+ const detailConfig = rowDetails && typeof rowDetails === 'object' ? rowDetails : null;
127
+ const pageConfig: PaginateConfig = paginate === true ? {} : paginate || {};
128
+ const pageSize = pageConfig.pageSize || 10;
129
+ const totalCols = leafColumns(resolvedColumns).length + Number(!!selectionMode) + Number(!!rowDetails);
130
+ const contextValue: TableContextValue = {
131
+ id, columns: resolvedColumns, data, primaryKey,
132
+ selectionMode, selectionPosition, selectionVerticalAlign,
133
+ selectedKeys: new Set(initialSelection || []), allowSelectAll, disabled, clickableRows,
134
+ groupBy, groupColumns: groupConfig?.columns || [],
135
+ groupHeaders: groupConfig?.headers || groupConfig?.columns || [],
136
+ groupValues: groupConfig?.values || {},
137
+ groups, expandedGroups, expandedRows: new Set(detailConfig?.expand || []),
138
+ rowDetails, responsive, totalCols, placeholder, infinite, loading,
139
+ };
140
+ const tableClasses = classnames(
141
+ 'usa-table', 'usx-data-table',
142
+ striped && 'usx-data-table--striped', borderless && 'usx-data-table--borderless',
143
+ compact && 'usx-data-table--compact', stickyHeader && 'usx-data-table--sticky-header',
144
+ responsive === 'stack' && 'usx-data-table--stacked',
145
+ responsive === 'stack-header' && 'usx-data-table--stacked-header',
146
+ stickyFirstColumn && 'usx-data-table--sticky-first-col', className,
147
+ );
148
+ const table = <table id={id} className={tableClasses} {...props}>
149
+ {caption && <Caption>{caption}</Caption>}
150
+ {children || <><TableHead /><TableBody />{showFooter && <TableFoot />}</>}
151
+ </table>;
152
+
153
+ return <TableContext.Provider value={contextValue}>
154
+ <div className="usx-data-table-shell" data-usx-data-table
155
+ data-searchable={searchable || undefined} data-paginate={!!paginate || undefined}
156
+ data-page-size={paginate ? pageSize : undefined}
157
+ data-initial-sort-key={initialSort?.direction ? initialSort.key || undefined : undefined}
158
+ data-initial-sort-direction={initialSort?.direction || undefined}
159
+ data-total-count={pageConfig.totalCount} data-infinite={infinite || undefined}>
160
+ {searchable && <div className="usx-data-table__toolbar">
161
+ <Input id={`${id}-search`} label="Search" formGroup={false} placeholder={searchPlaceholder} />
162
+ </div>}
163
+ {scrollable || height ? <div className="usx-data-table-container--scrollable" tabIndex={0}
164
+ style={height ? { maxHeight: height, overflow: 'auto' } : undefined}>{table}</div> : table}
165
+ {!!paginate && <Pagination className="usx-data-table__pagination" currentPage={1} pageSize={pageSize}
166
+ totalItems={pageConfig.totalCount ?? data.length}
167
+ pageSizeOptions={pageConfig.pageSizeOptions ?? [pageSize, 10, 25, 50].filter((value, index, list) => list.indexOf(value) === index)}
168
+ showStepOptions={pageConfig.showStepOptions !== false} showSummary={pageConfig.showSummary !== false}
169
+ stepOptionsId={`${id}-page-size`} ariaLabel={`${typeof caption === 'string' ? caption : 'Data table'} pages`} />}
170
+ </div>
171
+ </TableContext.Provider>;
172
+ }
173
+
174
+ export default Object.assign(DataTable, {
175
+ Head: TableHead, Body: TableBody, Foot: TableFoot,
176
+ Row: TableRow, Cell: TableCell, Group: TableGroup, Caption,
177
+ });
@@ -0,0 +1,42 @@
1
+ # DataTable
2
+
3
+ `DataTable` is the USX table for interactive data sets. It uses the USWDS `usa-table` base class for table layout, borders, spacing, and caption styling, with `usx-data-table` classes for its richer behavior and USX theme colors. Load the USWDS table stylesheet separately; `@solexllc/usx` does not bundle it. `Table` remains the small USWDS table component.
4
+
5
+ Set `responsive="stack"` or `responsive="stack-header"` to use the USWDS-style stacked layout below the `mobile-lg` breakpoint (480px). Both modes hide the column header and show each cell's column label above its value. `stack-header` instead shades the first data cell in each row as its heading and omits that cell's repeated label. Set a column's `stackLabel` to customize its mobile label, including when its header is rendered as an element.
6
+
7
+ Both tables share sorted-column theme tokens. `table-sorted-header-bg` defaults to USWDS's `#97d4ea`, `table-sorted-column-bg` to `#e1f3f8`, and `table-sorted-stripe-bg` to `#c3ebfa`. Their text colors can be set independently with `table-sorted-header-text`, `table-sorted-column-text`, and `table-sorted-stripe-text`. Ordinary striped rows use `table-stripe-text`, which follows `text-ink` by default. `table-border` also follows `text-ink` by default, so inverted sorted-header text does not recolor the grid; it can be overridden separately. `table-sorted-icon-color` and `table-unsorted-icon-color` control the arrow artwork. Set these tokens in a USX theme or override their `--usx-*` custom properties at runtime.
8
+
9
+ ## React
10
+
11
+ ```tsx
12
+ <DataTable
13
+ caption="State admissions"
14
+ columns={[
15
+ { key: 'name', header: 'State', primary: true, sortable: true },
16
+ { key: 'order', header: 'Order admitted', sortable: true },
17
+ { key: 'region', header: 'Region' },
18
+ ]}
19
+ data={states}
20
+ searchable
21
+ paginate={{ pageSize: 25, pageSizeOptions: [10, 25, 50] }}
22
+ />
23
+ ```
24
+
25
+ The React and Django components render the complete table markup before JavaScript runs. DataTable interactions do not use React state or USWDS's table JavaScript. Load `@solexllc/usx/js/start` once or call `dataTable.init(root)` from `@solexllc/usx/js/data-table` after mounting a table. `start` observes inserted DataTables; an explicit `init(root)` call is useful when your app controls the mount lifecycle. The same initializer provides search, sorting, pagination, selection, grouped rows, and row details in React, Django, and static HTML. Initial values can be set with `sort`, `select`, `groupBy.expand`, and `rowDetails.expand`; `sort` is applied on initialization. Listen on the `.usx-data-table-shell` for `usx:data-table:sort`, `:select`, `:search`, `:page-change`, `:group-toggle`, `:detail-toggle`, `:row-activate`, and `:more` events. `searchValue(row)` supplies searchable text for a computed cell; `filterable: false` excludes a column from search. `sortValue(row)` supplies a comparable value for custom sorting. Set `clickableRows` to make rows keyboard and pointer activatable.
26
+
27
+ Rows can set `cellProps` by column key, with `rowSpan`, `colSpan`, `backgroundColor`, and `color`. A row can set `rowProps.backgroundColor` and `rowProps.color`; columns can set `backgroundColor`, `color`, `headerBackgroundColor`, and `headerColor`. You can also apply USX `bg-*` and `text-*` utility classes through `rowProps.className`, column `className` or `headerClassName`, and `cellProps[key].className`. Row classes color the whole row, including its cells. Cell classes take precedence over column classes of the same color family, followed by row classes. Utility colors use `!important`, so they also override inline colors. Spans are clamped to the visible leaf columns and the current group or page. Covered cells are omitted automatically.
28
+
29
+ Set `align: 'center'` on a column to center text, buttons, avatars, or other compact content horizontally while retaining cell padding and top alignment. Add `verticalAlign: 'middle'` to center it vertically too. `cellProps[columnKey]` can override either setting for a particular row. In compound mode, use `<DataTable.Cell align="center" verticalAlign="middle">`. Selection checkboxes and radios are centered both ways by default; set `selectionVerticalAlign="top"` to keep them at the padded top of tall rows. Their labels remain accessible through input names while the visible controls use a fixed hit area.
30
+
31
+ For grouped rows with multiple cells, pass `groupBy={{ property, columns, values }}`. `columns` defines the group-row cells; the first contains the disclosure button, and the others can show totals. Set `groupBy.headers` to show a separate top header band with broader labels, so it need not repeat the group-row labels. The spans in each set must add up to the number of visible data columns. `groupBy.rowClassName` applies classes, including `bg-*` and `text-*`, across the whole group row. `values` maps each group key to values by group column key; each value can also be `{ value, backgroundColor, color }`. Regular table `columns` can be nested for additional header levels. `GroupedRows` shows regional case totals; `GroupedMatrix` shows grant outcomes by agency and program.
32
+
33
+ ## Django and static HTML
34
+
35
+ ```django
36
+ {% load usx_components %}
37
+ {% data_table caption="State admissions" columns=columns data=rows searchable=True paginate=page_options %}{% enddata_table %}
38
+ ```
39
+
40
+ Load `@solexllc/usx/js/start` on the page, or call `dataTable.init(root)` from `@solexllc/usx/js/data-table` after inserting markup. It is safe to call `init` more than once on an already enhanced table. If rows change inside the same table shell, call `dataTable.off(root)` and then `dataTable.init(root)` after the update so the enhancer reads the new rows. `data-table.html` shows the static markup contract. Django accepts `rowDetailField` for detail content and built-in aggregate names for footer values. React render callbacks produce cell and detail markup during rendering; they do not provide interaction behavior.
41
+
42
+ The HTML story shows the static reference. React and Django snapshot boards have matching play checks.
@@ -0,0 +1,123 @@
1
+ import React from 'react';
2
+ import classnames from 'classnames';
3
+ import { useTableContext } from './TableContext';
4
+ import TableRow from './TableRow';
5
+ import TableGroup from './TableGroup';
6
+ import type { RowKey, TableColumn, TableRowData } from './types';
7
+ import { leafColumns } from './columns';
8
+ import { mergeCellClasses, planCells } from './cells';
9
+ import type { PlannedCell } from './cells';
10
+ import Checkbox from '../checkbox/Checkbox';
11
+ import RadioButtons from '../radio-buttons/RadioButtons';
12
+ import Button from '../button/Button';
13
+
14
+ function getDataLabel(col: TableColumn): string | undefined {
15
+ if (col.stackLabel) return col.stackLabel;
16
+ return typeof col.header === 'string' ? col.header : undefined;
17
+ }
18
+
19
+ function DataRow({ row, rowIndex, plannedCells }: { row: TableRowData; rowIndex: number; plannedCells: PlannedCell[] }) {
20
+ const {
21
+ columns, id, primaryKey, selectionMode, selectionPosition, selectionVerticalAlign,
22
+ selectedKeys, disabled, clickableRows, responsive, rowDetails, expandedRows,
23
+ } = useTableContext();
24
+ const key = row[primaryKey] as RowKey;
25
+ const selected = selectedKeys.has(key);
26
+ const isDisabled = disabled.includes(key);
27
+ const visibleCols = leafColumns(columns);
28
+ const hasRowDetails = !!rowDetails;
29
+ const isExpanded = expandedRows.has(key);
30
+ const renderDetail = typeof rowDetails === 'function' ? rowDetails : rowDetails?.render;
31
+ const expandLabel = rowDetails && typeof rowDetails === 'object' ? rowDetails.expandLabel : undefined;
32
+ const totalCols = visibleCols.length + Number(!!selectionMode) + Number(hasRowDetails);
33
+ const selectionInputId = `${id}-select-${String(key)}`;
34
+ const searchText = visibleCols.filter((col) => col.filterable !== false).map((col) =>
35
+ String(col.searchValue ? col.searchValue(row) : row[col.key] ?? '')).join(' ');
36
+
37
+ const selectionCell = <td key="__selection__" className={classnames(
38
+ 'usx-data-table__cell', 'usx-data-table__cell--selection', `usx-data-table__cell--valign-${selectionVerticalAlign}`)}>
39
+ {selectionMode === 'radio'
40
+ ? <RadioButtons name={`${id}-selection`} fieldset={false} small={true} formGroup={false}
41
+ defaultValue={selected ? String(key) : undefined}
42
+ options={[{ id: selectionInputId, value: String(key), label: '', ariaLabel: `Select row ${rowIndex + 1}`, disabled: isDisabled }]} />
43
+ : <Checkbox id={selectionInputId} name={`${id}-selection`} value={String(key)}
44
+ label="" ariaLabel={`Select row ${rowIndex + 1}`} small={true} formGroup={false}
45
+ checked={selected} disabled={isDisabled} />}
46
+ </td>;
47
+ const detailToggleCell = hasRowDetails && <td key="__detail-toggle__" className="usx-data-table__cell usx-data-table__cell--detail-toggle">
48
+ <Button variant="unstyled" className="usx-data-table__detail-toggle"
49
+ aria-expanded={isExpanded} aria-controls={`${id}-row-detail-${key}`}
50
+ data-detail-label={expandLabel ? 'custom' : undefined}
51
+ aria-label={expandLabel ? typeof expandLabel === 'function' ? expandLabel(row) : expandLabel
52
+ : `${isExpanded ? 'Collapse' : 'Expand'} row details`}
53
+ iconProps={[{ name: 'expand_more', size: 2 }]} />
54
+ </td>;
55
+ const dataCells = plannedCells.map(({ column: col, options, colSpan, rowSpan }) => {
56
+ const Tag = col.primary ? 'th' : 'td';
57
+ const align = options.align ?? col.align;
58
+ const verticalAlign = options.verticalAlign ?? col.verticalAlign;
59
+ const content = col.render ? col.render(row, rowIndex) : row[col.key] as React.ReactNode;
60
+ const raw = col.sortValue ? col.sortValue(row) : row[col.key];
61
+ const sortValue = typeof raw === 'string' || typeof raw === 'number' ? String(raw) : undefined;
62
+ return <Tag key={col.key}
63
+ className={classnames('usx-data-table__cell', align && `usx-data-table__cell--align-${align}`,
64
+ verticalAlign && `usx-data-table__cell--valign-${verticalAlign}`, mergeCellClasses(col.className, options.className))}
65
+ scope={col.primary ? rowSpan > 1 ? 'rowgroup' : 'row' : undefined}
66
+ data-label={responsive ? getDataLabel(col) : undefined}
67
+ colSpan={colSpan > 1 ? colSpan : undefined} rowSpan={rowSpan > 1 ? rowSpan : undefined}
68
+ data-column-key={col.key} data-sort-value={sortValue}
69
+ style={{ width: col.width, backgroundColor: options.backgroundColor || col.backgroundColor,
70
+ color: options.color || col.color }}>
71
+ {align === 'center' ? <div className="usx-data-table__cell-content">{content ?? '--'}</div> : content ?? '--'}
72
+ </Tag>;
73
+ });
74
+ const cells: React.ReactNode[] = [];
75
+ if (detailToggleCell) cells.push(detailToggleCell);
76
+ if (selectionMode && selectionPosition === 'left') cells.push(selectionCell);
77
+ cells.push(...dataCells);
78
+ if (selectionMode && selectionPosition === 'right') cells.push(selectionCell);
79
+
80
+ return <>
81
+ <TableRow rowKey={key} searchValue={searchText} selected={selected} disabled={isDisabled}
82
+ clickable={clickableRows}
83
+ className={row.rowProps?.className}
84
+ style={{ '--usx-data-table-row-bg': row.rowProps?.backgroundColor, color: row.rowProps?.color } as React.CSSProperties}>
85
+ {cells}
86
+ </TableRow>
87
+ {hasRowDetails && <tr id={`${id}-row-detail-${key}`} className="usx-data-table__detail-row" hidden={!isExpanded}>
88
+ <td className="usx-data-table__detail-cell" colSpan={totalCols}>{renderDetail?.(row)}</td>
89
+ </tr>}
90
+ </>;
91
+ }
92
+
93
+ export type TableBodyProps = React.HTMLAttributes<HTMLTableSectionElement>;
94
+
95
+ /** Complete initial rows; data-table.mjs filters, sorts, pages, and expands them. */
96
+ export default function TableBody({ className = '', children, ...props }: TableBodyProps) {
97
+ const { columns, data, primaryKey, groupBy, groups, placeholder, totalCols, infinite, loading } = useTableContext();
98
+ const bodyClass = classnames('usx-data-table__body', className);
99
+ if (children) return <tbody className={bodyClass} {...props}>{children}</tbody>;
100
+
101
+ const renderRows = (rows: TableRowData[]) =>
102
+ planCells(rows, leafColumns(columns)).map(({ row, cells }, rowIndex) =>
103
+ <DataRow key={(row[primaryKey] as RowKey) ?? rowIndex} row={row} rowIndex={rowIndex} plannedCells={cells} />);
104
+ const placeholderRow = data.length === 0 && placeholder && <tr className="usx-data-table__placeholder-row">
105
+ <td className="usx-data-table__placeholder-cell" colSpan={totalCols}>{placeholder}</td>
106
+ </tr>;
107
+ const loadingRow = loading && <tr className="usx-data-table__loading-row" aria-live="polite">
108
+ <td className="usx-data-table__loading-cell" colSpan={totalCols}>Loading more rows…</td>
109
+ </tr>;
110
+ const sentinel = infinite && <tr className="usx-data-table__sentinel" aria-hidden="true"><td colSpan={totalCols} /></tr>;
111
+
112
+ if (!groupBy) return <tbody className={bodyClass} {...props}>
113
+ {placeholderRow}{renderRows(data)}{loadingRow}{sentinel}
114
+ </tbody>;
115
+
116
+ return <>
117
+ {placeholderRow && <tbody className={bodyClass} {...props}>{placeholderRow}</tbody>}
118
+ {(groups || []).map(({ key, rows }) => <TableGroup key={key} groupKey={key} label={key} rows={rows}>
119
+ {renderRows(rows)}
120
+ </TableGroup>)}
121
+ {(loadingRow || sentinel) && <tbody className={bodyClass} {...props}>{loadingRow}{sentinel}</tbody>}
122
+ </>;
123
+ }
@@ -1,10 +1,11 @@
1
1
  import React from 'react';
2
2
  import classnames from 'classnames';
3
- import type { Align } from './types';
3
+ import type { Align, VerticalAlign } from './types';
4
4
 
5
5
  export interface TableCellProps extends React.HTMLAttributes<HTMLTableCellElement> {
6
6
  as?: 'td' | 'th';
7
7
  align?: Align;
8
+ verticalAlign?: VerticalAlign;
8
9
  headerAlign?: Align;
9
10
  colSpan?: number;
10
11
  rowSpan?: number;
@@ -17,6 +18,7 @@ export interface TableCellProps extends React.HTMLAttributes<HTMLTableCellElemen
17
18
  export default function TableCell({
18
19
  as: Tag = 'td',
19
20
  align,
21
+ verticalAlign,
20
22
  headerAlign,
21
23
  colSpan,
22
24
  rowSpan,
@@ -27,11 +29,12 @@ export default function TableCell({
27
29
  ...props
28
30
  }: TableCellProps) {
29
31
  const resolvedAlign = Tag === 'th' ? headerAlign || align : align;
30
- const classes = classnames('usx-table__cell', resolvedAlign && `usx-table__cell--align-${resolvedAlign}`, className);
32
+ const classes = classnames('usx-data-table__cell', resolvedAlign && `usx-data-table__cell--align-${resolvedAlign}`,
33
+ verticalAlign && `usx-data-table__cell--valign-${verticalAlign}`, className);
31
34
 
32
35
  return (
33
36
  <Tag className={classes} colSpan={colSpan} rowSpan={rowSpan} scope={scope} data-label={dataLabel} {...props}>
34
- {children}
37
+ {resolvedAlign === 'center' ? <div className="usx-data-table__cell-content">{children}</div> : children}
35
38
  </Tag>
36
39
  );
37
40
  }
@@ -0,0 +1,49 @@
1
+ import { createContext, useContext } from 'react';
2
+ import type { ReactNode } from 'react';
3
+ import type {
4
+ GroupBy, GroupColumn, Responsive, RowDetails, RowKey, SelectionMode,
5
+ TableColumn, TableGroupEntry, TableRowData, VerticalAlign,
6
+ } from './types';
7
+
8
+ /** Render-time data shared by the markup components. Interaction state lives in data-table.mjs. */
9
+ export interface TableContextValue {
10
+ id: string;
11
+ columns: TableColumn[];
12
+ data: TableRowData[];
13
+ primaryKey: string;
14
+ selectionMode: SelectionMode;
15
+ selectionPosition: 'left' | 'right';
16
+ selectionVerticalAlign: VerticalAlign;
17
+ selectedKeys: Set<RowKey>;
18
+ allowSelectAll: boolean;
19
+ disabled: RowKey[];
20
+ clickableRows: boolean;
21
+ groupBy: GroupBy;
22
+ groupColumns: GroupColumn[];
23
+ groupHeaders: GroupColumn[];
24
+ groupValues: Record<string, Record<string, unknown>>;
25
+ groups: TableGroupEntry[] | null;
26
+ expandedGroups: Set<string>;
27
+ expandedRows: Set<RowKey>;
28
+ rowDetails: RowDetails;
29
+ responsive: Responsive;
30
+ totalCols: number;
31
+ placeholder: ReactNode;
32
+ infinite: boolean;
33
+ loading: boolean;
34
+ }
35
+
36
+ export const TableContext = createContext<TableContextValue>({
37
+ id: '', columns: [], data: [], primaryKey: 'id',
38
+ selectionMode: null,
39
+ selectionPosition: 'left', selectionVerticalAlign: 'middle',
40
+ selectedKeys: new Set(), allowSelectAll: true, disabled: [], clickableRows: false,
41
+ groupBy: null, groupColumns: [], groupHeaders: [], groupValues: {}, groups: null,
42
+ expandedGroups: new Set(), expandedRows: new Set(), rowDetails: null,
43
+ responsive: false, totalCols: 0, placeholder: null,
44
+ infinite: false, loading: false,
45
+ });
46
+
47
+ export function useTableContext() {
48
+ return useContext(TableContext);
49
+ }
@@ -2,6 +2,7 @@ import React from 'react';
2
2
  import classnames from 'classnames';
3
3
  import { useTableContext } from './TableContext';
4
4
  import type { Aggregate, TableRowData } from './types';
5
+ import { leafColumns } from './columns';
5
6
 
6
7
  function aggregate(data: TableRowData[], key: string, type: Aggregate): React.ReactNode {
7
8
  const vals = data.map((row) => Number(row[key])).filter((v) => !isNaN(v));
@@ -33,21 +34,21 @@ export default function TableFoot({ className = '', children, ...props }: TableF
33
34
 
34
35
  if (children) {
35
36
  return (
36
- <tfoot className={classnames('usx-table__foot', className)} {...props}>
37
+ <tfoot className={classnames('usx-data-table__foot', className)} {...props}>
37
38
  {children}
38
39
  </tfoot>
39
40
  );
40
41
  }
41
42
 
42
- const visibleCols = columns.filter((c) => !c.hidden);
43
+ const visibleCols = leafColumns(columns);
43
44
  const hasFooter = visibleCols.some((c) => c.footer !== undefined || c.aggregate);
44
45
  if (!hasFooter) return null;
45
46
 
46
47
  return (
47
- <tfoot className={classnames('usx-table__foot', className)} {...props}>
48
- <tr className="usx-table__foot-row">
49
- {!!rowDetails && <td className="usx-table__cell" />}
50
- {!!selectionMode && <td className="usx-table__cell usx-table__cell--selection" />}
48
+ <tfoot className={classnames('usx-data-table__foot', className)} {...props}>
49
+ <tr className="usx-data-table__foot-row">
50
+ {!!rowDetails && <td className="usx-data-table__cell" />}
51
+ {!!selectionMode && <td className="usx-data-table__cell usx-data-table__cell--selection" />}
51
52
 
52
53
  {visibleCols.map((col) => {
53
54
  let content: React.ReactNode = '--';
@@ -57,7 +58,7 @@ export default function TableFoot({ className = '', children, ...props }: TableF
57
58
  content = aggregate(data, col.key, col.aggregate);
58
59
  }
59
60
  return (
60
- <td key={col.key} className={classnames('usx-table__cell', col.align && `usx-table__cell--align-${col.align}`)}>
61
+ <td key={col.key} className={classnames('usx-data-table__cell', col.align && `usx-data-table__cell--align-${col.align}`)}>
61
62
  {content}
62
63
  </td>
63
64
  );
@@ -0,0 +1,62 @@
1
+ import React from 'react';
2
+ import classnames from 'classnames';
3
+ import { useTableContext } from './TableContext';
4
+ import type { GroupColumn, TableRowData } from './types';
5
+
6
+ export interface TableGroupProps extends React.HTMLAttributes<HTMLTableSectionElement> {
7
+ label: React.ReactNode;
8
+ groupKey: string;
9
+ rows?: TableRowData[];
10
+ /** Initial expanded state; runtime toggles are owned by data-table.mjs. */
11
+ expanded?: boolean;
12
+ colSpan?: number;
13
+ }
14
+
15
+ /** Group header and content sections, matching the Django table markup. */
16
+ export default function TableGroup({
17
+ label, groupKey, rows = [], expanded, colSpan, className = '', children, ...props
18
+ }: TableGroupProps) {
19
+ const { id, groupBy, expandedGroups, totalCols, groupColumns, groupValues,
20
+ selectionMode, selectionPosition, rowDetails } = useTableContext();
21
+ const rowClassName = typeof groupBy === 'object' && groupBy ? groupBy.rowClassName : undefined;
22
+ const isExpanded = expanded ?? expandedGroups.has(groupKey);
23
+ const cells: GroupColumn[] = groupColumns.length
24
+ ? groupColumns : [{ key: '__label__', header: label, colSpan: colSpan || totalCols || 1 }];
25
+ const contentId = `${id}-group-${groupKey}-content`;
26
+
27
+ return <>
28
+ <tbody className={classnames('usx-data-table__group usx-data-table__group--header', className)} {...props}>
29
+ <tr className={classnames('usx-data-table__group-row', rowClassName)}>
30
+ {!!groupColumns.length && rowDetails && <td className="usx-data-table__group-cell" />}
31
+ {!!groupColumns.length && selectionMode && selectionPosition === 'left' && <td className="usx-data-table__group-cell" />}
32
+ {cells.map((column, index) => {
33
+ const rawValue = groupValues[groupKey]?.[column.key];
34
+ const options = rawValue && typeof rawValue === 'object' && 'value' in rawValue
35
+ ? rawValue as { value: React.ReactNode; backgroundColor?: string; color?: string; colSpan?: number;
36
+ align?: 'left' | 'center' | 'right'; verticalAlign?: 'top' | 'middle' | 'bottom' } : null;
37
+ const align = options?.align ?? column.align;
38
+ const verticalAlign = options?.verticalAlign ?? column.verticalAlign;
39
+ const value = options ? options.value : rawValue as React.ReactNode;
40
+ const content = column.render ? column.render({ key: groupKey, rows }) : value;
41
+ const Tag = index === 0 ? 'th' : 'td';
42
+ const span = options?.colSpan || column.colSpan || 1;
43
+ return <Tag key={column.key} scope={index === 0 ? 'row' : undefined}
44
+ colSpan={span > 1 ? span : undefined}
45
+ className={classnames('usx-data-table__group-cell', align && `usx-data-table__cell--align-${align}`,
46
+ verticalAlign && `usx-data-table__cell--valign-${verticalAlign}`, column.className)}
47
+ style={{ backgroundColor: options?.backgroundColor || column.backgroundColor,
48
+ color: options?.color || column.color }}>
49
+ {index === 0
50
+ ? <button type="button" className="usx-data-table__group-toggle" aria-expanded={isExpanded}
51
+ aria-controls={contentId}>{content ?? label}</button>
52
+ : align === 'center' ? <div className="usx-data-table__cell-content">{content ?? null}</div> : content ?? null}
53
+ </Tag>;
54
+ })}
55
+ {!!groupColumns.length && selectionMode && selectionPosition === 'right' && <td className="usx-data-table__group-cell" />}
56
+ </tr>
57
+ </tbody>
58
+ <tbody className="usx-data-table__group usx-data-table__group--content" id={contentId} hidden={!isExpanded}>
59
+ {children}
60
+ </tbody>
61
+ </>;
62
+ }