-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
plot_api.js
3862 lines (3297 loc) · 140 KB
/
plot_api.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
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 strict';
var d3 = require('@plotly/d3');
var isNumeric = require('fast-isnumeric');
var hasHover = require('has-hover');
var Lib = require('../lib');
var nestedProperty = Lib.nestedProperty;
var Events = require('../lib/events');
var Queue = require('../lib/queue');
var Registry = require('../registry');
var PlotSchema = require('./plot_schema');
var Plots = require('../plots/plots');
var Axes = require('../plots/cartesian/axes');
var handleRangeDefaults = require('../plots/cartesian/range_defaults');
var cartesianLayoutAttributes = require('../plots/cartesian/layout_attributes');
var Drawing = require('../components/drawing');
var Color = require('../components/color');
var initInteractions = require('../plots/cartesian/graph_interact').initInteractions;
var xmlnsNamespaces = require('../constants/xmlns_namespaces');
var clearOutline = require('../components/selections').clearOutline;
var dfltConfig = require('./plot_config').dfltConfig;
var manageArrays = require('./manage_arrays');
var helpers = require('./helpers');
var subroutines = require('./subroutines');
var editTypes = require('./edit_types');
var AX_NAME_PATTERN = require('../plots/cartesian/constants').AX_NAME_PATTERN;
var numericNameWarningCount = 0;
var numericNameWarningCountLimit = 5;
/**
* Internal plot-creation function
*
* @param {string id or DOM element} gd
* the id or DOM element of the graph container div
* @param {array of objects} data
* array of traces, containing the data and display information for each trace
* @param {object} layout
* object describing the overall display of the plot,
* all the stuff that doesn't pertain to any individual trace
* @param {object} config
* configuration options (see ./plot_config.js for more info)
*
* OR
*
* @param {string id or DOM element} gd
* the id or DOM element of the graph container div
* @param {object} figure
* object containing `data`, `layout`, `config`, and `frames` members
*
*/
function _doPlot(gd, data, layout, config) {
var frames;
gd = Lib.getGraphDiv(gd);
// Events.init is idempotent and bails early if gd has already been init'd
Events.init(gd);
if(Lib.isPlainObject(data)) {
var obj = data;
data = obj.data;
layout = obj.layout;
config = obj.config;
frames = obj.frames;
}
var okToPlot = Events.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]);
if(okToPlot === false) return Promise.reject();
// if there's no data or layout, and this isn't yet a plotly plot
// container, log a warning to help plotly.js users debug
if(!data && !layout && !Lib.isPlotDiv(gd)) {
Lib.warn('Calling _doPlot as if redrawing ' +
'but this container doesn\'t yet have a plot.', gd);
}
function addFrames() {
if(frames) {
return exports.addFrames(gd, frames);
}
}
// transfer configuration options to gd until we move over to
// a more OO like model
setPlotContext(gd, config);
if(!layout) layout = {};
// hook class for plots main container (in case of plotly.js
// this won't be #embedded-graph or .js-tab-contents)
d3.select(gd).classed('js-plotly-plot', true);
// off-screen getBoundingClientRect testing space,
// in #js-plotly-tester (and stored as Drawing.tester)
// so we can share cached text across tabs
Drawing.makeTester();
// collect promises for any async actions during plotting
// any part of the plotting code can push to gd._promises, then
// before we move to the next step, we check that they're all
// complete, and empty out the promise list again.
if(!Array.isArray(gd._promises)) gd._promises = [];
var graphWasEmpty = ((gd.data || []).length === 0 && Array.isArray(data));
// if there is already data on the graph, append the new data
// if you only want to redraw, pass a non-array for data
if(Array.isArray(data)) {
helpers.cleanData(data);
if(graphWasEmpty) gd.data = data;
else gd.data.push.apply(gd.data, data);
// for routines outside graph_obj that want a clean tab
// (rather than appending to an existing one) gd.empty
// is used to determine whether to make a new tab
gd.empty = false;
}
if(!gd.layout || graphWasEmpty) {
gd.layout = helpers.cleanLayout(layout);
}
Plots.supplyDefaults(gd);
var fullLayout = gd._fullLayout;
var hasCartesian = fullLayout._has('cartesian');
// so we don't try to re-call _doPlot from inside
// legend and colorbar, if margins changed
fullLayout._replotting = true;
// make or remake the framework if we need to
if(graphWasEmpty || fullLayout._shouldCreateBgLayer) {
makePlotFramework(gd);
if(fullLayout._shouldCreateBgLayer) {
delete fullLayout._shouldCreateBgLayer;
}
}
// clear gradient and pattern defs on each .plot call, because we know we'll loop through all traces
Drawing.initGradients(gd);
Drawing.initPatterns(gd);
// save initial show spikes once per graph
if(graphWasEmpty) Axes.saveShowSpikeInitial(gd);
// prepare the data and find the autorange
// generate calcdata, if we need to
// to force redoing calcdata, just delete it before calling _doPlot
var recalc = !gd.calcdata || gd.calcdata.length !== (gd._fullData || []).length;
if(recalc) Plots.doCalcdata(gd);
// in case it has changed, attach fullData traces to calcdata
for(var i = 0; i < gd.calcdata.length; i++) {
gd.calcdata[i][0].trace = gd._fullData[i];
}
// make the figure responsive
if(gd._context.responsive) {
if(!gd._responsiveChartHandler) {
// Keep a reference to the resize handler to purge it down the road
gd._responsiveChartHandler = function() { if(!Lib.isHidden(gd)) Plots.resize(gd); };
// Listen to window resize
window.addEventListener('resize', gd._responsiveChartHandler);
}
} else {
Lib.clearResponsive(gd);
}
/*
* start async-friendly code - now we're actually drawing things
*/
var oldMargins = Lib.extendFlat({}, fullLayout._size);
// draw framework first so that margin-pushing
// components can position themselves correctly
var drawFrameworkCalls = 0;
function drawFramework() {
var basePlotModules = fullLayout._basePlotModules;
for(var i = 0; i < basePlotModules.length; i++) {
if(basePlotModules[i].drawFramework) {
basePlotModules[i].drawFramework(gd);
}
}
if(!fullLayout._glcanvas && fullLayout._has('gl')) {
fullLayout._glcanvas = fullLayout._glcontainer.selectAll('.gl-canvas').data([{
key: 'contextLayer',
context: true,
pick: false
}, {
key: 'focusLayer',
context: false,
pick: false
}, {
key: 'pickLayer',
context: false,
pick: true
}], function(d) { return d.key; });
fullLayout._glcanvas.enter().append('canvas')
.attr('class', function(d) {
return 'gl-canvas gl-canvas-' + d.key.replace('Layer', '');
})
.style({
position: 'absolute',
top: 0,
left: 0,
overflow: 'visible',
'pointer-events': 'none'
});
}
var plotGlPixelRatio = gd._context.plotGlPixelRatio;
if(fullLayout._glcanvas) {
fullLayout._glcanvas
.attr('width', fullLayout.width * plotGlPixelRatio)
.attr('height', fullLayout.height * plotGlPixelRatio)
.style('width', fullLayout.width + 'px')
.style('height', fullLayout.height + 'px');
var regl = fullLayout._glcanvas.data()[0].regl;
if(regl) {
// Unfortunately, this can happen when relayouting to large
// width/height on some browsers.
if(Math.floor(fullLayout.width * plotGlPixelRatio) !== regl._gl.drawingBufferWidth ||
Math.floor(fullLayout.height * plotGlPixelRatio) !== regl._gl.drawingBufferHeight
) {
var msg = 'WebGL context buffer and canvas dimensions do not match due to browser/WebGL bug.';
if(drawFrameworkCalls) {
Lib.error(msg);
} else {
Lib.log(msg + ' Clearing graph and plotting again.');
Plots.cleanPlot([], {}, gd._fullData, fullLayout);
Plots.supplyDefaults(gd);
fullLayout = gd._fullLayout;
Plots.doCalcdata(gd);
drawFrameworkCalls++;
return drawFramework();
}
}
}
}
if(fullLayout.modebar.orientation === 'h') {
fullLayout._modebardiv
.style('height', null)
.style('width', '100%');
} else {
fullLayout._modebardiv
.style('width', null)
.style('height', fullLayout.height + 'px');
}
return Plots.previousPromises(gd);
}
// draw anything that can affect margins.
function marginPushers() {
// First reset the list of things that are allowed to change the margins
// So any deleted traces or components will be wiped out of the
// automargin calculation.
// This means *every* margin pusher must be listed here, even if it
// doesn't actually try to push the margins until later.
Plots.clearAutoMarginIds(gd);
subroutines.drawMarginPushers(gd);
Axes.allowAutoMargin(gd);
if(gd._fullLayout.title.text && gd._fullLayout.title.automargin) Plots.allowAutoMargin(gd, 'title.automargin');
// TODO can this be moved elsewhere?
if(fullLayout._has('pie')) {
var fullData = gd._fullData;
for(var i = 0; i < fullData.length; i++) {
var trace = fullData[i];
if(trace.type === 'pie' && trace.automargin) {
Plots.allowAutoMargin(gd, 'pie.' + trace.uid + '.automargin');
}
}
}
Plots.doAutoMargin(gd);
return Plots.previousPromises(gd);
}
// in case the margins changed, draw margin pushers again
function marginPushersAgain() {
if(!Plots.didMarginChange(oldMargins, fullLayout._size)) return;
return Lib.syncOrAsync([
marginPushers,
subroutines.layoutStyles
], gd);
}
function positionAndAutorange() {
if(!recalc) {
doAutoRangeAndConstraints();
return;
}
// TODO: autosize extra for text markers and images
// see https://github.com/plotly/plotly.js/issues/1111
return Lib.syncOrAsync([
Registry.getComponentMethod('shapes', 'calcAutorange'),
Registry.getComponentMethod('annotations', 'calcAutorange'),
doAutoRangeAndConstraints
], gd);
}
function doAutoRangeAndConstraints() {
if(gd._transitioning) return;
subroutines.doAutoRangeAndConstraints(gd);
// store initial ranges *after* enforcing constraints, otherwise
// we will never look like we're at the initial ranges
if(graphWasEmpty) Axes.saveRangeInitial(gd);
// this one is different from shapes/annotations calcAutorange
// the others incorporate those components into ax._extremes,
// this one actually sets the ranges in rangesliders.
Registry.getComponentMethod('rangeslider', 'calcAutorange')(gd);
}
// draw ticks, titles, and calculate axis scaling (._b, ._m)
function drawAxes() {
return Axes.draw(gd, graphWasEmpty ? '' : 'redraw');
}
var seq = [
Plots.previousPromises,
addFrames,
drawFramework,
marginPushers,
marginPushersAgain
];
if(hasCartesian) seq.push(positionAndAutorange);
seq.push(subroutines.layoutStyles);
if(hasCartesian) {
seq.push(
drawAxes,
function insideTickLabelsAutorange(gd) {
var insideTickLabelsUpdaterange = gd._fullLayout._insideTickLabelsUpdaterange;
if(insideTickLabelsUpdaterange) {
gd._fullLayout._insideTickLabelsUpdaterange = undefined;
return relayout(gd, insideTickLabelsUpdaterange).then(function() {
Axes.saveRangeInitial(gd, true);
});
}
}
);
}
seq.push(
subroutines.drawData,
subroutines.finalDraw,
initInteractions,
Plots.addLinks,
Plots.rehover,
Plots.redrag,
Plots.reselect,
// TODO: doAutoMargin is only needed here for axis automargin, which
// happens outside of marginPushers where all the other automargins are
// calculated. Would be much better to separate margin calculations from
// component drawing - see https://github.com/plotly/plotly.js/issues/2704
Plots.doAutoMargin,
Plots.previousPromises
);
// even if everything we did was synchronous, return a promise
// so that the caller doesn't care which route we took
var plotDone = Lib.syncOrAsync(seq, gd);
if(!plotDone || !plotDone.then) plotDone = Promise.resolve();
return plotDone.then(function() {
emitAfterPlot(gd);
return gd;
});
}
function emitAfterPlot(gd) {
var fullLayout = gd._fullLayout;
if(fullLayout._redrawFromAutoMarginCount) {
fullLayout._redrawFromAutoMarginCount--;
} else {
gd.emit('plotly_afterplot');
}
}
function setPlotConfig(obj) {
return Lib.extendFlat(dfltConfig, obj);
}
function setBackground(gd, bgColor) {
try {
gd._fullLayout._paper.style('background', bgColor);
} catch(e) {
Lib.error(e);
}
}
function opaqueSetBackground(gd, bgColor) {
var blend = Color.combine(bgColor, 'white');
setBackground(gd, blend);
}
function setPlotContext(gd, config) {
if(!gd._context) {
gd._context = Lib.extendDeep({}, dfltConfig);
// stash <base> href, used to make robust clipPath URLs
var base = d3.select('base');
gd._context._baseUrl = base.size() && base.attr('href') ?
window.location.href.split('#')[0] :
'';
}
var context = gd._context;
var i, keys, key;
if(config) {
keys = Object.keys(config);
for(i = 0; i < keys.length; i++) {
key = keys[i];
if(key === 'editable' || key === 'edits') continue;
if(key in context) {
if(key === 'setBackground' && config[key] === 'opaque') {
context[key] = opaqueSetBackground;
} else {
context[key] = config[key];
}
}
}
// now deal with editable and edits - first editable overrides
// everything, then edits refines
var editable = config.editable;
if(editable !== undefined) {
// we're not going to *use* context.editable, we're only going to
// use context.edits... but keep it for the record
context.editable = editable;
keys = Object.keys(context.edits);
for(i = 0; i < keys.length; i++) {
context.edits[keys[i]] = editable;
}
}
if(config.edits) {
keys = Object.keys(config.edits);
for(i = 0; i < keys.length; i++) {
key = keys[i];
if(key in context.edits) {
context.edits[key] = config.edits[key];
}
}
}
// not part of the user-facing config options
context._exportedPlot = config._exportedPlot;
}
// staticPlot forces a bunch of others:
if(context.staticPlot) {
context.editable = false;
context.edits = {};
context.autosizable = false;
context.scrollZoom = false;
context.doubleClick = false;
context.showTips = false;
context.showLink = false;
context.displayModeBar = false;
}
// make sure hover-only devices have mode bar visible
if(context.displayModeBar === 'hover' && !hasHover) {
context.displayModeBar = true;
}
// default and fallback for setBackground
if(context.setBackground === 'transparent' || typeof context.setBackground !== 'function') {
context.setBackground = setBackground;
}
// Check if gd has a specified widht/height to begin with
context._hasZeroHeight = context._hasZeroHeight || gd.clientHeight === 0;
context._hasZeroWidth = context._hasZeroWidth || gd.clientWidth === 0;
// fill context._scrollZoom helper to help manage scrollZoom flaglist
var szIn = context.scrollZoom;
var szOut = context._scrollZoom = {};
if(szIn === true) {
szOut.cartesian = 1;
szOut.gl3d = 1;
szOut.geo = 1;
szOut.mapbox = 1;
szOut.map = 1;
} else if(typeof szIn === 'string') {
var parts = szIn.split('+');
for(i = 0; i < parts.length; i++) {
szOut[parts[i]] = 1;
}
} else if(szIn !== false) {
szOut.gl3d = 1;
szOut.geo = 1;
szOut.mapbox = 1;
szOut.map = 1;
}
}
// convenience function to force a full redraw, mostly for use by plotly.js
function redraw(gd) {
gd = Lib.getGraphDiv(gd);
if(!Lib.isPlotDiv(gd)) {
throw new Error('This element is not a Plotly plot: ' + gd);
}
helpers.cleanData(gd.data);
helpers.cleanLayout(gd.layout);
gd.calcdata = undefined;
return exports._doPlot(gd).then(function() {
gd.emit('plotly_redraw');
return gd;
});
}
/**
* Convenience function to make idempotent plot option obvious to users.
*
* @param gd
* @param {Object[]} data
* @param {Object} layout
* @param {Object} config
*/
function newPlot(gd, data, layout, config) {
gd = Lib.getGraphDiv(gd);
// remove gl contexts
Plots.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {});
Plots.purge(gd);
return exports._doPlot(gd, data, layout, config);
}
/**
* Wrap negative indicies to their positive counterparts.
*
* @param {Number[]} indices An array of indices
* @param {Number} maxIndex The maximum index allowable (arr.length - 1)
*/
function positivifyIndices(indices, maxIndex) {
var parentLength = maxIndex + 1;
var positiveIndices = [];
var i;
var index;
for(i = 0; i < indices.length; i++) {
index = indices[i];
if(index < 0) {
positiveIndices.push(parentLength + index);
} else {
positiveIndices.push(index);
}
}
return positiveIndices;
}
/**
* Ensures that an index array for manipulating gd.data is valid.
*
* Intended for use with addTraces, deleteTraces, and moveTraces.
*
* @param gd
* @param indices
* @param arrayName
*/
function assertIndexArray(gd, indices, arrayName) {
var i,
index;
for(i = 0; i < indices.length; i++) {
index = indices[i];
// validate that indices are indeed integers
if(index !== parseInt(index, 10)) {
throw new Error('all values in ' + arrayName + ' must be integers');
}
// check that all indices are in bounds for given gd.data array length
if(index >= gd.data.length || index < -gd.data.length) {
throw new Error(arrayName + ' must be valid indices for gd.data.');
}
// check that indices aren't repeated
if(indices.indexOf(index, i + 1) > -1 ||
index >= 0 && indices.indexOf(-gd.data.length + index) > -1 ||
index < 0 && indices.indexOf(gd.data.length + index) > -1) {
throw new Error('each index in ' + arrayName + ' must be unique.');
}
}
}
/**
* Private function used by Plotly.moveTraces to check input args
*
* @param gd
* @param currentIndices
* @param newIndices
*/
function checkMoveTracesArgs(gd, currentIndices, newIndices) {
// check that gd has attribute 'data' and 'data' is array
if(!Array.isArray(gd.data)) {
throw new Error('gd.data must be an array.');
}
// validate currentIndices array
if(typeof currentIndices === 'undefined') {
throw new Error('currentIndices is a required argument.');
} else if(!Array.isArray(currentIndices)) {
currentIndices = [currentIndices];
}
assertIndexArray(gd, currentIndices, 'currentIndices');
// validate newIndices array if it exists
if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
newIndices = [newIndices];
}
if(typeof newIndices !== 'undefined') {
assertIndexArray(gd, newIndices, 'newIndices');
}
// check currentIndices and newIndices are the same length if newIdices exists
if(typeof newIndices !== 'undefined' && currentIndices.length !== newIndices.length) {
throw new Error('current and new indices must be of equal length.');
}
}
/**
* A private function to reduce the type checking clutter in addTraces.
*
* @param gd
* @param traces
* @param newIndices
*/
function checkAddTracesArgs(gd, traces, newIndices) {
var i, value;
// check that gd has attribute 'data' and 'data' is array
if(!Array.isArray(gd.data)) {
throw new Error('gd.data must be an array.');
}
// make sure traces exists
if(typeof traces === 'undefined') {
throw new Error('traces must be defined.');
}
// make sure traces is an array
if(!Array.isArray(traces)) {
traces = [traces];
}
// make sure each value in traces is an object
for(i = 0; i < traces.length; i++) {
value = traces[i];
if(typeof value !== 'object' || (Array.isArray(value) || value === null)) {
throw new Error('all values in traces array must be non-array objects');
}
}
// make sure we have an index for each trace
if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
newIndices = [newIndices];
}
if(typeof newIndices !== 'undefined' && newIndices.length !== traces.length) {
throw new Error(
'if indices is specified, traces.length must equal indices.length'
);
}
}
/**
* A private function to reduce the type checking clutter in spliceTraces.
* Get all update Properties from gd.data. Validate inputs and outputs.
* Used by prependTrace and extendTraces
*
* @param gd
* @param update
* @param indices
* @param maxPoints
*/
function assertExtendTracesArgs(gd, update, indices, maxPoints) {
var maxPointsIsObject = Lib.isPlainObject(maxPoints);
if(!Array.isArray(gd.data)) {
throw new Error('gd.data must be an array');
}
if(!Lib.isPlainObject(update)) {
throw new Error('update must be a key:value object');
}
if(typeof indices === 'undefined') {
throw new Error('indices must be an integer or array of integers');
}
assertIndexArray(gd, indices, 'indices');
for(var key in update) {
/*
* Verify that the attribute to be updated contains as many trace updates
* as indices. Failure must result in throw and no-op
*/
if(!Array.isArray(update[key]) || update[key].length !== indices.length) {
throw new Error('attribute ' + key + ' must be an array of length equal to indices array length');
}
/*
* if maxPoints is an object it must match keys and array lengths of 'update' 1:1
*/
if(maxPointsIsObject &&
(!(key in maxPoints) || !Array.isArray(maxPoints[key]) ||
maxPoints[key].length !== update[key].length)) {
throw new Error('when maxPoints is set as a key:value object it must contain a 1:1 ' +
'corrispondence with the keys and number of traces in the update object');
}
}
}
/**
* A private function to reduce the type checking clutter in spliceTraces.
*
* @param {Object|HTMLDivElement} gd
* @param {Object} update
* @param {Number[]} indices
* @param {Number||Object} maxPoints
* @return {Object[]}
*/
function getExtendProperties(gd, update, indices, maxPoints) {
var maxPointsIsObject = Lib.isPlainObject(maxPoints);
var updateProps = [];
var trace, target, prop, insert, maxp;
// allow scalar index to represent a single trace position
if(!Array.isArray(indices)) indices = [indices];
// negative indices are wrapped around to their positive value. Equivalent to python indexing.
indices = positivifyIndices(indices, gd.data.length - 1);
// loop through all update keys and traces and harvest validated data.
for(var key in update) {
for(var j = 0; j < indices.length; j++) {
/*
* Choose the trace indexed by the indices map argument and get the prop setter-getter
* instance that references the key and value for this particular trace.
*/
trace = gd.data[indices[j]];
prop = nestedProperty(trace, key);
/*
* Target is the existing gd.data.trace.dataArray value like "x" or "marker.size"
* Target must exist as an Array to allow the extend operation to be performed.
*/
target = prop.get();
insert = update[key][j];
if(!Lib.isArrayOrTypedArray(insert)) {
throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array');
}
if(!Lib.isArrayOrTypedArray(target)) {
throw new Error('cannot extend missing or non-array attribute: ' + key);
}
if(target.constructor !== insert.constructor) {
throw new Error('cannot extend array with an array of a different type: ' + key);
}
/*
* maxPoints may be an object map or a scalar. If object select the key:value, else
* Use the scalar maxPoints for all key and trace combinations.
*/
maxp = maxPointsIsObject ? maxPoints[key][j] : maxPoints;
// could have chosen null here, -1 just tells us to not take a window
if(!isNumeric(maxp)) maxp = -1;
/*
* Wrap the nestedProperty in an object containing required data
* for lengthening and windowing this particular trace - key combination.
* Flooring maxp mirrors the behaviour of floats in the Array.slice JSnative function.
*/
updateProps.push({
prop: prop,
target: target,
insert: insert,
maxp: Math.floor(maxp)
});
}
}
// all target and insertion data now validated
return updateProps;
}
/**
* A private function to key Extend and Prepend traces DRY
*
* @param {Object|HTMLDivElement} gd
* @param {Object} update
* @param {Number[]} indices
* @param {Number||Object} maxPoints
* @param {Function} updateArray
* @return {Object}
*/
function spliceTraces(gd, update, indices, maxPoints, updateArray) {
assertExtendTracesArgs(gd, update, indices, maxPoints);
var updateProps = getExtendProperties(gd, update, indices, maxPoints);
var undoUpdate = {};
var undoPoints = {};
for(var i = 0; i < updateProps.length; i++) {
var prop = updateProps[i].prop;
var maxp = updateProps[i].maxp;
// return new array and remainder
var out = updateArray(updateProps[i].target, updateProps[i].insert, maxp);
prop.set(out[0]);
// build the inverse update object for the undo operation
if(!Array.isArray(undoUpdate[prop.astr])) undoUpdate[prop.astr] = [];
undoUpdate[prop.astr].push(out[1]);
// build the matching maxPoints undo object containing original trace lengths
if(!Array.isArray(undoPoints[prop.astr])) undoPoints[prop.astr] = [];
undoPoints[prop.astr].push(updateProps[i].target.length);
}
return {update: undoUpdate, maxPoints: undoPoints};
}
function concatTypedArray(arr0, arr1) {
var arr2 = new arr0.constructor(arr0.length + arr1.length);
arr2.set(arr0);
arr2.set(arr1, arr0.length);
return arr2;
}
/**
* extend && prepend traces at indices with update arrays, window trace lengths to maxPoints
*
* Extend and Prepend have identical APIs. Prepend inserts an array at the head while Extend
* inserts an array off the tail. Prepend truncates the tail of the array - counting maxPoints
* from the head, whereas Extend truncates the head of the array, counting backward maxPoints
* from the tail.
*
* If maxPoints is undefined, nonNumeric, negative or greater than extended trace length no
* truncation / windowing will be performed. If its zero, well the whole trace is truncated.
*
* @param {Object|HTMLDivElement} gd The graph div
* @param {Object} update The key:array map of target attributes to extend
* @param {Number|Number[]} indices The locations of traces to be extended
* @param {Number|Object} [maxPoints] Number of points for trace window after lengthening.
*
*/
function extendTraces(gd, update, indices, maxPoints) {
gd = Lib.getGraphDiv(gd);
function updateArray(target, insert, maxp) {
var newArray, remainder;
if(Lib.isTypedArray(target)) {
if(maxp < 0) {
var none = new target.constructor(0);
var both = concatTypedArray(target, insert);
if(maxp < 0) {
newArray = both;
remainder = none;
} else {
newArray = none;
remainder = both;
}
} else {
newArray = new target.constructor(maxp);
remainder = new target.constructor(target.length + insert.length - maxp);
if(maxp === insert.length) {
newArray.set(insert);
remainder.set(target);
} else if(maxp < insert.length) {
var numberOfItemsFromInsert = insert.length - maxp;
newArray.set(insert.subarray(numberOfItemsFromInsert));
remainder.set(target);
remainder.set(insert.subarray(0, numberOfItemsFromInsert), target.length);
} else {
var numberOfItemsFromTarget = maxp - insert.length;
var targetBegin = target.length - numberOfItemsFromTarget;
newArray.set(target.subarray(targetBegin));
newArray.set(insert, numberOfItemsFromTarget);
remainder.set(target.subarray(0, targetBegin));
}
}
} else {
newArray = target.concat(insert);
remainder = (maxp >= 0 && maxp < newArray.length) ?
newArray.splice(0, newArray.length - maxp) :
[];
}
return [newArray, remainder];
}
var undo = spliceTraces(gd, update, indices, maxPoints, updateArray);
var promise = exports.redraw(gd);
var undoArgs = [gd, undo.update, indices, undo.maxPoints];
Queue.add(gd, exports.prependTraces, undoArgs, extendTraces, arguments);
return promise;
}
function prependTraces(gd, update, indices, maxPoints) {
gd = Lib.getGraphDiv(gd);
function updateArray(target, insert, maxp) {
var newArray, remainder;
if(Lib.isTypedArray(target)) {
if(maxp <= 0) {
var none = new target.constructor(0);
var both = concatTypedArray(insert, target);
if(maxp < 0) {
newArray = both;
remainder = none;
} else {
newArray = none;
remainder = both;
}
} else {
newArray = new target.constructor(maxp);
remainder = new target.constructor(target.length + insert.length - maxp);
if(maxp === insert.length) {
newArray.set(insert);
remainder.set(target);
} else if(maxp < insert.length) {
var numberOfItemsFromInsert = insert.length - maxp;
newArray.set(insert.subarray(0, numberOfItemsFromInsert));
remainder.set(insert.subarray(numberOfItemsFromInsert));
remainder.set(target, numberOfItemsFromInsert);
} else {
var numberOfItemsFromTarget = maxp - insert.length;
newArray.set(insert);
newArray.set(target.subarray(0, numberOfItemsFromTarget), insert.length);
remainder.set(target.subarray(numberOfItemsFromTarget));
}
}
} else {
newArray = insert.concat(target);
remainder = (maxp >= 0 && maxp < newArray.length) ?
newArray.splice(maxp, newArray.length) :
[];
}
return [newArray, remainder];
}
var undo = spliceTraces(gd, update, indices, maxPoints, updateArray);
var promise = exports.redraw(gd);
var undoArgs = [gd, undo.update, indices, undo.maxPoints];
Queue.add(gd, exports.extendTraces, undoArgs, prependTraces, arguments);
return promise;
}
/**