-
Notifications
You must be signed in to change notification settings - Fork 224
/
Copy pathChartCanvas.tsx
1336 lines (1154 loc) · 44.1 KB
/
ChartCanvas.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 { extent as d3Extent, max, min } from "d3-array";
import { ScaleContinuousNumeric, ScaleTime } from "d3-scale";
import * as React from "react";
import { clearCanvas, functor, head, identity, isDefined, isNotDefined, last, shallowEqual } from "./utils";
import { IZoomAnchorOptions, mouseBasedZoomAnchor } from "./zoom";
import {
ChartConfig,
getChartConfigWithUpdatedYScales,
getCurrentCharts,
getCurrentItem,
getNewChartConfig,
} from "./utils/ChartDataUtil";
import { EventCapture } from "./EventCapture";
import { CanvasContainer, ICanvasContexts } from "./CanvasContainer";
import evaluator from "./utils/evaluator";
import type { MoreProps } from "./MoreProps";
const CANDIDATES_FOR_RESET = ["seriesName"];
const shouldResetChart = (thisProps: any, nextProps: any) => {
return !CANDIDATES_FOR_RESET.every((key) => {
const result = shallowEqual(thisProps[key], nextProps[key]);
return result;
});
};
const getCursorStyle = () => {
const tooltipStyle = `
.react-financial-charts-grabbing-cursor {
pointer-events: all;
cursor: -moz-grabbing;
cursor: -webkit-grabbing;
cursor: grabbing;
}
.react-financial-charts-crosshair-cursor {
pointer-events: all;
cursor: crosshair;
}
.react-financial-charts-tooltip-hover {
pointer-events: all;
cursor: pointer;
}
.react-financial-charts-avoid-interaction {
pointer-events: none;
}
.react-financial-charts-enable-interaction {
pointer-events: all;
}
.react-financial-charts-tooltip {
pointer-events: all;
cursor: pointer;
}
.react-financial-charts-default-cursor {
cursor: default;
}
.react-financial-charts-move-cursor {
cursor: move;
}
.react-financial-charts-pointer-cursor {
cursor: pointer;
}
.react-financial-charts-ns-resize-cursor {
cursor: ns-resize;
}
.react-financial-charts-ew-resize-cursor {
cursor: ew-resize;
}`;
return <style type="text/css">{tooltipStyle}</style>;
};
export interface ChartCanvasContextType<TXAxis extends number | Date> {
width: number;
height: number;
margin: { top: number; right: number; bottom: number; left: number };
chartId: number | string;
getCanvasContexts?: () => ICanvasContexts | undefined;
xScale: Function;
ratio: number;
// Not sure if it should be optional
xAccessor: (data: any) => TXAxis;
displayXAccessor: (data: any) => TXAxis;
xAxisZoom?: (newDomain: any) => void;
yAxisZoom?: (chartId: string, newDomain: any) => void;
redraw: () => void;
plotData: any[];
fullData: any[];
chartConfigs: ChartConfig[];
morePropsDecorator?: () => void;
generateSubscriptionId?: () => number;
getMutableState: () => {};
amIOnTop: (id: string | number) => boolean;
subscribe: (id: string | number, rest: any) => void;
unsubscribe: (id: string | number) => void;
setCursorClass: (className: string | null | undefined) => void;
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {};
export const chartCanvasContextDefaultValue: ChartCanvasContextType<number | Date> = {
amIOnTop: () => false,
chartConfigs: [],
chartId: 0,
ratio: 0,
displayXAccessor: () => 0,
fullData: [],
getMutableState: () => ({}),
height: 0,
margin: { top: 0, right: 0, bottom: 0, left: 0 },
plotData: [],
setCursorClass: noop,
subscribe: noop,
unsubscribe: noop,
redraw: noop,
width: 0,
xAccessor: () => 0,
xScale: noop,
};
export const ChartCanvasContext =
React.createContext<ChartCanvasContextType<number | Date>>(chartCanvasContextDefaultValue);
const getDimensions = <TXAxis extends number | Date>(props: ChartCanvasProps<TXAxis>) => {
const { margin, height, width } = props;
return {
height: height - margin.top - margin.bottom,
width: width - margin.left - margin.right,
};
};
const getXScaleDirection = (flipXScale?: boolean) => {
return flipXScale ? -1 : 1;
};
const calculateFullData = <TXAxis extends number | Date>(props: ChartCanvasProps<TXAxis>) => {
const {
data: fullData,
plotFull,
xScale,
clamp,
pointsPerPxThreshold,
flipXScale,
xAccessor,
displayXAccessor,
minPointsPerPxThreshold,
} = props;
const useWholeData = plotFull !== undefined ? plotFull : xAccessor === identity;
const { filterData } = evaluator({
xScale,
useWholeData,
clamp,
pointsPerPxThreshold,
minPointsPerPxThreshold,
flipXScale,
});
return {
xAccessor,
displayXAccessor: displayXAccessor ?? xAccessor,
xScale: xScale.copy(),
fullData,
filterData,
};
};
const resetChart = <TXAxis extends number | Date>(props: ChartCanvasProps<TXAxis>) => {
const state = calculateState(props);
const { xAccessor, displayXAccessor, fullData, plotData: initialPlotData, xScale } = state;
const { postCalculator, children } = props;
const plotData = postCalculator !== undefined ? postCalculator(initialPlotData) : initialPlotData;
const dimensions = getDimensions(props);
const chartConfigs = getChartConfigWithUpdatedYScales(
getNewChartConfig(dimensions, children),
{ plotData, xAccessor, displayXAccessor, fullData },
xScale.domain(),
);
return {
...state,
xScale,
plotData,
chartConfigs,
};
};
const updateChart = (
newState: any,
initialXScale: ScaleContinuousNumeric<number, number> | ScaleTime<number, number>,
props: any,
lastItemWasVisible: boolean,
initialChartConfig: any,
) => {
const { fullData, xScale, xAccessor, displayXAccessor, filterData } = newState;
const lastItem = last(fullData);
const lastXItem = xAccessor(lastItem);
const [start, end] = initialXScale.domain();
const { postCalculator, children, padding, flipXScale, maintainPointsPerPixelOnResize } = props;
const direction = getXScaleDirection(flipXScale);
const dimensions = getDimensions(props);
const updatedXScale = setXRange(xScale, dimensions, padding, direction);
let initialPlotData;
if (!lastItemWasVisible || end >= lastXItem) {
// resize comes here...
// get plotData between [start, end] and do not change the domain
const [rangeStart, rangeEnd] = initialXScale.range();
const [newRangeStart, newRangeEnd] = updatedXScale.range();
const newDomainExtent =
((newRangeEnd - newRangeStart) / (rangeEnd - rangeStart)) * (end.valueOf() - start.valueOf());
const newStart = maintainPointsPerPixelOnResize ? end.valueOf() - newDomainExtent : start;
const lastItemX = initialXScale(lastXItem);
const response = filterData(fullData, [newStart, end], xAccessor, updatedXScale, {
fallbackStart: start,
fallbackEnd: { lastItem, lastItemX },
});
initialPlotData = response.plotData;
updatedXScale.domain(response.domain);
} else if (lastItemWasVisible && end < lastXItem) {
// this is when a new item is added and last item was visible
// so slide over and show the new item also
// get plotData between [xAccessor(l) - (end - start), xAccessor(l)] and DO change the domain
const dx = initialXScale(lastXItem) - initialXScale.range()[1];
const [newStart, newEnd] = initialXScale
.range()
.map((x) => x + dx)
.map((x) => initialXScale.invert(x));
const response = filterData(fullData, [newStart, newEnd], xAccessor, updatedXScale);
initialPlotData = response.plotData;
updatedXScale.domain(response.domain); // if last item was visible, then shift
}
const plotData = postCalculator(initialPlotData);
const chartConfigs = getChartConfigWithUpdatedYScales(
getNewChartConfig(dimensions, children, initialChartConfig),
{ plotData, xAccessor, displayXAccessor, fullData },
updatedXScale.domain(),
);
return {
xScale: updatedXScale,
xAccessor,
chartConfigs,
plotData,
fullData,
filterData,
};
};
const calculateState = <TXAxis extends number | Date>(props: ChartCanvasProps<TXAxis>) => {
const { xAccessor: inputXAccessor, xExtents: xExtentsProp, data, padding, flipXScale } = props;
const direction = getXScaleDirection(flipXScale);
const dimensions = getDimensions(props);
const extent =
typeof xExtentsProp === "function"
? xExtentsProp(data)
: (d3Extent<number | Date>(
xExtentsProp.map((d: any) => functor(d)).map((each: any) => each(data, inputXAccessor)),
) as [TXAxis, TXAxis]);
const { xAccessor, displayXAccessor, xScale, fullData, filterData } = calculateFullData(props);
const updatedXScale = setXRange(xScale, dimensions, padding, direction);
const { plotData, domain } = filterData(fullData, extent, inputXAccessor, updatedXScale);
return {
plotData,
xScale: updatedXScale.domain(domain),
xAccessor,
displayXAccessor,
fullData,
filterData,
};
};
const setXRange = (xScale: any, dimensions: any, padding: any, direction = 1) => {
if (xScale.rangeRoundPoints) {
if (isNaN(padding)) {
throw new Error("padding has to be a number for ordinal scale");
}
xScale.rangeRoundPoints([0, dimensions.width], padding);
} else if (xScale.padding) {
if (isNaN(padding)) {
throw new Error("padding has to be a number for ordinal scale");
}
xScale.range([0, dimensions.width]);
xScale.padding(padding / 2);
} else {
const { left, right } = isNaN(padding) ? padding : { left: padding, right: padding };
if (direction > 0) {
xScale.range([left, dimensions.width - right]);
} else {
xScale.range([dimensions.width - right, left]);
}
}
return xScale;
};
const pinchCoordinates = (pinch: any) => {
const { touch1Pos, touch2Pos } = pinch;
return {
topLeft: [Math.min(touch1Pos[0], touch2Pos[0]), Math.min(touch1Pos[1], touch2Pos[1])],
bottomRight: [Math.max(touch1Pos[0], touch2Pos[0]), Math.max(touch1Pos[1], touch2Pos[1])],
};
};
const isInteractionEnabled = (
xScale: ScaleContinuousNumeric<number, number> | ScaleTime<number, number>,
xAccessor: any,
data: any,
) => {
const interaction = !isNaN(xScale(xAccessor(head(data)))) && isDefined(xScale.invert);
return interaction;
};
export interface ChartCanvasProps<TXAxis extends number | Date> {
readonly clamp?:
| boolean
| ("left" | "right" | "both")
| ((domain: [number, number], items: [number, number]) => [number, number]);
readonly className?: string;
readonly children?: React.ReactNode;
readonly data: any[];
readonly defaultFocus?: boolean;
readonly disableInteraction?: boolean;
readonly disablePan?: boolean;
readonly disableZoom?: boolean;
readonly displayXAccessor?: (data: any) => TXAxis;
readonly flipXScale?: boolean;
readonly height: number;
readonly margin: {
bottom: number;
left: number;
right: number;
top: number;
};
readonly maintainPointsPerPixelOnResize?: boolean;
readonly minPointsPerPxThreshold?: number;
readonly mouseMoveEvent?: boolean;
/**
* Called when panning left past the first data point.
*/
readonly onLoadAfter?: (start: TXAxis, end: TXAxis) => void;
/**
* Called when panning right past the last data point.
*/
readonly onLoadBefore?: (start: TXAxis, end: TXAxis) => void;
/**
* Click event handler.
*/
readonly onClick?: React.MouseEventHandler<HTMLDivElement>;
/**
* Double click event handler.
*/
readonly onDoubleClick?: React.MouseEventHandler<HTMLDivElement>;
readonly padding?:
| number
| {
bottom: number;
left: number;
right: number;
top: number;
};
readonly plotFull?: boolean;
readonly pointsPerPxThreshold?: number;
readonly postCalculator?: (plotData: any[]) => any[];
readonly ratio: number;
readonly seriesName: string;
readonly useCrossHairStyleCursor?: boolean;
readonly width: number;
readonly xAccessor: (data: any) => TXAxis;
readonly xExtents: ((data: any[]) => [TXAxis, TXAxis]) | (((data: any[]) => TXAxis) | TXAxis)[];
readonly xScale: ScaleContinuousNumeric<number, number> | ScaleTime<number, number>;
readonly zIndex?: number;
readonly zoomAnchor?: (options: IZoomAnchorOptions<any, TXAxis>) => TXAxis;
readonly zoomMultiplier?: number;
}
interface ChartCanvasState<TXAxis extends number | Date> {
lastProps?: ChartCanvasProps<TXAxis>;
propIteration?: number;
xAccessor: (data: any) => TXAxis;
displayXAccessor?: any;
filterData?: any;
chartConfigs: ChartConfig[];
plotData: any[];
xScale: ScaleContinuousNumeric<number, number> | ScaleTime<number, number>;
fullData: any[];
}
interface Subscription {
id: string;
getPanConditions: () => {
draggable: boolean;
panEnabled: boolean;
};
draw: (props: { trigger: string } | { force: boolean }) => void;
listener: (type: string, newMoreProps: MoreProps | undefined, state: any, e: any) => void;
}
interface MutableState {
mouseXY: [number, number];
currentItem: any;
currentCharts: string[];
}
export class ChartCanvas<TXAxis extends number | Date> extends React.Component<
ChartCanvasProps<TXAxis>,
ChartCanvasState<TXAxis>
> {
public static defaultProps = {
clamp: false,
className: "react-financial-charts",
defaultFocus: true,
disablePan: false,
disableInteraction: false,
disableZoom: false,
flipXScale: false,
maintainPointsPerPixelOnResize: true,
margin: { top: 0, right: 40, bottom: 40, left: 0 },
minPointsPerPxThreshold: 1 / 100,
mouseMoveEvent: true,
postCalculator: identity,
padding: 0,
pointsPerPxThreshold: 2,
useCrossHairStyleCursor: true,
xAccessor: identity as (data: any) => any,
xExtents: [min, max] as any[],
zIndex: 1,
zoomAnchor: mouseBasedZoomAnchor,
zoomMultiplier: 1.1,
};
private readonly canvasContainerRef = React.createRef<CanvasContainer>();
private readonly eventCaptureRef = React.createRef<EventCapture>();
private finalPinch?: boolean;
private lastSubscriptionId = 0;
private mutableState: MutableState = { mouseXY: [0, 0], currentCharts: [], currentItem: null };
private panInProgress = false;
private prevMouseXY?: number[];
private subscriptions: Subscription[] = [];
private waitingForPinchZoomAnimationFrame?: boolean;
private waitingForPanAnimationFrame?: boolean;
private waitingForMouseMoveAnimationFrame?: boolean;
// tslint:disable-next-line: variable-name
private hackyWayToStopPanBeyondBounds__plotData?: any[] | null;
// tslint:disable-next-line: variable-name
private hackyWayToStopPanBeyondBounds__domain?: any[] | null;
public constructor(props: ChartCanvasProps<TXAxis>) {
super(props);
this.state = resetChart(props);
}
public static getDerivedStateFromProps<TXAxis extends number | Date>(
props: ChartCanvasProps<TXAxis>,
state: ChartCanvasState<TXAxis>,
): ChartCanvasState<TXAxis> {
const { chartConfigs: initialChartConfig, plotData, xAccessor, xScale } = state;
const interaction = isInteractionEnabled(xScale, xAccessor, plotData);
const shouldReset = shouldResetChart(state.lastProps || {}, props);
let newState: ChartCanvasState<TXAxis>;
if (!interaction || shouldReset || !shallowEqual(state.lastProps?.xExtents, props.xExtents)) {
// do reset
newState = resetChart(props);
} else {
const [start, end] = xScale.domain();
const prevLastItem = last(state.fullData);
const calculatedState = calculateFullData(props);
const { xAccessor } = calculatedState;
const previousX = xAccessor(prevLastItem);
const lastItemWasVisible = previousX <= end && previousX >= start;
newState = updateChart(calculatedState, xScale, props, lastItemWasVisible, initialChartConfig);
}
return {
...newState,
lastProps: props,
propIteration: (state.propIteration || 0) + 1,
};
}
public getSnapshotBeforeUpdate(
prevProps: Readonly<ChartCanvasProps<TXAxis>>,
prevState: Readonly<ChartCanvasState<TXAxis>>,
) {
// propIteration is incremented when the props change to differentiate between state updates
// and prop updates
if (prevState.propIteration !== this.state.propIteration && !this.panInProgress) {
this.clearThreeCanvas();
}
return null;
}
public componentDidUpdate(prevProps: ChartCanvasProps<TXAxis>) {
if (prevProps.data !== this.props.data) {
this.triggerEvent("dataupdated", {
chartConfigs: this.state.chartConfigs,
xScale: this.state.xScale,
plotData: this.state.plotData,
});
}
}
public getMutableState = () => {
return this.mutableState;
};
public getCanvasContexts = () => {
return this.canvasContainerRef.current?.getCanvasContexts();
};
public generateSubscriptionId = () => {
this.lastSubscriptionId++;
return this.lastSubscriptionId;
};
public clearBothCanvas() {
const canvases = this.getCanvasContexts();
if (canvases && canvases.axes && canvases.mouseCoord) {
clearCanvas([canvases.axes, canvases.mouseCoord], this.props.ratio);
}
}
public clearMouseCanvas() {
const canvases = this.getCanvasContexts();
if (canvases && canvases.mouseCoord) {
clearCanvas([canvases.mouseCoord], this.props.ratio);
}
}
public clearThreeCanvas() {
const canvases = this.getCanvasContexts();
if (canvases && canvases.axes && canvases.mouseCoord && canvases.bg) {
clearCanvas([canvases.axes, canvases.mouseCoord, canvases.bg], this.props.ratio);
}
}
public subscribe = (id: string | number, rest: any) => {
const {
getPanConditions = functor({
draggable: false,
panEnabled: true,
}),
} = rest;
this.subscriptions = this.subscriptions.concat({
id,
...rest,
getPanConditions,
});
};
public unsubscribe = (id: string | number) => {
this.subscriptions = this.subscriptions.filter((each) => each.id !== id);
};
public getAllPanConditions = () => {
return this.subscriptions.map((each) => each.getPanConditions());
};
public setCursorClass = (className: string | null | undefined) => {
this.eventCaptureRef.current?.setCursorClass(className);
};
public amIOnTop = (id: string | number) => {
const dragableComponents = this.subscriptions.filter((each) => each.getPanConditions().draggable);
return dragableComponents.length > 0 && last(dragableComponents).id === id;
};
public handleContextMenu = (mouseXY: number[], e: React.MouseEvent) => {
const { xAccessor, chartConfigs, plotData, xScale } = this.state;
const currentCharts = getCurrentCharts(chartConfigs, mouseXY);
const currentItem = getCurrentItem(xScale, xAccessor, mouseXY, plotData);
this.triggerEvent(
"contextmenu",
{
mouseXY,
currentItem,
currentCharts,
},
e,
);
};
public calculateStateForDomain = (newDomain: any) => {
const {
xAccessor,
displayXAccessor,
xScale: initialXScale,
chartConfigs: initialChartConfig,
plotData: initialPlotData,
} = this.state;
const { filterData, fullData } = this.state;
const { postCalculator = ChartCanvas.defaultProps.postCalculator } = this.props;
const { plotData: beforePlotData, domain } = filterData(fullData, newDomain, xAccessor, initialXScale, {
currentPlotData: initialPlotData,
currentDomain: initialXScale!.domain(),
});
const plotData = postCalculator(beforePlotData);
const updatedScale = initialXScale.copy().domain(domain) as
| ScaleContinuousNumeric<number, number>
| ScaleTime<number, number>;
const chartConfigs = getChartConfigWithUpdatedYScales(
initialChartConfig,
{ plotData, xAccessor, displayXAccessor, fullData },
updatedScale.domain(),
);
return {
xScale: updatedScale,
plotData,
chartConfigs,
};
};
public pinchZoomHelper = (initialPinch: any, finalPinch: any) => {
const { xScale: initialPinchXScale } = initialPinch;
const {
xScale: initialXScale,
chartConfigs: initialChartConfig,
plotData: initialPlotData,
xAccessor,
displayXAccessor,
filterData,
fullData,
} = this.state;
const { postCalculator = ChartCanvas.defaultProps.postCalculator } = this.props;
const { topLeft: iTL, bottomRight: iBR } = pinchCoordinates(initialPinch);
const { topLeft: fTL, bottomRight: fBR } = pinchCoordinates(finalPinch);
const e = initialPinchXScale.range()[1];
const xDash = Math.round(-(iBR[0] * fTL[0] - iTL[0] * fBR[0]) / (iTL[0] - iBR[0]));
const yDash = Math.round(
e + ((e - iBR[0]) * (e - fTL[0]) - (e - iTL[0]) * (e - fBR[0])) / (e - iTL[0] - (e - iBR[0])),
);
const x = Math.round((-xDash * iTL[0]) / (-xDash + fTL[0]));
const y = Math.round(e - ((yDash - e) * (e - iTL[0])) / (yDash + (e - fTL[0])));
const newDomain = [x, y].map(initialPinchXScale.invert);
const { plotData: beforePlotData, domain } = filterData(fullData, newDomain, xAccessor, initialPinchXScale, {
currentPlotData: initialPlotData,
currentDomain: initialXScale!.domain(),
});
const plotData = postCalculator(beforePlotData);
const updatedScale = initialXScale!.copy().domain(domain) as
| ScaleContinuousNumeric<number, number>
| ScaleTime<number, number>;
const mouseXY = finalPinch.touch1Pos;
const chartConfigs = getChartConfigWithUpdatedYScales(
initialChartConfig,
{ plotData, xAccessor, displayXAccessor, fullData },
updatedScale.domain(),
);
const currentItem = getCurrentItem(updatedScale, xAccessor, mouseXY, plotData);
return {
chartConfigs,
xScale: updatedScale,
plotData,
mouseXY,
currentItem,
xAccessor,
fullData,
};
};
public cancelDrag() {
this.eventCaptureRef.current?.cancelDrag();
this.triggerEvent("dragcancel");
}
public handlePinchZoom = (initialPinch: any, finalPinch: any, e: any) => {
if (!this.waitingForPinchZoomAnimationFrame) {
this.waitingForPinchZoomAnimationFrame = true;
const state = this.pinchZoomHelper(initialPinch, finalPinch);
this.triggerEvent("pinchzoom", state, e);
this.finalPinch = finalPinch;
requestAnimationFrame(() => {
this.clearBothCanvas();
this.draw({ trigger: "pinchzoom" });
this.waitingForPinchZoomAnimationFrame = false;
});
}
};
public handlePinchZoomEnd = (initialPinch: any, e: any) => {
const { xAccessor = ChartCanvas.defaultProps.xAccessor } = this.state;
if (this.finalPinch) {
const state = this.pinchZoomHelper(initialPinch, this.finalPinch);
const { xScale, fullData } = state;
this.triggerEvent("pinchzoom", state, e);
this.finalPinch = undefined;
this.clearThreeCanvas();
const firstItem = head(fullData);
const scale_start = head(xScale.domain());
const data_start = xAccessor(firstItem);
const lastItem = last(fullData);
const scale_end = last(xScale.domain());
const data_end = xAccessor(lastItem);
const { onLoadAfter, onLoadBefore } = this.props;
this.setState(state, () => {
if (scale_start < data_start) {
if (onLoadBefore !== undefined) {
onLoadBefore(scale_start, data_start);
}
}
if (data_end < scale_end) {
if (onLoadAfter !== undefined) {
onLoadAfter(data_end, scale_end);
}
}
});
}
};
public handleZoom = (zoomDirection: any, mouseXY: any, e: any) => {
if (this.panInProgress) {
return;
}
const { xAccessor, xScale: initialXScale, plotData: initialPlotData, fullData } = this.state;
const {
zoomMultiplier = ChartCanvas.defaultProps.zoomMultiplier,
zoomAnchor = ChartCanvas.defaultProps.zoomAnchor,
} = this.props;
const item = zoomAnchor({
xScale: initialXScale!,
xAccessor: xAccessor!,
mouseXY,
plotData: initialPlotData,
});
const cx = initialXScale(item);
const c = zoomDirection > 0 ? 1 * zoomMultiplier : 1 / zoomMultiplier;
const newDomain = initialXScale!
.range()
.map((x) => cx + (x - cx) * c)
.map((x) => initialXScale.invert(x));
const { xScale, plotData, chartConfigs } = this.calculateStateForDomain(newDomain);
const currentItem = getCurrentItem(xScale, xAccessor, mouseXY, plotData);
const currentCharts = getCurrentCharts(chartConfigs, mouseXY);
this.clearThreeCanvas();
const firstItem = head(fullData);
const scale_start = head(xScale.domain());
const data_start = xAccessor!(firstItem);
const lastItem = last(fullData);
const scale_end = last(xScale.domain());
const data_end = xAccessor!(lastItem);
this.mutableState = {
mouseXY,
currentItem,
currentCharts,
};
this.triggerEvent(
"zoom",
{
xScale,
plotData,
chartConfigs,
mouseXY,
currentCharts,
currentItem,
show: true,
},
e,
);
const { onLoadAfter, onLoadBefore } = this.props;
this.setState(
{
xScale,
plotData,
chartConfigs,
},
() => {
if (scale_start < data_start) {
if (onLoadBefore !== undefined) {
onLoadBefore(scale_start, data_start);
}
}
if (data_end < scale_end) {
if (onLoadAfter !== undefined) {
onLoadAfter(data_end, scale_end);
}
}
},
);
};
public xAxisZoom = (newDomain: any) => {
const { xScale, plotData, chartConfigs } = this.calculateStateForDomain(newDomain);
this.clearThreeCanvas();
const { xAccessor, fullData } = this.state;
const firstItem = head(fullData);
const scale_start = head(xScale.domain());
const data_start = xAccessor!(firstItem);
const lastItem = last(fullData);
const scale_end = last(xScale.domain());
const data_end = xAccessor!(lastItem);
const { onLoadAfter, onLoadBefore } = this.props;
this.setState(
{
xScale,
plotData,
chartConfigs,
},
() => {
if (scale_start < data_start) {
if (onLoadBefore !== undefined) {
onLoadBefore(scale_start, data_start);
}
}
if (data_end < scale_end) {
if (onLoadAfter !== undefined) {
onLoadAfter(data_end, scale_end);
}
}
},
);
};
public yAxisZoom = (chartId: string, newDomain: any) => {
this.clearThreeCanvas();
const { chartConfigs: initialChartConfig } = this.state;
const chartConfigs = initialChartConfig.map((each: any) => {
if (each.id === chartId) {
const { yScale } = each;
return {
...each,
yScale: yScale.copy().domain(newDomain),
yPanEnabled: true,
};
} else {
return each;
}
});
this.setState({
chartConfigs,
});
};
public triggerEvent(type: any, props?: any, e?: any) {
this.subscriptions.forEach((each) => {
const state = {
...this.state,
subscriptions: this.subscriptions,
};
each.listener(type, props, state, e);
});
}
public draw = (props: { trigger: string } | { force: boolean }) => {
this.subscriptions.forEach((each) => {
if (isDefined(each.draw)) {
each.draw(props);
}
});
};
public redraw = () => {
this.clearThreeCanvas();
this.draw({ force: true });
};
public panHelper = (
mouseXY: [number, number],
initialXScale: ScaleContinuousNumeric<number, number> | ScaleTime<number, number>,
{ dx, dy }: { dx: number; dy: number },
chartsToPan: string[],
) => {
const { xAccessor, displayXAccessor, chartConfigs: initialChartConfig, filterData, fullData } = this.state;
const { postCalculator = ChartCanvas.defaultProps.postCalculator } = this.props;
const newDomain = initialXScale
.range()
.map((x) => x - dx)
.map((x) => initialXScale.invert(x));
const { plotData: beforePlotData, domain } = filterData(fullData, newDomain, xAccessor, initialXScale, {
currentPlotData: this.hackyWayToStopPanBeyondBounds__plotData,
currentDomain: this.hackyWayToStopPanBeyondBounds__domain,
ignoreThresholds: true,
});
const updatedScale = initialXScale.copy().domain(domain) as
| ScaleContinuousNumeric<number, number>
| ScaleTime<number, number>;
const plotData = postCalculator(beforePlotData);
const currentItem = getCurrentItem(updatedScale, xAccessor, mouseXY, plotData);
const chartConfigs = getChartConfigWithUpdatedYScales(
initialChartConfig,
{ plotData, xAccessor, displayXAccessor, fullData },
updatedScale.domain(),
dy,
chartsToPan,
);
const currentCharts = getCurrentCharts(chartConfigs, mouseXY);
return {
xScale: updatedScale,
plotData,
chartConfigs,
mouseXY,
currentCharts,
currentItem,
};
};
public handlePan = (
mousePosition: [number, number],
panStartXScale: ScaleContinuousNumeric<number, number> | ScaleTime<number, number>,
dxdy: { dx: number; dy: number },
chartsToPan: string[],
e: React.MouseEvent,
) => {
if (this.waitingForPanAnimationFrame) {
return;
}
this.waitingForPanAnimationFrame = true;
this.hackyWayToStopPanBeyondBounds__plotData =
this.hackyWayToStopPanBeyondBounds__plotData ?? this.state.plotData;
this.hackyWayToStopPanBeyondBounds__domain =
this.hackyWayToStopPanBeyondBounds__domain ?? this.state.xScale!.domain();
const newState = this.panHelper(mousePosition, panStartXScale, dxdy, chartsToPan);
this.hackyWayToStopPanBeyondBounds__plotData = newState.plotData;
this.hackyWayToStopPanBeyondBounds__domain = newState.xScale.domain();
this.panInProgress = true;
this.triggerEvent("pan", newState, e);