@spaced-out/ui-design-system
Version:
Sense UI components library
120 lines (111 loc) • 3.53 kB
Flow
// @flow strict
import type {ChartOptions, LegendOptionsType} from '../../types/charts';
import {commonChartOptions} from './charts';
import {deepMerge} from './helpers';
type DonutChartPropsType = {
legend?: LegendOptionsType,
defaultCenterHTML?: string,
};
/**
* Defining these constants here so that internal calculations are self explanatory.
*/
const INNER_SIZE = 0.5; // set .5 here for 50% inner size w.r.t the pie chart outer circle.
const LEGEND_WIDTH = 0.4; // set .4 here for 40% legend width w.r.t the plot width.
const CHART_WIDTH = 1 - LEGEND_WIDTH;
const CHART_CENTER = (1 - LEGEND_WIDTH) / 2;
const CHART_SIZE = 0.8; // chart size w.r.t area allocated to chart drawing;
export const rightLegendColumn = {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
itemMarginBottom: 12,
symbolPadding: 8,
symbolWidth: 8,
// take it as 10% of width as left margin
width: `${LEGEND_WIDTH * 90}%`,
};
/**
* This function modifies the the common chart behavior to donut chart default behavior.
* It will not take userPassed option into account.
*/
export const getDonutChartOptions = ({
legend,
defaultCenterHTML,
}: DonutChartPropsType): ChartOptions => {
const legendOption = deepMerge(commonChartOptions.legend, legend);
const isLegendEnabled = legendOption.enabled;
return {
...commonChartOptions,
chart: {
...commonChartOptions.chart,
type: 'pie',
spacing: [0, 0, 0, 0],
margin: [0, 0, 0, 0],
events: {
render() {
//$FlowFixMe[object-this-reference]
const chart = this;
const containerWidth = chart.renderTo.offsetWidth;
const desiredHeight = CHART_WIDTH * containerWidth;
// 5px adjustment required due to borderWidth mostly.
const centerTextX = isLegendEnabled
? parseInt(chart.plotWidth) * CHART_CENTER + 5
: 0;
chart.update(
{
chart: {
height: desiredHeight, // Set the height dynamically based on the container's width
},
subtitle: {
x: centerTextX,
},
},
false,
);
},
},
},
legend: {
...legendOption,
...rightLegendColumn,
},
plotOptions: {
pie: {
innerSize: `${INNER_SIZE * 100}%`,
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
// auto disabling the data label when legend is enabled.
enabled: !isLegendEnabled,
distance: 20,
},
showInLegend: true,
center: isLegendEnabled
? [`${CHART_CENTER * 100}%`, '50%']
: ['50%', '50%'],
size: `${CHART_SIZE * 100}%`,
borderWidth: 5,
borderRadius: 10,
minSize: 240,
clip: false,
},
},
subtitle: {
useHTML: true,
text: defaultCenterHTML,
verticalAlign: 'middle',
align: isLegendEnabled ? 'left' : 'center',
style: {
alignContent: 'center',
// Note: Width was not working, have given miWidth and maxWidth
minWidth: isLegendEnabled
? `${CHART_WIDTH * CHART_SIZE * INNER_SIZE * 80}%`
: `${CHART_SIZE * INNER_SIZE * 80}%`,
maxWidth: isLegendEnabled
? `${CHART_WIDTH * CHART_SIZE * INNER_SIZE * 80}%`
: `${CHART_SIZE * INNER_SIZE * 80}%`,
...(isLegendEnabled ? {transform: 'translate(-50%)'} : {}),
},
},
};
};