Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DataGrid] Add getSortComparator for more advanced sorting behaviors #12215

Merged
merged 3 commits into from
Feb 27, 2024
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
47 changes: 47 additions & 0 deletions docs/data/data-grid/sorting/GetSortComparator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import * as React from 'react';
import { DataGrid, gridStringOrNumberComparator } from '@mui/x-data-grid';
import {
randomQuantity,
randomId,
randomCommodity,
} from '@mui/x-data-grid-generator';

const columns = [
{ field: 'commodity', headerName: 'Commodity', width: 200 },
{
type: 'number',
field: 'quantity',
headerName: 'Quantity',
getSortComparator: (sortDirection) => {
const modifier = sortDirection === 'desc' ? -1 : 1;
return (value1, value2, cellParams1, cellParams2) => {
if (value1 === null) {
return 1;
}
if (value2 === null) {
return -1;
}
return (
modifier *
gridStringOrNumberComparator(value1, value2, cellParams1, cellParams2)
);
};
},
},
];

const rows = [
{ id: randomId(), commodity: randomCommodity(), quantity: randomQuantity() },
{ id: randomId(), commodity: randomCommodity(), quantity: null },
{ id: randomId(), commodity: randomCommodity(), quantity: randomQuantity() },
{ id: randomId(), commodity: randomCommodity(), quantity: null },
{ id: randomId(), commodity: randomCommodity(), quantity: randomQuantity() },
];

export default function GetSortComparator() {
return (
<div style={{ height: 400, width: '100%' }}>
<DataGrid columns={columns} rows={rows} />
</div>
);
}
51 changes: 51 additions & 0 deletions docs/data/data-grid/sorting/GetSortComparator.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import * as React from 'react';
import {
DataGrid,
GridColDef,
gridStringOrNumberComparator,
} from '@mui/x-data-grid';
import {
randomQuantity,
randomId,
randomCommodity,
} from '@mui/x-data-grid-generator';

const columns: GridColDef[] = [
{ field: 'commodity', headerName: 'Commodity', width: 200 },
{
type: 'number',
field: 'quantity',
headerName: 'Quantity',
getSortComparator: (sortDirection) => {
const modifier = sortDirection === 'desc' ? -1 : 1;
return (value1, value2, cellParams1, cellParams2) => {
if (value1 === null) {
return 1;
}
if (value2 === null) {
return -1;
}
return (
modifier *
gridStringOrNumberComparator(value1, value2, cellParams1, cellParams2)
);
};
},
},
];

const rows = [
{ id: randomId(), commodity: randomCommodity(), quantity: randomQuantity() },
{ id: randomId(), commodity: randomCommodity(), quantity: null },
{ id: randomId(), commodity: randomCommodity(), quantity: randomQuantity() },
{ id: randomId(), commodity: randomCommodity(), quantity: null },
{ id: randomId(), commodity: randomCommodity(), quantity: randomQuantity() },
];

export default function GetSortComparator() {
return (
<div style={{ height: 400, width: '100%' }}>
<DataGrid columns={columns} rows={rows} />
</div>
);
}
1 change: 1 addition & 0 deletions docs/data/data-grid/sorting/GetSortComparator.tsx.preview
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<DataGrid columns={columns} rows={rows} />
10 changes: 10 additions & 0 deletions docs/data/data-grid/sorting/sorting.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,16 @@ The sorting is based on `isAdmin` and then on `name`, if necessary. It re-uses t

{{"demo": "ExtendedSortComparator.js", "bg": "inline", "defaultCodeOpen": false}}

### Asymmetric comparator

The Data Grid considers the `sortComparator` function symmetric, automatically reversing the return value for descending sorting by multiplying it by `-1`.

While this is sufficient for most use cases, it is possible to define an asymmetric comparator using the `getSortComparator` function – it receives the sorting direction as an argument and returns a comparator function.

In the demo below, the `getSortComparator` function is used in the "Quantity" column to keep the `null` values at the bottom when sorting is applied (regardless of the sorting direction):

{{"demo": "GetSortComparator.js", "bg": "inline", "defaultCodeOpen": false}}

## Custom sort order

By default, the sort order cycles between these three different modes:
Expand Down
1 change: 1 addition & 0 deletions docs/pages/x/api/data-grid/grid-actions-col-def.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import { GridActionsColDef } from '@mui/x-data-grid';
| <span class="prop-name optional">flex<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">number</span> | | If set, it indicates that a column has fluid width. Range [0, ∞). |
| <span class="prop-name">getActions</span> | <span class="prop-type">(params: GridRowParams&lt;R&gt;) =&gt; React.ReactElement&lt;GridActionsCellItemProps&gt;[]</span> | | Function that returns the actions to be shown. |
| <span class="prop-name optional">getApplyQuickFilterFn<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">GetApplyQuickFilterFn&lt;R, V&gt;</span> | | The callback that generates a filtering function for a given quick filter value.<br />This function can return `null` to skip filtering for this value and column. |
| <span class="prop-name optional">getSortComparator<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">(sortDirection: GridSortDirection) =&gt; GridComparatorFn&lt;V&gt; \| undefined</span> | | Allows to use a different comparator function depending on the sort direction.<br />Takes precedence over `sortComparator`. |
| <span class="prop-name optional">groupable<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">boolean</span> | <span class="prop-default">true</span> | If `true`, the rows can be grouped based on this column values (pro-plan only).<br />Only available in DataGridPremium. |
| <span class="prop-name optional">groupingValueGetter<sup><abbr title="optional">?</abbr></sup> [<span class="plan-premium" title="Premium plan"></span>](/x/introduction/licensing/#premium-plan)</span> | <span class="prop-type">GridGroupingValueGetter&lt;R&gt;</span> | | Function that transforms a complex cell value into a key that be used for grouping the rows. |
| <span class="prop-name optional">headerAlign<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">GridAlignment</span> | | Header cell element alignment. |
Expand Down
1 change: 1 addition & 0 deletions docs/pages/x/api/data-grid/grid-col-def.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import { GridColDef } from '@mui/x-data-grid';
| <span class="prop-name optional">filterOperators<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">GridFilterOperator&lt;R, V, F&gt;[]</span> | | Allows setting the filter operators for this column. |
| <span class="prop-name optional">flex<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">number</span> | | If set, it indicates that a column has fluid width. Range [0, ∞). |
| <span class="prop-name optional">getApplyQuickFilterFn<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">GetApplyQuickFilterFn&lt;R, V&gt;</span> | | The callback that generates a filtering function for a given quick filter value.<br />This function can return `null` to skip filtering for this value and column. |
| <span class="prop-name optional">getSortComparator<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">(sortDirection: GridSortDirection) =&gt; GridComparatorFn&lt;V&gt; \| undefined</span> | | Allows to use a different comparator function depending on the sort direction.<br />Takes precedence over `sortComparator`. |
| <span class="prop-name optional">groupable<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">boolean</span> | <span class="prop-default">true</span> | If `true`, the rows can be grouped based on this column values (pro-plan only).<br />Only available in DataGridPremium. |
| <span class="prop-name optional">groupingValueGetter<sup><abbr title="optional">?</abbr></sup> [<span class="plan-premium" title="Premium plan"></span>](/x/introduction/licensing/#premium-plan)</span> | <span class="prop-type">GridGroupingValueGetter&lt;R&gt;</span> | | Function that transforms a complex cell value into a key that be used for grouping the rows. |
| <span class="prop-name optional">headerAlign<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">GridAlignment</span> | | Header cell element alignment. |
Expand Down
1 change: 1 addition & 0 deletions docs/pages/x/api/data-grid/grid-single-select-col-def.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import { GridSingleSelectColDef } from '@mui/x-data-grid';
| <span class="prop-name optional">getApplyQuickFilterFn<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">GetApplyQuickFilterFn&lt;R, V&gt;</span> | | The callback that generates a filtering function for a given quick filter value.<br />This function can return `null` to skip filtering for this value and column. |
| <span class="prop-name optional">getOptionLabel<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">(value: ValueOptions) =&gt; string</span> | | Used to determine the label displayed for a given value option. |
| <span class="prop-name optional">getOptionValue<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">(value: ValueOptions) =&gt; any</span> | | Used to determine the value used for a value option. |
| <span class="prop-name optional">getSortComparator<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">(sortDirection: GridSortDirection) =&gt; GridComparatorFn&lt;V&gt; \| undefined</span> | | Allows to use a different comparator function depending on the sort direction.<br />Takes precedence over `sortComparator`. |
| <span class="prop-name optional">groupable<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">boolean</span> | <span class="prop-default">true</span> | If `true`, the rows can be grouped based on this column values (pro-plan only).<br />Only available in DataGridPremium. |
| <span class="prop-name optional">groupingValueGetter<sup><abbr title="optional">?</abbr></sup> [<span class="plan-premium" title="Premium plan"></span>](/x/introduction/licensing/#premium-plan)</span> | <span class="prop-type">GridGroupingValueGetter&lt;R&gt;</span> | | Function that transforms a complex cell value into a key that be used for grouping the rows. |
| <span class="prop-name optional">headerAlign<sup><abbr title="optional">?</abbr></sup></span> | <span class="prop-type">GridAlignment</span> | | Header cell element alignment. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,18 @@ const parseSortItem = (
return null;
}

const comparator: GridComparatorFn = isDesc(sortItem.sort)
? (...args) => -1 * column.sortComparator!(...args)
: column.sortComparator!;
let comparator: GridComparatorFn | undefined;
if (column.getSortComparator) {
comparator = column.getSortComparator(sortItem.sort);
} else {
comparator = isDesc(sortItem.sort)
? (...args) => -1 * column.sortComparator!(...args)
: column.sortComparator!;
}

if (!comparator) {
return null;
}

const getSortCellParams = (id: GridRowId): GridSortCellParams => ({
id,
Expand Down
7 changes: 7 additions & 0 deletions packages/x-data-grid/src/models/colDef/gridColDef.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,13 @@ export interface GridBaseColDef<R extends GridValidRowModel = GridValidRowModel,
* A comparator function used to sort rows.
*/
sortComparator?: GridComparatorFn<V>;
/**
* Allows to use a different comparator function depending on the sort direction.
* Takes precedence over `sortComparator`.
* @param {GridSortDirection} sortDirection The direction of the sort.
* @returns {GridComparatorFn<V>} The comparator function to use.
*/
getSortComparator?: (sortDirection: GridSortDirection) => GridComparatorFn<V> | undefined;
/**
* The type of the column.
* @default 'string'
Expand Down
56 changes: 55 additions & 1 deletion packages/x-data-grid/src/tests/sorting.DataGrid.test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import * as React from 'react';
import { createRenderer, fireEvent, screen, act, waitFor } from '@mui-internal/test-utils';
import { expect } from 'chai';
import { DataGrid, DataGridProps, GridSortModel, useGridApiRef, GridApi } from '@mui/x-data-grid';
import {
DataGrid,
DataGridProps,
GridSortModel,
useGridApiRef,
GridApi,
GridColDef,
gridStringOrNumberComparator,
} from '@mui/x-data-grid';
import { getColumnValues, getColumnHeaderCell } from 'test/utils/helperFn';
import { spy } from 'sinon';
import { GridInitialState } from '@mui/x-data-grid-pro';
Expand Down Expand Up @@ -704,4 +712,50 @@ describe('<DataGrid /> - Sorting', () => {
expect(onSortModelChange.callCount).to.equal(0);
});
});

describe('getSortComparator', () => {
it('should allow to define sort comparators depending on the sort direction', async () => {
const cols: GridColDef[] = [
{
field: 'value',
getSortComparator: (sortDirection) => {
const modifier = sortDirection === 'desc' ? -1 : 1;
return (value1, value2, cellParams1, cellParams2) => {
if (value1 === null) {
return 1;
}
if (value2 === null) {
return -1;
}
return (
modifier * gridStringOrNumberComparator(value1, value2, cellParams1, cellParams2)
);
};
},
},
];
const rows = [
{ id: 1, value: 'a' },
{ id: 2, value: null },
{ id: 3, value: 'b' },
{ id: 4, value: null },
];
render(
<div style={{ width: 300, height: 300 }}>
<DataGrid autoHeight={isJSDOM} columns={cols} rows={rows} />
</div>,
);

expect(getColumnValues(0)).to.deep.equal(['a', '', 'b', '']);

const header = getColumnHeaderCell(0);
fireEvent.click(header);
await waitFor(() => {
expect(getColumnValues(0)).to.deep.equal(['a', 'b', '', '']);
});

fireEvent.click(header);
expect(getColumnValues(0)).to.deep.equal(['b', 'a', '', '']);
});
});
});
Loading