From 4cd0310c397d4bafc47cd2959d62bb379c29f24a Mon Sep 17 00:00:00 2001 From: junkerderprovinz Date: Sat, 7 Nov 2026 23:31:34 +0100 Subject: [PATCH 1/2] fix(DataTable): sort rows on the first render with an initial sort initialSortColumn and initialSortDirection set the header state, but the rows kept the order of data until data changed or a header was clicked. The row order is now sorted in its useState initializer, the approach agreed on in #4602. getSortedRowOrder moves out of the hook and looks up columns instead of headers so it can run before the headers exist. Co-authored-by: Ben Wittenberg <394958+bwittenberg@users.noreply.github.com> --- .changeset/datatable-initial-sort.md | 5 + .../DataTable/__tests__/DataTable.test.tsx | 157 +++++++++++++- packages/react/src/DataTable/useTable.ts | 195 +++++++++--------- 3 files changed, 260 insertions(+), 97 deletions(-) create mode 100644 .changeset/datatable-initial-sort.md diff --git a/.changeset/datatable-initial-sort.md b/.changeset/datatable-initial-sort.md new file mode 100644 index 00000000000..5cd9af81321 --- /dev/null +++ b/.changeset/datatable-initial-sort.md @@ -0,0 +1,5 @@ +--- +'@primer/react': patch +--- + +DataTable: Sort the rows on the first render when `initialSortColumn` or `initialSortDirection` is set. Before, only the header showed the sort direction and the rows stayed in the order of `data` until it changed or a header was clicked. diff --git a/packages/react/src/DataTable/__tests__/DataTable.test.tsx b/packages/react/src/DataTable/__tests__/DataTable.test.tsx index cd1b1bfad46..a260a964ac8 100644 --- a/packages/react/src/DataTable/__tests__/DataTable.test.tsx +++ b/packages/react/src/DataTable/__tests__/DataTable.test.tsx @@ -528,12 +528,165 @@ describe('DataTable', () => { return cells }) expect(rows).toEqual([ - ['a', 'c'], - ['b', 'b'], ['c', 'a'], + ['b', 'b'], + ['a', 'c'], ]) }) + it('should sort the rows on the first render using `initialSortColumn`', async () => { + render( + , + ) + + const rows = page + .getByRole('cell') + .elements() + .map(cell => cell.textContent) + expect(rows).toEqual(['1', '2', '3']) + }) + + it('should sort the rows on the first render when `initialSortColumn` is the field of a column with an id', async () => { + render( + , + ) + + const header = page.getByRole('columnheader', { + name: 'Value', + }) + await expect.element(header).toHaveAttribute('aria-sort', 'ascending') + + const rows = page + .getByRole('cell') + .elements() + .map(cell => cell.textContent) + expect(rows).toEqual(['1', '2', '3']) + }) + + it('should sort the rows on the first render using `initialSortDirection` and the column strategy', async () => { + render( + , + ) + + const header = page.getByRole('columnheader', { + name: 'Value', + }) + await expect.element(header).toHaveAttribute('aria-sort', 'descending') + + const rows = page + .getByRole('cell') + .elements() + .map(cell => cell.textContent) + expect(rows).toEqual(['z11', 'z3', 'z2']) + }) + + it('should keep the given row order when `externalSorting` is set', async () => { + render( + , + ) + + const rows = page + .getByRole('cell') + .elements() + .map(cell => cell.textContent) + expect(rows).toEqual(['3', '1', '2']) + }) + it('should not set a default sort state if `initialSortDirection` is provided but no columns are sortable', async () => { const spy = vi.spyOn(console, 'warn').mockImplementationOnce(() => {}) render( diff --git a/packages/react/src/DataTable/useTable.ts b/packages/react/src/DataTable/useTable.ts index a1bc1117f3a..91c2c6334f5 100644 --- a/packages/react/src/DataTable/useTable.ts +++ b/packages/react/src/DataTable/useTable.ts @@ -111,12 +111,17 @@ export function useTable({ onExpandedGroupsChange, }: TableConfig): Table { const tableId = useId() - const [rowOrder, setRowOrder] = useState>(data) - const [prevData, setPrevData] = useState(data) - const [prevColumns, setPrevColumns] = useState(columns) const [sortByColumn, setSortByColumn] = useState(() => { return getInitialSortState(columns, initialSortColumn, initialSortDirection) }) + const [rowOrder, setRowOrder] = useState>(() => { + if (externalSorting || sortByColumn === null) { + return data + } + return getSortedRowOrder(data, columns, sortByColumn) + }) + const [prevData, setPrevData] = useState(data) + const [prevColumns, setPrevColumns] = useState(columns) const [selectedRows, setSelectedRows] = useControllableState>({ name: 'DataTable selectedRows', value: controlledSelectedRows, @@ -197,101 +202,11 @@ export function useTable({ if (externalSorting || state === null) { setRowOrder(rows) } else { - const sortedRows = getSortedRowOrder(rows, state) + const sortedRows = getSortedRowOrder(rows, columns, state) setRowOrder(sortedRows) } } - /** - * Blank values are ordered last regardless of the sort direction. - */ - function getSortedRowOrder( - currentRowOrder: DataTableData, - state: Exclude, - ): DataTableData { - const header = headers.find(header => { - return header.id === state.id - }) - if (!header) { - throw new Error(`Unable to find header with id: ${state.id}`) - } - - if (header.column.sortBy === false || header.column.sortBy === undefined) { - throw new Error(`The column for this header is not sortable`) - } - const column = header.column - - const sortMethod = - column.sortBy === true - ? strategies.basic - : typeof column.sortBy === 'string' - ? strategies[column.sortBy] - : column.sortBy - - function sortData(rows: Array) { - return rows.slice().sort((a, b) => { - if (column.field === undefined) { - return 0 - } - - // Custom sort functions operate on the row versus the field - if (typeof column.sortBy === 'function') { - if (state.direction === SortDirection.ASC) { - // @ts-ignore todo - return sortMethod(a, b) - } - // @ts-ignore todo - return sortMethod(b, a) - } - - const valueA = get(a, column.field) - const valueB = get(b, column.field) - - const valueAIsBlank = isBlankValue(valueA) - const valueBIsBlank = isBlankValue(valueB) - - if (!valueAIsBlank && !valueBIsBlank) { - if (state.direction === SortDirection.ASC) { - // @ts-ignore todo - return sortMethod(valueA, valueB) - } - // @ts-ignore todo - return sortMethod(valueB, valueA) - } - - if (!valueAIsBlank) { - return -1 - } - - if (!valueBIsBlank) { - return 1 - } - return 0 - }) - } - - const sorted: DataTableData = [] - let ungroupedRows: Array = [] - - function appendUngroupedRows() { - for (const row of sortData(ungroupedRows)) { - sorted.push(row) - } - ungroupedRows = [] - } - - for (const item of currentRowOrder) { - if (isDataTableRowGroup(item)) { - appendUngroupedRows() - sorted.push({...item, rows: sortData(item.rows)}) - } else { - ungroupedRows.push(item) - } - } - appendUngroupedRows() - return sorted - } - function createRow(row: Data, rowIndex: number): Row { const rowId = getRowId(row) const rowHeaderIds = @@ -456,6 +371,96 @@ export function useTable({ } } +/** + * Blank values are ordered last regardless of the sort direction. + */ +function getSortedRowOrder( + currentRowOrder: DataTableData, + columns: Array>, + state: Exclude, +): DataTableData { + const column = columns.find(column => { + return (column.id ?? column.field) === state.id + }) + if (!column) { + throw new Error(`Unable to find column with id: ${state.id}`) + } + + if (column.sortBy === false || column.sortBy === undefined) { + throw new Error(`The column with id: ${state.id} is not sortable`) + } + + const sortMethod = + column.sortBy === true + ? strategies.basic + : typeof column.sortBy === 'string' + ? strategies[column.sortBy] + : column.sortBy + + const sortData = (rows: Array) => { + return rows.slice().sort((a, b) => { + if (column.field === undefined) { + return 0 + } + + // Custom sort functions operate on the row versus the field + if (typeof column.sortBy === 'function') { + if (state.direction === SortDirection.ASC) { + // @ts-ignore todo + return sortMethod(a, b) + } + // @ts-ignore todo + return sortMethod(b, a) + } + + const valueA = get(a, column.field) + const valueB = get(b, column.field) + + const valueAIsBlank = isBlankValue(valueA) + const valueBIsBlank = isBlankValue(valueB) + + if (!valueAIsBlank && !valueBIsBlank) { + if (state.direction === SortDirection.ASC) { + // @ts-ignore todo + return sortMethod(valueA, valueB) + } + // @ts-ignore todo + return sortMethod(valueB, valueA) + } + + if (!valueAIsBlank) { + return -1 + } + + if (!valueBIsBlank) { + return 1 + } + return 0 + }) + } + + const sorted: DataTableData = [] + let ungroupedRows: Array = [] + + function appendUngroupedRows() { + for (const row of sortData(ungroupedRows)) { + sorted.push(row) + } + ungroupedRows = [] + } + + for (const item of currentRowOrder) { + if (isDataTableRowGroup(item)) { + appendUngroupedRows() + sorted.push({...item, rows: sortData(item.rows)}) + } else { + ungroupedRows.push(item) + } + } + appendUngroupedRows() + return sorted +} + function isDataTableRowGroup( item: Data | DataTableRowGroup, ): item is DataTableRowGroup { @@ -493,7 +498,7 @@ function getInitialSortState( } return { - id: `${initialSortColumn}`, + id: column.id ?? column.field ?? `${initialSortColumn}`, direction: initialSortDirection ?? DEFAULT_SORT_DIRECTION, } } From 6ec7c2a71197c28e60aa9c5570b16b14ae3a73d8 Mon Sep 17 00:00:00 2001 From: junkerderprovinz Date: Sat, 21 Nov 2026 08:55:43 +0100 Subject: [PATCH 2/2] docs(DataTable): drop the pre-sort requirement from initialSortColumn --- packages/react/src/DataTable/DataTable.docs.json | 2 +- packages/react/src/DataTable/DataTable.tsx | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/react/src/DataTable/DataTable.docs.json b/packages/react/src/DataTable/DataTable.docs.json index d9a084e2e23..18e928cc604 100644 --- a/packages/react/src/DataTable/DataTable.docs.json +++ b/packages/react/src/DataTable/DataTable.docs.json @@ -190,7 +190,7 @@ "name": "initialSortColumn", "type": "string | number", "required": false, - "description": "Provide the id or field of the column by which the table is sorted. When\nusing this `prop`, the input data must be sorted by this column in\nascending order", + "description": "Provide the id or field of the column by which the table is sorted. The\nrows are sorted by this column on the first render, so the input data\ndoes not need to be sorted beforehand. With `externalSorting`, the table\ndoes not sort the rows, and the input data must arrive in the desired order", "defaultValue": "" }, { diff --git a/packages/react/src/DataTable/DataTable.tsx b/packages/react/src/DataTable/DataTable.tsx index 8c5e79c9c78..a74f62fcad4 100644 --- a/packages/react/src/DataTable/DataTable.tsx +++ b/packages/react/src/DataTable/DataTable.tsx @@ -54,9 +54,10 @@ type DataTableBaseProps = { columns: Array> /** - * Provide the id or field of the column by which the table is sorted. When - * using this `prop`, the input data must be sorted by this column in - * ascending order + * Provide the id or field of the column by which the table is sorted. The + * rows are sorted by this column on the first render, so the input data + * does not need to be sorted beforehand. With `externalSorting`, the table + * does not sort the rows, and the input data must arrive in the desired order */ initialSortColumn?: ObjectPaths | string | number