-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
generateCategoricalChart.tsx
2354 lines (2037 loc) · 74.5 KB
/
generateCategoricalChart.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
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { Component, cloneElement, isValidElement, createElement, ReactElement } from 'react';
import isNil from 'lodash/isNil';
import isFunction from 'lodash/isFunction';
import range from 'lodash/range';
import get from 'lodash/get';
import sortBy from 'lodash/sortBy';
import throttle from 'lodash/throttle';
import find from 'lodash/find';
import every from 'lodash/every';
import clsx from 'clsx';
// eslint-disable-next-line no-restricted-imports
import type { DebouncedFunc } from 'lodash';
import invariant from 'tiny-invariant';
import { getRadialCursorPoints } from '../util/cursor/getRadialCursorPoints';
import { getTicks } from '../cartesian/getTicks';
import { Surface } from '../container/Surface';
import { Layer } from '../container/Layer';
import { Tooltip } from '../component/Tooltip';
import { Legend } from '../component/Legend';
import { Curve } from '../shape/Curve';
import { Cross } from '../shape/Cross';
import { Sector } from '../shape/Sector';
import { Dot } from '../shape/Dot';
import { isInRectangle, Rectangle } from '../shape/Rectangle';
import {
filterProps,
findAllByType,
findChildByType,
getDisplayName,
getReactEventByType,
isChildrenEqual,
parseChildIndex,
renderByOrder,
validateWidthHeight,
} from '../util/ReactUtils';
import { CartesianAxis } from '../cartesian/CartesianAxis';
import { Brush } from '../cartesian/Brush';
import { getOffset } from '../util/DOMUtils';
import { findEntryInArray, getAnyElementOfObject, hasDuplicate, isNumber, uniqueId } from '../util/DataUtils';
import {
appendOffsetOfLegend,
AxisStackGroups,
BarPosition,
calculateActiveTickIndex,
combineEventHandlers,
getBandSizeOfAxis,
getBarPosition,
getBarSizeList,
getCoordinatesOfGrid,
getDomainOfDataByKey,
getDomainOfItemsWithSameAxis,
getDomainOfStackGroups,
getLegendProps,
getMainColorOfGraphicItem,
getStackedDataOfItem,
getStackGroupsByAxisId,
getTicksOfAxis,
getTooltipItem,
isCategoricalAxis,
parseDomainOfCategoryAxis,
parseErrorBarsOfAxis,
parseSpecifiedDomain,
} from '../util/ChartUtils';
import { detectReferenceElementsDomain } from '../util/DetectReferenceElementsDomain';
import { inRangeOfSector, polarToCartesian } from '../util/PolarUtils';
import { shallowEqual } from '../util/ShallowEqual';
import { eventCenter, SYNC_EVENT } from '../util/Events';
import {
adaptEventHandlers,
AxisType,
BaseAxisProps,
CartesianViewBox,
CategoricalChartOptions,
ChartCoordinate,
ChartOffset,
Coordinate,
DataKey,
GeometrySector,
LayoutType,
Margin,
StackOffsetType,
TickItem,
} from '../util/types';
import { AccessibilityManager } from './AccessibilityManager';
import { isDomainSpecifiedByUser } from '../util/isDomainSpecifiedByUser';
import { getActiveShapeIndexForTooltip, isFunnel, isPie, isScatter } from '../util/ActiveShapeUtils';
import { Props as YAxisProps } from '../cartesian/YAxis';
import { Props as XAxisProps } from '../cartesian/XAxis';
import { getCursorPoints } from '../util/cursor/getCursorPoints';
import { getCursorRectangle } from '../util/cursor/getCursorRectangle';
export interface MousePointer {
pageX: number;
pageY: number;
}
export type GraphicalItem<Props = Record<string, any>> = ReactElement<
Props,
string | React.JSXElementConstructor<Props>
> & {
item: ReactElement<Props, string | React.JSXElementConstructor<Props>>;
};
const ORIENT_MAP = {
xAxis: ['bottom', 'top'],
yAxis: ['left', 'right'],
};
const FULL_WIDTH_AND_HEIGHT = { width: '100%', height: '100%' };
const originCoordinate: Coordinate = { x: 0, y: 0 };
const calculateTooltipPos = (rangeObj: any, layout: LayoutType): any => {
if (layout === 'horizontal') {
return rangeObj.x;
}
if (layout === 'vertical') {
return rangeObj.y;
}
if (layout === 'centric') {
return rangeObj.angle;
}
return rangeObj.radius;
};
const getActiveCoordinate = (
layout: LayoutType,
tooltipTicks: TickItem[],
activeIndex: number,
rangeObj: any,
): ChartCoordinate => {
const entry = tooltipTicks.find(tick => tick && tick.index === activeIndex);
if (entry) {
if (layout === 'horizontal') {
return { x: entry.coordinate, y: rangeObj.y };
}
if (layout === 'vertical') {
return { x: rangeObj.x, y: entry.coordinate };
}
if (layout === 'centric') {
const angle = entry.coordinate;
const { radius } = rangeObj;
return {
...rangeObj,
...polarToCartesian(rangeObj.cx, rangeObj.cy, radius, angle),
angle,
radius,
};
}
const radius = entry.coordinate;
const { angle } = rangeObj;
return {
...rangeObj,
...polarToCartesian(rangeObj.cx, rangeObj.cy, radius, angle),
angle,
radius,
};
}
return originCoordinate;
};
const getDisplayedData = (
data: any[],
{
graphicalItems,
dataStartIndex,
dataEndIndex,
}: Pick<CategoricalChartState, 'graphicalItems' | 'dataStartIndex' | 'dataEndIndex'>,
): any[] => {
const itemsData = (graphicalItems ?? []).reduce<any[]>((result, child) => {
const itemData = child.props.data;
if (itemData && itemData.length) {
return [...result, ...itemData];
}
return result;
}, []);
if (itemsData.length > 0) {
return itemsData;
}
if (data && data.length && isNumber(dataStartIndex) && isNumber(dataEndIndex)) {
return data.slice(dataStartIndex, dataEndIndex + 1);
}
return [];
};
function getDefaultDomainByAxisType(axisType: 'number' | string) {
return axisType === 'number' ? [0, 'auto'] : undefined;
}
/**
* Get the content to be displayed in the tooltip
* @param {Object} state Current state
* @param {Array} chartData The data defined in chart
* @param {Number} activeIndex Active index of data
* @param {String} activeLabel Active label of data
* @return {Array} The content of tooltip
*/
const getTooltipContent = (
state: CategoricalChartState,
chartData: any[],
activeIndex: number,
activeLabel?: string,
): any[] => {
const { graphicalItems, tooltipAxis } = state;
const displayedData = getDisplayedData(chartData, state);
if (activeIndex < 0 || !graphicalItems || !graphicalItems.length || activeIndex >= displayedData.length) {
return null;
}
// get data by activeIndex when the axis don't allow duplicated category
return graphicalItems.reduce((result, child) => {
const { hide } = child.props;
if (hide) {
return result;
}
/**
* Fixes: https://github.com/recharts/recharts/issues/3669
* Defaulting to chartData below to fix an edge case where the tooltip does not include data from all charts
* when a separate dataset is passed to chart prop data and specified on Line/Area/etc prop data
*/
let data = child.props.data ?? chartData;
if (data && state.dataStartIndex + state.dataEndIndex !== 0) {
data = data.slice(state.dataStartIndex, state.dataEndIndex + 1);
}
let payload;
if (tooltipAxis.dataKey && !tooltipAxis.allowDuplicatedCategory) {
// graphic child has data props
const entries = data === undefined ? displayedData : data;
payload = findEntryInArray(entries, tooltipAxis.dataKey, activeLabel);
} else {
payload = (data && data[activeIndex]) || displayedData[activeIndex];
}
if (!payload) {
return result;
}
return [...result, getTooltipItem(child, payload)];
}, []);
};
/**
* Returns tooltip data based on a mouse position (as a parameter or in state)
* @param {Object} state current state
* @param {Array} chartData the data defined in chart
* @param {String} layout The layout type of chart
* @param {Object} rangeObj { x, y } coordinates
* @return {Object} Tooltip data data
*/
const getTooltipData = (state: CategoricalChartState, chartData: any[], layout: LayoutType, rangeObj?: any) => {
const rangeData = rangeObj || { x: state.chartX, y: state.chartY };
const pos = calculateTooltipPos(rangeData, layout);
const { orderedTooltipTicks: ticks, tooltipAxis: axis, tooltipTicks } = state;
const activeIndex = calculateActiveTickIndex(pos, ticks, tooltipTicks, axis);
if (activeIndex >= 0 && tooltipTicks) {
const activeLabel = tooltipTicks[activeIndex] && tooltipTicks[activeIndex].value;
const activePayload = getTooltipContent(state, chartData, activeIndex, activeLabel);
const activeCoordinate = getActiveCoordinate(layout, ticks, activeIndex, rangeData);
return {
activeTooltipIndex: activeIndex,
activeLabel,
activePayload,
activeCoordinate,
};
}
return null;
};
/**
* Get the configuration of axis by the options of axis instance
* @param {Object} props Latest props
* @param {Array} axes The instance of axes
* @param {Array} graphicalItems The instances of item
* @param {String} axisType The type of axis, xAxis - x-axis, yAxis - y-axis
* @param {String} axisIdKey The unique id of an axis
* @param {Object} stackGroups The items grouped by axisId and stackId
* @param {Number} dataStartIndex The start index of the data series when a brush is applied
* @param {Number} dataEndIndex The end index of the data series when a brush is applied
* @return {Object} Configuration
*/
export const getAxisMapByAxes = (
props: CategoricalChartProps,
{
axes,
graphicalItems,
axisType,
axisIdKey,
stackGroups,
dataStartIndex,
dataEndIndex,
}: {
axes: ReadonlyArray<ReactElement>;
graphicalItems: ReadonlyArray<ReactElement>;
axisType: AxisType;
axisIdKey: string;
stackGroups: AxisStackGroups;
dataStartIndex: number;
dataEndIndex: number;
},
): AxisMap => {
const { layout, children, stackOffset } = props;
const isCategorical = isCategoricalAxis(layout, axisType);
// Eliminate duplicated axes
return axes.reduce((result: AxisMap, child: ReactElement): AxisMap => {
const { type, dataKey, allowDataOverflow, allowDuplicatedCategory, scale, ticks, includeHidden } = child.props;
const axisId = child.props[axisIdKey];
if (result[axisId]) {
return result;
}
const displayedData = getDisplayedData(props.data, {
graphicalItems: graphicalItems.filter(item => item.props[axisIdKey] === axisId),
dataStartIndex,
dataEndIndex,
});
const len = displayedData.length;
let domain, duplicateDomain, categoricalDomain;
/*
* This is a hack to short-circuit the domain creation here to enhance performance.
* Usually, the data is used to determine the domain, but when the user specifies
* a domain upfront (via props), there is no need to calculate the domain start and end,
* which is very expensive for a larger amount of data.
* The only thing that would prohibit short-circuiting is when the user doesn't allow data overflow,
* because the axis is supposed to ignore the specified domain that way.
*/
if (isDomainSpecifiedByUser(child.props.domain, allowDataOverflow, type)) {
domain = parseSpecifiedDomain(child.props.domain, null, allowDataOverflow);
/* The chart can be categorical and have the domain specified in numbers
* we still need to calculate the categorical domain
* TODO: refactor this more
*/
if (isCategorical && (type === 'number' || scale !== 'auto')) {
categoricalDomain = getDomainOfDataByKey(displayedData, dataKey, 'category');
}
}
// if the domain is defaulted we need this for `originalDomain` as well
const defaultDomain = getDefaultDomainByAxisType(type);
// we didn't create the domain from user's props above, so we need to calculate it
if (!domain || domain.length === 0) {
const childDomain = child.props.domain ?? defaultDomain;
if (dataKey) {
// has dataKey in <Axis />
domain = getDomainOfDataByKey(displayedData, dataKey, type);
if (type === 'category' && isCategorical) {
// the field type is category data and this axis is categorical axis
const duplicate = hasDuplicate(domain);
if (allowDuplicatedCategory && duplicate) {
duplicateDomain = domain;
// When category axis has duplicated text, serial numbers are used to generate scale
domain = range(0, len);
} else if (!allowDuplicatedCategory) {
// remove duplicated category
domain = parseDomainOfCategoryAxis(childDomain, domain, child).reduce(
(finalDomain: any, entry: any) =>
finalDomain.indexOf(entry) >= 0 ? finalDomain : [...finalDomain, entry],
[],
);
}
} else if (type === 'category') {
// the field type is category data and this axis is numerical axis
if (!allowDuplicatedCategory) {
domain = parseDomainOfCategoryAxis(childDomain, domain, child).reduce(
(finalDomain: any, entry: any) =>
finalDomain.indexOf(entry) >= 0 || entry === '' || isNil(entry) ? finalDomain : [...finalDomain, entry],
[],
);
} else {
// eliminate undefined or null or empty string
domain = domain.filter((entry: any) => entry !== '' && !isNil(entry));
}
} else if (type === 'number') {
// the field type is numerical
const errorBarsDomain = parseErrorBarsOfAxis(
displayedData,
graphicalItems.filter(item => item.props[axisIdKey] === axisId && (includeHidden || !item.props.hide)),
dataKey,
axisType,
layout,
);
if (errorBarsDomain) {
domain = errorBarsDomain;
}
}
if (isCategorical && (type === 'number' || scale !== 'auto')) {
categoricalDomain = getDomainOfDataByKey(displayedData, dataKey, 'category');
}
} else if (isCategorical) {
// the axis is a categorical axis
domain = range(0, len);
} else if (stackGroups && stackGroups[axisId] && stackGroups[axisId].hasStack && type === 'number') {
// when stackOffset is 'expand', the domain may be calculated as [0, 1.000000000002]
domain =
stackOffset === 'expand'
? [0, 1]
: getDomainOfStackGroups(stackGroups[axisId].stackGroups, dataStartIndex, dataEndIndex);
} else {
domain = getDomainOfItemsWithSameAxis(
displayedData,
graphicalItems.filter(item => item.props[axisIdKey] === axisId && (includeHidden || !item.props.hide)),
type,
layout,
true,
);
}
if (type === 'number') {
// To detect wether there is any reference lines whose props alwaysShow is true
domain = detectReferenceElementsDomain(children, domain, axisId, axisType, ticks);
if (childDomain) {
domain = parseSpecifiedDomain(childDomain, domain, allowDataOverflow);
}
} else if (type === 'category' && childDomain) {
const axisDomain = childDomain;
const isDomainValid = domain.every((entry: string | number) => axisDomain.indexOf(entry) >= 0);
if (isDomainValid) {
domain = axisDomain;
}
}
}
return {
...result,
[axisId]: {
...child.props,
axisType,
domain,
categoricalDomain,
duplicateDomain,
originalDomain: child.props.domain ?? defaultDomain,
isCategorical,
layout,
},
};
}, {});
};
/**
* Get the configuration of axis by the options of item,
* this kind of axis does not display in chart
* @param {Object} props Latest props
* @param {Array} graphicalItems The instances of item
* @param {ReactElement} Axis Axis Component
* @param {String} axisType The type of axis, xAxis - x-axis, yAxis - y-axis
* @param {String} axisIdKey The unique id of an axis
* @param {Object} stackGroups The items grouped by axisId and stackId
* @param {Number} dataStartIndex The start index of the data series when a brush is applied
* @param {Number} dataEndIndex The end index of the data series when a brush is applied
* @return {Object} Configuration
*/
const getAxisMapByItems = (
props: CategoricalChartProps,
{
graphicalItems,
Axis,
axisType,
axisIdKey,
stackGroups,
dataStartIndex,
dataEndIndex,
}: {
axisIdKey: string;
axisType?: AxisType;
Axis?: React.ComponentType<BaseAxisProps>;
graphicalItems: ReadonlyArray<ReactElement>;
stackGroups: AxisStackGroups;
dataStartIndex: number;
dataEndIndex: number;
},
): AxisMap => {
const { layout, children } = props;
const displayedData = getDisplayedData(props.data, {
graphicalItems,
dataStartIndex,
dataEndIndex,
});
const len = displayedData.length;
const isCategorical = isCategoricalAxis(layout, axisType);
let index = -1;
// The default type of x-axis is category axis,
// The default contents of x-axis is the serial numbers of data
// The default type of y-axis is number axis
// The default contents of y-axis is the domain of data
return graphicalItems.reduce((result: AxisMap, child: ReactElement): AxisMap => {
const axisId = child.props[axisIdKey];
const originalDomain = getDefaultDomainByAxisType('number');
if (!result[axisId]) {
index++;
let domain;
if (isCategorical) {
domain = range(0, len);
} else if (stackGroups && stackGroups[axisId] && stackGroups[axisId].hasStack) {
domain = getDomainOfStackGroups(stackGroups[axisId].stackGroups, dataStartIndex, dataEndIndex);
domain = detectReferenceElementsDomain(children, domain, axisId, axisType);
} else {
domain = parseSpecifiedDomain(
originalDomain,
getDomainOfItemsWithSameAxis(
displayedData,
graphicalItems.filter((item: ReactElement) => item.props[axisIdKey] === axisId && !item.props.hide),
'number',
layout,
),
Axis.defaultProps.allowDataOverflow,
);
domain = detectReferenceElementsDomain(children, domain, axisId, axisType);
}
return {
...result,
[axisId]: {
axisType,
...Axis.defaultProps,
hide: true,
orientation: get(ORIENT_MAP, `${axisType}.${index % 2}`, null),
domain,
originalDomain,
isCategorical,
layout,
// specify scale when no Axis
// scale: isCategorical ? 'band' : 'linear',
},
};
}
return result;
}, {});
};
/**
* Get the configuration of all x-axis or y-axis
* @param {Object} props Latest props
* @param {String} axisType The type of axis
* @param {React.ComponentType} [AxisComp] Axis Component
* @param {Array} graphicalItems The instances of item
* @param {Object} stackGroups The items grouped by axisId and stackId
* @param {Number} dataStartIndex The start index of the data series when a brush is applied
* @param {Number} dataEndIndex The end index of the data series when a brush is applied
* @return {Object} Configuration
*/
const getAxisMap = (
props: CategoricalChartProps,
{
axisType = 'xAxis',
AxisComp,
graphicalItems,
stackGroups,
dataStartIndex,
dataEndIndex,
}: {
axisType?: AxisType;
AxisComp?: React.ComponentType;
graphicalItems: ReadonlyArray<ReactElement>;
stackGroups: AxisStackGroups;
dataStartIndex: number;
dataEndIndex: number;
},
): AxisMap => {
const { children } = props;
const axisIdKey = `${axisType}Id`;
// Get all the instance of Axis
const axes = findAllByType(children, AxisComp);
let axisMap: AxisMap = {};
if (axes && axes.length) {
axisMap = getAxisMapByAxes(props, {
axes,
graphicalItems,
axisType,
axisIdKey,
stackGroups,
dataStartIndex,
dataEndIndex,
});
} else if (graphicalItems && graphicalItems.length) {
axisMap = getAxisMapByItems(props, {
Axis: AxisComp,
graphicalItems,
axisType,
axisIdKey,
stackGroups,
dataStartIndex,
dataEndIndex,
});
}
return axisMap;
};
const tooltipTicksGenerator = (axisMap: AxisMap) => {
const axis: BaseAxisProps = getAnyElementOfObject(axisMap);
const tooltipTicks = getTicksOfAxis(axis, false, true);
return {
tooltipTicks,
orderedTooltipTicks: sortBy(tooltipTicks, o => o.coordinate),
tooltipAxis: axis,
tooltipAxisBandSize: getBandSizeOfAxis(axis, tooltipTicks),
};
};
/**
* Returns default, reset state for the categorical chart.
* @param {Object} props Props object to use when creating the default state
* @return {Object} Whole new state
*/
const createDefaultState = (props: CategoricalChartProps): CategoricalChartState => {
const { children, defaultShowTooltip } = props;
const brushItem = findChildByType(children, Brush);
const startIndex = (brushItem && brushItem.props && brushItem.props.startIndex) || 0;
const endIndex =
brushItem?.props?.endIndex !== undefined ? brushItem?.props?.endIndex : (props.data && props.data.length - 1) || 0;
return {
chartX: 0,
chartY: 0,
dataStartIndex: startIndex,
dataEndIndex: endIndex,
activeTooltipIndex: -1,
isTooltipActive: Boolean(defaultShowTooltip),
};
};
const hasGraphicalBarItem = (graphicalItems: ReadonlyArray<ReactElement>): boolean => {
if (!graphicalItems || !graphicalItems.length) {
return false;
}
return graphicalItems.some(item => {
const name = getDisplayName(item && item.type);
return name && name.indexOf('Bar') >= 0;
});
};
const getAxisNameByLayout = (layout: LayoutType) => {
if (layout === 'horizontal') {
return { numericAxisName: 'yAxis', cateAxisName: 'xAxis' } as const;
}
if (layout === 'vertical') {
return { numericAxisName: 'xAxis', cateAxisName: 'yAxis' } as const;
}
if (layout === 'centric') {
return { numericAxisName: 'radiusAxis', cateAxisName: 'angleAxis' } as const;
}
return { numericAxisName: 'angleAxis', cateAxisName: 'radiusAxis' } as const;
};
/**
* Calculate the offset of main part in the svg element
* @param {Object} params.props Latest props
* @param {Array} params.graphicalItems The instances of item
* @param {Object} params.xAxisMap The configuration of x-axis
* @param {Object} params.yAxisMap The configuration of y-axis
* @param {Object} prevLegendBBox The boundary box of legend
* @return {Object} The offset of main part in the svg element
*/
const calculateOffset = (
{
props,
graphicalItems,
xAxisMap = {},
yAxisMap = {},
}: {
props: CategoricalChartProps;
graphicalItems: Array<ReactElement>;
xAxisMap?: { [axisId: string]: XAxisProps };
yAxisMap?: { [axisId: string]: YAxisProps };
},
prevLegendBBox?: DOMRect | null,
): ChartOffset => {
const { width, height, children } = props;
const margin = props.margin || {};
const brushItem = findChildByType(children, Brush);
const legendItem = findChildByType(children, Legend);
const offsetH = Object.keys(yAxisMap).reduce(
(result, id) => {
const entry = yAxisMap[id];
const { orientation } = entry;
if (!entry.mirror && !entry.hide) {
return { ...result, [orientation]: result[orientation] + entry.width };
}
return result;
},
{ left: margin.left || 0, right: margin.right || 0 },
);
const offsetV = Object.keys(xAxisMap).reduce(
(result, id) => {
const entry = xAxisMap[id];
const { orientation } = entry;
if (!entry.mirror && !entry.hide) {
return { ...result, [orientation]: get(result, `${orientation}`) + entry.height };
}
return result;
},
{ top: margin.top || 0, bottom: margin.bottom || 0 },
);
let offset: ChartOffset = { ...offsetV, ...offsetH };
const brushBottom = offset.bottom;
if (brushItem) {
offset.bottom += brushItem.props.height || Brush.defaultProps.height;
}
if (legendItem && prevLegendBBox) {
// @ts-expect-error margin is optional in props but required in appendOffsetOfLegend
offset = appendOffsetOfLegend(offset, graphicalItems, props, prevLegendBBox);
}
const offsetWidth = width - offset.left - offset.right;
const offsetHeight = height - offset.top - offset.bottom;
return {
brushBottom,
...offset,
// never return negative values for height and width
width: Math.max(offsetWidth, 0),
height: Math.max(offsetHeight, 0),
};
};
type AxisMap = {
[axisId: string]: BaseAxisProps;
};
type AxisMapMap = {
[axisMapId: string]: AxisMap;
};
export interface CategoricalChartState {
chartX?: number;
chartY?: number;
dataStartIndex?: number;
dataEndIndex?: number;
activeTooltipIndex?: number;
isTooltipActive?: boolean;
updateId?: number;
xAxisMap?: AxisMap;
yAxisMap?: AxisMap;
zAxisMap?: AxisMap;
orderedTooltipTicks?: any;
tooltipAxis?: BaseAxisProps;
tooltipTicks?: TickItem[];
graphicalItems?: ReadonlyArray<ReactElement>;
activeCoordinate?: ChartCoordinate;
offset?: ChartOffset;
angleAxisMap?: any;
radiusAxisMap?: any;
formattedGraphicalItems?: any;
/** active tooltip payload */
activePayload?: any[];
tooltipAxisBandSize?: number;
/** active item */
activeItem?: any;
/** Active label of data */
activeLabel?: string;
activeIndex?: number;
xValue?: number;
yValue?: number;
legendBBox?: DOMRect | null;
prevDataKey?: DataKey<any>;
prevData?: any[];
prevWidth?: number;
prevHeight?: number;
prevLayout?: LayoutType;
prevStackOffset?: StackOffsetType;
prevMargin?: Margin;
prevChildren?: any;
stackGroups?: AxisStackGroups;
}
export type CategoricalChartFunc = (nextState: CategoricalChartState, event: any) => void;
export interface CategoricalChartProps {
syncId?: number | string;
syncMethod?: 'index' | 'value' | Function;
compact?: boolean;
width?: number;
height?: number;
dataKey?: DataKey<any>;
data?: any[];
layout?: LayoutType;
stackOffset?: StackOffsetType;
throttleDelay?: number;
margin?: Margin;
barCategoryGap?: number | string;
barGap?: number | string;
barSize?: number | string;
maxBarSize?: number;
style?: any;
className?: string;
children?: any;
defaultShowTooltip?: boolean;
onClick?: CategoricalChartFunc;
onMouseLeave?: CategoricalChartFunc;
onMouseEnter?: CategoricalChartFunc;
onMouseMove?: CategoricalChartFunc;
onMouseDown?: CategoricalChartFunc;
onMouseUp?: CategoricalChartFunc;
reverseStackOrder?: boolean;
id?: string;
startAngle?: number;
endAngle?: number;
cx?: number | string;
cy?: number | string;
innerRadius?: number | string;
outerRadius?: number | string;
title?: string;
desc?: string;
accessibilityLayer?: boolean;
role?: string;
tabIndex?: number;
}
type AxisObj = {
xAxis?: BaseAxisProps;
xAxisTicks?: Array<TickItem>;
yAxis?: BaseAxisProps;
yAxisTicks?: Array<TickItem>;
zAxis?: BaseAxisProps;
zAxisTicks?: Array<TickItem>;
angleAxis?: BaseAxisProps;
angleAxisTicks?: Array<TickItem>;
radiusAxis?: BaseAxisProps;
radiusAxisTicks?: Array<TickItem>;
};
export const generateCategoricalChart = ({
chartName,
GraphicalChild,
defaultTooltipEventType = 'axis',
validateTooltipEventTypes = ['axis'],
axisComponents,
legendContent,
formatAxisMap,
defaultProps,
}: CategoricalChartOptions) => {
const getFormatItems = (props: CategoricalChartProps, currentState: CategoricalChartState): any[] => {
const { graphicalItems, stackGroups, offset, updateId, dataStartIndex, dataEndIndex } = currentState;
const { barSize, layout, barGap, barCategoryGap, maxBarSize: globalMaxBarSize } = props;
const { numericAxisName, cateAxisName } = getAxisNameByLayout(layout);
const hasBar = hasGraphicalBarItem(graphicalItems);
const sizeList = hasBar && getBarSizeList({ barSize, stackGroups });
const formattedItems = [] as any[];
graphicalItems.forEach((item: ReactElement, index: number) => {
const displayedData = getDisplayedData(props.data, { graphicalItems: [item], dataStartIndex, dataEndIndex });
const { dataKey, maxBarSize: childMaxBarSize } = item.props;
// axisId of the numerical axis
const numericAxisId = item.props[`${numericAxisName}Id`];
// axisId of the categorical axis
const cateAxisId = item.props[`${cateAxisName}Id`];
const axisObjInitialValue: AxisObj = {};
const axisObj: AxisObj = axisComponents.reduce((result: AxisObj, entry: BaseAxisProps): AxisObj => {
// map of axisId to axis for a specific axis type
const axisMap: AxisMap | undefined = currentState[`${entry.axisType}Map` as const];
// axisId of axis we are currently computing
const id: string = item.props[`${entry.axisType}Id`];
/**
* tell the user in dev mode that their configuration is incorrect if we cannot find a match between
* axisId on the chart and axisId on the axis. zAxis does not get passed in the map for ComposedChart,
* leave it out of the check for now.
*/
invariant(
(axisMap && axisMap[id]) || entry.axisType === 'zAxis',
`Specifying a(n) ${entry.axisType}Id requires a corresponding ${
entry.axisType
// @ts-expect-error we should stop reading data from ReactElements
}Id on the targeted graphical component ${item?.type?.displayName ?? ''}`,
);
// the axis we are currently formatting
const axis = axisMap[id];
return {
...result,
[entry.axisType]: axis,
[`${entry.axisType}Ticks`]: getTicksOfAxis(axis),
};
}, axisObjInitialValue);
const cateAxis = axisObj[cateAxisName];
const cateTicks = axisObj[`${cateAxisName}Ticks` as const];
const stackedData =
stackGroups &&
stackGroups[numericAxisId] &&
stackGroups[numericAxisId].hasStack &&
getStackedDataOfItem(item, stackGroups[numericAxisId].stackGroups);
const itemIsBar = getDisplayName(item.type).indexOf('Bar') >= 0;
const bandSize = getBandSizeOfAxis(cateAxis, cateTicks);
let barPosition: ReadonlyArray<BarPosition> = [];
if (itemIsBar) {
// 如果是bar,计算bar的位置
const maxBarSize: number = isNil(childMaxBarSize) ? globalMaxBarSize : childMaxBarSize;
const barBandSize: number = getBandSizeOfAxis(cateAxis, cateTicks, true) ?? maxBarSize ?? 0;
barPosition = getBarPosition({
barGap,
barCategoryGap,
bandSize: barBandSize !== bandSize ? barBandSize : bandSize,
sizeList: sizeList[cateAxisId],
maxBarSize,
});
if (barBandSize !== bandSize) {
barPosition = barPosition.map(pos => ({
...pos,
position: { ...pos.position, offset: pos.position.offset - barBandSize / 2 },
}));
}
}
// @ts-expect-error we should stop reading data from ReactElements
const composedFn = item && item.type && item.type.getComposedData;
if (composedFn) {
formattedItems.push({