-
Notifications
You must be signed in to change notification settings - Fork 829
/
xy-plot.js
605 lines (566 loc) · 16.8 KB
/
xy-plot.js
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
// Copyright (c) 2016 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import PropTypes from 'prop-types';
import equal from 'lodash/isEqual';
import {getCombinedClassName} from 'utils/styling-utils';
import {
extractScalePropsFromProps,
getMissingScaleProps,
getOptionalScaleProps,
getXYPlotValues
} from 'utils/scales-utils';
import {
getStackedData,
getSeriesChildren,
getSeriesPropsFromChildren
} from 'utils/series-utils';
import {
getInnerDimensions,
MarginPropType,
DEFAULT_MARGINS
} from 'utils/chart-utils';
import {AnimationPropType} from 'animation';
import {
CONTINUOUS_COLOR_RANGE,
EXTENDED_DISCRETE_COLOR_RANGE,
SIZE_RANGE,
OPACITY_TYPE
} from 'theme';
import CanvasWrapper from './series/canvas-wrapper';
const ATTRIBUTES = [
'x',
'y',
'radius',
'angle',
'color',
'fill',
'stroke',
'opacity',
'size'
];
/**
* Remove parents from tree formatted data. deep-equal doesnt play nice with data
* that has circular structures, so we make every node single directional by pruning the parents.
* @param {Array} data - the data object to have circular deps resolved in
* @returns {Array} the sanitized data
*/
function cleanseData(data) {
return data.map(series => {
if (!Array.isArray(series)) {
return series;
}
return series.map(row => ({...row, parent: null}));
});
}
/**
* Wrapper on the deep-equal method for checking equality of next props vs current props
* @param {Object} scaleMixins - Scale object.
* @param {Object} nextScaleMixins - Scale object.
* @param {Boolean} hasTreeStructure - Whether or not to cleanse the data of possible cyclic structures
* @returns {Boolean} whether or not the two mixins objects are equal
*/
function checkIfMixinsAreEqual(nextScaleMixins, scaleMixins, hasTreeStructure) {
const newMixins = {
...nextScaleMixins,
_allData: hasTreeStructure
? cleanseData(nextScaleMixins._allData)
: nextScaleMixins._allData
};
const oldMixins = {
...scaleMixins,
_allData: hasTreeStructure
? cleanseData(scaleMixins._allData)
: scaleMixins._allData
};
// it's hard to say if this function is reasonable?
return equal(newMixins, oldMixins);
}
class XYPlot extends React.Component {
static get defaultProps() {
return {
className: ''
};
}
static get propTypes() {
return {
animation: AnimationPropType,
className: PropTypes.string,
dontCheckIfEmpty: PropTypes.bool,
height: PropTypes.number.isRequired,
margin: MarginPropType,
onClick: PropTypes.func,
onDoubleClick: PropTypes.func,
onMouseDown: PropTypes.func,
onMouseUp: PropTypes.func,
onMouseEnter: PropTypes.func,
onMouseLeave: PropTypes.func,
onMouseMove: PropTypes.func,
onTouchStart: PropTypes.func,
onTouchMove: PropTypes.func,
onTouchEnd: PropTypes.func,
onTouchCancel: PropTypes.func,
onWheel: PropTypes.func,
stackBy: PropTypes.oneOf(ATTRIBUTES),
style: PropTypes.object,
width: PropTypes.number.isRequired
};
}
constructor(props) {
super(props);
const {stackBy} = props;
const children = getSeriesChildren(props.children);
const data = getStackedData(children, stackBy);
this.state = {
scaleMixins: this._getScaleMixins(data, props),
data
};
}
// eslint-disable-next-line react/no-deprecated
componentWillReceiveProps(nextProps) {
const children = getSeriesChildren(nextProps.children);
const nextData = getStackedData(children, nextProps.stackBy);
const {scaleMixins} = this.state;
const nextScaleMixins = this._getScaleMixins(nextData, nextProps);
if (
!checkIfMixinsAreEqual(
nextScaleMixins,
scaleMixins,
nextProps.hasTreeStructure
)
) {
this.setState({
scaleMixins: nextScaleMixins,
data: nextData
});
}
}
/**
* Trigger click related callbacks if they are available.
* @param {React.SyntheticEvent} event Click event.
* @private
*/
_clickHandler = event => {
const {onClick} = this.props;
if (onClick) {
onClick(event);
}
};
/**
* Trigger doule-click related callbacks if they are available.
* @param {React.SyntheticEvent} event Double-click event.
* @private
*/
_doubleClickHandler = event => {
const {onDoubleClick} = this.props;
if (onDoubleClick) {
onDoubleClick(event);
}
};
_childPropCache = Object.create(null);
/**
* Memoizes the props of the child.
* This is keyed off of the childs 'key' property or defaults to its index.
* @param {number} index The index of the child
* @param {object} newValues The childs props
*/
_getChildProps(index, newValues) {
const key = newValues.key || `@@series-${index}`;
const cached = this._childPropCache[key];
if (!equal(cached, newValues)) {
this._childPropCache[key] = {...newValues};
}
return this._childPropCache[key];
}
/**
* Prepare the child components (including series) for rendering.
* @returns {Array} Array of child components.
* @private
*/
_getClonedChildComponents() {
const props = this.props;
const {animation} = this.props;
const {scaleMixins, data} = this.state;
const dimensions = getInnerDimensions(this.props, DEFAULT_MARGINS);
const children = React.Children.toArray(this.props.children);
const seriesProps = getSeriesPropsFromChildren(children);
const XYPlotValues = getXYPlotValues(props, children);
return children.map((child, index) => {
let dataProps = null;
if (seriesProps[index]) {
// Get the index of the series in the list of props and retrieve
// the data property from it.
const {seriesIndex} = seriesProps[index];
dataProps = {data: data[seriesIndex]};
}
const childProps = this._getChildProps(index, {
...dimensions,
animation,
...seriesProps[index],
...scaleMixins,
...child.props,
...XYPlotValues[index],
...dataProps
});
const refProp =
dataProps && child.type.prototype && child.type.prototype.render
? {
ref: ref =>
(this[`series${seriesProps[index].seriesIndex}`] = ref)
}
: {};
return React.cloneElement(child, {...childProps, ...refProp});
});
}
/**
* Get the list of scale-related settings that should be applied by default.
* @param {Object} props Object of props.
* @returns {Object} Defaults.
* @private
*/
_getDefaultScaleProps(props) {
const {innerWidth, innerHeight} = getInnerDimensions(
props,
DEFAULT_MARGINS
);
const colorRanges = ['color', 'fill', 'stroke'].reduce((acc, attr) => {
const range =
props[`${attr}Type`] === 'category'
? EXTENDED_DISCRETE_COLOR_RANGE
: CONTINUOUS_COLOR_RANGE;
return {...acc, [`${attr}Range`]: range};
}, {});
return {
xRange: [0, innerWidth],
yRange: [innerHeight, 0],
...colorRanges,
opacityType: OPACITY_TYPE,
sizeRange: SIZE_RANGE
};
}
/**
* Get the map of scales from the props, apply defaults to them and then pass
* them further.
* @param {Object} data Array of all data.
* @param {Object} props Props of the component.
* @returns {Object} Map of scale-related props.
* @private
*/
_getScaleMixins(data, props) {
const filteredData = data.filter(d => d);
const allData = [].concat(...filteredData);
const defaultScaleProps = this._getDefaultScaleProps(props);
const optionalScaleProps = getOptionalScaleProps(props);
const userScaleProps = extractScalePropsFromProps(props, ATTRIBUTES);
const missingScaleProps = getMissingScaleProps(
{
...defaultScaleProps,
...optionalScaleProps,
...userScaleProps
},
allData,
ATTRIBUTES
);
const children = getSeriesChildren(props.children);
const zeroBaseProps = {};
const adjustBy = new Set();
const adjustWhat = new Set();
children.forEach((child, index) => {
if (!child || !data[index]) {
return;
}
ATTRIBUTES.forEach(attr => {
const {
isDomainAdjustmentNeeded,
zeroBaseValue
} = child.type.getParentConfig(attr, child.props);
if (isDomainAdjustmentNeeded) {
adjustBy.add(attr);
adjustWhat.add(index);
}
if (zeroBaseValue) {
const specifiedDomain = props[`${attr}Domain`];
zeroBaseProps[`${attr}BaseValue`] = specifiedDomain
? specifiedDomain[0]
: 0;
}
});
});
return {
...defaultScaleProps,
...zeroBaseProps,
...userScaleProps,
...missingScaleProps,
_allData: data,
_adjustBy: Array.from(adjustBy),
_adjustWhat: Array.from(adjustWhat),
_stackBy: props.stackBy
};
}
/**
* Checks if the plot is empty or not.
* Currently checks the data only.
* @returns {boolean} True for empty.
* @private
*/
_isPlotEmpty() {
const {data} = this.state;
return (
!data ||
!data.length ||
!data.some(series => series && series.some(d => d))
);
}
/**
* Trigger mouse-down related callbacks if they are available.
* @param {React.SyntheticEvent} event Mouse down event.
* @private
*/
_mouseDownHandler = event => {
const {onMouseDown, children} = this.props;
if (onMouseDown) {
onMouseDown(event);
}
const seriesChildren = getSeriesChildren(children);
seriesChildren.forEach((child, index) => {
const component = this[`series${index}`];
if (component && component.onParentMouseDown) {
component.onParentMouseDown(event);
}
});
};
/**
* Trigger onMouseEnter handler if it was passed in props.
* @param {React.SyntheticEvent} event Mouse enter event.
* @private
*/
_mouseEnterHandler = event => {
const {onMouseEnter, children} = this.props;
if (onMouseEnter) {
onMouseEnter(event);
}
const seriesChildren = getSeriesChildren(children);
seriesChildren.forEach((child, index) => {
const component = this[`series${index}`];
if (component && component.onParentMouseEnter) {
component.onParentMouseEnter(event);
}
});
};
/**
* Trigger onMouseLeave handler if it was passed in props.
* @param {React.SyntheticEvent} event Mouse leave event.
* @private
*/
_mouseLeaveHandler = event => {
const {onMouseLeave, children} = this.props;
if (onMouseLeave) {
onMouseLeave(event);
}
const seriesChildren = getSeriesChildren(children);
seriesChildren.forEach((child, index) => {
const component = this[`series${index}`];
if (component && component.onParentMouseLeave) {
component.onParentMouseLeave(event);
}
});
};
/**
* Trigger movement-related callbacks if they are available.
* @param {React.SyntheticEvent} event Mouse move event.
* @private
*/
_mouseMoveHandler = event => {
const {onMouseMove, children} = this.props;
if (onMouseMove) {
onMouseMove(event);
}
const seriesChildren = getSeriesChildren(children);
seriesChildren.forEach((child, index) => {
const component = this[`series${index}`];
if (component && component.onParentMouseMove) {
component.onParentMouseMove(event);
}
});
};
/**
* Trigger mouse-up related callbacks if they are available.
* @param {React.SyntheticEvent} event Mouse up event.
* @private
*/
_mouseUpHandler = event => {
const {onMouseUp, children} = this.props;
if (onMouseUp) {
onMouseUp(event);
}
const seriesChildren = getSeriesChildren(children);
seriesChildren.forEach((child, index) => {
const component = this[`series${index}`];
if (component && component.onParentMouseUp) {
component.onParentMouseUp(event);
}
});
};
/**
* Trigger onTouchCancel handler if it was passed in props.
* @param {React.SyntheticEvent} event Touch Cancel event.
* @private
*/
_touchCancelHandler = event => {
const {onTouchCancel} = this.props;
if (onTouchCancel) {
onTouchCancel(event);
}
};
/**
* Trigger onTouchEnd handler if it was passed in props.
* @param {React.SyntheticEvent} event Touch End event.
* @private
*/
_touchEndHandler = event => {
const {onTouchEnd} = this.props;
if (onTouchEnd) {
onTouchEnd(event);
}
};
/**
* Trigger touch movement-related callbacks if they are available.
* @param {React.SyntheticEvent} event Touch move event.
* @private
*/
_touchMoveHandler = event => {
const {onTouchMove, children} = this.props;
if (onTouchMove) {
onTouchMove(event);
}
const seriesChildren = getSeriesChildren(children);
seriesChildren.forEach((child, index) => {
const component = this[`series${index}`];
if (component && component.onParentTouchMove) {
component.onParentTouchMove(event);
}
});
};
/**
* Trigger touch-start related callbacks if they are available.
* @param {React.SyntheticEvent} event Touch start event.
* @private
*/
_touchStartHandler = event => {
const {onTouchStart, children} = this.props;
if (onTouchStart) {
onTouchStart(event);
}
const seriesChildren = getSeriesChildren(children);
seriesChildren.forEach((child, index) => {
const component = this[`series${index}`];
if (component && component.onParentTouchStart) {
component.onParentTouchStart(event);
}
});
};
renderCanvasComponents(components) {
const componentsToRender = components.filter(
c => c && !c.type.requiresSVG && c.type.isCanvas
);
if (componentsToRender.length === 0) {
return null;
}
const {
marginLeft,
marginTop,
marginBottom,
marginRight,
innerHeight,
innerWidth
} = componentsToRender[0].props;
return (
<CanvasWrapper
{...{
innerHeight,
innerWidth,
marginLeft,
marginTop,
marginBottom,
marginRight
}}
>
{componentsToRender}
</CanvasWrapper>
);
}
render() {
const {
className,
dontCheckIfEmpty,
style,
width,
height,
onWheel
} = this.props;
if (!dontCheckIfEmpty && this._isPlotEmpty()) {
return (
<div
className={getCombinedClassName('rv-xy-plot', className)}
style={{
width: `${width}px`,
height: `${height}px`,
...this.props.style
}}
/>
);
}
const components = this._getClonedChildComponents();
return (
<div
style={{
width: `${width}px`,
height: `${height}px`
}}
className={getCombinedClassName('rv-xy-plot', className)}
>
<svg
className="rv-xy-plot__inner"
width={width}
height={height}
style={style}
onClick={this._clickHandler}
onDoubleClick={this._doubleClickHandler}
onMouseDown={this._mouseDownHandler}
onMouseUp={this._mouseUpHandler}
onMouseMove={this._mouseMoveHandler}
onMouseLeave={this._mouseLeaveHandler}
onMouseEnter={this._mouseEnterHandler}
onTouchStart={this._mouseDownHandler}
onTouchMove={this._touchMoveHandler}
onTouchEnd={this._touchEndHandler}
onTouchCancel={this._touchCancelHandler}
onWheel={onWheel}
>
{components.filter(c => c && c.type.requiresSVG)}
</svg>
{this.renderCanvasComponents(components)}
{components.filter(c => c && !c.type.requiresSVG && !c.type.isCanvas)}
</div>
);
}
}
XYPlot.displayName = 'XYPlot';
export default XYPlot;