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): axis labels rotation(X axis) #309

Merged
merged 9 commits into from
Sep 26, 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
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import React from 'react';
import {StoryObj} from '@storybook/react';
import {withKnobs} from '@storybook/addon-knobs';
import {Button} from '@gravity-ui/uikit';
import {settings} from '../../../libs';
import {D3Plugin} from '..';
import {settings} from '../../../../libs';
import {D3Plugin} from '../..';
import {
BasicBarXChart,
BasicLinearBarXChart,
BasicDateTimeBarXChart,
} from '../examples/bar-x/Basic';
import {GroupedColumns} from '../examples/bar-x/GroupedColumns';
import {StackedColumns} from '../examples/bar-x/StackedColumns';
} from '../../examples/bar-x/Basic';
import {GroupedColumns} from '../../examples/bar-x/GroupedColumns';
import {StackedColumns} from '../../examples/bar-x/StackedColumns';

const ChartStory = ({Chart}: {Chart: React.FC}) => {
const [shown, setShown] = React.useState(false);
Expand Down
78 changes: 78 additions & 0 deletions src/plugins/d3/__stories__/bar-x/Playground.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import React from 'react';
import {StoryObj} from '@storybook/react';
import {Button} from '@gravity-ui/uikit';
import {settings} from '../../../../libs';
import {D3Plugin} from '../..';
import {ChartKitWidgetData} from '../../../../types';
import {ChartKit} from '../../../../components/ChartKit';
import {groups} from 'd3';
import nintendoGames from '../../examples/nintendoGames';

function prepareData(): ChartKitWidgetData {
const gamesByPlatform = groups(nintendoGames, (item) => item['platform']);
const data = gamesByPlatform.map(([value, games]) => ({
x: value,
y: games.length,
}));

return {
series: {
data: [
{
type: 'bar-x',
data,
name: 'Games released',
},
],
},
xAxis: {
type: 'category',
categories: gamesByPlatform.map(([key]) => key),
title: {
text: 'Game Platforms',
},
labels: {
enabled: true,
rotation: 30,
},
},
yAxis: [{title: {text: 'Number of games released'}}],
};
}

const ChartStory = ({data}: {data: ChartKitWidgetData}) => {
const [shown, setShown] = React.useState(false);

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

return (
<div
style={{
height: '80vh',
width: '100%',
}}
>
<ChartKit type="d3" data={data} />
</div>
);
};

export const PlaygroundBarXChartStory: StoryObj<typeof ChartStory> = {
name: 'Playground',
args: {
data: prepareData(),
},
argTypes: {
data: {
control: 'object',
},
},
};

export default {
title: 'Plugins/D3/Bar-X',
component: ChartStory,
};
1 change: 1 addition & 0 deletions src/plugins/d3/examples/bar-x/Basic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export const BasicBarXChart = () => {
text: 'Game Platforms',
},
},
yAxis: [{title: {text: 'Number of games released'}}],
};

return <ChartKit type="d3" data={widgetData} />;
Expand Down
13 changes: 5 additions & 8 deletions src/plugins/d3/renderer/components/AxisX.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export const AxisX = React.memo(({axis, width, height, scale}: Props) => {
labelsStyle: axis.labels.style,
count: getTicksCount({axis, range: width}),
maxTickCount: getMaxTickCount({axis, width}),
autoRotation: axis.labels.autoRotation,
rotation: axis.labels.rotation,
},
domain: {
size: width,
Expand All @@ -70,22 +70,19 @@ export const AxisX = React.memo(({axis, width, height, scale}: Props) => {
const svgElement = select(ref.current);
svgElement.selectAll('*').remove();

svgElement
.call(xAxisGenerator)
.attr('class', b())
.style('font-size', axis.labels.style.fontSize);
svgElement.call(xAxisGenerator).attr('class', b());

// add an axis header if necessary
if (axis.title.text) {
const textY =
axis.title.height + parseInt(axis.labels.style.fontSize) + axis.labels.padding;
const y =
axis.title.height + axis.title.margin + axis.labels.height + axis.labels.margin;

svgElement
.append('text')
.attr('class', b('title'))
.attr('text-anchor', 'middle')
.attr('x', width / 2)
.attr('y', textY)
.attr('y', y)
.attr('font-size', axis.title.style.fontSize)
.text(axis.title.text)
.call(setEllipsisForOverflowText, width);
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/d3/renderer/components/AxisY.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export const AxisY = ({axises, width, height, scale}: Props) => {
.remove();

if (axis.title.text) {
const textY = axis.title.height + axis.labels.margin;
const textY = axis.title.margin + axis.labels.margin + axis.labels.width;

svgElement
.append('text')
Expand Down
20 changes: 18 additions & 2 deletions src/plugins/d3/renderer/components/Chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ import {AxisX} from './AxisX';
import {Legend} from './Legend';
import {Title} from './Title';
import {Tooltip, TooltipTriggerArea} from './Tooltip';
import {getPreparedXAxis} from '../hooks/useChartOptions/x-axis';
import {getWidthOccupiedByYAxis} from '../hooks/useChartDimensions/utils';
import {getPreparedYAxis} from '../hooks/useChartOptions/y-axis';

import './styles.scss';

Expand All @@ -37,9 +40,19 @@ export const Chart = (props: Props) => {
const dispatcher = React.useMemo(() => {
return getD3Dispatcher();
}, []);
const {chart, title, tooltip, xAxis, yAxis} = useChartOptions({
const {chart, title, tooltip} = useChartOptions({
data,
});
const xAxis = React.useMemo(
() => getPreparedXAxis({xAxis: data.xAxis, width, series: data.series.data}),
[data, width],
);

const yAxis = React.useMemo(
() => getPreparedYAxis({series: data.series.data, yAxis: data.yAxis}),
[data, width],
);

const {
legendItems,
legendConfig,
Expand Down Expand Up @@ -87,14 +100,17 @@ export const Chart = (props: Props) => {
svgContainer: svgRef.current,
});

const boundsOffsetTop = chart.margin.top;
const boundsOffsetLeft = chart.margin.left + getWidthOccupiedByYAxis({preparedAxis: yAxis});

return (
<React.Fragment>
<svg ref={svgRef} className={b()} width={width} height={height}>
{title && <Title {...title} chartWidth={width} />}
<g
width={boundsWidth}
height={boundsHeight}
transform={`translate(${[chart.margin.left, chart.margin.top].join(',')})`}
transform={`translate(${[boundsOffsetLeft, boundsOffsetTop].join(',')})`}
>
{xScale && yScale && (
<React.Fragment>
Expand Down
52 changes: 26 additions & 26 deletions src/plugins/d3/renderer/components/Legend.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ const appendPaginator = (args: {
const {container, offset, maxPage, legend, transform, onArrowClick} = args;
const paginationLine = container.append('g').attr('class', b('pagination'));
let computedWidth = 0;

paginationLine
.append('text')
.text('▲')
Expand Down Expand Up @@ -115,7 +116,6 @@ export const Legend = (props: Props) => {
? items.slice(paginationOffset * limit, paginationOffset * limit + limit)
: items;
pageItems.forEach((line, lineIndex) => {
const textWidths: number[] = [];
const legendLine = svgElement.append('g').attr('class', b('line'));
const legendItemTemplate = legendLine
.selectAll('legend-history')
Expand All @@ -125,23 +125,27 @@ export const Legend = (props: Props) => {
.attr('class', b('item'))
.on('click', function (e, d) {
onItemClick({name: d.name, metaKey: e.metaKey});
})
.each(function (d) {
textWidths.push(d.textWidth);
});
legendItemTemplate
.append('rect')
.attr('x', function (legendItem, i) {

const getXPosition = (i: number) => {
return line.slice(0, i).reduce((acc, legendItem) => {
return (
i * legendItem.symbol.width +
i * legend.itemDistance +
i * legendItem.symbol.padding +
textWidths.slice(0, i).reduce((acc, tw) => acc + tw, 0)
acc +
legendItem.symbol.width +
legendItem.symbol.padding +
legendItem.textWidth +
legend.itemDistance
);
}, 0);
};

legendItemTemplate
.append('rect')
.attr('x', function (_d, i) {
return getXPosition(i);
})
.attr('y', (legendItem) => {
const lineOffset = legend.lineHeight * lineIndex;
return config.offset.top + lineOffset - legendItem.symbol.height / 2;
return (legend.lineHeight - legendItem.symbol.height) / 2;
})
.attr('width', (legendItem) => {
return legendItem.symbol.width;
Expand All @@ -154,28 +158,21 @@ export const Legend = (props: Props) => {
.style('fill', function (d) {
return d.visible ? d.color : '';
});

legendItemTemplate
.append('text')
.attr('x', function (legendItem, i) {
return (
i * legendItem.symbol.width +
i * legend.itemDistance +
i * legendItem.symbol.padding +
legendItem.symbol.width +
legendItem.symbol.padding +
textWidths.slice(0, i).reduce((acc, tw) => acc + tw, 0)
);
return getXPosition(i) + legendItem.symbol.width + legendItem.symbol.padding;
})
.attr('y', config.offset.top + legend.lineHeight * lineIndex)
.attr('height', legend.lineHeight)
.attr('class', function (d) {
const mods = {selected: d.visible, unselected: !d.visible};
return b('item-text', mods);
})
.text(function (d) {
return ('name' in d && d.name) as string;
})
.style('font-size', legend.itemStyle.fontSize)
.style('alignment-baseline', 'middle');
.style('font-size', legend.itemStyle.fontSize);

const contentWidth = legendLine.node()?.getBoundingClientRect().width || 0;
const {left} = getLegendPosition({
Expand All @@ -184,14 +181,17 @@ export const Legend = (props: Props) => {
offsetWidth: config.offset.left,
contentWidth,
});
const top = config.offset.top + legend.lineHeight * lineIndex;

legendLine.attr('transform', `translate(${[left, 0].join(',')})`);
legendLine.attr('transform', `translate(${[left, top].join(',')})`);
});

if (config.pagination) {
const transform = `translate(${[
config.offset.left,
config.offset.top + legend.lineHeight * config.pagination.limit,
config.offset.top +
legend.lineHeight * config.pagination.limit +
legend.lineHeight / 2,
].join(',')})`;
appendPaginator({
container: svgElement,
Expand Down
2 changes: 2 additions & 0 deletions src/plugins/d3/renderer/components/styles.scss
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
}

&__title {
alignment-baseline: after-edge;
fill: var(--g-color-text-secondary);
}
}
Expand All @@ -32,6 +33,7 @@

&__item-text {
fill: var(--g-color-text-secondary);
alignment-baseline: before-edge;

&_unselected {
fill: var(--g-color-text-hint);
Expand Down
14 changes: 14 additions & 0 deletions src/plugins/d3/renderer/constants/defaults/axis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,17 @@ export const axisLabelsDefaults = {
padding: 10,
fontSize: 11,
};

const axisTitleDefaults = {
fontSize: '14px',
};

export const xAxisTitleDefaults = {
...axisTitleDefaults,
margin: 4,
};

export const yAxisTitleDefaults = {
...axisTitleDefaults,
margin: 8,
};
1 change: 0 additions & 1 deletion src/plugins/d3/renderer/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,3 @@ export const DEFAULT_PALETTE = [
];

export const DEFAULT_AXIS_LABEL_FONT_SIZE = '11px';
export const DEFAULT_AXIS_TITLE_FONT_SIZE = '14px';
Loading