Skip to content

Commit

Permalink
feat: useSortBy invertSort
Browse files Browse the repository at this point in the history
  • Loading branch information
bryanmylee committed May 10, 2022
1 parent c2da222 commit 83349a5
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
14 changes: 13 additions & 1 deletion src/lib/plugins/useSortBy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export interface SortByColumnOptions {
disable?: boolean;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getSortValue?: (value: any) => string | number | (string | number)[];
invert?: boolean;
}

export type SortByPropSet = NewTablePropSet<{
Expand Down Expand Up @@ -111,6 +112,7 @@ export const useSortBy =
const _sortedRows = [...rows];
_sortedRows.sort((a, b) => {
for (const key of $sortKeys) {
const invert = columnOptions[key.id]?.invert ?? false;
const cellA = a.cellForId[key.id];
const cellB = b.cellForId[key.id];
let order = 0;
Expand All @@ -126,7 +128,17 @@ export const useSortBy =
order = compare(cellA.value, cellB.value as string | number);
}
if (order !== 0) {
return key.order === 'asc' ? order : -order;
let orderFactor = 1;
// If the current key order is `'desc'`, reverse the order.
if (key.order === 'desc') {
orderFactor *= -1;
}
// If `invert` is `true`, we want to invert the sort without
// affecting the view model's indication.
if (invert) {
orderFactor *= -1;
}
return order * orderFactor;
}
}
return 0;
Expand Down
4 changes: 3 additions & 1 deletion src/routes/index.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
filter: useColumnFilters(),
orderColumns: useColumnOrder({
initialColumnIdOrder: ['firstName', 'lastName'],
hideUnspecifiedColumns: true,
}),
hideColumns: useHiddenColumns(),
});
Expand All @@ -49,6 +48,9 @@
header: createRender(Italic, { text: 'First Name' }),
accessor: 'firstName',
plugins: {
sort: {
invert: true,
},
filter: {
fn: textPrefixFilter,
render: ({ filterValue, values }) =>
Expand Down

0 comments on commit 83349a5

Please sign in to comment.