Skip to content

Commit

Permalink
feat(D3 plugin): add bar-x sorting setting (#282)
Browse files Browse the repository at this point in the history
  • Loading branch information
kuzmadom authored Sep 7, 2023
1 parent 637a64e commit 446b374
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
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';
};
};
};

0 comments on commit 446b374

Please sign in to comment.