Skip to content

Commit

Permalink
Add Multiple Sort Fields
Browse files Browse the repository at this point in the history
  • Loading branch information
jameskerr committed Mar 28, 2024
1 parent f717e78 commit 8a51691
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 11 deletions.
4 changes: 2 additions & 2 deletions modules/react-arborist/src/nodes/default-accessors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function createDefaultAccessors<T>(): SourceDataAccessors<T> {
return true;
}
},
sortBy: (_d: T) => 0,
sortOrder: "asc",
sortBy: [],
sortOrder: [],
};
}
42 changes: 33 additions & 9 deletions modules/react-arborist/src/nodes/source-data-accessor.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { toArray } from "../utils";
import { createDefaultAccessors } from "./default-accessors";

type GetSortField<T> = (d: T) => number | string | boolean;
type SortOrder = "asc" | "desc";

export type SourceDataAccessors<T> = {
id: (d: T) => string;
children: (d: T) => T[] | null;
isLeaf: (d: T) => boolean;
sortBy: (d: T) => number | string | boolean;
sortOrder: "asc" | "desc";
sortBy: GetSortField<T> | GetSortField<T>[];
sortOrder: SortOrder | SortOrder[];
};

export class SourceDataAccessor<T> {
Expand All @@ -28,19 +32,39 @@ export class SourceDataAccessor<T> {
}

sort(array: T[]) {
return array.sort((a, b) => {
const first = this.access.sortBy(a);
const second = this.access.sortBy(b);
const orders = toArray(this.access.sortOrder);
const compares = toArray(this.access.sortBy);

if (this.asc) {
return first < second ? -1 : 1;
} else {
return first > second ? -1 : 1;
return array.sort((a, b) => {
for (let i = 0; i < compares.length; i++) {
const comparator = this.createComparator(
compares[i],
orders[i] || "asc",
);
const result = comparator(a, b);
if (result !== 0) return result;
}
return 0;
});
}

get asc() {
return this.access.sortOrder === "asc";
}

createComparator(getField: GetSortField<T>, sortOrder: SortOrder) {
return (a: T, b: T) => {
const first = getField(a);
const second = getField(b);

if (sortOrder === "asc") {
if (first < second) return -1;
if (first > second) return 1;
} else {
if (first < second) return 1;
if (first > second) return -1;
}
return 0;
};
}
}
5 changes: 5 additions & 0 deletions modules/react-arborist/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,3 +173,8 @@ export function getInsertParentId(tree: TreeApi<any>) {
if (focus.parent && !focus.parent.isRoot) return focus.parent.id;
return null;
}

export function toArray<T>(itemOrArray: T | T[]): T[] {
if (Array.isArray(itemOrArray)) return itemOrArray;
else return [itemOrArray];
}

0 comments on commit 8a51691

Please sign in to comment.