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 basic bar chart #225

Merged
merged 5 commits into from
Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
154 changes: 154 additions & 0 deletions src/plugins/d3/__stories__/Bar.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import React from 'react';
import {Meta, Story} from '@storybook/react';
import {withKnobs} from '@storybook/addon-knobs';
import {Button} from '@gravity-ui/uikit';
import {settings} from '../../../libs';
import {ChartKit} from '../../../components/ChartKit';
import type {ChartKitRef} from '../../../types';
import type {ChartKitWidgetData} from '../../../types/widget-data';
import {D3Plugin} from '..';

const Template: Story = () => {
const [shown, setShown] = React.useState(false);
const chartkitRef = React.useRef<ChartKitRef>();
const chartBaseOptions = {
legend: {enabled: true},
tooltip: {enabled: false},
yAxis: [
{
type: 'linear',
labels: {enabled: true},
min: 0,
},
],
series: {
data: [
{
type: 'bar',
visible: true,
data: [
{
category: 'A',
x: 10,
y: 100,
},
{
category: 'B',
x: 12,
y: 80,
},
],
name: 'AB',
},
{
type: 'bar',
visible: true,
data: [
{
category: 'C',
x: 95.5,
y: 120,
},
],
name: 'C',
color: 'salmon',
},
],
},
};

const categoryXAxis = {
...chartBaseOptions,
title: {text: 'Category axis'},
xAxis: {
type: 'category',
categories: ['A', 'B', 'C'],
labels: {enabled: true},
},
} as ChartKitWidgetData;

const linearXAxis = {
...chartBaseOptions,
title: {text: 'Linear axis'},
xAxis: {
type: 'linear',
labels: {enabled: true},
},
} as ChartKitWidgetData;

const dateTimeXAxis = {
...chartBaseOptions,
title: {text: 'DateTime axis'},
xAxis: {
type: 'datetime',
labels: {enabled: true},
},
series: {
data: [
{
type: 'bar',
visible: true,
data: [
{
x: Number(new Date(2022, 10, 10)),
y: 100,
},
{
x: Number(new Date(2023, 2, 5)),
y: 80,
},
],
name: 'AB',
},
{
type: 'bar',
visible: true,
data: [
{
x: Number(new Date(2022, 11, 25)),
y: 120,
},
],
name: 'C',
color: 'salmon',
},
],
},
} as ChartKitWidgetData;

if (!shown) {
settings.set({plugins: [D3Plugin]});
return <Button onClick={() => setShown(true)}>Show chart</Button>;
}

return (
<div
style={{
height: '80vh',
width: '100%',
display: 'grid',
gridTemplateColumns: '50% auto',
gridColumnGap: '20px',
}}
>
<div>
<ChartKit ref={chartkitRef} type="d3" data={categoryXAxis} />
</div>
<div>
<ChartKit ref={chartkitRef} type="d3" data={linearXAxis} />
</div>
<div>
<ChartKit ref={chartkitRef} type="d3" data={dateTimeXAxis} />
</div>
</div>
);
};

export const Bar = Template.bind({});

const meta: Meta = {
title: 'Plugins/D3',
decorators: [withKnobs],
};

export default meta;
4 changes: 3 additions & 1 deletion src/plugins/d3/__stories__/LinearCategories.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,9 @@ const shapeScatterChartData = (
}

return {
series,
series: {
data: series,
},
xAxis,
yAxis: [yAxis],
title: {
Expand Down
4 changes: 3 additions & 1 deletion src/plugins/d3/__stories__/Timestamp.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ const shapeData = (data: Record<string, any>[]): ChartKitWidgetData<string> => {
};

return {
series: [scatterSeries],
series: {
data: [scatterSeries],
},
xAxis: {
type: 'datetime',
timestamps: data.map((d) => d.x),
Expand Down
6 changes: 3 additions & 3 deletions src/plugins/d3/renderer/components/Chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export const Chart = ({width, height, data}: Props) => {
// FIXME: add data validation
const {series} = data;
const svgRef = React.createRef<SVGSVGElement>();
const hasAxisRelatedSeries = series.some(isAxisRelatedSeries);
const hasAxisRelatedSeries = series.data.some(isAxisRelatedSeries);
const {chartHovered, handleMouseEnter, handleMouseLeave} = useChartEvents();
const {chart, legend, title, tooltip, xAxis, yAxis} = useChartOptions(data);
const {boundsWidth, boundsHeight, legendHeight} = useChartDimensions({
Expand All @@ -46,8 +46,8 @@ export const Chart = ({width, height, data}: Props) => {
xAxis,
yAxis,
});
const {activeLegendItems, handleLegendItemClick} = useLegend({series});
const {chartSeries} = useSeries({activeLegendItems, series});
const {activeLegendItems, handleLegendItemClick} = useLegend({series: series.data});
const {chartSeries} = useSeries({activeLegendItems, series: series.data});
const {xScale, yScale} = useScales({
boundsWidth,
boundsHeight,
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/d3/renderer/hooks/useChartOptions/chart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const getPreparedChart = (args: {
const marginLeft =
get(chart, 'margin.left', AXIS_WIDTH) +
preparedY1Axis.labels.padding +
getAxisLabelMaxWidth({axis: preparedY1Axis, series}) +
getAxisLabelMaxWidth({axis: preparedY1Axis, series: series.data}) +
(preparedY1Axis.title.height || 0);

return {
Expand Down
8 changes: 5 additions & 3 deletions src/plugins/d3/renderer/hooks/useChartOptions/legend.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import get from 'lodash/get';

import type {ChartKitWidgetData} from '../../../../../types/widget-data';

import type {PreparedLegend} from './types';
Expand All @@ -9,5 +7,9 @@ export const getPreparedLegend = (args: {
series: ChartKitWidgetData['series'];
}): PreparedLegend => {
const {legend, series} = args;
return {enabled: get(legend, 'enabled', true) && series.length > 1};
const enabled = legend?.enabled;

return {
enabled: typeof enabled === 'boolean' ? enabled : series.data.length > 1,
};
};
1 change: 1 addition & 0 deletions src/plugins/d3/renderer/hooks/useChartOptions/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export type PreparedAxis = Omit<ChartKitWidgetAxis, 'type' | 'labels'> & {
text: string;
style: BaseTextStyle;
};
min?: number;
};

export type PreparedTitle = ChartKitWidgetData['title'] & {
Expand Down
1 change: 1 addition & 0 deletions src/plugins/d3/renderer/hooks/useChartOptions/y-axis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export const getPreparedYAxis = ({yAxis}: {yAxis: ChartKitWidgetData['yAxis']}):
? getHorisontalSvgTextDimensions({text: y1TitleText, style: y1TitleStyle})
: 0,
},
min: get(yAxis1, 'min'),
};

return [preparedY1Axis];
Expand Down
21 changes: 13 additions & 8 deletions src/plugins/d3/renderer/hooks/useScales/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,11 @@ export const useScales = (args: Args): ReturnValue => {
const {boundsWidth, boundsHeight, series, xAxis, yAxis} = args;
const scales = React.useMemo(() => {
const xType = get(xAxis, 'type', 'linear');
const xCatigories = get(xAxis, 'categories');
const xCategories = get(xAxis, 'categories');
const xTimestamps = get(xAxis, 'timestamps');
const yType = get(yAxis[0], 'type', 'linear');
const yCatigories = get(yAxis[0], 'categories');
const yMin = get(yAxis[0], 'min');
const yCategories = get(yAxis[0], 'categories');
const yTimestamps = get(xAxis, 'timestamps');
let visibleSeries = getOnlyVisibleSeries(series);
// Reassign to all series in case of all series unselected,
Expand All @@ -66,9 +67,9 @@ export const useScales = (args: Args): ReturnValue => {
break;
}
case 'category': {
if (xCatigories) {
if (xCategories) {
const filteredCategories = filterCategoriesByVisibleSeries(
xCatigories,
xCategories,
visibleSeries,
);
xScale = scaleBand().domain(filteredCategories).range([0, boundsWidth]);
Expand Down Expand Up @@ -102,16 +103,20 @@ export const useScales = (args: Args): ReturnValue => {
const domain = getDomainDataYBySeries(visibleSeries);

if (isNumericalArrayData(domain)) {
const [yMin, yMax] = extent(domain) as [number, number];
yScale = scaleLinear().domain([yMin, yMax]).range([boundsHeight, 0]).nice();
const [domainYMin, yMax] = extent(domain) as [number, number];
const yMinValue = typeof yMin === 'number' ? yMin : domainYMin;
yScale = scaleLinear()
.domain([yMinValue, yMax])
.range([boundsHeight, 0])
.nice();
}

break;
}
case 'category': {
if (yCatigories) {
if (yCategories) {
const filteredCategories = filterCategoriesByVisibleSeries(
yCatigories,
yCategories,
visibleSeries,
);
yScale = scaleBand().domain(filteredCategories).range([boundsHeight, 0]);
Expand Down
Loading