-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
BarPlot.tsx
363 lines (325 loc) · 10.9 KB
/
BarPlot.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { useTransition } from '@react-spring/web';
import { useCartesianContext } from '../context/CartesianProvider';
import { BarElement, BarElementSlotProps, BarElementSlots } from './BarElement';
import { AxisDefaultized } from '../models/axis';
import { BarItemIdentifier } from '../models';
import getColor from './getColor';
import { useChartId, useDrawingArea } from '../hooks';
import { AnimationData, CompletedBarData, MaskData } from './types';
import { BarClipPath } from './BarClipPath';
import { BarLabelItemProps, BarLabelSlotProps, BarLabelSlots } from './BarLabel/BarLabelItem';
import { BarLabelPlot } from './BarLabel/BarLabelPlot';
import { checkScaleErrors } from './checkScaleErrors';
import { useBarSeries } from '../hooks/useSeries';
import { SeriesFormatterResult } from '../context/PluginProvider';
import { useSkipAnimation } from '../context/AnimationProvider';
/**
* Solution of the equations
* W = barWidth * N + offset * (N-1)
* offset / (offset + barWidth) = r
* @param bandWidth The width available to place bars.
* @param numberOfGroups The number of bars to place in that space.
* @param gapRatio The ratio of the gap between bars over the bar width.
* @returns The bar width and the offset between bars.
*/
function getBandSize({
bandWidth: W,
numberOfGroups: N,
gapRatio: r,
}: {
bandWidth: number;
numberOfGroups: number;
gapRatio: number;
}) {
if (r === 0) {
return {
barWidth: W / N,
offset: 0,
};
}
const barWidth = W / (N + (N - 1) * r);
const offset = r * barWidth;
return {
barWidth,
offset,
};
}
export interface BarPlotSlots extends BarElementSlots, BarLabelSlots {}
export interface BarPlotSlotProps extends BarElementSlotProps, BarLabelSlotProps {}
export interface BarPlotProps extends Pick<BarLabelItemProps, 'barLabel'> {
/**
* If `true`, animations are skipped.
* @default undefined
*/
skipAnimation?: boolean;
/**
* Callback fired when a bar item is clicked.
* @param {React.MouseEvent<SVGElement, MouseEvent>} event The event source of the callback.
* @param {BarItemIdentifier} barItemIdentifier The bar item identifier.
*/
onItemClick?: (
event: React.MouseEvent<SVGElement, MouseEvent>,
barItemIdentifier: BarItemIdentifier,
) => void;
/**
* Defines the border radius of the bar element.
*/
borderRadius?: number;
/**
* The props used for each component slot.
* @default {}
*/
slotProps?: BarPlotSlotProps;
/**
* Overridable component slots.
* @default {}
*/
slots?: BarPlotSlots;
}
const useAggregatedData = (): {
completedData: CompletedBarData[];
masksData: MaskData[];
} => {
const seriesData =
useBarSeries() ??
({ series: {}, stackingGroups: [], seriesOrder: [] } as SeriesFormatterResult<'bar'>);
const axisData = useCartesianContext();
const drawingArea = useDrawingArea();
const chartId = useChartId();
const { series, stackingGroups } = seriesData;
const { xAxis, yAxis, xAxisIds, yAxisIds } = axisData;
const defaultXAxisId = xAxisIds[0];
const defaultYAxisId = yAxisIds[0];
const masks: Record<string, MaskData> = {};
const data = stackingGroups.flatMap(({ ids: groupIds }, groupIndex) => {
const xMin = drawingArea.left;
const xMax = drawingArea.left + drawingArea.width;
const yMin = drawingArea.top;
const yMax = drawingArea.top + drawingArea.height;
return groupIds.flatMap((seriesId) => {
const xAxisId = series[seriesId].xAxisId ?? defaultXAxisId;
const yAxisId = series[seriesId].yAxisId ?? defaultYAxisId;
const xAxisConfig = xAxis[xAxisId];
const yAxisConfig = yAxis[yAxisId];
const verticalLayout = series[seriesId].layout === 'vertical';
checkScaleErrors(verticalLayout, seriesId, xAxisId, xAxis, yAxisId, yAxis);
const baseScaleConfig = (
verticalLayout ? xAxisConfig : yAxisConfig
) as AxisDefaultized<'band'>;
const xScale = xAxisConfig.scale;
const yScale = yAxisConfig.scale;
const colorGetter = getColor(series[seriesId], xAxis[xAxisId], yAxis[yAxisId]);
const bandWidth = baseScaleConfig.scale.bandwidth();
const { barWidth, offset } = getBandSize({
bandWidth,
numberOfGroups: stackingGroups.length,
gapRatio: baseScaleConfig.barGapRatio,
});
const barOffset = groupIndex * (barWidth + offset);
const { stackedData } = series[seriesId];
return stackedData
.map((values, dataIndex: number) => {
const valueCoordinates = values.map((v) => (verticalLayout ? yScale(v)! : xScale(v)!));
const minValueCoord = Math.round(Math.min(...valueCoordinates));
const maxValueCoord = Math.round(Math.max(...valueCoordinates));
const stackId = series[seriesId].stack;
const result = {
seriesId,
dataIndex,
layout: series[seriesId].layout,
x: verticalLayout
? xScale(xAxis[xAxisId].data?.[dataIndex])! + barOffset
: minValueCoord,
y: verticalLayout
? minValueCoord
: yScale(yAxis[yAxisId].data?.[dataIndex])! + barOffset,
xOrigin: xScale(0)!,
yOrigin: yScale(0)!,
height: verticalLayout ? maxValueCoord - minValueCoord : barWidth,
width: verticalLayout ? barWidth : maxValueCoord - minValueCoord,
color: colorGetter(dataIndex),
value: series[seriesId].data[dataIndex],
maskId: `${chartId}_${stackId || seriesId}_${groupIndex}_${dataIndex}`,
};
if (
result.x > xMax ||
result.x + result.width < xMin ||
result.y > yMax ||
result.y + result.height < yMin
) {
return null;
}
if (!masks[result.maskId]) {
masks[result.maskId] = {
id: result.maskId,
width: 0,
height: 0,
hasNegative: false,
hasPositive: false,
layout: result.layout,
xOrigin: xScale(0)!,
yOrigin: yScale(0)!,
x: 0,
y: 0,
};
}
const mask = masks[result.maskId];
mask.width = result.layout === 'vertical' ? result.width : mask.width + result.width;
mask.height = result.layout === 'vertical' ? mask.height + result.height : result.height;
mask.x = Math.min(mask.x === 0 ? Infinity : mask.x, result.x);
mask.y = Math.min(mask.y === 0 ? Infinity : mask.y, result.y);
mask.hasNegative = mask.hasNegative || (result.value ?? 0) < 0;
mask.hasPositive = mask.hasPositive || (result.value ?? 0) > 0;
return result;
})
.filter((rectangle) => rectangle !== null);
});
});
return {
completedData: data,
masksData: Object.values(masks),
};
};
const leaveStyle = ({ layout, yOrigin, x, width, y, xOrigin, height }: AnimationData) => ({
...(layout === 'vertical'
? {
y: yOrigin,
x,
height: 0,
width,
}
: {
y,
x: xOrigin,
height,
width: 0,
}),
});
const enterStyle = ({ x, width, y, height }: AnimationData) => ({
y,
x,
height,
width,
});
/**
* Demos:
*
* - [Bars](https://mui.com/x/react-charts/bars/)
* - [Bar demonstration](https://mui.com/x/react-charts/bar-demo/)
* - [Stacking](https://mui.com/x/react-charts/stacking/)
*
* API:
*
* - [BarPlot API](https://mui.com/x/api/charts/bar-plot/)
*/
function BarPlot(props: BarPlotProps) {
const { completedData, masksData } = useAggregatedData();
const { skipAnimation: inSkipAnimation, onItemClick, borderRadius, barLabel, ...other } = props;
const skipAnimation = useSkipAnimation(inSkipAnimation);
const withoutBorderRadius = !borderRadius || borderRadius <= 0;
const transition = useTransition(completedData, {
keys: (bar) => `${bar.seriesId}-${bar.dataIndex}`,
from: leaveStyle,
leave: leaveStyle,
enter: enterStyle,
update: enterStyle,
immediate: skipAnimation,
});
const maskTransition = useTransition(withoutBorderRadius ? [] : masksData, {
keys: (v) => v.id,
from: leaveStyle,
leave: leaveStyle,
enter: enterStyle,
update: enterStyle,
immediate: skipAnimation,
});
return (
<React.Fragment>
{!withoutBorderRadius &&
maskTransition((style, { id, hasPositive, hasNegative, layout }) => {
return (
<BarClipPath
maskId={id}
borderRadius={borderRadius}
hasNegative={hasNegative}
hasPositive={hasPositive}
layout={layout}
style={style}
/>
);
})}
{transition((style, { seriesId, dataIndex, color, maskId }) => {
const barElement = (
<BarElement
id={seriesId}
dataIndex={dataIndex}
color={color}
{...other}
onClick={
onItemClick &&
((event) => {
onItemClick(event, { type: 'bar', seriesId, dataIndex });
})
}
style={style}
/>
);
if (withoutBorderRadius) {
return barElement;
}
return <g clipPath={`url(#${maskId})`}>{barElement}</g>;
})}
{barLabel && (
<BarLabelPlot
bars={completedData}
skipAnimation={skipAnimation}
barLabel={barLabel}
{...other}
/>
)}
</React.Fragment>
);
}
BarPlot.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the TypeScript types and run "pnpm proptypes" |
// ----------------------------------------------------------------------
/**
* If provided, the function will be used to format the label of the bar.
* It can be set to 'value' to display the current value.
* @param {BarItem} item The item to format.
* @param {BarLabelContext} context data about the bar.
* @returns {string} The formatted label.
*/
barLabel: PropTypes.oneOfType([PropTypes.oneOf(['value']), PropTypes.func]),
/**
* Defines the border radius of the bar element.
*/
borderRadius: PropTypes.number,
/**
* Callback fired when a bar item is clicked.
* @param {React.MouseEvent<SVGElement, MouseEvent>} event The event source of the callback.
* @param {BarItemIdentifier} barItemIdentifier The bar item identifier.
*/
onItemClick: PropTypes.func,
/**
* If `true`, animations are skipped.
* @default undefined
*/
skipAnimation: PropTypes.bool,
/**
* The props used for each component slot.
* @default {}
*/
slotProps: PropTypes.object,
/**
* Overridable component slots.
* @default {}
*/
slots: PropTypes.object,
} as any;
export { BarPlot };