-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathplots.js
2311 lines (1864 loc) · 74.1 KB
/
plots.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
/**
* Copyright 2012-2017, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var d3 = require('d3');
var isNumeric = require('fast-isnumeric');
var Plotly = require('../plotly');
var PlotSchema = require('../plot_api/plot_schema');
var Registry = require('../registry');
var Lib = require('../lib');
var Color = require('../components/color');
var BADNUM = require('../constants/numerical').BADNUM;
var plots = module.exports = {};
var animationAttrs = require('./animation_attributes');
var frameAttrs = require('./frame_attributes');
var relinkPrivateKeys = Lib.relinkPrivateKeys;
// Expose registry methods on Plots for backward-compatibility
Lib.extendFlat(plots, Registry);
plots.attributes = require('./attributes');
plots.attributes.type.values = plots.allTypes;
plots.fontAttrs = require('./font_attributes');
plots.layoutAttributes = require('./layout_attributes');
// TODO make this a plot attribute?
plots.fontWeight = 'normal';
var subplotsRegistry = plots.subplotsRegistry;
var transformsRegistry = plots.transformsRegistry;
var ErrorBars = require('../components/errorbars');
var commandModule = require('./command');
plots.executeAPICommand = commandModule.executeAPICommand;
plots.computeAPICommandBindings = commandModule.computeAPICommandBindings;
plots.manageCommandObserver = commandModule.manageCommandObserver;
plots.hasSimpleAPICommandBindings = commandModule.hasSimpleAPICommandBindings;
/**
* Find subplot ids in data.
* Meant to be used in the defaults step.
*
* Use plots.getSubplotIds to grab the current
* subplot ids later on in Plotly.plot.
*
* @param {array} data plotly data array
* (intended to be _fullData, but does not have to be).
* @param {string} type subplot type to look for.
*
* @return {array} list of subplot ids (strings).
* N.B. these ids possibly un-ordered.
*
* TODO incorporate cartesian/gl2d axis finders in this paradigm.
*/
plots.findSubplotIds = function findSubplotIds(data, type) {
var subplotIds = [];
if(!plots.subplotsRegistry[type]) return subplotIds;
var attr = plots.subplotsRegistry[type].attr;
for(var i = 0; i < data.length; i++) {
var trace = data[i];
if(plots.traceIs(trace, type) && subplotIds.indexOf(trace[attr]) === -1) {
subplotIds.push(trace[attr]);
}
}
return subplotIds;
};
/**
* Get the ids of the current subplots.
*
* @param {object} layout plotly full layout object.
* @param {string} type subplot type to look for.
*
* @return {array} list of ordered subplot ids (strings).
*
*/
plots.getSubplotIds = function getSubplotIds(layout, type) {
var _module = plots.subplotsRegistry[type];
if(!_module) return [];
// layout must be 'fullLayout' here
if(type === 'cartesian' && (!layout._has || !layout._has('cartesian'))) return [];
if(type === 'gl2d' && (!layout._has || !layout._has('gl2d'))) return [];
if(type === 'cartesian' || type === 'gl2d') {
return Object.keys(layout._plots || {});
}
var idRegex = _module.idRegex,
layoutKeys = Object.keys(layout),
subplotIds = [];
for(var i = 0; i < layoutKeys.length; i++) {
var layoutKey = layoutKeys[i];
if(idRegex.test(layoutKey)) subplotIds.push(layoutKey);
}
// order the ids
var idLen = _module.idRoot.length;
subplotIds.sort(function(a, b) {
var aNum = +(a.substr(idLen) || 1),
bNum = +(b.substr(idLen) || 1);
return aNum - bNum;
});
return subplotIds;
};
/**
* Get the data trace(s) associated with a given subplot.
*
* @param {array} data plotly full data array.
* @param {string} type subplot type to look for.
* @param {string} subplotId subplot id to look for.
*
* @return {array} list of trace objects.
*
*/
plots.getSubplotData = function getSubplotData(data, type, subplotId) {
if(!plots.subplotsRegistry[type]) return [];
var attr = plots.subplotsRegistry[type].attr,
subplotData = [],
trace;
for(var i = 0; i < data.length; i++) {
trace = data[i];
if(type === 'gl2d' && plots.traceIs(trace, 'gl2d')) {
var spmatch = Plotly.Axes.subplotMatch,
subplotX = 'x' + subplotId.match(spmatch)[1],
subplotY = 'y' + subplotId.match(spmatch)[2];
if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) {
subplotData.push(trace);
}
}
else {
if(trace[attr] === subplotId) subplotData.push(trace);
}
}
return subplotData;
};
/**
* Get calcdata traces(s) associated with a given subplot
*
* @param {array} calcData (as in gd.calcdata)
* @param {string} type subplot type
* @param {string} subplotId subplot id to look for
*
* @return {array} array of calcdata traces
*/
plots.getSubplotCalcData = function(calcData, type, subplotId) {
if(!plots.subplotsRegistry[type]) return [];
var attr = plots.subplotsRegistry[type].attr;
var subplotCalcData = [];
for(var i = 0; i < calcData.length; i++) {
var calcTrace = calcData[i],
trace = calcTrace[0].trace;
if(trace[attr] === subplotId) subplotCalcData.push(calcTrace);
}
return subplotCalcData;
};
// in some cases the browser doesn't seem to know how big
// the text is at first, so it needs to draw it,
// then wait a little, then draw it again
plots.redrawText = function(gd) {
// do not work if polar is present
if((gd.data && gd.data[0] && gd.data[0].r)) return;
return new Promise(function(resolve) {
setTimeout(function() {
Registry.getComponentMethod('annotations', 'draw')(gd);
Registry.getComponentMethod('legend', 'draw')(gd);
(gd.calcdata || []).forEach(function(d) {
if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb();
});
resolve(plots.previousPromises(gd));
}, 300);
});
};
// resize plot about the container size
plots.resize = function(gd) {
return new Promise(function(resolve, reject) {
if(!gd || d3.select(gd).style('display') === 'none') {
reject(new Error('Resize must be passed a plot div element.'));
}
if(gd._redrawTimer) clearTimeout(gd._redrawTimer);
gd._redrawTimer = setTimeout(function() {
// return if there is nothing to resize
if(gd.layout.width && gd.layout.height) {
resolve(gd);
return;
}
delete gd.layout.width;
delete gd.layout.height;
// autosizing doesn't count as a change that needs saving
var oldchanged = gd.changed;
// nor should it be included in the undo queue
gd.autoplay = true;
Plotly.relayout(gd, { autosize: true }).then(function() {
gd.changed = oldchanged;
resolve(gd);
});
}, 100);
});
};
// for use in Lib.syncOrAsync, check if there are any
// pending promises in this plot and wait for them
plots.previousPromises = function(gd) {
if((gd._promises || []).length) {
return Promise.all(gd._promises)
.then(function() { gd._promises = []; });
}
};
/**
* Adds the 'Edit chart' link.
* Note that now Plotly.plot() calls this so it can regenerate whenever it replots
*
* Add source links to your graph inside the 'showSources' config argument.
*/
plots.addLinks = function(gd) {
// Do not do anything if showLink and showSources are not set to true in config
if(!gd._context.showLink && !gd._context.showSources) return;
var fullLayout = gd._fullLayout;
var linkContainer = fullLayout._paper
.selectAll('text.js-plot-link-container').data([0]);
linkContainer.enter().append('text')
.classed('js-plot-link-container', true)
.style({
'font-family': '"Open Sans", Arial, sans-serif',
'font-size': '12px',
'fill': Color.defaultLine,
'pointer-events': 'all'
})
.each(function() {
var links = d3.select(this);
links.append('tspan').classed('js-link-to-tool', true);
links.append('tspan').classed('js-link-spacer', true);
links.append('tspan').classed('js-sourcelinks', true);
});
// The text node inside svg
var text = linkContainer.node(),
attrs = {
y: fullLayout._paper.attr('height') - 9
};
// If text's width is bigger than the layout
// Check that text is a child node or document.body
// because otherwise IE/Edge might throw an exception
// when calling getComputedTextLength().
// Apparently offsetParent is null for invisibles.
if(document.body.contains(text) && text.getComputedTextLength() >= (fullLayout.width - 20)) {
// Align the text at the left
attrs['text-anchor'] = 'start';
attrs.x = 5;
}
else {
// Align the text at the right
attrs['text-anchor'] = 'end';
attrs.x = fullLayout._paper.attr('width') - 7;
}
linkContainer.attr(attrs);
var toolspan = linkContainer.select('.js-link-to-tool'),
spacespan = linkContainer.select('.js-link-spacer'),
sourcespan = linkContainer.select('.js-sourcelinks');
if(gd._context.showSources) gd._context.showSources(gd);
// 'view in plotly' link for embedded plots
if(gd._context.showLink) positionPlayWithData(gd, toolspan);
// separator if we have both sources and tool link
spacespan.text((toolspan.text() && sourcespan.text()) ? ' - ' : '');
};
// note that now this function is only adding the brand in
// iframes and 3rd-party apps
function positionPlayWithData(gd, container) {
container.text('');
var link = container.append('a')
.attr({
'xlink:xlink:href': '#',
'class': 'link--impt link--embedview',
'font-weight': 'bold'
})
.text(gd._context.linkText + ' ' + String.fromCharCode(187));
if(gd._context.sendData) {
link.on('click', function() {
plots.sendDataToCloud(gd);
});
}
else {
var path = window.location.pathname.split('/');
var query = window.location.search;
link.attr({
'xlink:xlink:show': 'new',
'xlink:xlink:href': '/' + path[2].split('.')[0] + '/' + path[1] + query
});
}
}
plots.sendDataToCloud = function(gd) {
gd.emit('plotly_beforeexport');
var baseUrl = (window.PLOTLYENV && window.PLOTLYENV.BASE_URL) || 'https://plot.ly';
var hiddenformDiv = d3.select(gd)
.append('div')
.attr('id', 'hiddenform')
.style('display', 'none');
var hiddenform = hiddenformDiv
.append('form')
.attr({
action: baseUrl + '/external',
method: 'post',
target: '_blank'
});
var hiddenformInput = hiddenform
.append('input')
.attr({
type: 'text',
name: 'data'
});
hiddenformInput.node().value = plots.graphJson(gd, false, 'keepdata');
hiddenform.node().submit();
hiddenformDiv.remove();
gd.emit('plotly_afterexport');
return false;
};
// Fill in default values:
//
// gd.data, gd.layout:
// are precisely what the user specified,
// these fields shouldn't be modified nor used directly
// after the supply defaults step.
//
// gd._fullData, gd._fullLayout:
// are complete descriptions of how to draw the plot,
// use these fields in all required computations.
//
// gd._fullLayout._modules
// is a list of all the trace modules required to draw the plot.
//
// gd._fullLayout._basePlotModules
// is a list of all the plot modules required to draw the plot.
//
// gd._fullLayout._transformModules
// is a list of all the transform modules invoked.
//
plots.supplyDefaults = function(gd) {
var oldFullLayout = gd._fullLayout || {},
newFullLayout = gd._fullLayout = {},
newLayout = gd.layout || {};
var oldFullData = gd._fullData || [],
newFullData = gd._fullData = [],
newData = gd.data || [];
var i;
// Create all the storage space for frames, but only if doesn't already exist
if(!gd._transitionData) plots.createTransitionData(gd);
// first fill in what we can of layout without looking at data
// because fullData needs a few things from layout
if(oldFullLayout._initialAutoSizeIsDone) {
// coerce the updated layout while preserving width and height
var oldWidth = oldFullLayout.width,
oldHeight = oldFullLayout.height;
plots.supplyLayoutGlobalDefaults(newLayout, newFullLayout);
if(!newLayout.width) newFullLayout.width = oldWidth;
if(!newLayout.height) newFullLayout.height = oldHeight;
}
else {
// coerce the updated layout and autosize if needed
plots.supplyLayoutGlobalDefaults(newLayout, newFullLayout);
var missingWidthOrHeight = (!newLayout.width || !newLayout.height),
autosize = newFullLayout.autosize,
autosizable = gd._context && gd._context.autosizable,
initialAutoSize = missingWidthOrHeight && (autosize || autosizable);
if(initialAutoSize) plots.plotAutoSize(gd, newLayout, newFullLayout);
else if(missingWidthOrHeight) plots.sanitizeMargins(gd);
// for backwards-compatibility with Plotly v1.x.x
if(!autosize && missingWidthOrHeight) {
newLayout.width = newFullLayout.width;
newLayout.height = newFullLayout.height;
}
}
newFullLayout._initialAutoSizeIsDone = true;
// keep track of how many traces are inputted
newFullLayout._dataLength = newData.length;
// then do the data
newFullLayout._globalTransforms = (gd._context || {}).globalTransforms;
plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout);
// attach helper method to check whether a plot type is present on graph
newFullLayout._has = plots._hasPlotType.bind(newFullLayout);
// special cases that introduce interactions between traces
var _modules = newFullLayout._modules;
for(i = 0; i < _modules.length; i++) {
var _module = _modules[i];
if(_module.cleanData) _module.cleanData(newFullData);
}
if(oldFullData.length === newData.length) {
for(i = 0; i < newFullData.length; i++) {
relinkPrivateKeys(newFullData[i], oldFullData[i]);
}
}
// finally, fill in the pieces of layout that may need to look at data
plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData);
// TODO remove in v2.0.0
// add has-plot-type refs to fullLayout for backward compatibility
newFullLayout._hasCartesian = newFullLayout._has('cartesian');
newFullLayout._hasGeo = newFullLayout._has('geo');
newFullLayout._hasGL3D = newFullLayout._has('gl3d');
newFullLayout._hasGL2D = newFullLayout._has('gl2d');
newFullLayout._hasTernary = newFullLayout._has('ternary');
newFullLayout._hasPie = newFullLayout._has('pie');
// clean subplots and other artifacts from previous plot calls
plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout);
// relink / initialize subplot axis objects
plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout);
// relink functions and _ attributes to promote consistency between plots
relinkPrivateKeys(newFullLayout, oldFullLayout);
// TODO may return a promise
plots.doAutoMargin(gd);
// set scale after auto margin routine
var axList = Plotly.Axes.list(gd);
for(i = 0; i < axList.length; i++) {
var ax = axList[i];
ax.setScale();
}
// update object references in calcdata
if((gd.calcdata || []).length === newFullData.length) {
for(i = 0; i < newFullData.length; i++) {
var newTrace = newFullData[i];
var cd0 = gd.calcdata[i][0];
if(cd0 && cd0.trace) {
if(cd0.trace._hasCalcTransform) {
remapTransformedArrays(cd0, newTrace);
} else {
cd0.trace = newTrace;
}
}
}
}
};
function remapTransformedArrays(cd0, newTrace) {
var oldTrace = cd0.trace;
var arrayAttrs = oldTrace._arrayAttrs;
var transformedArrayHash = {};
var i, astr;
for(i = 0; i < arrayAttrs.length; i++) {
astr = arrayAttrs[i];
transformedArrayHash[astr] = Lib.nestedProperty(oldTrace, astr).get().slice();
}
cd0.trace = newTrace;
for(i = 0; i < arrayAttrs.length; i++) {
astr = arrayAttrs[i];
Lib.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]);
}
}
// Create storage for all of the data related to frames and transitions:
plots.createTransitionData = function(gd) {
// Set up the default keyframe if it doesn't exist:
if(!gd._transitionData) {
gd._transitionData = {};
}
if(!gd._transitionData._frames) {
gd._transitionData._frames = [];
}
if(!gd._transitionData._frameHash) {
gd._transitionData._frameHash = {};
}
if(!gd._transitionData._counter) {
gd._transitionData._counter = 0;
}
if(!gd._transitionData._interruptCallbacks) {
gd._transitionData._interruptCallbacks = [];
}
};
// helper function to be bound to fullLayout to check
// whether a certain plot type is present on plot
plots._hasPlotType = function(category) {
var basePlotModules = this._basePlotModules || [];
for(var i = 0; i < basePlotModules.length; i++) {
var _module = basePlotModules[i];
if(_module.name === category) return true;
}
return false;
};
plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
var i, j;
var basePlotModules = oldFullLayout._basePlotModules || [];
for(i = 0; i < basePlotModules.length; i++) {
var _module = basePlotModules[i];
if(_module.clean) {
_module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout);
}
}
var hasPaper = !!oldFullLayout._paper;
var hasInfoLayer = !!oldFullLayout._infolayer;
oldLoop:
for(i = 0; i < oldFullData.length; i++) {
var oldTrace = oldFullData[i],
oldUid = oldTrace.uid;
for(j = 0; j < newFullData.length; j++) {
var newTrace = newFullData[j];
if(oldUid === newTrace.uid) continue oldLoop;
}
var query = (
'.hm' + oldUid +
',.contour' + oldUid +
',.carpet' + oldUid +
',#clip' + oldUid +
',.trace' + oldUid
);
// clean old heatmap, contour traces and clip paths
// that rely on uid identifiers
if(hasPaper) {
oldFullLayout._paper.selectAll(query).remove();
}
// clean old colorbars and range slider plot
if(hasInfoLayer) {
oldFullLayout._infolayer.selectAll('.cb' + oldUid).remove();
oldFullLayout._infolayer.selectAll('g.rangeslider-container')
.selectAll(query).remove();
}
}
if(oldFullLayout._zoomlayer) {
oldFullLayout._zoomlayer.selectAll('.select-outline').remove();
}
};
plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
var oldSubplots = oldFullLayout._plots || {},
newSubplots = newFullLayout._plots = {};
var mockGd = {
_fullData: newFullData,
_fullLayout: newFullLayout
};
var ids = Plotly.Axes.getSubplots(mockGd);
var i;
for(i = 0; i < ids.length; i++) {
var id = ids[i];
var oldSubplot = oldSubplots[id];
var xaxis = Plotly.Axes.getFromId(mockGd, id, 'x');
var yaxis = Plotly.Axes.getFromId(mockGd, id, 'y');
var plotinfo;
if(oldSubplot) {
plotinfo = newSubplots[id] = oldSubplot;
if(plotinfo._scene2d) {
plotinfo._scene2d.updateRefs(newFullLayout);
}
if(plotinfo.xaxis.layer !== xaxis.layer) {
plotinfo.xlines.attr('d', null);
plotinfo.xaxislayer.selectAll('*').remove();
}
if(plotinfo.yaxis.layer !== yaxis.layer) {
plotinfo.ylines.attr('d', null);
plotinfo.yaxislayer.selectAll('*').remove();
}
} else {
plotinfo = newSubplots[id] = {};
plotinfo.id = id;
}
plotinfo.xaxis = xaxis;
plotinfo.yaxis = yaxis;
// By default, we clip at the subplot level,
// but if one trace on a given subplot has *cliponaxis* set to false,
// we need to clip at the trace module layer level;
// find this out here, once of for all.
plotinfo._hasClipOnAxisFalse = false;
for(var j = 0; j < newFullData.length; j++) {
var trace = newFullData[j];
if(
trace.xaxis === plotinfo.xaxis._id &&
trace.yaxis === plotinfo.yaxis._id &&
trace.cliponaxis === false
) {
plotinfo._hasClipOnAxisFalse = true;
break;
}
}
}
// while we're at it, link overlaying axes to their main axes and
// anchored axes to the axes they're anchored to
var axList = Plotly.Axes.list(mockGd, null, true);
for(i = 0; i < axList.length; i++) {
var ax = axList[i];
var mainAx = null;
if(ax.overlaying) {
mainAx = Plotly.Axes.getFromId(mockGd, ax.overlaying);
// you cannot overlay an axis that's already overlaying another
if(mainAx && mainAx.overlaying) {
ax.overlaying = false;
mainAx = null;
}
}
ax._mainAxis = mainAx || ax;
/*
* For now force overlays to overlay completely... so they
* can drag together correctly and share backgrounds.
* Later perhaps we make separate axis domain and
* tick/line domain or something, so they can still share
* the (possibly larger) dragger and background but don't
* have to both be drawn over that whole domain
*/
if(mainAx) ax.domain = mainAx.domain.slice();
ax._anchorAxis = ax.anchor === 'free' ?
null :
Plotly.Axes.getFromId(mockGd, ax.anchor);
}
};
// This function clears any trace attributes with valType: color and
// no set dflt filed in the plot schema. This is needed because groupby (which
// is the only transform for which this currently applies) supplies parent
// trace defaults, then expanded trace defaults. The result is that `null`
// colors are default-supplied and inherited as a color instead of a null.
// The result is that expanded trace default colors have no effect, with
// the final result that groups are indistinguishable. This function clears
// those colors so that individual groupby groups get unique colors.
plots.clearExpandedTraceDefaultColors = function(trace) {
var colorAttrs, path, i;
// This uses weird closure state in order to satisfy the linter rule
// that we can't create functions in a loop.
function locateColorAttrs(attr, attrName, attrs, level) {
path[level] = attrName;
path.length = level + 1;
if(attr.valType === 'color' && attr.dflt === undefined) {
colorAttrs.push(path.join('.'));
}
}
path = [];
// Get the cached colorAttrs:
colorAttrs = trace._module._colorAttrs;
// Or else compute and cache the colorAttrs on the module:
if(!colorAttrs) {
trace._module._colorAttrs = colorAttrs = [];
PlotSchema.crawl(
trace._module.attributes,
locateColorAttrs
);
}
for(i = 0; i < colorAttrs.length; i++) {
var origprop = Lib.nestedProperty(trace, '_input.' + colorAttrs[i]);
if(!origprop.get()) {
Lib.nestedProperty(trace, colorAttrs[i]).set(null);
}
}
};
plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) {
var i, fullTrace, trace;
var modules = fullLayout._modules = [],
basePlotModules = fullLayout._basePlotModules = [],
cnt = 0;
fullLayout._transformModules = [];
function pushModule(fullTrace) {
dataOut.push(fullTrace);
var _module = fullTrace._module;
if(!_module) return;
Lib.pushUnique(modules, _module);
Lib.pushUnique(basePlotModules, fullTrace._module.basePlotModule);
cnt++;
}
var carpetIndex = {};
var carpetDependents = [];
for(i = 0; i < dataIn.length; i++) {
trace = dataIn[i];
fullTrace = plots.supplyTraceDefaults(trace, cnt, fullLayout, i);
fullTrace.index = i;
fullTrace._input = trace;
fullTrace._expandedIndex = cnt;
if(fullTrace.transforms && fullTrace.transforms.length) {
var expandedTraces = applyTransforms(fullTrace, dataOut, layout, fullLayout);
for(var j = 0; j < expandedTraces.length; j++) {
var expandedTrace = expandedTraces[j];
var fullExpandedTrace = plots.supplyTraceDefaults(expandedTrace, cnt, fullLayout, i);
// mutate uid here using parent uid and expanded index
// to promote consistency between update calls
expandedTrace.uid = fullExpandedTrace.uid = fullTrace.uid + j;
// add info about parent data trace
fullExpandedTrace.index = i;
fullExpandedTrace._input = trace;
fullExpandedTrace._fullInput = fullTrace;
// add info about the expanded data
fullExpandedTrace._expandedIndex = cnt;
fullExpandedTrace._expandedInput = expandedTrace;
pushModule(fullExpandedTrace);
}
}
else {
// add identify refs for consistency with transformed traces
fullTrace._fullInput = fullTrace;
fullTrace._expandedInput = fullTrace;
pushModule(fullTrace);
}
if(Registry.traceIs(fullTrace, 'carpetAxis')) {
carpetIndex[fullTrace.carpet] = fullTrace;
}
if(Registry.traceIs(fullTrace, 'carpetDependent')) {
carpetDependents.push(i);
}
}
for(i = 0; i < carpetDependents.length; i++) {
fullTrace = dataOut[carpetDependents[i]];
if(!fullTrace.visible) continue;
var carpetAxis = carpetIndex[fullTrace.carpet];
fullTrace._carpet = carpetAxis;
if(!carpetAxis || !carpetAxis.visible) {
fullTrace.visible = false;
continue;
}
fullTrace.xaxis = carpetAxis.xaxis;
fullTrace.yaxis = carpetAxis.yaxis;
}
};
plots.supplyAnimationDefaults = function(opts) {
opts = opts || {};
var i;
var optsOut = {};
function coerce(attr, dflt) {
return Lib.coerce(opts || {}, optsOut, animationAttrs, attr, dflt);
}
coerce('mode');
coerce('direction');
coerce('fromcurrent');
if(Array.isArray(opts.frame)) {
optsOut.frame = [];
for(i = 0; i < opts.frame.length; i++) {
optsOut.frame[i] = plots.supplyAnimationFrameDefaults(opts.frame[i] || {});
}
} else {
optsOut.frame = plots.supplyAnimationFrameDefaults(opts.frame || {});
}
if(Array.isArray(opts.transition)) {
optsOut.transition = [];
for(i = 0; i < opts.transition.length; i++) {
optsOut.transition[i] = plots.supplyAnimationTransitionDefaults(opts.transition[i] || {});
}
} else {
optsOut.transition = plots.supplyAnimationTransitionDefaults(opts.transition || {});
}
return optsOut;
};
plots.supplyAnimationFrameDefaults = function(opts) {
var optsOut = {};
function coerce(attr, dflt) {
return Lib.coerce(opts || {}, optsOut, animationAttrs.frame, attr, dflt);
}
coerce('duration');
coerce('redraw');
return optsOut;
};
plots.supplyAnimationTransitionDefaults = function(opts) {
var optsOut = {};
function coerce(attr, dflt) {
return Lib.coerce(opts || {}, optsOut, animationAttrs.transition, attr, dflt);
}
coerce('duration');
coerce('easing');
return optsOut;
};
plots.supplyFrameDefaults = function(frameIn) {
var frameOut = {};
function coerce(attr, dflt) {
return Lib.coerce(frameIn, frameOut, frameAttrs, attr, dflt);
}
coerce('group');
coerce('name');
coerce('traces');
coerce('baseframe');
coerce('data');
coerce('layout');
return frameOut;
};
plots.supplyTraceDefaults = function(traceIn, traceOutIndex, layout, traceInIndex) {
var traceOut = {},
defaultColor = Color.defaults[traceOutIndex % Color.defaults.length];
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, plots.attributes, attr, dflt);
}
function coerceSubplotAttr(subplotType, subplotAttr) {
if(!plots.traceIs(traceOut, subplotType)) return;
return Lib.coerce(traceIn, traceOut,
plots.subplotsRegistry[subplotType].attributes, subplotAttr);
}
var visible = coerce('visible');
coerce('type');
coerce('uid');
coerce('name', 'trace ' + traceInIndex);
// coerce subplot attributes of all registered subplot types
var subplotTypes = Object.keys(subplotsRegistry);
for(var i = 0; i < subplotTypes.length; i++) {
var subplotType = subplotTypes[i];
// done below (only when visible is true)
// TODO unified this pattern
if(['cartesian', 'gl2d'].indexOf(subplotType) !== -1) continue;
var attr = subplotsRegistry[subplotType].attr;
if(attr) coerceSubplotAttr(subplotType, attr);
}
if(visible) {
coerce('customdata');
coerce('ids');
var _module = plots.getModule(traceOut);
traceOut._module = _module;
if(plots.traceIs(traceOut, 'showLegend')) {
coerce('showlegend');
coerce('legendgroup');
}
Registry.getComponentMethod(
'fx',
'supplyDefaults'
)(traceIn, traceOut, defaultColor, layout);
// TODO add per-base-plot-module trace defaults step
if(_module) {
_module.supplyDefaults(traceIn, traceOut, defaultColor, layout);
Lib.coerceHoverinfo(traceIn, traceOut, layout);
}