Skip to content

Commit 9a75974

Browse files
hustccAarebecca
authored andcommitted
feat: grid sortBy support sort function
1 parent 920abc5 commit 9a75974

File tree

2 files changed

+27
-24
lines changed

2 files changed

+27
-24
lines changed

packages/layout/src/grid.ts

+26-23
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { isNumber, isString } from '@antv/util';
1+
import { isFunction, isNumber, isString } from '@antv/util';
22
import type {
33
Edge,
44
Graph,
@@ -127,33 +127,36 @@ export class GridLayout implements Layout<GridLayoutOptions> {
127127
(node) => cloneFormatData(node) as OutNode,
128128
);
129129

130-
if (
131-
// `id` should be reserved keyword
132-
sortBy !== 'id' &&
133-
(!isString(sortBy) || (layoutNodes[0] as any).data[sortBy] === undefined)
134-
) {
135-
sortBy = 'degree';
136-
}
137-
138-
if (sortBy === 'degree') {
130+
if (isString(sortBy)) {
131+
if (sortBy === 'id') {
132+
// sort nodes by ID
133+
layoutNodes.sort(({ id: id1 }, { id: id2 }) =>
134+
isNumber(id2) && isNumber(id1)
135+
? id2 - id1
136+
: `${id1}`.localeCompare(`${id2}`),
137+
);
138+
} else if (sortBy === 'degree') {
139+
layoutNodes.sort(
140+
(n1, n2) =>
141+
graph.getDegree(n2.id, 'both') - graph.getDegree(n1.id, 'both'),
142+
);
143+
} else {
144+
// sort nodes by value
145+
layoutNodes.sort(
146+
(n1, n2) => n2.data[sortBy as string] - n1.data[sortBy as string],
147+
);
148+
}
149+
} else if (isFunction(sortBy)) {
150+
// sort by custom function
151+
layoutNodes.sort(sortBy);
152+
} else {
153+
// sort nodes by degree
139154
layoutNodes.sort(
140155
(n1, n2) =>
141156
graph.getDegree(n2.id, 'both') - graph.getDegree(n1.id, 'both'),
142157
);
143-
} else if (sortBy === 'id') {
144-
// sort nodes by ID
145-
layoutNodes.sort((n1, n2) => {
146-
if (isNumber(n2.id) && isNumber(n1.id)) {
147-
return n2.id - n1.id;
148-
}
149-
return `${n1.id}`.localeCompare(`${n2.id}`);
150-
});
151-
} else {
152-
// sort nodes by value
153-
layoutNodes.sort(
154-
(n1, n2) => (n2 as any).data[sortBy!] - (n1 as any).data[sortBy!],
155-
);
156158
}
159+
157160
const width =
158161
!propsWidth && typeof window !== 'undefined'
159162
? window.innerWidth

packages/layout/src/types.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ export interface GridLayoutOptions {
117117
condense?: boolean;
118118
rows?: number;
119119
cols?: number;
120-
sortBy?: string;
120+
sortBy?: string | ((n1: any, n2: any) => number);
121121
position?: (node?: Node) => { row?: number; col?: number };
122122
nodeSpacing?: ((node?: Node) => number) | number;
123123
}

0 commit comments

Comments
 (0)