-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathBarChart.tsx
More file actions
394 lines (374 loc) · 14 KB
/
BarChart.tsx
File metadata and controls
394 lines (374 loc) · 14 KB
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
'use client';
import { enrichEventWithDetails, ThemingParameters, useIsRTL, useSyncRef } from '@ui5/webcomponents-react-base';
import type { CSSProperties } from 'react';
import { useRef, forwardRef, useCallback } from 'react';
import {
Bar,
BarChart as BarChartLib,
Brush,
CartesianGrid,
Cell,
LabelList,
Legend,
ReferenceLine,
Tooltip,
XAxis,
YAxis,
} from 'recharts';
import type { YAxisProps } from 'recharts';
import { useCancelAnimationFallback } from '../../hooks/useCancelAnimationFallback.js';
import { useChartMargin } from '../../hooks/useChartMargin.js';
import { useLabelFormatter } from '../../hooks/useLabelFormatter.js';
import { useLegendItemClick } from '../../hooks/useLegendItemClick.js';
import { useLongestYAxisLabelBar } from '../../hooks/useLongestYAxisLabelBar.js';
import { useObserveXAxisHeights } from '../../hooks/useObserveXAxisHeights.js';
import { useOnClickInternal } from '../../hooks/useOnClickInternal.js';
import { usePrepareDimensionsAndMeasures } from '../../hooks/usePrepareDimensionsAndMeasures.js';
import { useTooltipFormatter } from '../../hooks/useTooltipFormatter.js';
import type { ActivePayload, IChartBaseProps } from '../../interfaces/IChartBaseProps.js';
import type { IChartDimension } from '../../interfaces/IChartDimension.js';
import type { IChartMeasure } from '../../interfaces/IChartMeasure.js';
import { ChartContainer } from '../../internal/ChartContainer.js';
import { ChartDataLabel } from '../../internal/ChartDataLabel.js';
import { defaultFormatter } from '../../internal/defaults.js';
import { brushProps, tickLineConfig, tooltipContentStyle, tooltipFillOpacity } from '../../internal/staticProps.js';
import { getCellColors, resolvePrimaryAndSecondaryMeasures } from '../../internal/Utils.js';
import { XAxisTicks } from '../../internal/XAxisTicks.js';
import { YAxisTicks } from '../../internal/YAxisTicks.js';
import { BarChartPlaceholder } from './Placeholder.js';
const dimensionDefaults = {
formatter: defaultFormatter,
};
const measureDefaults = {
formatter: defaultFormatter,
opacity: 1,
};
interface MeasureConfig extends IChartMeasure {
/**
* Bar Width
* @default auto
*/
width?: number;
/**
* Bar Opacity
* @default 1
*/
opacity?: number;
/**
* Bar Stack ID
* @default undefined
*/
stackId?: string;
/**
* Highlight color of defined elements
* @param value {string | number} Current value of the highlighted measure
* @param measure {IChartMeasure} Current measure object
* @param dataElement {object} Current data element
*/
highlightColor?: (value: number, measure: MeasureConfig, dataElement: Record<string, any>) => CSSProperties['color'];
}
interface DimensionConfig extends IChartDimension {
/**
* Interval of dimension axis labels
*/
interval?: YAxisProps['interval'];
}
export interface BarChartProps extends IChartBaseProps {
/**
* An array of config objects. Each object will define one dimension of the chart.
*
* **Required Properties**
* - `accessor`: string containing the path to the dataset key the dimension should display. Supports object structures by using <code>'parent.child'</code>.
* Can also be a getter.
*
* **Optional Properties**
* - `formatter`: function will be called for each data label and allows you to format it according to your needs
* - `interval`: number that controls how many ticks are rendered on the x axis
*
*/
dimensions: DimensionConfig[];
/**
* An array of config objects. Each object is defining one bar in the chart.
*
* **Required properties**
* - `accessor`: string containing the path to the dataset key this bar should display. Supports object structures by using <code>'parent.child'</code>.
* Can also be a getter.
*
* **Optional properties**
*
* - `label`: Label to display in legends or tooltips. Falls back to the <code>accessor</code> if not present.
* - `color`: any valid CSS Color or CSS Variable. Defaults to the `sapChart_OrderedColor_` colors
* - `formatter`: function will be called for each data label and allows you to format it according to your needs
* - `hideDataLabel`: flag whether the data labels should be hidden in the chart for this bar.
* - `DataLabel`: a custom component to be used for the data label
* - `width`: bar width, defaults to `auto`
* - `opacity`: bar opacity, defaults to `1`
* - `stackId`: bars with the same stackId will be stacked
* - `highlightColor`: function will be called to define a custom color of a specific element which matches the
* defined condition. Overwrites code>color</code> of the element.
*
*/
measures: MeasureConfig[];
}
/**
* A `BarChart` is a data visualization where each category is represented by a rectangle, with the width of the rectangle being proportional to the values being plotted.
*/
const BarChart = forwardRef<HTMLDivElement, BarChartProps>((props, ref) => {
const {
loading,
loadingDelay,
dataset,
noLegend,
noAnimation,
tooltipConfig,
onDataPointClick,
onLegendClick,
onClick,
style,
className,
slot,
syncId,
ChartPlaceholder,
children,
...rest
} = props;
const chartConfig: BarChartProps['chartConfig'] = {
margin: {},
yAxisVisible: true,
xAxisVisible: true,
gridStroke: ThemingParameters.sapList_BorderColor,
gridHorizontal: true,
gridVertical: false,
legendPosition: 'bottom',
legendHorizontalAlign: 'left',
barGap: 3,
zoomingTool: false,
resizeDebounce: 250,
yAxisConfig: {},
xAxisConfig: {},
secondXAxisConfig: {},
...props.chartConfig,
};
const referenceLine = chartConfig.referenceLine;
const { dimensions, measures } = usePrepareDimensionsAndMeasures(
props.dimensions,
props.measures,
dimensionDefaults,
measureDefaults,
);
const tooltipValueFormatter = useTooltipFormatter(measures);
const primaryDimension = dimensions[0];
const { primaryMeasure, secondaryMeasure } = resolvePrimaryAndSecondaryMeasures(
measures,
chartConfig?.secondYAxis?.dataKey,
);
const dataKeys = measures.map(({ accessor }) => accessor);
const colorSecondY = chartConfig.secondYAxis
? dataKeys.findIndex((key) => key === chartConfig.secondYAxis?.dataKey)
: 0;
const [componentRef, chartRef] = useSyncRef<any>(ref);
const activePayloadsRef = useRef<ActivePayload[]>(measures);
const onItemLegendClick = useLegendItemClick(onLegendClick);
const tooltipLabelFormatter = useLabelFormatter(primaryDimension?.formatter);
const onDataPointClickInternal = useCallback(
(payload, i, event) => {
if (payload && onDataPointClick) {
const value = payload.value.length ? payload.value[1] - payload.value[0] : payload.value;
onDataPointClick(
enrichEventWithDetails(event, {
dataKey: Object.keys(payload)
.filter((key) => key !== 'value')
.find((key) => payload[key] === value),
value,
payload: payload.payload,
dataIndex: i,
}),
);
}
},
[onDataPointClick],
);
const onClickInternal = useOnClickInternal(onClick, dataset, activePayloadsRef);
const isBigDataSet = dataset?.length > 30;
const primaryDimensionAccessor = primaryDimension?.accessor;
const [width, legendPosition] = useLongestYAxisLabelBar(dataset, dimensions, chartConfig.legendPosition);
const marginChart = useChartMargin(chartConfig.margin, chartConfig.zoomingTool);
const [xAxisHeight] = useObserveXAxisHeights(chartRef, 1);
const isRTL = useIsRTL(chartRef);
const { isMounted, handleBarAnimationStart, handleBarAnimationEnd } = useCancelAnimationFallback(noAnimation);
const { chartConfig: _0, dimensions: _1, measures: _2, ...propsWithoutOmitted } = rest;
return (
<ChartContainer
dataset={dataset}
loading={loading}
loadingDelay={loadingDelay}
Placeholder={ChartPlaceholder ?? BarChartPlaceholder}
ref={componentRef}
style={style}
className={className}
slot={slot}
resizeDebounce={chartConfig.resizeDebounce}
{...propsWithoutOmitted}
>
<BarChartLib
syncId={syncId}
onClick={onClickInternal}
stackOffset="sign"
margin={marginChart}
layout="vertical"
data={dataset}
barGap={chartConfig.barGap}
accessibilityLayer={chartConfig.accessibilityLayer}
className={
typeof onDataPointClick === 'function' || typeof onClick === 'function' ? 'has-click-handler' : undefined
}
>
<CartesianGrid
vertical={chartConfig.gridVertical}
horizontal={chartConfig.gridHorizontal}
stroke={chartConfig.gridStroke}
/>
{chartConfig.xAxisVisible && (
<XAxis
interval={0}
type="number"
tick={<XAxisTicks formatter={primaryMeasure?.formatter} />}
axisLine={chartConfig.xAxisVisible}
tickLine={tickLineConfig}
height={xAxisHeight}
reversed={isRTL}
{...chartConfig.xAxisConfig}
/>
)}
{chartConfig.secondYAxis?.dataKey && (
<XAxis
dataKey={chartConfig.secondYAxis.dataKey}
axisLine={{
stroke: chartConfig.secondYAxis.color ?? `var(--sapChart_OrderedColor_${(colorSecondY % 12) + 1})`,
}}
tick={
<XAxisTicks
formatter={secondaryMeasure?.formatter}
secondYAxisConfig={{
color: chartConfig.secondYAxis.color ?? `var(--sapChart_OrderedColor_${(colorSecondY % 12) + 1})`,
}}
/>
}
tickLine={{
stroke: chartConfig.secondYAxis.color ?? `var(--sapChart_OrderedColor_${(colorSecondY % 12) + 1})`,
}}
label={{ value: chartConfig.secondYAxis.name, offset: 2, angle: +90, position: 'center' }}
orientation="top"
interval={0}
xAxisId="secondary"
type="number"
{...chartConfig.secondXAxisConfig}
/>
)}
{chartConfig.yAxisVisible &&
dimensions.map((dimension, index) => {
return (
<YAxis
interval={dimension?.interval ?? 'preserveStartEnd'}
minTickGap={isBigDataSet ? undefined : -10}
type="category"
key={dimension.reactKey}
dataKey={dimension.accessor}
tick={<YAxisTicks formatter={dimension?.formatter} />}
tickLine={index < 1}
axisLine={index < 1}
yAxisId={index}
width={width[index]}
allowDuplicatedCategory={index === 0}
orientation={isRTL ? 'right' : 'left'}
{...chartConfig.yAxisConfig}
/>
);
})}
{isMounted &&
measures.map((element, index) => {
const color = element.color ?? `var(--sapChart_OrderedColor_${(index % 12) + 1})`;
const dataKey = element.accessor;
const name = element.label ?? element.accessor;
const opacity = element.opacity ?? 1;
activePayloadsRef.current[index].color = color;
activePayloadsRef.current[index].stroke = color;
activePayloadsRef.current[index].dataKey = dataKey;
activePayloadsRef.current[index].hide = element.hide;
activePayloadsRef.current[index].name = name;
activePayloadsRef.current[index].fillOpacity = opacity;
activePayloadsRef.current[index].strokeOpacity = opacity;
return (
<Bar
key={element.reactKey}
fill={color}
stroke={color}
stackId={element.stackId}
name={name}
fillOpacity={element.opacity}
strokeOpacity={element.opacity}
type="monotone"
dataKey={dataKey}
barSize={element.width}
onClick={onDataPointClickInternal}
isAnimationActive={!noAnimation}
onAnimationStart={handleBarAnimationStart}
onAnimationEnd={handleBarAnimationEnd}
>
<LabelList
dataKey={element.accessor}
content={<ChartDataLabel config={element} chartType="bar" position={'insideRight'} />}
/>
{dataset.map((data, i) => {
return (
<Cell
key={i}
fill={getCellColors(element, data, index)}
stroke={getCellColors(element, data, index)}
/>
);
})}
</Bar>
);
})}
{!noLegend && (
<Legend
verticalAlign={chartConfig.legendPosition}
align={chartConfig.legendHorizontalAlign}
onClick={onItemLegendClick}
wrapperStyle={legendPosition}
{...chartConfig.legendConfig}
/>
)}
{referenceLine && (
<ReferenceLine
{...referenceLine}
stroke={referenceLine?.color ?? referenceLine?.stroke}
x={referenceLine?.value ?? referenceLine?.x}
label={referenceLine?.label}
/>
)}
{tooltipConfig?.active !== false && (
<Tooltip
cursor={tooltipFillOpacity}
formatter={tooltipValueFormatter}
contentStyle={tooltipContentStyle}
labelFormatter={tooltipLabelFormatter}
{...tooltipConfig}
/>
)}
{!!chartConfig.zoomingTool && (
<Brush
dataKey={primaryDimensionAccessor}
tickFormatter={primaryDimension?.formatter}
{...brushProps}
{...(typeof chartConfig.zoomingTool === 'object' ? chartConfig.zoomingTool : {})}
/>
)}
{children}
</BarChartLib>
</ChartContainer>
);
});
BarChart.displayName = 'BarChart';
export { BarChart };