(
sortCallback: MultiSortCallback,
{ defaultSortBy, defaultSortDirection = {} }: MultiSortOptions = {}
)
| 21 | * @param options Optional default sort-by values. |
| 22 | */ |
| 23 | export function createMultiSort( |
| 24 | sortCallback: MultiSortCallback, |
| 25 | { defaultSortBy, defaultSortDirection = {} }: MultiSortOptions = {} |
| 26 | ): MultiSortReturn { |
| 27 | if (!sortCallback) { |
| 28 | throw Error(`Required parameter "sortCallback" not specified`); |
| 29 | } |
| 30 | |
| 31 | // The sort criteria are replaced (never mutated) when they change, |
| 32 | // so that they can be stored in React state (e.g. with useState) and compared by reference. |
| 33 | // (This also leaves the caller's defaultSortBy array unchanged.) |
| 34 | let sortBy: string[] = defaultSortBy ? [...defaultSortBy] : []; |
| 35 | let sortDirection: SortDirectionMap = {}; |
| 36 | sortBy.forEach((dataKey) => { |
| 37 | sortDirection[dataKey] = |
| 38 | defaultSortDirection[dataKey] !== undefined |
| 39 | ? defaultSortDirection[dataKey] |
| 40 | : "ASC"; |
| 41 | }); |
| 42 | |
| 43 | const toggle = (direction: SortDirectionMap[string]) => |
| 44 | direction === "ASC" ? "DESC" : "ASC"; |
| 45 | |
| 46 | function sort({ |
| 47 | defaultSortDirection, |
| 48 | event, |
| 49 | sortBy: dataKey |
| 50 | }: MultiSortParams): void { |
| 51 | if (event.shiftKey) { |
| 52 | // Shift + click appends a column to existing criteria (or toggles its direction) |
| 53 | if (sortDirection[dataKey] !== undefined) { |
| 54 | sortDirection = { |
| 55 | ...sortDirection, |
| 56 | [dataKey]: toggle(sortDirection[dataKey]) |
| 57 | }; |
| 58 | } else { |
| 59 | sortBy = [...sortBy, dataKey]; |
| 60 | sortDirection = { ...sortDirection, [dataKey]: defaultSortDirection }; |
| 61 | } |
| 62 | } else if (event.ctrlKey || event.metaKey) { |
| 63 | // Control + click removes column from sort (if present) |
| 64 | if (sortBy.includes(dataKey)) { |
| 65 | sortBy = sortBy.filter((key) => key !== dataKey); |
| 66 | sortDirection = { ...sortDirection }; |
| 67 | delete sortDirection[dataKey]; |
| 68 | } |
| 69 | } else { |
| 70 | // Sort by the selected key only. |
| 71 | // If it is already selected, reverse its sort direction; else, use the default direction. |
| 72 | sortDirection = { |
| 73 | [dataKey]: |
| 74 | sortDirection[dataKey] !== undefined |
| 75 | ? toggle(sortDirection[dataKey]) |
| 76 | : defaultSortDirection |
| 77 | }; |
| 78 | sortBy = [dataKey]; |
| 79 | } |
| 80 |
no outgoing calls