File tree Expand file tree Collapse file tree 2 files changed +58
-3
lines changed Expand file tree Collapse file tree 2 files changed +58
-3
lines changed Original file line number Diff line number Diff line change @@ -24,13 +24,30 @@ var helpers = require('./helpers');
2424
2525var MAIN_TITLE = 1 ;
2626
27+ var LEGEND_PATTERN = / ^ l e g e n d [ 0 - 9 ] * $ / ;
28+
2729module . exports = function draw ( gd , opts ) {
2830 if ( opts ) {
2931 drawOne ( gd , opts ) ;
3032 } else {
31- var legends = gd . _fullLayout . _legends ;
32- for ( var i = 0 ; i < legends . length ; i ++ ) {
33- var legendId = legends [ i ] ;
33+ var fullLayout = gd . _fullLayout ;
34+ var newLegends = fullLayout . _legends ;
35+
36+ // remove old legends that won't stay on the graph
37+ var oldLegends = fullLayout . _infolayer . selectAll ( '[class^="legend"]' ) ;
38+
39+ oldLegends . each ( function ( ) {
40+ var el = d3 . select ( this ) ;
41+ var classes = el . attr ( 'class' ) ;
42+ var cls = classes . split ( ' ' ) [ 0 ] ;
43+ if ( cls . match ( LEGEND_PATTERN ) && newLegends . indexOf ( cls ) === - 1 ) {
44+ el . remove ( ) ;
45+ }
46+ } ) ;
47+
48+ // draw/update new legends
49+ for ( var i = 0 ; i < newLegends . length ; i ++ ) {
50+ var legendId = newLegends [ i ] ;
3451 var legendObj = gd . _fullLayout [ legendId ] ;
3552 drawOne ( gd , legendObj ) ;
3653 }
Original file line number Diff line number Diff line change @@ -1122,6 +1122,44 @@ describe('legend relayout update', function() {
11221122 } )
11231123 . then ( done , done . fail ) ;
11241124 } ) ;
1125+
1126+ it ( 'should be able to add & clear multiple legends using react' , function ( done ) {
1127+ var fig1 = {
1128+ data : [ {
1129+ y : [ 1 , 2 , 3 ]
1130+ } ]
1131+ } ;
1132+
1133+ var fig2 = {
1134+ data : [ {
1135+ y : [ 1 , 2 , 3 ]
1136+ } , {
1137+ y : [ 3 , 1 , 2 ] ,
1138+ legend : 'legend2'
1139+ } ] ,
1140+ layout : {
1141+ legend2 : { y : 0.5 }
1142+ }
1143+ } ;
1144+
1145+ Plotly . newPlot ( gd , fig1 )
1146+ . then ( function ( ) {
1147+ expect ( d3SelectAll ( '.legend2' ) [ 0 ] . length ) . toBe ( 0 ) ;
1148+ } )
1149+ . then ( function ( ) {
1150+ return Plotly . react ( gd , fig2 ) ;
1151+ } )
1152+ . then ( function ( ) {
1153+ expect ( d3SelectAll ( '.legend2' ) [ 0 ] . length ) . toBe ( 1 ) ;
1154+ } )
1155+ . then ( function ( ) {
1156+ return Plotly . react ( gd , fig1 ) ;
1157+ } )
1158+ . then ( function ( ) {
1159+ expect ( d3SelectAll ( '.legend2' ) [ 0 ] . length ) . toBe ( 0 ) ;
1160+ } )
1161+ . then ( done , done . fail ) ;
1162+ } ) ;
11251163} ) ;
11261164
11271165describe ( 'legend orientation change:' , function ( ) {
You can’t perform that action at this time.
0 commit comments