1
1
import {
2
2
Cell ,
3
3
Pie ,
4
+ PieLabel ,
4
5
PieProps ,
5
6
PieChart as ReChartsPieChart ,
6
7
ResponsiveContainer ,
@@ -98,6 +99,9 @@ export interface DonutChartProps
98
99
/** Props passed down to recharts `PieChart` component */
99
100
pieChartProps ?: React . ComponentPropsWithoutRef < typeof ReChartsPieChart > ;
100
101
102
+ /** Type of labels to display, `'value'` by default */
103
+ labelsType ?: 'value' | 'percent' ;
104
+
101
105
/** A function to format values inside the tooltip */
102
106
valueFormatter ?: ( value : number ) => string ;
103
107
}
@@ -118,6 +122,7 @@ const defaultProps: Partial<DonutChartProps> = {
118
122
strokeWidth : 1 ,
119
123
startAngle : 0 ,
120
124
endAngle : 360 ,
125
+ labelsType : 'value' ,
121
126
tooltipDataSource : 'all' ,
122
127
} ;
123
128
@@ -131,6 +136,40 @@ const varsResolver = createVarsResolver<DonutChartFactory>(
131
136
} )
132
137
) ;
133
138
139
+ const getLabelValue = (
140
+ labelsType : DonutChartProps [ 'labelsType' ] ,
141
+ value : number ,
142
+ percent : number ,
143
+ valueFormatter ?: DonutChartProps [ 'valueFormatter' ]
144
+ ) => {
145
+ if ( labelsType === 'percent' ) {
146
+ return `${ ( percent * 100 ) . toFixed ( 0 ) } %` ;
147
+ }
148
+
149
+ if ( typeof valueFormatter === 'function' ) {
150
+ return valueFormatter ( value ) ;
151
+ }
152
+
153
+ return value ;
154
+ } ;
155
+
156
+ const getLabel =
157
+ ( labelsType : 'value' | 'percent' , valueFormatter ?: DonutChartProps [ 'valueFormatter' ] ) : PieLabel =>
158
+ ( { x, y, cx, cy, percent, value } ) => (
159
+ < text
160
+ x = { x }
161
+ y = { y }
162
+ cx = { cx }
163
+ cy = { cy }
164
+ textAnchor = { x > cx ? 'start' : 'end' }
165
+ fill = "var(--chart-labels-color, var(--mantine-color-dimmed))"
166
+ fontFamily = "var(--mantine-font-family)"
167
+ fontSize = { 12 }
168
+ >
169
+ < tspan x = { x } > { getLabelValue ( labelsType , value , percent , valueFormatter ) } </ tspan >
170
+ </ text >
171
+ ) ;
172
+
134
173
export const DonutChart = factory < DonutChartFactory > ( ( _props , ref ) => {
135
174
const props = useProps ( 'DonutChart' , defaultProps , _props ) ;
136
175
const {
@@ -159,6 +198,7 @@ export const DonutChart = factory<DonutChartFactory>((_props, ref) => {
159
198
pieChartProps,
160
199
valueFormatter,
161
200
strokeColor,
201
+ labelsType,
162
202
...others
163
203
} = props ;
164
204
@@ -205,15 +245,7 @@ export const DonutChart = factory<DonutChartFactory>((_props, ref) => {
205
245
paddingAngle = { paddingAngle }
206
246
startAngle = { startAngle }
207
247
endAngle = { endAngle }
208
- label = {
209
- withLabels
210
- ? {
211
- fill : 'var(--chart-labels-color, var(--mantine-color-dimmed))' ,
212
- fontSize : 12 ,
213
- fontFamily : 'var(--mantine-font-family)' ,
214
- }
215
- : false
216
- }
248
+ label = { withLabels ? getLabel ( labelsType || 'value' , valueFormatter ) : false }
217
249
labelLine = {
218
250
withLabelsLine
219
251
? {
0 commit comments