-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathutilities.ts
More file actions
2721 lines (2472 loc) · 86.6 KB
/
Copy pathutilities.ts
File metadata and controls
2721 lines (2472 loc) · 86.6 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
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
'use client';
import type { Axis as D3Axis } from 'd3-axis';
import { axisRight as d3AxisRight, axisBottom as d3AxisBottom, axisLeft as d3AxisLeft } from 'd3-axis';
import {
max as d3Max,
min as d3Min,
ticks as d3Ticks,
nice as d3nice,
sum as d3Sum,
mean as d3Mean,
median as d3Median,
} from 'd3-array';
import type { NumberValue } from 'd3-scale';
import {
scaleLinear as d3ScaleLinear,
scaleBand as d3ScaleBand,
scaleUtc as d3ScaleUtc,
scaleTime as d3ScaleTime,
scaleLog as d3ScaleLog,
type ScaleContinuousNumeric,
type ScaleLinear,
type ScaleBand,
type ScaleTime,
} from 'd3-scale';
import type { Selection } from 'd3-selection';
import { select as d3Select, selectAll as d3SelectAll } from 'd3-selection';
import { format as d3Format } from 'd3-format';
import type { JSXElement } from '@fluentui/react-utilities';
import type {
TimeLocaleObject as d3TimeLocaleObject,
TimeLocaleDefinition as d3TimeLocaleDefinition,
} from 'd3-time-format';
import {
timeFormat as d3TimeFormat,
timeFormatLocale as d3TimeFormatLocale,
utcFormat as d3UtcFormat,
} from 'd3-time-format';
import {
timeSecond as d3TimeSecond,
timeMinute as d3TimeMinute,
timeHour as d3TimeHour,
timeDay as d3TimeDay,
timeMonth as d3TimeMonth,
timeWeek as d3TimeWeek,
timeYear as d3TimeYear,
utcSecond as d3UtcSecond,
utcMinute as d3UtcMinute,
utcHour as d3UtcHour,
utcDay as d3UtcDay,
utcMonth as d3UtcMonth,
utcWeek as d3UtcWeek,
utcYear as d3UtcYear,
} from 'd3-time';
import type { CurveFactory } from 'd3-shape';
import {
curveLinear as d3CurveLinear,
curveNatural as d3CurveNatural,
curveStep as d3CurveStep,
curveStepAfter as d3CurveStepAfter,
curveStepBefore as d3CurveStepBefore,
} from 'd3-shape';
import type { AxisProps, AxisScaleType, ScatterChartPoints } from '../types/DataPoint';
import type {
AccessibilityProps,
EventsAnnotationProps,
LineChartPoints,
LineChartDataPoint,
ScatterChartDataPoint,
GanttChartDataPoint,
DataPoint,
VerticalStackedBarDataPoint,
VerticalBarChartDataPoint,
HorizontalBarChartWithAxisDataPoint,
LineChartLineOptions,
AxisCategoryOrder,
YValueHover,
} from '../index';
import { formatPrefix as d3FormatPrefix } from 'd3-format';
import { useFluent_unstable as useFluent } from '@fluentui/react-shared-contexts';
import {
formatDateToLocaleString,
formatToLocaleString,
getMultiLevelDateTimeFormatOptions,
isInvalidValue,
isNumber,
} from '@fluentui/chart-utilities';
export const MIN_DOMAIN_MARGIN = 8;
export const MIN_DONUT_RADIUS = 1;
export const DEFAULT_DATE_STRING = '2000-01-01';
export const CARTESIAN_XAXIS_CLASSNAME = 'fui-cart__xAxis';
const CARTESIAN_XAXIS_TEXT_SELECTOR = `.${CARTESIAN_XAXIS_CLASSNAME} text`;
export type NumericAxis = D3Axis<number | { valueOf(): number }>;
export type StringAxis = D3Axis<string>;
export enum ChartTypes {
AreaChart,
LineChart,
VerticalBarChart,
VerticalStackedBarChart,
GroupedVerticalBarChart,
HeatMapChart,
HorizontalBarChartWithAxis,
ScatterChart,
GanttChart,
}
export enum XAxisTypes {
NumericAxis,
DateAxis,
StringAxis,
}
export enum YAxisType {
NumericAxis,
DateAxis,
StringAxis,
}
export interface IWrapLabelProps {
node: SVGSVGElement | null;
xAxis: NumericAxis | StringAxis;
noOfCharsToTruncate: number;
showXAxisLablesTooltip: boolean;
width?: number | number[];
container?: HTMLElement | null;
}
export interface IRotateLabelProps {
node: SVGSVGElement | null;
xAxis: NumericAxis | StringAxis;
}
export interface IAxisData {
yAxisDomainValues: number[];
yAxisTickText: string[];
}
export interface IMargins {
/**
* left margin for the chart.
* @default 40
*/
left?: number;
/**
* Right margin for the chart.
* @default 20
*/
right?: number;
/**
* Top margin for the chart.
* @default 20
*/
top?: number;
/**
* Bottom margin for the chart.
* @default 35
*/
bottom?: number;
}
export interface IDomainNRange {
dStartValue: number | Date;
dEndValue: number | Date;
rStartValue: number;
rEndValue: number;
}
export interface IXAxisParams extends AxisProps {
domainNRangeValues: IDomainNRange;
xAxisElement?: SVGSVGElement | null;
xAxisCount?: number;
showRoundOffXTickValues?: boolean;
xAxistickSize?: number;
tickPadding?: number;
xAxisPadding?: number;
xAxisInnerPadding?: number;
xAxisOuterPadding?: number;
margins: IMargins;
containerHeight: number;
containerWidth: number;
hideTickOverlap?: boolean;
calcMaxLabelWidth: (x: (string | number)[]) => number;
xMaxValue?: number;
xMinValue?: number;
}
export interface ITickParams {
tickValues?: Date[] | number[] | string[];
tickFormat?: string | ((value: number | Date) => string);
}
export interface IYAxisParams extends AxisProps {
yMinMaxValues?: {
startValue: number;
endValue: number;
};
maxOfYVal?: number;
margins: IMargins;
containerWidth: number;
containerHeight: number;
yAxisElement?: SVGSVGElement | null;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
yAxisTickFormat?: any;
yAxisTickCount: number;
yMaxValue?: number;
yMinValue?: number;
tickPadding?: number;
eventAnnotationProps?: EventsAnnotationProps;
eventLabelHeight?: number;
yAxisPadding?: number;
tickValues?: Date[] | number[] | string[];
}
function yAxisTickFormatterInternal(value: number, limitWidth: boolean = false): string {
// Use SI format prefix with 2 decimal places without insignificant trailing zeros
let formatter = d3FormatPrefix('.2~', value);
if (Math.abs(value) < 1) {
// Don't use SI notation for small numbers as it is less readable
formatter = d3Format('.2~g');
} else if (limitWidth && Math.abs(value) >= 1000) {
// If width is limited, use SI format prefix with 1 point precision
formatter = d3FormatPrefix('.1~', value);
}
const formattedValue = formatter(value);
// Replace 'G' with 'B' if the value is greater than 10^9 as it is a more common convention
if (Math.abs(value) >= 1e9) {
return formattedValue.replace('G', 'B');
}
return formattedValue;
}
/**
* Formatter for y axis ticks.
* @param value - The number to format.
* @returns The formatted string .
*/
export function defaultYAxisTickFormatter(value: number): string {
return yAxisTickFormatterInternal(value);
}
/**
* Create Numeric X axis
* @export
* @param {IXAxisParams} xAxisParams
*/
export function createNumericXAxis(
xAxisParams: IXAxisParams,
tickParams: ITickParams,
chartType: ChartTypes,
culture?: string,
scaleType?: AxisScaleType,
_useRtl?: boolean,
): {
xScale: ScaleLinear<number, number>;
tickValues: number[];
tickLabels: string[];
} {
const {
domainNRangeValues,
showRoundOffXTickValues = false,
xAxistickSize = 6,
tickPadding = 10,
xAxisCount,
xAxisElement,
hideTickOverlap,
calcMaxLabelWidth,
tickStep,
tick0,
tickText,
} = xAxisParams;
const dStartValue = domainNRangeValues.dStartValue as number;
const dEndValue = domainNRangeValues.dEndValue as number;
const finalXmin = xAxisParams.xMinValue !== undefined ? Math.min(dStartValue, xAxisParams.xMinValue) : dStartValue;
const finalXmax = xAxisParams.xMaxValue !== undefined ? Math.max(dEndValue, xAxisParams.xMaxValue) : dEndValue;
const xAxisScale = createNumericScale(scaleType)
.domain([finalXmin, finalXmax])
.range([domainNRangeValues.rStartValue, domainNRangeValues.rEndValue]);
showRoundOffXTickValues && xAxisScale.nice();
let tickCount = xAxisCount ?? 6;
const tickFormat = (domainValue: NumberValue, _index: number, defaultFormat?: (val: NumberValue) => string) => {
if (tickParams.tickValues && tickText && typeof tickText[_index] !== 'undefined') {
return tickText[_index];
}
if (tickParams.tickFormat) {
return typeof tickParams.tickFormat === 'function'
? tickParams.tickFormat(typeof domainValue === 'number' ? domainValue : domainValue.valueOf())
: d3Format(tickParams.tickFormat)(domainValue);
}
const xAxisValue = typeof domainValue === 'number' ? domainValue : domainValue.valueOf();
return defaultFormat?.(xAxisValue) === '' ? '' : (formatToLocaleString(xAxisValue, culture) as string);
};
if (hideTickOverlap) {
const longestLabelWidth =
calcMaxLabelWidth(xAxisScale.ticks().map((v: NumberValue, i: number) => tickFormat(v, i))) + 20;
const [start, end] = xAxisScale.range();
tickCount = Math.min(Math.max(1, Math.floor(Math.abs(end - start) / longestLabelWidth)), 10);
}
const xAxis = d3AxisBottom(xAxisScale)
.tickSize(xAxistickSize)
.tickPadding(tickPadding)
.ticks(tickCount)
.tickFormat((v, i) => tickFormat(v as NumberValue, i, xAxisScale.tickFormat(tickCount)));
if ([ChartTypes.HorizontalBarChartWithAxis, ChartTypes.GanttChart].includes(chartType)) {
xAxis.tickSizeInner(-(xAxisParams.containerHeight - xAxisParams.margins.top!));
}
let customTickValues: number[] | undefined;
if (tickParams.tickValues) {
customTickValues = tickParams.tickValues as number[];
} else if (tickStep) {
customTickValues = generateNumericTicks(scaleType, tickStep, tick0, xAxisScale.domain());
}
if (customTickValues) {
xAxis.tickValues(customTickValues);
}
if (xAxisElement) {
d3Select(xAxisElement)
.call(xAxis)
.selectAll('text')
.attr('aria-hidden', 'true')
.style('direction', 'ltr')
.style('unicode-bidi', 'isolate');
}
const tickValues = customTickValues ?? xAxisScale.ticks(tickCount);
const tickLabels = tickValues.map(xAxis.tickFormat()!);
return { xScale: xAxisScale, tickValues, tickLabels };
}
/**
* This function returns a multilevel formatter for a given date range.
* It determines the appropriate date format to accommodate each tick value.
* The goal is to represent the date label in the smallest possible format without loss of information.
* The challenge here is to adhere to locale specific formats while ensuring the complete label is shown.
* There is an exhaustive map of all possible date/time units and their respective formats.
* Based on the range of formatting granularity levels, a format spanning the range is returned.
* @param startLevel - The starting level of the date format.
* @param endLevel - The ending level of the date format.
* @param locale - The locale object for formatting.
* @param useUTC
* @returns
*/
function getMultiLevelD3DateFormatter(
startLevel: number,
endLevel: number,
locale?: d3TimeLocaleObject,
useUTC?: boolean,
) {
const timeFormat = locale ? (useUTC ? locale.utcFormat : locale.format) : useUTC ? d3UtcFormat : d3TimeFormat;
// Refer to https://d3js.org/d3-time-format#locale_format to see explanation about each format specifier
const DEFAULT = '%c';
const MS = '.%L';
const MS_S = ':%S.%L';
const MS_S_MIN = '%M:%S.%L';
const MS_S_MIN_H = '%-I:%M:%S.%L %p';
const MS_S_MIN_H_D = '%a %d, %X';
const MS_S_MIN_H_D_W = '%b %d, %X';
const MS_S_MIN_H_D_W_M = MS_S_MIN_H_D_W;
const MS_S_MIN_H_D_W_M_Y = DEFAULT;
const S = ':%S';
const S_MIN = '%-I:%M:%S';
const S_MIN_H = '%X';
const S_MIN_H_D = MS_S_MIN_H_D;
const S_MIN_H_D_W = MS_S_MIN_H_D_W;
const S_MIN_H_D_W_M = MS_S_MIN_H_D_W_M;
const S_MIN_H_D_W_M_Y = DEFAULT;
const MIN = '%-I:%M %p';
const MIN_H = MIN;
const MIN_H_D = '%a %d, %-I:%M %p';
const MIN_H_D_W = '%b %d, %-I:%M %p';
const MIN_H_D_W_M = MIN_H_D_W;
const MIN_H_D_W_M_Y = '%x, %-I:%M %p';
const H = '%-I %p';
const H_D = '%a %d, %-I %p';
const H_D_W = '%b %d, %-I %p';
const H_D_W_M = H_D_W;
const H_D_W_M_Y = '%x, %-I %p';
const D = '%a %d';
const D_W = '%b %d';
const D_W_M = D_W;
const D_W_M_Y = '%x';
const W = D_W;
const W_M = W;
const W_M_Y = D_W_M_Y;
const M = '%B';
const M_Y = '%b %Y';
const Y = '%Y';
const MULTI_LEVEL_DATE_TIME_FORMATS = [
// ms, s, min, h, d, w, m, y
[MS, MS_S, MS_S_MIN, MS_S_MIN_H, MS_S_MIN_H_D, MS_S_MIN_H_D_W, MS_S_MIN_H_D_W_M, MS_S_MIN_H_D_W_M_Y], // ms
[DEFAULT, S, S_MIN, S_MIN_H, S_MIN_H_D, S_MIN_H_D_W, S_MIN_H_D_W_M, S_MIN_H_D_W_M_Y], // s
[DEFAULT, DEFAULT, MIN, MIN_H, MIN_H_D, MIN_H_D_W, MIN_H_D_W_M, MIN_H_D_W_M_Y], // min
[DEFAULT, DEFAULT, DEFAULT, H, H_D, H_D_W, H_D_W_M, H_D_W_M_Y], // h
[DEFAULT, DEFAULT, DEFAULT, DEFAULT, D, D_W, D_W_M, D_W_M_Y], // d
[DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, W, W_M, W_M_Y], // w
[DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, M, M_Y], // m
[DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, Y], // y
];
const formatter = timeFormat(MULTI_LEVEL_DATE_TIME_FORMATS[startLevel][endLevel]);
return formatter;
}
export function getDateFormatLevel(date: Date, useUTC?: boolean): number {
const timeSecond = useUTC ? d3UtcSecond : d3TimeSecond;
const timeMinute = useUTC ? d3UtcMinute : d3TimeMinute;
const timeHour = useUTC ? d3UtcHour : d3TimeHour;
const timeDay = useUTC ? d3UtcDay : d3TimeDay;
const timeMonth = useUTC ? d3UtcMonth : d3TimeMonth;
const timeWeek = useUTC ? d3UtcWeek : d3TimeWeek;
const timeYear = useUTC ? d3UtcYear : d3TimeYear;
const formats = [
{ formatLevel: 0, condition: (d: Date) => timeSecond(d) < d }, // Milliseconds
{ formatLevel: 1, condition: (d: Date) => timeMinute(d) < d }, // Seconds
{ formatLevel: 2, condition: (d: Date) => timeHour(d) < d }, // Minutes
{ formatLevel: 3, condition: (d: Date) => timeDay(d) < d }, // Hours
{ formatLevel: 4, condition: (d: Date) => timeMonth(d) < d && timeWeek(d) < d }, // Days
{ formatLevel: 5, condition: (d: Date) => timeMonth(d) < d }, // Weeks
{ formatLevel: 6, condition: (d: Date) => timeYear(d) < d }, // Months
{ formatLevel: 7, condition: () => true }, // Years (default)
];
const matchedFormat = formats.find(({ condition }) => condition(date));
return matchedFormat?.formatLevel ?? 7;
}
/**
* Creating Date x axis of the Chart
* @export
* @param {IXAxisParams} xAxisParams
* @param {ITickParams} tickParams
*/
export function createDateXAxis(
xAxisParams: IXAxisParams,
tickParams: ITickParams,
culture?: string,
options?: Intl.DateTimeFormatOptions,
timeFormatLocale?: d3TimeLocaleDefinition,
customDateTimeFormatter?: (dateTime: Date) => string,
useUTC?: string | boolean,
chartType?: ChartTypes,
): { xScale: ScaleTime<number, number>; tickValues: Date[]; tickLabels: string[] } {
const {
domainNRangeValues,
xAxisElement,
tickPadding = 6,
xAxistickSize = 6,
xAxisCount,
hideTickOverlap,
calcMaxLabelWidth,
tickStep,
tick0,
tickText,
} = xAxisParams;
const isUtcSet = useUTC === true || useUTC === 'utc';
const xAxisScale = isUtcSet ? d3ScaleUtc() : d3ScaleTime();
xAxisScale
.domain([domainNRangeValues.dStartValue, domainNRangeValues.dEndValue])
.range([domainNRangeValues.rStartValue, domainNRangeValues.rEndValue])
.nice();
let tickCount = xAxisCount ?? 6;
let lowestFormatLevel = 100;
let highestFormatLevel = -1;
const locale = timeFormatLocale ? d3TimeFormatLocale(timeFormatLocale) : undefined;
xAxisScale.ticks().forEach((domainValue: Date) => {
const formatLevel = getDateFormatLevel(domainValue, isUtcSet);
if (formatLevel > highestFormatLevel) {
highestFormatLevel = formatLevel;
}
if (formatLevel < lowestFormatLevel) {
lowestFormatLevel = formatLevel;
}
});
const formatOptions = options ?? getMultiLevelDateTimeFormatOptions(lowestFormatLevel, highestFormatLevel);
const formatFn: (date: Date) => string = getMultiLevelD3DateFormatter(
lowestFormatLevel,
highestFormatLevel,
locale,
isUtcSet,
);
const tickFormat = (domainValue: Date, _index: number) => {
if (tickParams.tickValues && tickText && typeof tickText[_index] !== 'undefined') {
return tickText[_index];
}
if (typeof tickParams.tickFormat === 'function') {
return tickParams.tickFormat(domainValue);
}
if (customDateTimeFormatter) {
return customDateTimeFormatter(domainValue);
}
if (timeFormatLocale) {
return formatFn(domainValue);
}
if (culture === undefined && tickParams.tickFormat) {
if (useUTC) {
return d3UtcFormat(tickParams.tickFormat)(domainValue);
} else {
return d3TimeFormat(tickParams.tickFormat)(domainValue);
}
}
return formatDateToLocaleString(domainValue, culture, useUTC ? true : false, false, formatOptions);
};
if (hideTickOverlap) {
const longestLabelWidth = calcMaxLabelWidth(xAxisScale.ticks().map(tickFormat)) + 40;
const [start, end] = xAxisScale.range();
tickCount = Math.min(Math.max(1, Math.floor(Math.abs(end - start) / longestLabelWidth)), 10);
}
const xAxis = d3AxisBottom(xAxisScale)
.tickSize(xAxistickSize)
.tickPadding(tickPadding)
.ticks(tickCount)
.tickFormat(tickFormat);
if ([ChartTypes.GanttChart].includes(chartType!)) {
xAxis.tickSizeInner(-(xAxisParams.containerHeight - xAxisParams.margins.top!));
}
let customTickValues: Date[] | undefined;
if (tickParams.tickValues) {
customTickValues = tickParams.tickValues as Date[];
} else if (tickStep) {
customTickValues = generateDateTicks(tickStep, tick0, xAxisScale.domain(), useUTC as boolean);
}
if (customTickValues) {
xAxis.tickValues(customTickValues);
}
if (xAxisElement) {
d3Select(xAxisElement).call(xAxis).selectAll('text').attr('aria-hidden', 'true');
}
const tickValues = customTickValues ?? xAxisScale.ticks(tickCount);
const tickLabels = tickValues.map(xAxis.tickFormat()!);
return { xScale: xAxisScale, tickValues, tickLabels };
}
/**
* Create String X axis
* Currently using for only Vetical stacked bar chart and grouped vertical bar chart
* @export
* @param {IXAxisParams} xAxisParams
* @param {ITickParams} tickParams
* @param {string[]} dataset
* @returns
*/
export function createStringXAxis(
xAxisParams: IXAxisParams,
tickParams: ITickParams,
dataset: string[],
culture?: string,
_useRtl?: boolean,
): {
xScale: ScaleBand<string>;
tickValues: string[];
tickLabels: string[];
} {
const {
domainNRangeValues,
xAxistickSize = 6,
tickPadding = 10,
xAxisPadding = 0.1,
xAxisInnerPadding,
xAxisOuterPadding,
containerWidth,
hideTickOverlap,
calcMaxLabelWidth,
tickText,
} = xAxisParams;
const xAxisScale = d3ScaleBand()
.domain(dataset!)
.range([domainNRangeValues.rStartValue, domainNRangeValues.rEndValue])
.paddingInner(typeof xAxisInnerPadding !== 'undefined' ? xAxisInnerPadding : xAxisPadding)
.paddingOuter(typeof xAxisOuterPadding !== 'undefined' ? xAxisOuterPadding : xAxisPadding);
let tickValues = (tickParams.tickValues as string[] | undefined) ?? dataset;
const tickFormat = (domainValue: string, _index: number) => {
if (tickParams.tickValues && tickText && typeof tickText[_index] !== 'undefined') {
return tickText[_index];
}
return domainValue;
};
if (hideTickOverlap) {
let nonOverlappingTickValues = [];
const tickSizes = tickValues.map(value => calcMaxLabelWidth([value]));
// for LTR
let start = 0;
let end = containerWidth;
let sign = 1;
const range = xAxisScale.range();
if (range[1] - range[0] < 0) {
// for RTL
start = containerWidth;
end = 0;
sign = -1;
}
for (let i = tickValues.length - 1; i >= 0; i--) {
const tickPosition = xAxisScale(tickValues[i])!;
if (
sign * (tickPosition - (sign * tickSizes[i]) / 2 - start) >= 0 &&
sign * (tickPosition + (sign * tickSizes[i]) / 2 - end) <= 0
) {
nonOverlappingTickValues.push(tickValues[i]);
end = tickPosition - sign * (tickSizes[i] / 2 + 10);
}
}
nonOverlappingTickValues = nonOverlappingTickValues.reverse();
tickValues = nonOverlappingTickValues;
}
const xAxis = d3AxisBottom(xAxisScale)
.tickSize(xAxistickSize)
.tickPadding(tickPadding)
.tickValues(tickValues)
.tickFormat(tickFormat);
if (xAxisParams.xAxisElement) {
d3Select(xAxisParams.xAxisElement)
.call(xAxis)
.selectAll('text')
.attr('aria-hidden', 'true')
.style('direction', 'ltr')
.style('unicode-bidi', 'isolate');
}
return { xScale: xAxisScale, tickValues, tickLabels: tickValues.map(xAxis.tickFormat()!) };
}
export function useRtl(): boolean {
const { dir } = useFluent(); // "dir" returns "ltr" or "rtl"
return dir === 'rtl';
}
function isPowerOf10(num: number): boolean {
const roundedfinalYMax = handleFloatingPointPrecisionError(num);
return Math.log10(roundedfinalYMax) % 1 === 0;
}
//for reference, go through this 'https://docs.python.org/release/2.5.1/tut/node16.html'
function handleFloatingPointPrecisionError(num: number): number {
const rounded = Math.round(num);
return Math.abs(num - rounded) < 1e-6 ? rounded : num;
}
/**
* This method is used to calculate the rounded tick values for the y-axis
* @param {number} minVal
* @param {number} maxVal
* @param {number} splitInto
* @returns {number[]}
*/
function calculateRoundedTicks(minVal: number, maxVal: number, splitInto: number) {
const finalYmin = minVal >= 0 && minVal === maxVal ? 0 : minVal;
const finalYmax = minVal < 0 && minVal === maxVal ? 0 : maxVal;
const ticksInterval = d3nice(finalYmin, finalYmax, splitInto);
const ticks = d3Ticks(ticksInterval[0], ticksInterval[ticksInterval.length - 1], splitInto);
if (ticks[ticks.length - 1] > finalYmax && isPowerOf10(finalYmax)) {
ticks.pop();
}
return ticks;
}
/**
* This method used for creating data points for the y axis.
* @export
* @param {number} maxVal
* @param {number} minVal
* @param {number} splitInto
* @param {boolean} isIntegralDataset
* @returns {number[]}
*/
export function prepareDatapoints(
maxVal: number,
minVal: number,
splitInto: number,
isIntegralDataset: boolean,
roundedTicks?: boolean,
): number[] {
if (roundedTicks) {
return calculateRoundedTicks(minVal, maxVal, splitInto);
}
const val = isIntegralDataset
? Math.ceil((maxVal - minVal) / splitInto)
: (maxVal - minVal) / splitInto >= 1
? Math.ceil((maxVal - minVal) / splitInto)
: (maxVal - minVal) / splitInto;
/*
For cases where we have negative and positive values
The dataPointsArray is filled from 0 to minVal by val difference
Then the array is reversed and values from 0(excluding 0) to maxVal are appended
This ensures presence of 0 to act as an anchor reference.
For simple cases where the scale may not encounter such a need for 0,
We simply fill from minVal to maxVal
*/
const dataPointsArray: number[] = [minVal < 0 && maxVal >= 0 ? 0 : minVal];
/*For the case of all positive or all negative, we need to add another value
in array for atleast one interval, but in case of mix of positive and negative,
there will always be one more entry that will be added by the logic we have*/
if (dataPointsArray[0] === minVal) {
dataPointsArray.push(minVal + val);
}
if (minVal < 0 && maxVal >= 0) {
while (dataPointsArray[dataPointsArray.length - 1] > minVal) {
dataPointsArray.push(dataPointsArray[dataPointsArray.length - 1] - val);
}
dataPointsArray.reverse();
}
while (dataPointsArray[dataPointsArray.length - 1] < maxVal) {
dataPointsArray.push(dataPointsArray[dataPointsArray.length - 1] + val);
}
return dataPointsArray;
}
export function createYAxisForHorizontalBarChartWithAxis(
yAxisParams: IYAxisParams,
isRtl: boolean,
axisData: IAxisData,
): ScaleLinear<number, number> {
const {
yMinMaxValues = { startValue: 0, endValue: 0 },
yAxisElement = null,
yMaxValue = 0,
yMinValue = 0,
containerHeight,
margins,
tickPadding = 12,
maxOfYVal = 0,
yAxisTickFormat,
yAxisTickCount = 4,
tickValues,
tickStep,
tick0,
tickText,
} = yAxisParams;
// maxOfYVal coming from horizontal bar chart with axis (Calculation done at base file)
const tempVal = maxOfYVal || yMinMaxValues.endValue;
const finalYmax = tempVal > yMaxValue ? tempVal : yMaxValue!;
const finalYmin = yMinMaxValues.startValue < yMinValue ? Math.min(0, yMinMaxValues.startValue) : yMinValue!;
const yAxisScale = d3ScaleLinear()
.domain([finalYmin, finalYmax])
.range([containerHeight - margins.bottom!, margins.top!]);
const axis = isRtl ? d3AxisRight(yAxisScale) : d3AxisLeft(yAxisScale);
const yAxis = axis.tickPadding(tickPadding).ticks(yAxisTickCount);
const tickFormat = (domainValue: NumberValue, index: number) => {
if (tickValues && tickText && typeof tickText[index] !== 'undefined') {
return tickText[index];
}
if (typeof yAxisTickFormat === 'function') {
return yAxisTickFormat(domainValue, index);
}
if (typeof yAxisTickFormat === 'string') {
return d3Format(yAxisTickFormat)(domainValue);
}
const value = typeof domainValue === 'number' ? domainValue : domainValue.valueOf();
return defaultYAxisTickFormatter(value);
};
yAxis.tickFormat(tickFormat);
let customTickValues: number[] | undefined;
if (tickValues) {
customTickValues = tickValues as number[];
} else if (tickStep) {
customTickValues = generateNumericTicks(undefined, tickStep, tick0, yAxisScale.domain());
}
if (customTickValues) {
yAxis.tickValues(customTickValues);
}
yAxisElement ? d3Select(yAxisElement).call(yAxis).selectAll('text').attr('aria-hidden', 'true') : '';
axisData.yAxisDomainValues = yAxisScale.domain();
axisData.yAxisTickText = (yAxis.tickValues() ?? yAxisScale.ticks(yAxisTickCount)).map(yAxis.tickFormat()!);
return yAxisScale;
}
export function createNumericYAxis(
yAxisParams: IYAxisParams,
isRtl: boolean,
axisData: IAxisData,
isIntegralDataset: boolean,
chartType: ChartTypes,
useSecondaryYScale: boolean = false,
roundedTicks: boolean = false,
scaleType?: AxisScaleType,
_useRtl?: boolean,
): ScaleLinear<number, number> {
const {
yMinMaxValues = { startValue: 0, endValue: 0 },
yAxisElement = null,
yMaxValue = 0,
yMinValue = 0,
containerHeight,
containerWidth,
margins,
tickPadding = 12,
maxOfYVal = 0,
yAxisTickFormat,
yAxisTickCount = 4,
eventAnnotationProps,
eventLabelHeight,
tickValues,
tickStep,
tick0,
tickText,
} = yAxisParams;
// maxOfYVal coming from only area chart and Grouped vertical bar chart(Calculation done at base file)
const tempVal = maxOfYVal || yMinMaxValues.endValue || 0;
const finalYmax = tempVal > yMaxValue ? tempVal : yMaxValue!;
const finalYmin = Math.min(yMinMaxValues.startValue || 0, yMinValue || 0);
const domainValues = prepareDatapoints(finalYmax, finalYmin, yAxisTickCount, isIntegralDataset, roundedTicks);
let yMin = finalYmin;
let yMax = domainValues[domainValues.length - 1];
if (chartType === ChartTypes.ScatterChart) {
const yPadding = (yMax - yMin) * 0.1;
yMin = yMin - yPadding;
yMax = yMax + yPadding;
}
let scaleDomain = [domainValues[0], domainValues[domainValues.length - 1]];
if (scaleType === 'log') {
let domainStart = yMinMaxValues.startValue;
let domainEnd = yMinMaxValues.endValue;
if (yMinValue > 0) {
domainStart = Math.min(domainStart, yMinValue);
}
if (yMaxValue > 0) {
domainEnd = Math.max(domainEnd, yMaxValue);
}
scaleDomain = [domainStart, domainEnd];
}
const yAxisScale = createNumericScale(scaleType)
.domain(scaleDomain)
.range([containerHeight - margins.bottom!, margins.top! + (eventAnnotationProps! ? eventLabelHeight! : 0)]);
const axis =
(!isRtl && useSecondaryYScale) || (isRtl && !useSecondaryYScale) ? d3AxisRight(yAxisScale) : d3AxisLeft(yAxisScale);
const yAxis = axis.tickPadding(tickPadding).tickSizeInner(-(containerWidth - margins.left! - margins.right!));
let customTickValues: number[] | undefined;
if (tickValues) {
customTickValues = tickValues as number[];
} else if (tickStep) {
customTickValues = generateNumericTicks(scaleType, tickStep, tick0, yAxisScale.domain());
}
if (customTickValues) {
yAxis.tickValues(customTickValues);
axisData.yAxisDomainValues = customTickValues;
} else if (scaleType !== 'log') {
yAxis.tickValues(domainValues);
}
const tickFormat = (domainValue: NumberValue, index: number, defaultFormat?: (val: NumberValue) => string) => {
if (tickValues && tickText && typeof tickText[index] !== 'undefined') {
return tickText[index];
}
if (typeof yAxisTickFormat === 'function') {
return yAxisTickFormat(domainValue, index);
}
if (typeof yAxisTickFormat === 'string') {
return d3Format(yAxisTickFormat)(domainValue);
}
const value = typeof domainValue === 'number' ? domainValue : domainValue.valueOf();
return defaultFormat?.(value) === '' ? '' : defaultYAxisTickFormatter(value);
};
yAxis.tickFormat((v, i) => tickFormat(v as NumberValue, i, yAxisScale.tickFormat(yAxisTickCount)));
yAxisElement
? d3Select(yAxisElement)
.call(yAxis)
.selectAll('text')
.attr('aria-hidden', 'true')
.style('direction', 'ltr')
.style('unicode-bidi', 'isolate')
.style('text-anchor', !useSecondaryYScale && (_useRtl ? 'start' : 'end'))
: '';
axisData.yAxisDomainValues = yAxisScale.domain();
axisData.yAxisTickText = (yAxis.tickValues() ?? yAxisScale.ticks(yAxisTickCount)).map(yAxis.tickFormat()!);
return yAxisScale;
}
/**
* Creating String Y axis of the chart for Horizontal Bar Chart With Axis
* @param yAxisParams
* @param dataPoints
* @param isRtl
*/
export const createStringYAxisForHorizontalBarChartWithAxis = (
yAxisParams: IYAxisParams,
dataPoints: string[],
isRtl: boolean,
axisData: IAxisData,
barWidth: number,
): ScaleBand<string> => {
const {
containerHeight,
tickPadding = 12,
margins,
yAxisTickFormat,
yAxisElement,
yAxisPadding,
tickValues,
tickText,
} = yAxisParams;
let yAxisPaddingValue = yAxisPadding ?? 0.5;
yAxisPaddingValue = yAxisPaddingValue === 1 ? 0.99 : yAxisPaddingValue;
const yAxisScale = d3ScaleBand()
.domain(dataPoints)
.range([containerHeight - margins.bottom!, margins.top!])
.padding(yAxisPaddingValue);
const axis = isRtl ? d3AxisRight(yAxisScale) : d3AxisLeft(yAxisScale);
const customTickValues = (tickValues as string[] | undefined) ?? dataPoints;
const tickFormat = (domainValue: string, _index: number) => {
if (tickValues && tickText && typeof tickText[_index] !== 'undefined') {
return tickText[_index];
}
if (typeof yAxisTickFormat === 'function') {
return yAxisTickFormat(domainValue, _index);
}
return domainValue;
};
const yAxis = axis.tickPadding(tickPadding).tickValues(customTickValues).tickFormat(tickFormat);
yAxisElement ? d3Select(yAxisElement).call(yAxis).selectAll('text') : '';
axisData.yAxisTickText = yAxis.tickValues()!.map(yAxis.tickFormat()!);
return yAxisScale;
};
/**
* Creating String Y axis of the chart for other chart except Horizontal Bar Chart With Axis
* @param yAxisParams
* @param dataPoints
* @param isRtl
*/
export const createStringYAxis = (
yAxisParams: IYAxisParams,
dataPoints: string[],
isRtl: boolean,
axisData: IAxisData,
barWidth?: number,
chartType?: ChartTypes,
): ScaleBand<string> => {
const {
containerHeight,
tickPadding = 12,
margins,
yAxisTickFormat,
yAxisElement,
yAxisPadding = 0,
containerWidth,
tickValues,
tickText,
} = yAxisParams;
const yAxisScale = d3ScaleBand()
.domain(dataPoints)
.range([containerHeight - margins.bottom!, margins.top!])
.padding(yAxisPadding);
if (chartType === ChartTypes.VerticalStackedBarChart) {
yAxisScale.paddingInner(1).paddingOuter(0);
}
const axis = isRtl ? d3AxisRight(yAxisScale) : d3AxisLeft(yAxisScale);
const customTickValues = (tickValues as string[] | undefined) ?? dataPoints;
const tickFormat = (domainValue: string, _index: number) => {
if (tickValues && tickText && typeof tickText[_index] !== 'undefined') {
return tickText[_index];
}
if (typeof yAxisTickFormat === 'function') {
return yAxisTickFormat(domainValue, _index);
}
return domainValue;
};
const yAxis = axis.tickPadding(tickPadding).tickValues(customTickValues).tickFormat(tickFormat).tickSize(0);
if (chartType === ChartTypes.VerticalStackedBarChart) {
axis.tickSizeInner(-(containerWidth - margins.left! - margins.right!));
}
yAxisElement ? d3Select(yAxisElement).call(yAxis).selectAll('text') : '';
axisData.yAxisTickText = yAxis.tickValues()!.map(yAxis.tickFormat()!);
return yAxisScale;