Skip to content

Commit 60d2de9

Browse files
authored
Merge pull request marmelab#10334 from marmelab/fix-datagrid-header-sort-label
Fix Datagrid header tooltip sometimes indicates the wrong sort order
2 parents c3d43a1 + a50ed71 commit 60d2de9

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

packages/ra-ui-materialui/src/list/datagrid/DatagridHeaderCell.spec.tsx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,11 @@ describe('<DatagridHeaderCell />', () => {
4141
await screen.findByText('ID');
4242
await screen.findByLabelText('Sort by Id descending');
4343
await screen.findByText('TITLE');
44-
await screen.findByLabelText('Sort by Title descending');
44+
await screen.findByLabelText('Sort by Title ascending');
4545
await screen.findByText('AUTHOR');
46-
await screen.findByLabelText('Sort by Author descending');
46+
await screen.findByLabelText('Sort by Author ascending');
4747
await screen.findByText('YEAR');
48-
await screen.findByLabelText('Sort by Year descending');
48+
await screen.findByLabelText('Sort by Year ascending');
4949
});
5050

5151
describe('sorting on a column', () => {

packages/ra-ui-materialui/src/list/datagrid/DatagridHeaderCell.tsx

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,15 @@ import { TableCellProps } from '@mui/material/TableCell';
77
import {
88
FieldTitle,
99
useTranslate,
10-
SortPayload,
1110
useResourceContext,
1211
useTranslateLabel,
1312
} from 'ra-core';
13+
import type { SortPayload } from 'ra-core';
14+
15+
const oppositeOrder: Record<SortPayload['order'], SortPayload['order']> = {
16+
ASC: 'DESC',
17+
DESC: 'ASC',
18+
};
1419

1520
export const DatagridHeaderCell = (
1621
props: DatagridHeaderCellProps
@@ -20,6 +25,13 @@ export const DatagridHeaderCell = (
2025

2126
const translate = useTranslate();
2227
const translateLabel = useTranslateLabel();
28+
const nextSortOrder = field
29+
? sort && sort.field === (field.props.sortBy || field.props.source)
30+
? // active sort field, use opposite order
31+
oppositeOrder[sort.order]
32+
: // non active sort field, use default order
33+
field?.props.sortByOrder ?? 'ASC'
34+
: undefined;
2335
const sortLabel = translate('ra.sort.sort_by', {
2436
field: field
2537
? translateLabel({
@@ -31,7 +43,7 @@ export const DatagridHeaderCell = (
3143
source: field.props.source,
3244
})
3345
: undefined,
34-
order: translate(`ra.sort.${sort?.order === 'ASC' ? 'DESC' : 'ASC'}`),
46+
order: translate(`ra.sort.${nextSortOrder}`),
3547
_: translate('ra.action.sort'),
3648
});
3749

0 commit comments

Comments
 (0)