Skip to content

Commit

Permalink
[@mantine/charts] DonutChart: Fix valueFormatter prop not working, …
Browse files Browse the repository at this point in the history
…add `labelsType` prop support (#7153)

* [DonutChart] Add render label function

* remove export

* prettier --write
  • Loading branch information
me-gusta-v authored Nov 24, 2024
1 parent 931565c commit d2c0f1b
Showing 1 changed file with 41 additions and 9 deletions.
50 changes: 41 additions & 9 deletions packages/@mantine/charts/src/DonutChart/DonutChart.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
Cell,
Pie,
PieLabel,
PieProps,
PieChart as ReChartsPieChart,
ResponsiveContainer,
Expand Down Expand Up @@ -98,6 +99,9 @@ export interface DonutChartProps
/** Props passed down to recharts `PieChart` component */
pieChartProps?: React.ComponentPropsWithoutRef<typeof ReChartsPieChart>;

/** Type of labels to display, `'value'` by default */
labelsType?: 'value' | 'percent';

/** A function to format values inside the tooltip */
valueFormatter?: (value: number) => string;
}
Expand All @@ -118,6 +122,7 @@ const defaultProps: Partial<DonutChartProps> = {
strokeWidth: 1,
startAngle: 0,
endAngle: 360,
labelsType: 'value',
tooltipDataSource: 'all',
};

Expand All @@ -131,6 +136,40 @@ const varsResolver = createVarsResolver<DonutChartFactory>(
})
);

const getLabelValue = (
labelsType: DonutChartProps['labelsType'],
value: number,
percent: number,
valueFormatter?: DonutChartProps['valueFormatter']
) => {
if (labelsType === 'percent') {
return `${(percent * 100).toFixed(0)}%`;
}

if (typeof valueFormatter === 'function') {
return valueFormatter(value);
}

return value;
};

const getLabel =
(labelsType: 'value' | 'percent', valueFormatter?: DonutChartProps['valueFormatter']): PieLabel =>
({ x, y, cx, cy, percent, value }) => (
<text
x={x}
y={y}
cx={cx}
cy={cy}
textAnchor={x > cx ? 'start' : 'end'}
fill="var(--chart-labels-color, var(--mantine-color-dimmed))"
fontFamily="var(--mantine-font-family)"
fontSize={12}
>
<tspan x={x}>{getLabelValue(labelsType, value, percent, valueFormatter)}</tspan>
</text>
);

export const DonutChart = factory<DonutChartFactory>((_props, ref) => {
const props = useProps('DonutChart', defaultProps, _props);
const {
Expand Down Expand Up @@ -159,6 +198,7 @@ export const DonutChart = factory<DonutChartFactory>((_props, ref) => {
pieChartProps,
valueFormatter,
strokeColor,
labelsType,
...others
} = props;

Expand Down Expand Up @@ -205,15 +245,7 @@ export const DonutChart = factory<DonutChartFactory>((_props, ref) => {
paddingAngle={paddingAngle}
startAngle={startAngle}
endAngle={endAngle}
label={
withLabels
? {
fill: 'var(--chart-labels-color, var(--mantine-color-dimmed))',
fontSize: 12,
fontFamily: 'var(--mantine-font-family)',
}
: false
}
label={withLabels ? getLabel(labelsType || 'value', valueFormatter) : false}
labelLine={
withLabelsLine
? {
Expand Down

0 comments on commit d2c0f1b

Please sign in to comment.