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(D3 plugin): add bar-x sorting setting #282

Merged
merged 1 commit into from
Sep 7, 2023
Merged
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
24 changes: 22 additions & 2 deletions src/plugins/d3/renderer/hooks/useShapes/bar-x.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {max, pointer, select} from 'd3';
import {ascending, descending, max, pointer, select, sort} from 'd3';
import type {ScaleBand, ScaleLinear, ScaleTime} from 'd3';
import React from 'react';
import get from 'lodash/get';
Expand Down Expand Up @@ -61,6 +61,22 @@ function prepareData(args: {
const barPadding = get(seriesOptions, 'bar-x.barPadding', defaultBarPadding);
const groupPadding = get(seriesOptions, 'bar-x.groupPadding', defaultGroupPadding);

const sortingOptions = get(seriesOptions, 'bar-x.dataSorting');
const comparator = sortingOptions?.direction === 'desc' ? descending : ascending;
const sortKey = (() => {
switch (sortingOptions?.key) {
case 'y': {
return 'data.y';
}
case 'name': {
return 'series.name';
}
default: {
return undefined;
}
}
})();

const data: Record<
string | number,
Record<string, {data: BarXSeriesData; series: PreparedBarXSeries}[]>
Expand Down Expand Up @@ -123,7 +139,11 @@ function prepareData(args: {
const currentGroupWidth = rectWidth * stacks.length + rectGap * (stacks.length - 1);
stacks.forEach((yValues, groupItemIndex) => {
let stackHeight = 0;
yValues.forEach((yValue) => {

const sortedData = sortKey
? sort(yValues, (a, b) => comparator(get(a, sortKey), get(b, sortKey)))
: yValues;
sortedData.forEach((yValue) => {
let xCenter;
if (xAxis.type === 'category') {
const xBandScale = xScale as ScaleBand<string>;
Expand Down
15 changes: 15 additions & 0 deletions src/types/widget-data/series.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,20 @@ export type ChartKitWidgetSeriesOptions = {
* @default 0.2
*/
groupPadding?: number;

dataSorting?: {
/** Determines what data value should be used to sort by.
* Possible values are undefined to disable, "name" to sort by series name or "y"
*
* @default undefined
* */
key?: 'name' | 'y' | undefined;

/** Sorting direction.
*
* @default 'asc'
* */
direction?: 'asc' | 'desc';
};
};
};