* Sort the rows of a table with the given column sort state. If the data in the table is sparse, * blank values will be ordered last regardless of the sort direction.
(state: Exclude<ColumnSortState, null>)
| 120 | * blank values will be ordered last regardless of the sort direction. |
| 121 | */ |
| 122 | function sortRows(state: Exclude<ColumnSortState, null>) { |
| 123 | const header = headers.find(header => { |
| 124 | return header.id === state.id |
| 125 | }) |
| 126 | if (!header) { |
| 127 | throw new Error(`Unable to find header with id: ${state.id}`) |
| 128 | } |
| 129 | |
| 130 | if (header.column.sortBy === false || header.column.sortBy === undefined) { |
| 131 | throw new Error(`The column for this header is not sortable`) |
| 132 | } |
| 133 | |
| 134 | const sortMethod = |
| 135 | header.column.sortBy === true |
| 136 | ? strategies.basic |
| 137 | : typeof header.column.sortBy === 'string' |
| 138 | ? strategies[header.column.sortBy] |
| 139 | : header.column.sortBy |
| 140 | |
| 141 | setRowOrder(rowOrder => { |
| 142 | return rowOrder.slice().sort((a, b) => { |
| 143 | if (header.column.field === undefined) { |
| 144 | return 0 |
| 145 | } |
| 146 | |
| 147 | // Custom sort functions operate on the row versus the field |
| 148 | if (typeof header.column.sortBy === 'function') { |
| 149 | if (state.direction === SortDirection.ASC) { |
| 150 | // @ts-ignore todo |
| 151 | return sortMethod(a, b) |
| 152 | } |
| 153 | // @ts-ignore todo |
| 154 | return sortMethod(b, a) |
| 155 | } |
| 156 | |
| 157 | const valueA = get(a, header.column.field) |
| 158 | const valueB = get(b, header.column.field) |
| 159 | |
| 160 | if (valueA && valueB) { |
| 161 | if (state.direction === SortDirection.ASC) { |
| 162 | // @ts-ignore todo |
| 163 | return sortMethod(valueA, valueB) |
| 164 | } |
| 165 | // @ts-ignore todo |
| 166 | return sortMethod(valueB, valueA) |
| 167 | } |
| 168 | |
| 169 | if (valueA) { |
| 170 | return -1 |
| 171 | } |
| 172 | |
| 173 | if (valueB) { |
| 174 | return 1 |
| 175 | } |
| 176 | return 0 |
| 177 | }) |
| 178 | }) |
| 179 | } |