Skip to content

Commit

Permalink
refactor: Use pie-charts provided by @mui/x-chart
Browse files Browse the repository at this point in the history
  • Loading branch information
tklein1801 committed Jan 30, 2024
1 parent ccc32d6 commit 4948e4a
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 0 deletions.
69 changes: 69 additions & 0 deletions src/components/Base/Charts/MuiPieChart.component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import React from 'react';
import { alpha, hexToRgb, useTheme } from '@mui/material';
import { PieChart, type PieValueType, type PieChartProps } from '@mui/x-charts';
import { type MakeOptional } from '@mui/x-date-pickers/internals/models/helpers';
import { PieCenterLabel } from './PieCenterLabel.component';
import { formatBalance } from '@/utils';

export type TMuiChartData = MakeOptional<PieValueType, 'id'>[];

export type TMuiChartProps = Omit<PieChartProps, 'series'> & {
data: TMuiChartData;
formatAsCurrency?: boolean;
showTotalSum?: boolean;
};

export const MuiPieChart: React.FC<TMuiChartProps> = ({
data,
formatAsCurrency = false,
showTotalSum = false,
...props
}) => {
const theme = useTheme();

const sum = React.useMemo(() => {
return data.reduce((acc, { value }) => acc + value, 0);
}, [data]);

const colorRange: string[] = React.useMemo(() => {
return data
.map((_, idx, arr) => {
return data.length > 1
? alpha(hexToRgb(theme.palette.primary.main), (1 / arr.length) * (idx + 1))
: alpha(hexToRgb(theme.palette.primary.main), 1);
})
.reverse();
}, [data]);

const formatNumber = React.useCallback(
(num: number) => {
return formatAsCurrency ? formatBalance(num) : num;
},
[formatAsCurrency]
);

return (
<PieChart
colors={colorRange}
series={[
{
type: 'pie',
data: data,
color: theme.palette.primary.main,
innerRadius: 100,
cornerRadius: 5,
arcLabel: (item) => `${item.label} ${formatNumber(item.value)}`,
arcLabelMinAngle: 10,
paddingAngle: 0.25,
sortingValues: (a, b) => b - a,
valueFormatter: ({ value }) => formatBalance(value),
},
]}
margin={{ right: 0 }}
slotProps={{ legend: { hidden: true } }}
{...props}
>
{showTotalSum && <PieCenterLabel>{formatNumber(sum)}</PieCenterLabel>}
</PieChart>
);
};
19 changes: 19 additions & 0 deletions src/components/Base/Charts/PieCenterLabel.component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { styled } from '@mui/material';
import { useDrawingArea } from '@mui/x-charts';

const StyledText = styled('text')(({ theme }) => ({
fill: theme.palette.text.primary,
textAnchor: 'middle',
fontWeight: 'bolder',
dominantBaseline: 'central',
fontSize: 28,
}));

export const PieCenterLabel: React.FC<React.PropsWithChildren> = ({ children }) => {
const { width, height, left, top } = useDrawingArea();
return (
<StyledText x={left + width / 2} y={top + height / 2}>
{children}
</StyledText>
);
};

0 comments on commit 4948e4a

Please sign in to comment.