Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: grid sortBy support sort function #207

Open
wants to merge 1 commit into
base: v5
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 26 additions & 23 deletions packages/layout/src/grid.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isNumber, isString } from '@antv/util';
import { isFunction, isNumber, isString } from '@antv/util';
import type {
Edge,
Graph,
Expand Down Expand Up @@ -127,33 +127,36 @@ export class GridLayout implements Layout<GridLayoutOptions> {
(node) => cloneFormatData(node) as OutNode,
);

if (
// `id` should be reserved keyword
sortBy !== 'id' &&
(!isString(sortBy) || (layoutNodes[0] as any).data[sortBy] === undefined)
) {
sortBy = 'degree';
}

if (sortBy === 'degree') {
if (isString(sortBy)) {
if (sortBy === 'id') {
// sort nodes by ID
layoutNodes.sort(({ id: id1 }, { id: id2 }) =>
isNumber(id2) && isNumber(id1)
? id2 - id1
: `${id1}`.localeCompare(`${id2}`),
);
} else if (sortBy === 'degree') {
layoutNodes.sort(
(n1, n2) =>
graph.getDegree(n2.id, 'both') - graph.getDegree(n1.id, 'both'),
);
} else {
// sort nodes by value
layoutNodes.sort(
(n1, n2) => n2.data[sortBy as string] - n1.data[sortBy as string],
);
}
} else if (isFunction(sortBy)) {
// sort by custom function
layoutNodes.sort(sortBy);
} else {
// sort nodes by degree
layoutNodes.sort(
(n1, n2) =>
graph.getDegree(n2.id, 'both') - graph.getDegree(n1.id, 'both'),
);
} else if (sortBy === 'id') {
// sort nodes by ID
layoutNodes.sort((n1, n2) => {
if (isNumber(n2.id) && isNumber(n1.id)) {
return n2.id - n1.id;
}
return `${n1.id}`.localeCompare(`${n2.id}`);
});
} else {
// sort nodes by value
layoutNodes.sort(
(n1, n2) => (n2 as any).data[sortBy!] - (n1 as any).data[sortBy!],
);
}

const width =
!propsWidth && typeof window !== 'undefined'
? window.innerWidth
Expand Down
2 changes: 1 addition & 1 deletion packages/layout/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ export interface GridLayoutOptions {
condense?: boolean;
rows?: number;
cols?: number;
sortBy?: string;
sortBy?: string | ((n1: any, n2: any) => number);
position?: (node?: Node) => { row?: number; col?: number };
nodeSpacing?: ((node?: Node) => number) | number;
}
Expand Down
Loading