From 446b37405cc34f2a7b8e69b773f3d148678f3a56 Mon Sep 17 00:00:00 2001 From: Irina Kuzmina Date: Thu, 7 Sep 2023 18:29:47 +0300 Subject: [PATCH] feat(D3 plugin): add bar-x sorting setting (#282) --- .../d3/renderer/hooks/useShapes/bar-x.tsx | 24 +++++++++++++++++-- src/types/widget-data/series.ts | 15 ++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/plugins/d3/renderer/hooks/useShapes/bar-x.tsx b/src/plugins/d3/renderer/hooks/useShapes/bar-x.tsx index 4673a373..be30be7c 100644 --- a/src/plugins/d3/renderer/hooks/useShapes/bar-x.tsx +++ b/src/plugins/d3/renderer/hooks/useShapes/bar-x.tsx @@ -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'; @@ -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 @@ -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; diff --git a/src/types/widget-data/series.ts b/src/types/widget-data/series.ts index 53928517..31d35caf 100644 --- a/src/types/widget-data/series.ts +++ b/src/types/widget-data/series.ts @@ -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'; + }; }; };