forked from esnet/react-timeseries-charts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLineChart.js
454 lines (404 loc) · 19.9 KB
/
LineChart.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
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _underscore = require("underscore");
var _underscore2 = _interopRequireDefault(_underscore);
var _d3Shape = require("d3-shape");
var _merge = require("merge");
var _merge2 = _interopRequireDefault(_merge);
var _react = require("react");
var _react2 = _interopRequireDefault(_react);
var _pondjs = require("pondjs");
var _styler = require("../js/styler");
var _util = require("../js/util");
var _curve = require("../js/curve");
var _curve2 = _interopRequireDefault(_curve);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* Copyright (c) 2015-present, The Regents of the University of California,
* through Lawrence Berkeley National Laboratory (subject to receipt
* of any required approvals from the U.S. Dept. of Energy).
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
var defaultStyle = {
normal: { stroke: "steelblue", fill: "none", strokeWidth: 1 },
highlighted: { stroke: "#5a98cb", fill: "none", strokeWidth: 1 },
selected: { stroke: "steelblue", fill: "none", strokeWidth: 2 },
muted: { stroke: "steelblue", fill: "none", opacity: 0.4, strokeWidth: 1 }
};
/**
* The `<LineChart>` component is able to display multiple columns of a TimeSeries
* as separate line charts.
*
* The `<LineChart>` should be used within `<ChartContainer>` etc., as this will
* construct the horizontal and vertical axis, and manage other elements.
*
* Here is an example of two columns of a TimeSeries being plotted with the `<LineChart>`:
*
* ```
<ChartContainer timeRange={this.state.timerange} >
<ChartRow height="200">
<YAxis id="y" label="Price ($)" min={0.5} max={1.5} format="$,.2f" />
<Charts>
<LineChart
axis="y"
breakLine={false}
series={currencySeries}
columns={["aud", "euro"]}
style={style}
interpolation="curveBasis" />
</Charts>
</ChartRow>
</ChartContainer>
* ```
*/
var LineChart = function (_React$Component) {
_inherits(LineChart, _React$Component);
function LineChart() {
_classCallCheck(this, LineChart);
return _possibleConstructorReturn(this, (LineChart.__proto__ || Object.getPrototypeOf(LineChart)).apply(this, arguments));
}
_createClass(LineChart, [{
key: "shouldComponentUpdate",
value: function shouldComponentUpdate(nextProps) {
var newSeries = nextProps.series;
var oldSeries = this.props.series;
var width = nextProps.width;
var timeScale = nextProps.timeScale;
var yScale = nextProps.yScale;
var interpolation = nextProps.interpolation;
var highlight = nextProps.highlight;
var selection = nextProps.selection;
var columns = nextProps.columns;
// What changed?
var widthChanged = this.props.width !== width;
var timeScaleChanged = (0, _util.scaleAsString)(this.props.timeScale) !== (0, _util.scaleAsString)(timeScale);
var yAxisScaleChanged = this.props.yScale !== yScale;
var interpolationChanged = this.props.interpolation !== interpolation;
var highlightChanged = this.props.highlight !== highlight;
var selectionChanged = this.props.selection !== selection;
var columnsChanged = this.props.columns !== columns;
var seriesChanged = false;
if (oldSeries.length !== newSeries.length) {
seriesChanged = true;
} else {
seriesChanged = !_pondjs.TimeSeries.is(oldSeries, newSeries);
}
return widthChanged || seriesChanged || timeScaleChanged || yAxisScaleChanged || interpolationChanged || highlightChanged || selectionChanged || columnsChanged;
}
}, {
key: "handleHover",
value: function handleHover(e, column) {
if (this.props.onHighlightChange) {
this.props.onHighlightChange(column);
}
}
}, {
key: "handleHoverLeave",
value: function handleHoverLeave() {
if (this.props.onHighlightChange) {
this.props.onHighlightChange(null);
}
}
}, {
key: "handleClick",
value: function handleClick(e, column) {
e.stopPropagation();
if (this.props.onSelectionChange) {
this.props.onSelectionChange(column);
}
}
}, {
key: "providedPathStyleMap",
value: function providedPathStyleMap(column) {
var style = {};
if (this.props.style) {
if (this.props.style instanceof _styler.Styler) {
style = this.props.style.lineChartStyle()[column];
} else if (_underscore2.default.isObject(this.props.style)) {
style = this.props.style[column];
} else if (_underscore2.default.isFunction(this.props.style)) {
style = this.props.style(column);
}
}
return style;
}
/**
* Returns the style used for drawing the path
*/
}, {
key: "pathStyle",
value: function pathStyle(column) {
var style = void 0;
var styleMap = this.providedPathStyleMap(column);
var isHighlighted = this.props.highlight && column === this.props.highlight;
var isSelected = this.props.selection && column === this.props.selection;
if (this.props.selection) {
if (isSelected) {
style = (0, _merge2.default)(true, defaultStyle.selected, styleMap.selected ? styleMap.selected : {});
} else if (isHighlighted) {
style = (0, _merge2.default)(true, defaultStyle.highlighted, styleMap.highlighted ? styleMap.highlighted : {});
} else {
style = (0, _merge2.default)(true, defaultStyle.muted, styleMap.muted ? styleMap.muted : {});
}
} else if (isHighlighted) {
style = (0, _merge2.default)(true, defaultStyle.highlighted, styleMap.highlighted ? styleMap.highlighted : {});
} else {
style = (0, _merge2.default)(true, defaultStyle.normal, styleMap.normal);
}
style.pointerEvents = "none";
return style;
}
}, {
key: "renderPath",
value: function renderPath(data, column, key) {
var _this2 = this;
var hitStyle = {
stroke: "white",
fill: "none",
opacity: 0.0,
strokeWidth: 7,
cursor: "crosshair",
pointerEvents: "stroke"
};
// D3 generates each path
var path = (0, _d3Shape.line)().curve(_curve2.default[this.props.interpolation]).x(function (d) {
return _this2.props.timeScale(d.x);
}).y(function (d) {
return _this2.props.yScale(d.y);
})(data);
return _react2.default.createElement(
"g",
{ key: key },
_react2.default.createElement("path", { d: path, style: this.pathStyle(column) }),
_react2.default.createElement("path", {
d: path,
style: hitStyle,
onClick: function onClick(e) {
return _this2.handleClick(e, column);
},
onMouseLeave: function onMouseLeave() {
return _this2.handleHoverLeave();
},
onMouseMove: function onMouseMove(e) {
return _this2.handleHover(e, column);
}
})
);
}
}, {
key: "renderLines",
value: function renderLines() {
var _this3 = this;
return _underscore2.default.map(this.props.columns, function (column) {
return _this3.renderLine(column);
});
}
}, {
key: "renderLine",
value: function renderLine(column) {
var pathLines = [];
var count = 1;
if (this.props.breakLine) {
// Remove nulls and NaNs from the line by generating a break in the line
var currentPoints = null;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.props.series.events()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var d = _step.value;
var timestamp = new Date(d.begin().getTime() + (d.end().getTime() - d.begin().getTime()) / 2);
var value = d.get(column);
var badPoint = _underscore2.default.isNull(value) || _underscore2.default.isNaN(value) || !_underscore2.default.isFinite(value);
if (!badPoint) {
if (!currentPoints) currentPoints = [];
currentPoints.push({ x: timestamp, y: value });
} else if (currentPoints) {
if (currentPoints.length > 1) {
pathLines.push(this.renderPath(currentPoints, column, count));
count += 1;
}
currentPoints = null;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
if (currentPoints && currentPoints.length > 1) {
pathLines.push(this.renderPath(currentPoints, column, count));
count += 1;
}
} else {
// Ignore nulls and NaNs in the line
var cleanedPoints = [];
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = this.props.series.events()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var _d = _step2.value;
var _timestamp = new Date(_d.begin().getTime() + (_d.end().getTime() - _d.begin().getTime()) / 2);
var _value = _d.get(column);
var _badPoint = _underscore2.default.isNull(_value) || _underscore2.default.isNaN(_value) || !_underscore2.default.isFinite(_value);
if (!_badPoint) {
cleanedPoints.push({ x: _timestamp, y: _value });
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
pathLines.push(this.renderPath(cleanedPoints, column, count));
count += 1;
}
return _react2.default.createElement(
"g",
{ key: column },
pathLines
);
}
}, {
key: "render",
value: function render() {
return _react2.default.createElement(
"g",
null,
this.renderLines()
);
}
}]);
return LineChart;
}(_react2.default.Component);
exports.default = LineChart;
LineChart.propTypes = {
/**
* What [Pond TimeSeries](http://software.es.net/pond#timeseries) data to visualize
*/
series: _react2.default.PropTypes.instanceOf(_pondjs.TimeSeries).isRequired,
/**
* Reference to the axis which provides the vertical scale for drawing.
* e.g. specifying `axis="trafficRate"` would refer the y-scale of the YAxis
* with id="trafficRate".
*/
axis: _react2.default.PropTypes.string.isRequired, // eslint-disable-line
/**
* Which columns from the series to draw.
*/
columns: _react2.default.PropTypes.arrayOf(_react2.default.PropTypes.string),
/**
* The styles to apply to the underlying SVG lines. This is a mapping
* of column names to objects with style attributes, in the following
* format:
*
* ```
* const style = {
* in: {
* normal: {stroke: "steelblue", fill: "none", strokeWidth: 1},
* highlighted: {stroke: "#5a98cb", fill: "none", strokeWidth: 1},
* selected: {stroke: "steelblue", fill: "none", strokeWidth: 1},
* muted: {stroke: "steelblue", fill: "none", opacity: 0.4, strokeWidth: 1}
* },
* out: {
* ...
* }
* };
*
* <LineChart style={style} ... />
* ```
*
* Alternatively, you can pass in a `Styler`. For example:
*
* ```
* const currencyStyle = Styler([
* {key: "aud", color: "steelblue", width: 1, dashed: true},
* {key: "euro", color: "#F68B24", width: 2}
* ]);
*
* <LineChart columns={["aud", "euro"]} style={currencyStyle} ... />
*
* ```
*/
style: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.object, _react2.default.PropTypes.func, _react2.default.PropTypes.instanceOf(_styler.Styler)]),
/**
* Any of D3's interpolation modes.
*/
interpolation: _react2.default.PropTypes.oneOf(["curveBasis", "curveBasisOpen", "curveBundle", "curveCardinal", "curveCardinalOpen", "curveCatmullRom", "curveCatmullRomOpen", "curveLinear", "curveMonotoneX", "curveMonotoneY", "curveNatural", "curveRadial", "curveStep", "curveStepAfter", "curveStepBefore"]),
/**
* The determines how to handle bad/missing values in the supplied
* TimeSeries. A missing value can be null or NaN. If breakLine
* is set to true then the line will be broken on either side of
* the bad value(s). If breakLine is false (the default) bad values
* are simply removed and the adjoining points are connected.
*/
breakLine: _react2.default.PropTypes.bool,
/**
* The selected item, which will be rendered in the "selected" style.
* If a line is selected, all other lines will be rendered in the "muted" style.
*
* See also `onSelectionChange`
*/
selection: _react2.default.PropTypes.string,
/**
* A callback that will be called when the selection changes. It will be called
* with the column corresponding to the line being clicked.
*/
onSelectionChange: _react2.default.PropTypes.func,
/**
* The highlighted column, which will be rendered in the "highlighted" style.
*
* See also `onHighlightChange`
*/
highlight: _react2.default.PropTypes.string,
/**
* A callback that will be called when the hovered over line changes.
* It will be called with the corresponding column.
*/
onHighlightChange: _react2.default.PropTypes.func,
/**
* [Internal] The timeScale supplied by the surrounding ChartContainer
*/
timeScale: _react2.default.PropTypes.func,
/**
* [Internal] The yScale supplied by the associated YAxis
*/
yScale: _react2.default.PropTypes.func,
/**
* [Internal] The width supplied by the surrounding ChartContainer
*/
width: _react2.default.PropTypes.number
};
LineChart.defaultProps = {
columns: ["value"],
smooth: true,
interpolation: "curveLinear",
breakLine: true
};