Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/salty-bikes-learn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@primer/react': minor
---

Add support for the `onToggleSort` prop to `DataTable`
7 changes: 7 additions & 0 deletions packages/react/src/DataTable/DataTable.docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,13 @@
"required": false,
"description": "Provide the sort direction that the table should be sorted by on the\ncurrently sorted column",
"defaultValue": ""
},
{
"name": "onToggleSort",
"type": "(columnId: ObjectPaths<Data> | string | number, direction: 'ASC' | 'DESC') => void",
"required": false,
"description": "Fires every time the user clicks a sortable column header. It reports the column id that is now sorted and the direction after the toggle (never 'NONE').",
"defaultValue": ""
}
],
"subcomponents": [
Expand Down
63 changes: 63 additions & 0 deletions packages/react/src/DataTable/DataTable.features.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1446,6 +1446,69 @@ export const WithRightAlignedColumns = () => {
)
}

export const WithSortEvents = () => (
<Table.Container>
<Table.Title as="h2" id="repositories">
Repositories
</Table.Title>
<Table.Subtitle as="p" id="repositories-subtitle">
Click any sortable header and watch the Actions panel.
</Table.Subtitle>

<DataTable
aria-labelledby="repositories"
aria-describedby="repositories-subtitle"
data={data}
onToggleSort={(columnId, direction) => action('onToggleSort')({columnId, direction})}
columns={[
{
header: 'Repository',
field: 'name',
rowHeader: true,
sortBy: 'alphanumeric',
},
{
header: 'Type',
field: 'type',
renderCell: row => <Label>{uppercase(row.type)}</Label>,
},
{
header: 'Updated',
field: 'updatedAt',
sortBy: 'datetime',
renderCell: row => <RelativeTime date={new Date(row.updatedAt)} />,
},
{
header: 'Dependabot',
field: 'securityFeatures.dependabot',
renderCell: row =>
row.securityFeatures.dependabot.length ? (
<LabelGroup>
{row.securityFeatures.dependabot.map(feature => (
<Label key={feature}>{uppercase(feature)}</Label>
))}
</LabelGroup>
) : null,
},
{
header: 'Code scanning',
field: 'securityFeatures.codeScanning',
renderCell: row =>
row.securityFeatures.codeScanning.length ? (
<LabelGroup>
{row.securityFeatures.codeScanning.map(feature => (
<Label key={feature}>{uppercase(feature)}</Label>
))}
</LabelGroup>
) : null,
},
]}
initialSortColumn="updatedAt"
initialSortDirection="DESC"
/>
</Table.Container>
)

export const WithPagination = () => {
const pageSize = 10
const [pageIndex, setPageIndex] = React.useState(0)
Expand Down
11 changes: 11 additions & 0 deletions packages/react/src/DataTable/DataTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ export type DataTableProps<Data extends UniqueRow> = {
* @returns The unique identifier for the row, which can be a string or number.
*/
getRowId?: (rowData: Data) => string | number

/**
* Fires every time the user clicks a sortable column header. It reports
* the column id that is now sorted and the direction after the toggle
* (never `"NONE"`).
*/
onToggleSort?: (columnId: ObjectPaths<Data> | string | number, direction: Exclude<SortDirection, 'NONE'>) => void
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Had to resolve a merge conflict, too, and opted to force-push a single commit.

}

function defaultGetRowId<D extends UniqueRow>(row: D) {
Expand All @@ -74,6 +81,7 @@ function DataTable<Data extends UniqueRow>({
initialSortColumn,
initialSortDirection,
getRowId = defaultGetRowId,
onToggleSort,
}: DataTableProps<Data>) {
const {headers, rows, actions, gridTemplateColumns} = useTable({
data,
Expand All @@ -100,7 +108,10 @@ function DataTable<Data extends UniqueRow>({
align={header.column.align}
direction={header.getSortDirection()}
onToggleSort={() => {
const nextDirection: Exclude<SortDirection, 'NONE'> =
header.getSortDirection() === 'ASC' ? 'DESC' : 'ASC'
actions.sortBy(header)
onToggleSort?.(header.id, nextDirection)
}}
>
{typeof header.column.header === 'string' ? header.column.header : header.column.header()}
Expand Down
35 changes: 35 additions & 0 deletions packages/react/src/DataTable/__tests__/DataTable.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -886,6 +886,41 @@ describe('DataTable', () => {
expect(customSortFn).toHaveBeenCalled()
expect(getRowOrder()).toEqual(['3', '2', '1'])
})

it('invokes onToggleSort with column id and next direction', async () => {
const user = userEvent.setup()
const handler = vi.fn()

render(
<DataTable
data={[
{id: 1, first: 'a', second: 'c'},
{id: 2, first: 'b', second: 'b'},
{id: 3, first: 'c', second: 'a'},
]}
columns={[
{header: 'First', field: 'first', sortBy: true},
{header: 'Second', field: 'second', sortBy: true},
]}
initialSortColumn="first"
initialSortDirection="ASC"
onToggleSort={handler}
/>,
)

// No calls on initial render
expect(handler).not.toHaveBeenCalled()

// Same column, flips ASC to DESC
await user.click(screen.getByText('First'))
expect(handler).toHaveBeenLastCalledWith('first', 'DESC')

// Different column, resets to ASC on that column
await user.click(screen.getByText('Second'))
expect(handler).toHaveBeenLastCalledWith('second', 'ASC')

expect(handler).toHaveBeenCalledTimes(2)
})
})

describe('column widths', () => {
Expand Down
Loading