This repository has been archived by the owner on Jun 3, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 146
/
Graph.react.js
464 lines (404 loc) · 13.8 KB
/
Graph.react.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
import React, {Component} from 'react';
import ResizeDetector from 'react-resize-detector';
import {
equals,
filter,
has,
includes,
isNil,
mergeDeepRight,
omit,
type,
} from 'ramda';
import PropTypes from 'prop-types';
import {graphPropTypes, graphDefaultProps} from '../components/Graph.react';
/* global Plotly:true */
/**
* `autosize: true` causes Plotly.js to conform to the parent element size.
* This is necessary for `dcc.Graph` call to `Plotly.Plots.resize(target)` to do something.
*
* Users can override this value for specific use-cases by explicitly passing `autoresize: true`
* if `responsive` is not set to True.
*/
const RESPONSIVE_LAYOUT = {
autosize: true,
height: undefined,
width: undefined,
};
const AUTO_LAYOUT = {};
const UNRESPONSIVE_LAYOUT = {
autosize: false,
};
/**
* `responsive: true` causes Plotly.js to resize the graph on `window.resize`.
* This is necessary for `dcc.Graph` call to `Plotly.Plots.resize(target)` to do something.
*
* Users can override this value for specific use-cases by explicitly passing `responsive: false`
* if `responsive` is not set to True.
*/
const RESPONSIVE_CONFIG = {
responsive: true,
};
const AUTO_CONFIG = {};
const UNRESPONSIVE_CONFIG = {
responsive: false,
};
const filterEventData = (gd, eventData, event) => {
let filteredEventData;
if (includes(event, ['click', 'hover', 'selected'])) {
const points = [];
if (isNil(eventData)) {
return null;
}
/*
* remove `data`, `layout`, `xaxis`, etc
* objects from the event data since they're so big
* and cause JSON stringify ciricular structure errors.
*
* also, pull down the `customdata` point from the data array
* into the event object
*/
const data = gd.data;
for (let i = 0; i < eventData.points.length; i++) {
const fullPoint = eventData.points[i];
const pointData = filter(function(o) {
return !includes(type(o), ['Object', 'Array']);
}, fullPoint);
if (
has('curveNumber', fullPoint) &&
has('pointNumber', fullPoint) &&
has('customdata', data[pointData.curveNumber])
) {
pointData.customdata =
data[pointData.curveNumber].customdata[
fullPoint.pointNumber
];
}
// specific to histogram. see https://github.com/plotly/plotly.js/pull/2113/
if (has('pointNumbers', fullPoint)) {
pointData.pointNumbers = fullPoint.pointNumbers;
}
points[i] = pointData;
}
filteredEventData = {points};
} else if (event === 'relayout' || event === 'restyle') {
/*
* relayout shouldn't include any big objects
* it will usually just contain the ranges of the axes like
* "xaxis.range[0]": 0.7715822247381828,
* "xaxis.range[1]": 3.0095292008680063`
*/
filteredEventData = eventData;
}
if (has('range', eventData)) {
filteredEventData.range = eventData.range;
}
if (has('lassoPoints', eventData)) {
filteredEventData.lassoPoints = eventData.lassoPoints;
}
return filteredEventData;
};
/**
* Graph can be used to render any plotly.js-powered data visualization.
*
* You can define callbacks based on user interaction with Graphs such as
* hovering, clicking or selecting
*/
class PlotlyGraph extends Component {
constructor(props) {
super(props);
this.gd = React.createRef();
this._hasPlotted = false;
this._prevGd = null;
this.bindEvents = this.bindEvents.bind(this);
this.getConfig = this.getConfig.bind(this);
this.getConfigOverride = this.getConfigOverride.bind(this);
this.getLayout = this.getLayout.bind(this);
this.getLayoutOverride = this.getLayoutOverride.bind(this);
this.graphResize = this.graphResize.bind(this);
this.isResponsive = this.isResponsive.bind(this);
}
plot(props) {
let {figure, config} = props;
const {animate, animation_options, responsive} = props;
const gd = this.gd.current;
figure = props._dashprivate_transformFigure(figure, gd);
config = props._dashprivate_transformConfig(config, gd);
if (
animate &&
this._hasPlotted &&
figure.data.length === gd.data.length
) {
return Plotly.animate(gd, figure, animation_options);
}
const configClone = this.getConfig(config, responsive);
const layoutClone = this.getLayout(figure.layout, responsive);
gd.classList.add('dash-graph--pending');
return Plotly.react(gd, {
data: figure.data,
layout: layoutClone,
frames: figure.frames,
config: configClone,
}).then(() => {
const gd = this.gd.current;
// double-check gd hasn't been unmounted
if (!gd) {
return;
}
gd.classList.remove('dash-graph--pending');
// in case we've made a new DOM element, transfer events
if (this._hasPlotted && gd !== this._prevGd) {
if (this._prevGd && this._prevGd.removeAllListeners) {
this._prevGd.removeAllListeners();
Plotly.purge(this._prevGd);
}
this._hasPlotted = false;
}
if (!this._hasPlotted) {
this.bindEvents();
this.graphResize(true);
this._hasPlotted = true;
this._prevGd = gd;
}
});
}
mergeTraces(props, dataKey, plotlyFnKey) {
const clearState = props.clearState;
const dataArray = props[dataKey];
dataArray.forEach(data => {
let updateData, traceIndices, maxPoints;
if (Array.isArray(data) && typeof data[0] === 'object') {
[updateData, traceIndices, maxPoints] = data;
} else {
updateData = data;
}
if (!traceIndices) {
function getFirstProp(data) {
return data[Object.keys(data)[0]];
}
function generateIndices(data) {
return Array.from(Array(getFirstProp(data).length).keys());
}
traceIndices = generateIndices(updateData);
}
const gd = this.gd.current;
return Plotly[plotlyFnKey](gd, updateData, traceIndices, maxPoints);
});
clearState(dataKey);
}
getConfig(config, responsive) {
return mergeDeepRight(config, this.getConfigOverride(responsive));
}
getLayout(layout, responsive) {
if (!layout) {
return layout;
}
return mergeDeepRight(layout, this.getLayoutOverride(responsive));
}
getConfigOverride(responsive) {
switch (responsive) {
case false:
return UNRESPONSIVE_CONFIG;
case true:
return RESPONSIVE_CONFIG;
default:
return AUTO_CONFIG;
}
}
getLayoutOverride(responsive) {
switch (responsive) {
case false:
return UNRESPONSIVE_LAYOUT;
case true:
return RESPONSIVE_LAYOUT;
default:
return AUTO_LAYOUT;
}
}
isResponsive(props) {
const {config, figure, responsive} = props;
if (type(responsive) === 'Boolean') {
return responsive;
}
return Boolean(
config.responsive &&
(!figure.layout ||
((figure.layout.autosize ||
isNil(figure.layout.autosize)) &&
(isNil(figure.layout.height) ||
isNil(figure.layout.width))))
);
}
graphResize(force = false) {
if (!force && !this.isResponsive(this.props)) {
return;
}
const gd = this.gd.current;
if (!gd) {
return;
}
gd.classList.add('dash-graph--pending');
Plotly.Plots.resize(gd)
.catch(() => {})
.finally(() => gd.classList.remove('dash-graph--pending'));
}
bindEvents() {
const {
setProps,
clear_on_unhover,
relayoutData,
restyleData,
hoverData,
selectedData,
} = this.props;
const gd = this.gd.current;
gd.on('plotly_click', eventData => {
const clickData = filterEventData(gd, eventData, 'click');
if (!isNil(clickData)) {
setProps({clickData});
}
});
gd.on('plotly_clickannotation', eventData => {
const clickAnnotationData = omit(
['event', 'fullAnnotation'],
eventData
);
setProps({clickAnnotationData});
});
gd.on('plotly_hover', eventData => {
const hover = filterEventData(gd, eventData, 'hover');
if (!isNil(hover) && !equals(hover, hoverData)) {
setProps({hoverData: hover});
}
});
gd.on('plotly_selected', eventData => {
const selected = filterEventData(gd, eventData, 'selected');
if (!isNil(selected) && !equals(selected, selectedData)) {
setProps({selectedData: selected});
}
});
gd.on('plotly_deselect', () => {
setProps({selectedData: null});
});
gd.on('plotly_relayout', eventData => {
const relayout = filterEventData(gd, eventData, 'relayout');
if (!isNil(relayout) && !equals(relayout, relayoutData)) {
setProps({relayoutData: relayout});
}
});
gd.on('plotly_restyle', eventData => {
const restyle = filterEventData(gd, eventData, 'restyle');
if (!isNil(restyle) && !equals(restyle, restyleData)) {
setProps({restyleData: restyle});
}
});
gd.on('plotly_unhover', () => {
if (clear_on_unhover) {
setProps({hoverData: null});
}
});
}
componentDidMount() {
this.plot(this.props);
if (this.props.prependData) {
this.mergeTraces(this.props, 'prependData', 'prependTraces');
}
if (this.props.extendData) {
this.mergeTraces(this.props, 'extendData', 'extendTraces');
}
if (this.props.prependData?.length || this.props.extendData?.length) {
this.props._dashprivate_onFigureModified(this.props.figure);
}
}
componentWillUnmount() {
const gd = this.gd.current;
if (gd && gd.removeAllListeners) {
gd.removeAllListeners();
if (this._hasPlotted) {
Plotly.purge(gd);
}
}
}
shouldComponentUpdate(nextProps) {
return (
this.props.id !== nextProps.id ||
JSON.stringify(this.props.style) !==
JSON.stringify(nextProps.style) ||
JSON.stringify(this.props.loading_state) !==
JSON.stringify(nextProps.loading_state)
);
}
UNSAFE_componentWillReceiveProps(nextProps) {
const idChanged = this.props.id !== nextProps.id;
if (idChanged) {
/*
* then the dom needs to get re-rendered with a new ID.
* the graph will get updated in componentDidUpdate
*/
return;
}
if (
this.props.figure !== nextProps.figure ||
this.props._dashprivate_transformConfig !==
nextProps._dashprivate_transformConfig ||
this.props._dashprivate_transformFigure !==
nextProps._dashprivate_transformFigure
) {
this.plot(nextProps);
}
if (this.props.prependData !== nextProps.prependData) {
this.mergeTraces(nextProps, 'prependData', 'prependTraces');
}
if (this.props.extendData !== nextProps.extendData) {
this.mergeTraces(nextProps, 'extendData', 'extendTraces');
}
if (this.props.prependData?.length || this.props.extendData?.length) {
this.props._dashprivate_onFigureModified(this.props.figure);
}
}
componentDidUpdate(prevProps) {
if (prevProps.id !== this.props.id) {
this.plot(this.props);
}
}
render() {
const {className, id, style, loading_state} = this.props;
return (
<div
id={id}
key={id}
data-dash-is-loading={
(loading_state && loading_state.is_loading) || undefined
}
className={className}
style={style}
>
<ResizeDetector
handleHeight={true}
handleWidth={true}
refreshMode="debounce"
refreshOptions={{trailing: true}}
refreshRate={50}
onResize={this.graphResize}
/>
<div ref={this.gd} style={{height: '100%', width: '100%'}} />
</div>
);
}
}
PlotlyGraph.propTypes = {
...graphPropTypes,
prependData: PropTypes.arrayOf(
PropTypes.oneOfType([PropTypes.array, PropTypes.object])
),
extendData: PropTypes.arrayOf(
PropTypes.oneOfType([PropTypes.array, PropTypes.object])
),
clearState: PropTypes.func.isRequired,
};
PlotlyGraph.defaultProps = {
...graphDefaultProps,
prependData: [],
extendData: [],
};
export default PlotlyGraph;