From 3a70fee4c82326aa864387ea511b84aec4207faa Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Fri, 2 Nov 2018 22:45:38 -0400 Subject: [PATCH 01/33] make hover label test independent of selection order --- test/jasmine/assets/custom_assertions.js | 75 ++++++++++++++++++------ 1 file changed, 57 insertions(+), 18 deletions(-) diff --git a/test/jasmine/assets/custom_assertions.js b/test/jasmine/assets/custom_assertions.js index 86496bb2033..b33cbe3aeea 100644 --- a/test/jasmine/assets/custom_assertions.js +++ b/test/jasmine/assets/custom_assertions.js @@ -59,9 +59,7 @@ exports.assertHoverLabelStyle = function(g, expectation, msg, textSelector) { expect(textStyle.fill).toBe(expectation.fontColor, msg + ': font.color'); }; -function assertLabelContent(label, expectation, msg) { - if(!expectation) expectation = ''; - +function getLabelContent(label) { var lines = label.selectAll('tspan.line'); var content = []; @@ -77,8 +75,15 @@ function assertLabelContent(label, expectation, msg) { } else { fill(label); } + return content.join('\n'); +} + +function assertLabelContent(label, expectation, msg) { + if(!expectation) expectation = ''; + + var content = getLabelContent(label); - expect(content.join('\n')).toBe(expectation, msg + ': text content'); + expect(content).toBe(expectation, msg + ': text content'); } function count(selector) { @@ -130,35 +135,63 @@ exports.assertHoverLabelContent = function(expectation, msg) { expect(ptCnt) .toBe(expectation.name.length, ptMsg + ' # of visible labels'); - var bboxes = []; + var observed = []; + var expected = expectation.nums.map(function(num, i) { + return { + num: num, + name: expectation.name[i], + order: (expectation.hOrder || expectation.vOrder || []).indexOf(i) + }; + }); d3.selectAll(ptSelector).each(function(_, i) { var g = d3.select(this); var numsSel = g.select('text.nums'); var nameSel = g.select('text.name'); - assertLabelContent(numsSel, expectation.nums[i], ptMsg + ' (nums ' + i + ')'); - assertLabelContent(nameSel, expectation.name[i], ptMsg + ' (name ' + i + ')'); + // Label selection can be out of order... dunno why, but on AJ's Mac, + // just for certain box and violin cases, the order looks correct but + // it's different from what we see in CI (and presumably on + // other systems) which looks wrong. + // Anyway we don't *really* care about the order within the selection, + // we just care that each label is correct. So collect all the info + // about each label, and sort both observed and expected identically. + observed.push({ + num: getLabelContent(numsSel), + name: getLabelContent(nameSel), + bbox: this.getBoundingClientRect(), + order: -1 + }); if('isRotated' in expectation) { expect(g.attr('transform').match(reRotate)) .negateIf(expectation.isRotated) .toBe(null, ptMsg + ' ' + i + ' should be rotated'); } - - bboxes.push({bbox: this.getBoundingClientRect(), index: i}); }); - if(expectation.vOrder) { - bboxes.sort(function(a, b) { - return (a.bbox.top + a.bbox.bottom - b.bbox.top - b.bbox.bottom) / 2; + if(expectation.vOrder || expectation.hOrder) { + var o2 = observed.slice(); + o2.sort(function(a, b) { + return expectation.vOrder ? + (a.bbox.top + a.bbox.bottom - b.bbox.top - b.bbox.bottom) / 2 : + (b.bbox.left + b.bbox.right - a.bbox.left - a.bbox.right) / 2; }); - expect(bboxes.map(function(d) { return d.index; })).toEqual(expectation.vOrder); - } - if(expectation.hOrder) { - bboxes.sort(function(a, b) { - return (b.bbox.left + b.bbox.right - a.bbox.left - a.bbox.right) / 2; + o2.forEach(function(item, i) { + item.order = i; + delete item.bbox; }); - expect(bboxes.map(function(d) { return d.index; })).toEqual(expectation.hOrder); } + observed.sort(labelSorter); + expected.sort(labelSorter); + // don't use .toEqual here because we want the message + expect(observed.length).toBe(expected.length, ptMsg); + observed.forEach(function(obsi, i) { + var expi = expected[i]; + expect(obsi.num).toBe(expi.num, ptMsg + ' (nums ' + i + ')'); + expect(obsi.name).toBe(expi.name, ptMsg + ' (name ' + i + ')'); + if(expectation.vOrder || expectation.hOrder) { + expect(obsi.order).toBe(expi.order, ptMsg + ' (order ' + i + ')'); + } + }); } else { if(expectation.nums) { fail(ptMsg + ': expecting *nums* labels, did not find any.'); @@ -181,6 +214,12 @@ exports.assertHoverLabelContent = function(expectation, msg) { } }; +function labelSorter(a, b) { + if(a.name !== b.name) return a.name > b.name ? 1 : -1; + if(a.num !== b.num) return a.num > b.num ? 1 : -1; + return a.order - b.order; +} + exports.assertClip = function(sel, isClipped, size, msg) { expect(sel.size()).toBe(size, msg + ' clip path (selection size)'); From a86ca58f3639ea6664c6ec68c8bd56986a86d88f Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Wed, 31 Oct 2018 15:48:07 -0400 Subject: [PATCH 02/33] fix and :lock: bug with impliedEdits and groupby transform --- src/plot_api/plot_api.js | 12 ++++++- test/jasmine/tests/plot_api_test.js | 56 ++++++++++++++++++++--------- 2 files changed, 51 insertions(+), 17 deletions(-) diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index dfc66dd9868..64c3f47c91c 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1420,6 +1420,16 @@ function _restyle(gd, aobj, traces) { function rangeAttr(axName) { return 'LAYOUT' + axName + '.range'; } + function getFullTrace(traceIndex) { + // usually fullData maps 1:1 onto data, but with groupby transforms + // the fullData index can be greater. Take the *first* matching trace. + for(var j = traceIndex; j < fullData.length; j++) { + if(fullData[j]._input === data[traceIndex]) return fullData[j]; + } + // should never get here - and if we *do* it should cause an error + // later on undefined fullTrace is passed to nestedProperty. + } + // for attrs that interact (like scales & autoscales), save the // old vals before making the change // val=undefined will not set a value, just record what the value was. @@ -1507,7 +1517,7 @@ function _restyle(gd, aobj, traces) { undoit[ai] = a0(); for(i = 0; i < traces.length; i++) { cont = data[traces[i]]; - contFull = fullData[traces[i]]; + contFull = getFullTrace(traces[i]); param = Lib.nestedProperty(cont, ai); oldVal = param.get(); newVal = Array.isArray(vi) ? vi[i % vi.length] : vi; diff --git a/test/jasmine/tests/plot_api_test.js b/test/jasmine/tests/plot_api_test.js index 3ff769c6ece..8f72baf0bb0 100644 --- a/test/jasmine/tests/plot_api_test.js +++ b/test/jasmine/tests/plot_api_test.js @@ -1266,28 +1266,52 @@ describe('Test plot api', function() { .then(done); }); - it('sets x/ytype scaled when editing heatmap x0/dx/y0/dy', function(done) { - var x0 = 3; - var dy = 5; - - function check(scaled, msg) { - expect(gd.data[0].x0).negateIf(!scaled).toBe(x0, msg); - expect(gd.data[0].xtype).toBe(scaled ? 'scaled' : undefined, msg); - expect(gd.data[0].dy).negateIf(!scaled).toBe(dy, msg); - expect(gd.data[0].ytype).toBe(scaled ? 'scaled' : undefined, msg); - } + function checkScaling(xyType, xyTypeIn, iIn, iOut) { + expect(gd._fullData[iOut].xtype).toBe(xyType); + expect(gd._fullData[iOut].ytype).toBe(xyType); + expect(gd.data[iIn].xtype).toBe(xyTypeIn); + expect(gd.data[iIn].ytype).toBe(xyTypeIn); + } - Plotly.plot(gd, [{x: [1, 2, 4], y: [2, 3, 5], z: [[1, 2], [3, 4]], type: 'heatmap'}]) + it('sets heatmap xtype/ytype when you edit x/y data or scaling params', function(done) { + Plotly.plot(gd, [{type: 'heatmap', z: [[0, 1], [2, 3]]}]) .then(function() { - check(false, 'initial'); - return Plotly.restyle(gd, {x0: x0, dy: dy}); + // TODO would probably be better to actively default to 'array' here... + checkScaling(undefined, undefined, 0, 0); + return Plotly.restyle(gd, {x: [[2, 4]], y: [[3, 5]]}, [0]); }) .then(function() { - check(true, 'set x0 & dy'); - return Queue.undo(gd); + checkScaling('array', 'array', 0, 0); + return Plotly.restyle(gd, {x0: 1, dy: 3}, [0]); }) .then(function() { - check(false, 'undo'); + checkScaling('scaled', 'scaled', 0, 0); + }) + .catch(failTest) + .then(done); + }); + + it('sets heatmap xtype/ytype even when data/fullData indices mismatch', function(done) { + Plotly.plot(gd, [ + { + // importantly, this is NOT a heatmap trace, so _fullData[1] + // will not have the same attributes as data[1] + x: [1, -1, -2, 0], + y: [1, 2, 3, 1], + transforms: [{type: 'groupby', groups: ['a', 'b', 'a', 'b']}] + }, + {type: 'heatmap', z: [[0, 1], [2, 3]]} + ]) + .then(function() { + checkScaling(undefined, undefined, 1, 2); + return Plotly.restyle(gd, {x: [[2, 4]], y: [[3, 5]]}, [1]); + }) + .then(function() { + checkScaling('array', 'array', 1, 2); + return Plotly.restyle(gd, {x0: 1, dy: 3}, [1]); + }) + .then(function() { + checkScaling('scaled', 'scaled', 1, 2); }) .catch(failTest) .then(done); From 4ca328a8c1ba51e013a8558a9c93329941bab201 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Wed, 31 Oct 2018 15:49:12 -0400 Subject: [PATCH 03/33] remove impliedEdits that got forgotten in #3044 --- src/traces/histogram/attributes.js | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/traces/histogram/attributes.js b/src/traces/histogram/attributes.js index 80bf57e1585..e38c213b270 100644 --- a/src/traces/histogram/attributes.js +++ b/src/traces/histogram/attributes.js @@ -172,11 +172,6 @@ module.exports = { dflt: null, role: 'style', editType: 'calc', - impliedEdits: { - 'ybins.start': undefined, - 'ybins.end': undefined, - 'ybins.size': undefined - }, description: [ 'Obsolete: since v1.42 each bin attribute is auto-determined', 'separately and `autobiny` is not needed. However, we accept', From 082ac3818a94bfb488c2fb5e1fd60b9629f563a4 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Wed, 31 Oct 2018 15:55:49 -0400 Subject: [PATCH 04/33] alias `Lib.nestedProperty` separately in plot_api omitted some from this commit because another commit will point them to a new function --- src/plot_api/plot_api.js | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 64c3f47c91c..0442267805b 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -15,6 +15,8 @@ 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'); @@ -842,7 +844,7 @@ function getExtendProperties(gd, update, indices, maxPoints) { * instance that references the key and value for this particular trace. */ trace = gd.data[indices[j]]; - prop = Lib.nestedProperty(trace, key); + prop = nestedProperty(trace, key); /* * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size" @@ -1528,7 +1530,7 @@ function _restyle(gd, aobj, traces) { var prefix = ai.substr(0, ai.length - finalPart.length - 1); var prefixDot = prefix ? prefix + '.' : ''; var innerContFull = prefix ? - Lib.nestedProperty(contFull, prefix).get() : contFull; + nestedProperty(contFull, prefix).get() : contFull; valObject = PlotSchema.getTraceValObject(contFull, param.parts); @@ -1575,14 +1577,14 @@ function _restyle(gd, aobj, traces) { Lib.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); if(oldVal === 'pie') { - Lib.nestedProperty(cont, 'marker.color') - .set(Lib.nestedProperty(cont, 'marker.colors').get()); + nestedProperty(cont, 'marker.color') + .set(nestedProperty(cont, 'marker.colors').get()); // super kludgy - but if all pies are gone we won't remove them otherwise fullLayout._pielayer.selectAll('g.trace').remove(); } else if(Registry.traceIs(cont, 'cartesian')) { - Lib.nestedProperty(cont, 'marker.colors') - .set(Lib.nestedProperty(cont, 'marker.color').get()); + nestedProperty(cont, 'marker.colors') + .set(nestedProperty(cont, 'marker.color').get()); } } @@ -1653,7 +1655,7 @@ function _restyle(gd, aobj, traces) { // swap hovermode if set to "compare x/y data" if(ai === 'orientationaxes') { - var hovermode = Lib.nestedProperty(gd.layout, 'hovermode'); + var hovermode = nestedProperty(gd.layout, 'hovermode'); if(hovermode.get() === 'x') { hovermode.set('y'); } else if(hovermode.get() === 'y') { @@ -1908,8 +1910,8 @@ function _relayout(gd, aobj) { var pleafPlus = p.parts[pend - 1] + '.' + pleaf; // trunk nodes (everything except the leaf) var ptrunk = p.parts.slice(0, pend).join('.'); - var parentIn = Lib.nestedProperty(gd.layout, ptrunk).get(); - var parentFull = Lib.nestedProperty(fullLayout, ptrunk).get(); + var parentIn = nestedProperty(gd.layout, ptrunk).get(); + var parentFull = nestedProperty(fullLayout, ptrunk).get(); var vOld = p.get(); if(vi === undefined) continue; @@ -1954,12 +1956,12 @@ function _relayout(gd, aobj) { // check autorange vs range else if(pleafPlus.match(AX_RANGE_RE)) { recordAlteredAxis(pleafPlus); - Lib.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } else if(pleafPlus.match(AX_AUTORANGE_RE)) { recordAlteredAxis(pleafPlus); - Lib.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); - var axFull = Lib.nestedProperty(fullLayout, ptrunk).get(); + nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + var axFull = nestedProperty(fullLayout, ptrunk).get(); if(axFull._inputDomain) { // if we're autoranging and this axis has a constrained domain, // reset it so we don't get locked into a shrunken size @@ -1967,7 +1969,7 @@ function _relayout(gd, aobj) { } } else if(pleafPlus.match(AX_DOMAIN_RE)) { - Lib.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); + nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); } // toggling axis type between log and linear: we need to convert @@ -2036,10 +2038,10 @@ function _relayout(gd, aobj) { doextra(ptrunk + '.autorange', true); doextra(ptrunk + '.range', null); } - Lib.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } else if(pleaf.match(AX_NAME_PATTERN)) { - var fullProp = Lib.nestedProperty(fullLayout, ai).get(), + var fullProp = nestedProperty(fullLayout, ai).get(), newType = (vi || {}).type; // This can potentially cause strange behavior if the autotype is not @@ -2116,7 +2118,7 @@ function _relayout(gd, aobj) { // now we've collected component edits - execute them all together for(arrayStr in arrayEdits) { var finished = manageArrays.applyContainerArrayChanges(gd, - Lib.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); + nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); if(!finished) flags.plot = true; } From b134a52e34aae28703c3be27e36dad549a1fc33e Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Wed, 31 Oct 2018 17:05:09 -0400 Subject: [PATCH 05/33] fix obscure undo/redo bug with container array relayout removal --- src/plot_api/plot_api.js | 4 +--- test/jasmine/tests/annotations_test.js | 32 +++++++++++++++++++++++++- test/jasmine/tests/lib_test.js | 3 +-- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 0442267805b..bf9ba602080 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -2063,8 +2063,6 @@ function _relayout(gd, aobj) { arrayStr = containerArrayMatch.array; i = containerArrayMatch.index; var propStr = containerArrayMatch.property; - var componentArray = Lib.nestedProperty(layout, arrayStr); - var obji = (componentArray || [])[i] || {}; var updateValObject = valObject || {editType: 'calc'}; if(i !== '' && propStr === '') { @@ -2074,7 +2072,7 @@ function _relayout(gd, aobj) { if(manageArrays.isAddVal(vi)) { undoit[ai] = null; } else if(manageArrays.isRemoveVal(vi)) { - undoit[ai] = obji; + undoit[ai] = (nestedProperty(layout, arrayStr).get() || [])[i]; } else { Lib.warn('unrecognized full object value', aobj); } diff --git a/test/jasmine/tests/annotations_test.js b/test/jasmine/tests/annotations_test.js index 2b863f862c8..7ac6b6d0cbe 100644 --- a/test/jasmine/tests/annotations_test.js +++ b/test/jasmine/tests/annotations_test.js @@ -1,6 +1,7 @@ var Annotations = require('@src/components/annotations'); var Plotly = require('@lib/index'); +var Queue = require('@src/lib/queue'); var Plots = require('@src/plots/plots'); var Lib = require('@src/lib'); var Loggers = require('@src/lib/loggers'); @@ -191,11 +192,20 @@ describe('annotations relayout', function() { Plotly.plot(gd, mockData, mockLayout).then(done); spyOn(Loggers, 'warn'); + + Plotly.setPlotConfig({queueLength: 3}); }); - afterEach(destroyGraphDiv); + afterEach(function() { + destroyGraphDiv(); + Plotly.setPlotConfig({queueLength: 0}); + }); function countAnnotations() { + // also check that no annotations are empty objects + (gd.layout.annotations || []).forEach(function(ann, i) { + expect(JSON.stringify(ann)).not.toBe(JSON.stringify({}), i); + }); return d3.selectAll('g.annotation').size(); } @@ -220,11 +230,31 @@ describe('annotations relayout', function() { .then(function() { expect(countAnnotations()).toEqual(len); + return Queue.undo(gd); + }) + .then(function() { + expect(countAnnotations()).toBe(len + 1); + + return Queue.redo(gd); + }) + .then(function() { + expect(countAnnotations()).toBe(len); + return Plotly.relayout(gd, 'annotations[0]', null); }) .then(function() { expect(countAnnotations()).toEqual(len - 1); + return Queue.undo(gd); + }) + .then(function() { + expect(countAnnotations()).toBe(len); + + return Queue.redo(gd); + }) + .then(function() { + expect(countAnnotations()).toBe(len - 1); + return Plotly.relayout(gd, 'annotations[0].visible', false); }) .then(function() { diff --git a/test/jasmine/tests/lib_test.js b/test/jasmine/tests/lib_test.js index 2ffe0710c55..376a6f7a2c7 100644 --- a/test/jasmine/tests/lib_test.js +++ b/test/jasmine/tests/lib_test.js @@ -2631,9 +2631,8 @@ describe('Queue', function() { return Plotly.relayout(gd, 'updatemenus[0]', null); }) .then(function() { - // buttons have been stripped out because it's an empty container array... expect(gd.undoQueue.queue[1].undo.args[0][1]) - .toEqual({ 'updatemenus[0]': {} }); + .toEqual({ 'updatemenus[0]': { buttons: [] } }); expect(gd.undoQueue.queue[1].redo.args[0][1]) .toEqual({ 'updatemenus[0]': null }); From c62cf2546b369de630931b8fe17c89d60e6f8129 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Fri, 2 Nov 2018 18:09:44 -0400 Subject: [PATCH 06/33] clean up handleHover3d it was putting the whole layout into the relayout call --- src/components/modebar/buttons.js | 60 ++++++++++++++----------------- 1 file changed, 27 insertions(+), 33 deletions(-) diff --git a/src/components/modebar/buttons.js b/src/components/modebar/buttons.js index 22875894d53..6d1ce4a6369 100644 --- a/src/components/modebar/buttons.js +++ b/src/components/modebar/buttons.js @@ -370,53 +370,47 @@ modeBarButtons.hoverClosest3d = { click: handleHover3d }; -function handleHover3d(gd, ev) { +function getNextHover3d(gd, ev) { var button = ev.currentTarget; - var val = button._previousVal || false; - var layout = gd.layout; + var val = button._previousVal; var fullLayout = gd._fullLayout; var sceneIds = fullLayout._subplots.gl3d; var axes = ['xaxis', 'yaxis', 'zaxis']; - var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor']; // initialize 'current spike' object to be stored in the DOM var currentSpikes = {}; - var axisSpikes = {}; var layoutUpdate = {}; if(val) { - layoutUpdate = Lib.extendDeep(layout, val); + layoutUpdate = val; button._previousVal = null; } else { - layoutUpdate = { - 'allaxes.showspikes': false - }; - for(var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i], - sceneLayout = fullLayout[sceneId], - sceneSpikes = currentSpikes[sceneId] = {}; + var sceneId = sceneIds[i]; + var sceneLayout = fullLayout[sceneId]; - sceneSpikes.hovermode = sceneLayout.hovermode; - layoutUpdate[sceneId + '.hovermode'] = false; + var hovermodeAStr = sceneId + '.hovermode'; + currentSpikes[hovermodeAStr] = sceneLayout.hovermode; + layoutUpdate[hovermodeAStr] = false; // copy all the current spike attrs for(var j = 0; j < 3; j++) { var axis = axes[j]; - axisSpikes = sceneSpikes[axis] = {}; - - for(var k = 0; k < spikeAttrs.length; k++) { - var spikeAttr = spikeAttrs[k]; - axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr]; - } + var spikeAStr = sceneId + '.' + axis + '.showspikes'; + layoutUpdate[spikeAStr] = false; + currentSpikes[spikeAStr] = sceneLayout[axis].showspikes; } } - button._previousVal = Lib.extendDeep({}, currentSpikes); + button._previousVal = currentSpikes; } + return layoutUpdate; +} +function handleHover3d(gd, ev) { + var layoutUpdate = getNextHover3d(gd, ev); Registry.call('relayout', gd, layoutUpdate); } @@ -501,17 +495,19 @@ modeBarButtons.hoverClosestPie = { click: toggleHover }; -function toggleHover(gd) { +function getNextHover(gd) { var fullLayout = gd._fullLayout; - var onHoverVal; + if(fullLayout.hovermode) return false; + if(fullLayout._has('cartesian')) { - onHoverVal = fullLayout._isHoriz ? 'y' : 'x'; + return fullLayout._isHoriz ? 'y' : 'x'; } - else onHoverVal = 'closest'; - - var newHover = gd._fullLayout.hovermode ? false : onHoverVal; + return 'closest'; +} +function toggleHover(gd) { + var newHover = getNextHover(gd); Registry.call('relayout', gd, 'hovermode', newHover); } @@ -526,12 +522,10 @@ modeBarButtons.toggleHover = { icon: Icons.tooltip_basic, gravity: 'ne', click: function(gd, ev) { - toggleHover(gd); + var layoutUpdate = getNextHover3d(gd, ev); + layoutUpdate.hovermode = getNextHover(gd); - // the 3d hovermode update must come - // last so that layout.hovermode update does not - // override scene?.hovermode?.layout. - handleHover3d(gd, ev); + Registry.call('relayout', gd, layoutUpdate); } }; From a11ec44f388741dd21046d08a782e4e76fc8ba22 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Fri, 2 Nov 2018 18:23:22 -0400 Subject: [PATCH 07/33] add _gui(Restyle|Relayout|Update) and _storeDirectGUIEdit and track changes --- src/components/annotations/draw.js | 6 +- src/components/colorbar/draw.js | 2 +- src/components/legend/draw.js | 4 +- src/components/legend/handle_click.js | 4 +- src/components/modebar/buttons.js | 18 ++-- src/components/rangeselector/draw.js | 2 +- src/components/rangeslider/draw.js | 5 +- src/components/shapes/draw.js | 2 +- src/components/titles/index.js | 4 +- src/core.js | 3 +- src/plot_api/index.js | 4 + src/plot_api/plot_api.js | 134 +++++++++++++++++++++----- src/plots/cartesian/dragbox.js | 6 +- src/plots/geo/geo.js | 2 +- src/plots/geo/zoom.js | 8 +- src/plots/gl2d/scene2d.js | 32 +++--- src/plots/gl3d/scene.js | 1 + src/plots/mapbox/mapbox.js | 2 + src/plots/plots.js | 18 ++++ src/plots/polar/polar.js | 10 +- src/plots/ternary/ternary.js | 28 +++--- src/traces/parcoords/plot.js | 36 ++++++- src/traces/table/plot.js | 3 + 23 files changed, 235 insertions(+), 99 deletions(-) diff --git a/src/components/annotations/draw.js b/src/components/annotations/draw.js index 7669ab2a2da..ed18530d558 100644 --- a/src/components/annotations/draw.js +++ b/src/components/annotations/draw.js @@ -584,7 +584,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { }); }, doneFn: function() { - Registry.call('relayout', gd, getUpdateObj()); + Registry.call('_guiRelayout', gd, getUpdateObj()); var notesBox = document.querySelector('.js-notes-box-panel'); if(notesBox) notesBox.redraw(notesBox.selectedObj); } @@ -667,7 +667,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { }, doneFn: function() { setCursor(annTextGroupInner); - Registry.call('relayout', gd, getUpdateObj()); + Registry.call('_guiRelayout', gd, getUpdateObj()); var notesBox = document.querySelector('.js-notes-box-panel'); if(notesBox) notesBox.redraw(notesBox.selectedObj); } @@ -691,7 +691,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { modifyBase(ya._name + '.autorange', true); } - Registry.call('relayout', gd, getUpdateObj()); + Registry.call('_guiRelayout', gd, getUpdateObj()); }); } else annText.call(textLayout); diff --git a/src/components/colorbar/draw.js b/src/components/colorbar/draw.js index 18d776a2873..71c5b9dd7ff 100644 --- a/src/components/colorbar/draw.js +++ b/src/components/colorbar/draw.js @@ -627,7 +627,7 @@ module.exports = function draw(gd, id) { setCursor(container); if(xf !== undefined && yf !== undefined) { - Registry.call('restyle', + Registry.call('_guiRestyle', gd, {'colorbar.x': xf, 'colorbar.y': yf}, getTrace().index diff --git a/src/components/legend/draw.js b/src/components/legend/draw.js index 30d3c66aa7e..9b444268489 100644 --- a/src/components/legend/draw.js +++ b/src/components/legend/draw.js @@ -339,7 +339,7 @@ module.exports = function draw(gd) { }, doneFn: function() { if(xf !== undefined && yf !== undefined) { - Registry.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); + Registry.call('_guiRelayout', gd, {'legend.x': xf, 'legend.y': yf}); } }, clickFn: function(numClicks, e) { @@ -446,7 +446,7 @@ function drawTexts(g, gd, maxLength) { update.name = newName; } - return Registry.call('restyle', gd, update, traceIndex); + return Registry.call('_guiRestyle', gd, update, traceIndex); }); } else { textLayout(textEl); diff --git a/src/components/legend/handle_click.js b/src/components/legend/handle_click.js index b12bf50e8e3..608c4a272da 100644 --- a/src/components/legend/handle_click.js +++ b/src/components/legend/handle_click.js @@ -111,7 +111,7 @@ module.exports = function handleClick(g, gd, numClicks) { } } - Registry.call('relayout', gd, 'hiddenlabels', hiddenSlices); + Registry.call('_guiRelayout', gd, 'hiddenlabels', hiddenSlices); } else { var hasLegendgroup = legendgroup && legendgroup.length; var traceIndicesInGroup = []; @@ -217,6 +217,6 @@ module.exports = function handleClick(g, gd, numClicks) { } } - Registry.call('restyle', gd, attrUpdate, attrIndices); + Registry.call('_guiRestyle', gd, attrUpdate, attrIndices); } }; diff --git a/src/components/modebar/buttons.js b/src/components/modebar/buttons.js index 6d1ce4a6369..eca5d398ead 100644 --- a/src/components/modebar/buttons.js +++ b/src/components/modebar/buttons.js @@ -261,7 +261,7 @@ function handleCartesian(gd, ev) { aobj[astr] = val; } - Registry.call('relayout', gd, aobj); + Registry.call('_guiRelayout', gd, aobj); } modeBarButtons.zoom3d = { @@ -317,7 +317,7 @@ function handleDrag3d(gd, ev) { var val2d = (val === 'pan') ? val : 'zoom'; layoutUpdate.dragmode = val2d; - Registry.call('relayout', gd, layoutUpdate); + Registry.call('_guiRelayout', gd, layoutUpdate); } modeBarButtons.resetCameraDefault3d = { @@ -356,7 +356,7 @@ function handleCamera3d(gd, ev) { } } - Registry.call('relayout', gd, aobj); + Registry.call('_guiRelayout', gd, aobj); } modeBarButtons.hoverClosest3d = { @@ -411,7 +411,7 @@ function getNextHover3d(gd, ev) { function handleHover3d(gd, ev) { var layoutUpdate = getNextHover3d(gd, ev); - Registry.call('relayout', gd, layoutUpdate); + Registry.call('_guiRelayout', gd, layoutUpdate); } modeBarButtons.zoomInGeo = { @@ -467,7 +467,7 @@ function handleGeo(gd, ev) { var scale = geoLayout.projection.scale; var newScale = (val === 'in') ? 2 * scale : 0.5 * scale; - Registry.call('relayout', gd, id + '.projection.scale', newScale); + Registry.call('_guiRelayout', gd, id + '.projection.scale', newScale); } else if(attr === 'reset') { resetView(gd, 'geo'); } @@ -508,7 +508,7 @@ function getNextHover(gd) { function toggleHover(gd) { var newHover = getNextHover(gd); - Registry.call('relayout', gd, 'hovermode', newHover); + Registry.call('_guiRelayout', gd, 'hovermode', newHover); } // buttons when more then one plot types are present @@ -525,7 +525,7 @@ modeBarButtons.toggleHover = { var layoutUpdate = getNextHover3d(gd, ev); layoutUpdate.hovermode = getNextHover(gd); - Registry.call('relayout', gd, layoutUpdate); + Registry.call('_guiRelayout', gd, layoutUpdate); } }; @@ -561,7 +561,7 @@ modeBarButtons.toggleSpikelines = { var aobj = setSpikelineVisibility(gd); - Registry.call('relayout', gd, aobj); + Registry.call('_guiRelayout', gd, aobj); } }; @@ -608,5 +608,5 @@ function resetView(gd, subplotType) { } } - Registry.call('relayout', gd, aObj); + Registry.call('_guiRelayout', gd, aObj); } diff --git a/src/components/rangeselector/draw.js b/src/components/rangeselector/draw.js index aa717d663b5..f3bbe3e5505 100644 --- a/src/components/rangeselector/draw.js +++ b/src/components/rangeselector/draw.js @@ -69,7 +69,7 @@ module.exports = function draw(gd) { button.on('click', function() { if(gd._dragged) return; - Registry.call('relayout', gd, update); + Registry.call('_guiRelayout', gd, update); }); button.on('mouseover', function() { diff --git a/src/components/rangeslider/draw.js b/src/components/rangeslider/draw.js index e1d0b9f609c..5d0bf72f23e 100644 --- a/src/components/rangeslider/draw.js +++ b/src/components/rangeslider/draw.js @@ -286,7 +286,10 @@ function setDataRange(rangeSlider, gd, axisOpts, opts) { dataMax = clamp(opts.p2d(opts._pixelMax)); window.requestAnimationFrame(function() { - Registry.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); + var update = {}; + update[axisOpts._name + '.range[0]'] = dataMin; + update[axisOpts._name + '.range[1]'] = dataMax; + Registry.call('_guiRelayout', gd, update); }); } diff --git a/src/components/shapes/draw.js b/src/components/shapes/draw.js index 793536597a1..ca24704caa3 100644 --- a/src/components/shapes/draw.js +++ b/src/components/shapes/draw.js @@ -306,7 +306,7 @@ function setupDragElement(gd, shapePath, shapeOptions, index, shapeLayer) { // Don't rely on clipPath being activated during re-layout setClipPath(shapePath, gd, shapeOptions); - Registry.call('relayout', gd, editHelpers.getUpdateObj()); + Registry.call('_guiRelayout', gd, editHelpers.getUpdateObj()); } function abortDrag() { diff --git a/src/components/titles/index.js b/src/components/titles/index.js index e2211dd88df..8fed7ba9684 100644 --- a/src/components/titles/index.js +++ b/src/components/titles/index.js @@ -237,9 +237,9 @@ function draw(gd, titleClass, options) { el.call(svgTextUtils.makeEditable, {gd: gd}) .on('edit', function(text) { if(traceIndex !== undefined) { - Registry.call('restyle', gd, prop, text, traceIndex); + Registry.call('_guiRestyle', gd, prop, text, traceIndex); } else { - Registry.call('relayout', gd, prop, text); + Registry.call('_guiRelayout', gd, prop, text); } }) .on('cancel', function() { diff --git a/src/core.js b/src/core.js index 1025c37d4a7..04a026f7d6c 100644 --- a/src/core.js +++ b/src/core.js @@ -29,7 +29,8 @@ var plotApi = require('./plot_api'); var methodNames = Object.keys(plotApi); for(var i = 0; i < methodNames.length; i++) { var name = methodNames[i]; - exports[name] = plotApi[name]; + // _ -> private API methods, but still registered for internal use + if(name.charAt(0) !== '_') exports[name] = plotApi[name]; register({ moduleType: 'apiMethod', name: name, diff --git a/src/plot_api/index.js b/src/plot_api/index.js index ac81c327b05..410b2da6f87 100644 --- a/src/plot_api/index.js +++ b/src/plot_api/index.js @@ -16,6 +16,10 @@ exports.restyle = main.restyle; exports.relayout = main.relayout; exports.redraw = main.redraw; exports.update = main.update; +exports._guiRestyle = main._guiRestyle; +exports._guiRelayout = main._guiRelayout; +exports._guiUpdate = main._guiUpdate; +exports._storeDirectGUIEdit = main._storeDirectGUIEdit; exports.react = main.react; exports.extendTraces = main.extendTraces; exports.prependTraces = main.prependTraces; diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index bf9ba602080..f9c907fa8e5 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1315,7 +1315,7 @@ exports.moveTraces = function moveTraces(gd, currentIndices, newIndices) { * If the array is too short, it will wrap around (useful for * style files that want to specify cyclical default values). */ -exports.restyle = function restyle(gd, astr, val, _traces) { +function restyle(gd, astr, val, _traces) { gd = Lib.getGraphDiv(gd); helpers.clearPromiseQueue(gd); @@ -1385,7 +1385,8 @@ exports.restyle = function restyle(gd, astr, val, _traces) { gd.emit('plotly_restyle', specs.eventData); return gd; }); -}; +} +exports.restyle = restyle; // for undo: undefined initial vals must be turned into nulls // so that we unset rather than ignore them @@ -1394,11 +1395,74 @@ function undefinedToNull(val) { return val; } +/** + * modified Lib.nestedProperty to also record GUI edits + */ +function npWithGuiEdits(container, attr, preGUI, guiEditFlag) { + var np = nestedProperty(container, attr); + + var npSet = np.set; + function setWithGuiEdits(val) { + // preGUI is not nested, it's flat with attribute strings + // flatten it the rest of the way, even if currentVal is nested + storeCurrent(attr, np.get(), val, preGUI); + npSet(val); + } + + if(guiEditFlag) { + np.set = setWithGuiEdits; + } + + return np; +} + +function storeCurrent(attr, val, newVal, preGUI) { + if(Array.isArray(val) || Array.isArray(newVal)) { + var arrayVal = Array.isArray(val) ? val : []; + var arrayNew = Array.isArray(newVal) ? newVal : []; + var maxLen = Math.max(arrayVal.length, arrayNew.length); + for(var i = 0; i < maxLen; i++) { + storeCurrent(attr + '[' + i + ']', arrayVal[i], arrayNew[i], preGUI); + } + } + else if(Lib.isPlainObject(val) || Lib.isPlainObject(newVal)) { + var objVal = Lib.isPlainObject(val) ? val : {}; + var objNew = Lib.isPlainObject(newVal) ? newVal : {}; + var objBoth = Lib.extendFlat({}, objVal, objNew); + for(var key in objBoth) { + storeCurrent(attr + '.' + key, objVal[key], objNew[key], preGUI); + } + } + else if(preGUI[attr] === undefined) { + preGUI[attr] = undefinedToNull(val); + } +} + +/* + * storeDirectGUIEdit: for routines that skip restyle/relayout and mock it + * by emitting a plotly_restyle or plotly_relayout event, this routine + * applies the changes to the input objects and keeps track of the initial state + * in _preGUI for use by uirevision + * + * @param {object} container: the input attributes container (eg `layout` or a `trace`) + * @param {object} fullContainer: the full partner to `container` + * @param {object} edits: the {attr: val} object as normally passed to `relayout` etc + * @param {boolean} apply: should we apply these changes to the input object? + */ +exports._storeDirectGUIEdit = function(container, preGUI, edits, apply) { + for(var attr in edits) { + var np = nestedProperty(container, attr); + storeCurrent(attr, np.get(), edits[attr], preGUI); + if(apply) np.set(edits[attr]); + } +}; + function _restyle(gd, aobj, traces) { - var fullLayout = gd._fullLayout, - fullData = gd._fullData, - data = gd.data, - i; + var fullLayout = gd._fullLayout; + var fullData = gd._fullData; + var data = gd.data; + var guiEditFlag = fullLayout._guiEditing; + var i; // initialize flags var flags = editTypes.traceFlags(); @@ -1447,9 +1511,11 @@ function _restyle(gd, aobj, traces) { var extraparam; if(attr.substr(0, 6) === 'LAYOUT') { - extraparam = Lib.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); + extraparam = npWithGuiEdits(gd.layout, attr.replace('LAYOUT', ''), fullLayout._preGUI, guiEditFlag); } else { - extraparam = Lib.nestedProperty(data[traces[i]], attr); + var tracei = traces[i]; + var preGUI = fullLayout._tracePreGUI[getFullTrace(tracei)._fullInput.uid]; + extraparam = npWithGuiEdits(data[tracei], attr, preGUI, guiEditFlag); } if(!(attr in undoit)) { @@ -1504,7 +1570,7 @@ function _restyle(gd, aobj, traces) { redoit[ai] = vi; if(ai.substr(0, 6) === 'LAYOUT') { - param = Lib.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); + param = npWithGuiEdits(gd.layout, ai.replace('LAYOUT', ''), fullLayout._preGUI, guiEditFlag); undoit[ai] = [undefinedToNull(param.get())]; // since we're allowing val to be an array, allow it here too, // even though that's meaningless @@ -1520,7 +1586,8 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { cont = data[traces[i]]; contFull = getFullTrace(traces[i]); - param = Lib.nestedProperty(cont, ai); + var preGUI = fullLayout._tracePreGUI[contFull._fullInput.uid]; + param = npWithGuiEdits(cont, ai, preGUI, guiEditFlag); oldVal = param.get(); newVal = Array.isArray(vi) ? vi[i % vi.length] : vi; @@ -1718,7 +1785,7 @@ function _restyle(gd, aobj, traces) { * attribute object `{astr1: val1, astr2: val2 ...}` * allows setting multiple attributes simultaneously */ -exports.relayout = function relayout(gd, astr, val) { +function relayout(gd, astr, val) { gd = Lib.getGraphDiv(gd); helpers.clearPromiseQueue(gd); @@ -1781,7 +1848,8 @@ exports.relayout = function relayout(gd, astr, val) { gd.emit('plotly_relayout', specs.eventData); return gd; }); -}; +} +exports.relayout = relayout; // Optimization mostly for large splom traces where // Plots.supplyDefaults can take > 100ms @@ -1826,14 +1894,14 @@ var AX_AUTORANGE_RE = /^[xyz]axis[0-9]*\.autorange$/; var AX_DOMAIN_RE = /^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/; function _relayout(gd, aobj) { - var layout = gd.layout, - fullLayout = gd._fullLayout, - keys = Object.keys(aobj), - axes = Axes.list(gd), - arrayEdits = {}, - arrayStr, - i, - j; + var layout = gd.layout; + var fullLayout = gd._fullLayout; + var guiEditFlag = fullLayout._guiEditing; + var keys = Object.keys(aobj); + var axes = Axes.list(gd); + var arrayEdits = {}; + + var arrayStr, i, j; // look for 'allaxes', split out into all axes // in case of 3D the axis are nested within a scene which is held in _id @@ -1873,7 +1941,7 @@ function _relayout(gd, aobj) { // via a parent) do not override with this auto-generated extra if(attr in aobj || helpers.hasParent(aobj, attr)) return; - var p = Lib.nestedProperty(layout, attr); + var p = npWithGuiEdits(layout, attr, fullLayout._preGUI, guiEditFlag); if(!(attr in undoit)) { undoit[attr] = undefinedToNull(p.get()); } @@ -1898,7 +1966,7 @@ function _relayout(gd, aobj) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } - var p = Lib.nestedProperty(layout, ai); + var p = npWithGuiEdits(layout, ai, fullLayout._preGUI, guiEditFlag); var vi = aobj[ai]; var plen = p.parts.length; // p.parts may end with an index integer if the property is an array @@ -2194,7 +2262,7 @@ function updateAutosize(gd) { * integer or array of integers for the traces to alter (all if omitted) * */ -exports.update = function update(gd, traceUpdate, layoutUpdate, _traces) { +function update(gd, traceUpdate, layoutUpdate, _traces) { gd = Lib.getGraphDiv(gd); helpers.clearPromiseQueue(gd); @@ -2274,7 +2342,25 @@ exports.update = function update(gd, traceUpdate, layoutUpdate, _traces) { return gd; }); -}; +} +exports.update = update; + +/* + * internal-use-only restyle/relayout/update variants that record the initial + * values in (fullLayout|fullTrace)._preGUI so changes can be persisted across + * Plotly.react data updates, dependent on uirevision attributes + */ +function guiEdit(func) { + return function wrappedEdit(gd) { + gd._fullLayout._guiEditing = true; + var p = func.apply(null, arguments); + gd._fullLayout._guiEditing = false; + return p; + }; +} +exports._guiRestyle = guiEdit(restyle); +exports._guiRelayout = guiEdit(relayout); +exports._guiUpdate = guiEdit(update); /** * Plotly.react: diff --git a/src/plots/cartesian/dragbox.js b/src/plots/cartesian/dragbox.js index 6f8d03c8cc2..817bd4d1ad7 100644 --- a/src/plots/cartesian/dragbox.js +++ b/src/plots/cartesian/dragbox.js @@ -271,7 +271,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { .on('edit', function(text) { var v = ax.d2r(text); if(v !== undefined) { - Registry.call('relayout', gd, attrStr, v); + Registry.call('_guiRelayout', gd, attrStr, v); } }); } @@ -712,7 +712,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { } gd.emit('plotly_doubleclick', null); - Registry.call('relayout', gd, attrs); + Registry.call('_guiRelayout', gd, attrs); } // dragTail - finish a drag event with a redraw @@ -726,7 +726,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { // accumulated MathJax promises - wait for them before we relayout. Lib.syncOrAsync([ Plots.previousPromises, - function() { Registry.call('relayout', gd, updates); } + function() { Registry.call('_guiRelayout', gd, updates); } ], gd); } diff --git a/src/plots/geo/geo.js b/src/plots/geo/geo.js index 83153e0dfe3..af681ea1f8e 100644 --- a/src/plots/geo/geo.js +++ b/src/plots/geo/geo.js @@ -367,7 +367,7 @@ proto.updateFx = function(fullLayout, geoLayout) { updateObj[_this.id + '.' + k] = viewInitial[k]; } - Registry.call('relayout', gd, updateObj); + Registry.call('_guiRelayout', gd, updateObj); gd.emit('plotly_doubleclick', null); } diff --git a/src/plots/geo/zoom.js b/src/plots/geo/zoom.js index f55e123f202..247ed1553c4 100644 --- a/src/plots/geo/zoom.js +++ b/src/plots/geo/zoom.js @@ -11,6 +11,7 @@ var d3 = require('d3'); var Lib = require('../../lib'); +var Registry = require('../../registry'); var radians = Math.PI / 180; var degrees = 180 / Math.PI; @@ -47,8 +48,10 @@ function initZoom(geo, projection) { function sync(geo, projection, cb) { var id = geo.id; var gd = geo.graphDiv; - var userOpts = gd.layout[id]; - var fullOpts = gd._fullLayout[id]; + var layout = gd.layout; + var userOpts = layout[id]; + var fullLayout = gd._fullLayout; + var fullOpts = fullLayout[id]; var eventData = {}; @@ -64,6 +67,7 @@ function sync(geo, projection, cb) { cb(set); set('projection.scale', projection.scale() / geo.fitScale); + Registry.call('_storeDirectGUIEdit', layout, fullLayout._preGUI, eventData); gd.emit('plotly_relayout', eventData); } diff --git a/src/plots/gl2d/scene2d.js b/src/plots/gl2d/scene2d.js index 56e12929508..d406125e4bf 100644 --- a/src/plots/gl2d/scene2d.js +++ b/src/plots/gl2d/scene2d.js @@ -313,27 +313,21 @@ proto.updateRefs = function(newFullLayout) { }; proto.relayoutCallback = function() { - var graphDiv = this.graphDiv, - xaxis = this.xaxis, - yaxis = this.yaxis, - layout = graphDiv.layout; - - // update user layout - layout.xaxis.autorange = xaxis.autorange; - layout.xaxis.range = xaxis.range.slice(0); - layout.yaxis.autorange = yaxis.autorange; - layout.yaxis.range = yaxis.range.slice(0); - - // make a meaningful value to be passed on to the possible 'plotly_relayout' subscriber(s) - // scene.camera has no many useful projection or scale information - // helps determine which one is the latest input (if async) - var update = { - lastInputTime: this.camera.lastInputTime - }; + var graphDiv = this.graphDiv; + var xaxis = this.xaxis; + var yaxis = this.yaxis; + + // make a meaningful value to be passed on to possible 'plotly_relayout' subscriber(s) + var update = {}; + update[xaxis._name + '.range'] = xaxis.range.slice(); + update[yaxis._name + '.range'] = yaxis.range.slice(); + update[xaxis._name + '.autorange'] = xaxis.autorange; + update[yaxis._name + '.autorange'] = yaxis.autorange; - update[xaxis._name] = xaxis.range.slice(0); - update[yaxis._name] = yaxis.range.slice(0); + Registry.call('_storeDirectGUIEdit', graphDiv.layout, graphDiv._fullLayout._preGUI, update, true); + // lastInputTime helps determine which one is the latest input (if async) + update.lastInputTime = this.camera.lastInputTime; graphDiv.emit('plotly_relayout', update); }; diff --git a/src/plots/gl3d/scene.js b/src/plots/gl3d/scene.js index 4911a4967ff..8b1e7eb8ed8 100644 --- a/src/plots/gl3d/scene.js +++ b/src/plots/gl3d/scene.js @@ -222,6 +222,7 @@ function initializeGLPlot(scene, fullLayout, canvas, gl) { var update = {}; update[scene.id + '.camera'] = getLayoutCamera(scene.camera); + Registry.call('_storeDirectGUIEdit', gd.layout, gd._fullLayout._preGUI, update); scene.saveCamera(gd.layout); scene.graphDiv.emit('plotly_relayout', update); }; diff --git a/src/plots/mapbox/mapbox.js b/src/plots/mapbox/mapbox.js index 77da3871017..f3b745cacdd 100644 --- a/src/plots/mapbox/mapbox.js +++ b/src/plots/mapbox/mapbox.js @@ -13,6 +13,7 @@ var mapboxgl = require('mapbox-gl'); var Fx = require('../../components/fx'); var Lib = require('../../lib'); +var Registry = require('../../registry'); var dragElement = require('../../components/dragelement'); var prepSelect = require('../cartesian/select').prepSelect; var selectOnClick = require('../cartesian/select').selectOnClick; @@ -210,6 +211,7 @@ proto.createMap = function(calcData, fullLayout, resolve, reject) { for(var k in view) { evtData[id + '.' + k] = view[k]; } + Registry.call('_storeDirectGUIEdit', gd.layout, gd._fullLayout._preGUI, evtData); gd.emit('plotly_relayout', evtData); } diff --git a/src/plots/plots.js b/src/plots/plots.js index a6d222da003..c053b8c9c6f 100644 --- a/src/plots/plots.js +++ b/src/plots/plots.js @@ -479,6 +479,24 @@ plots.supplyDefaults = function(gd, opts) { // relink functions and _ attributes to promote consistency between plots relinkPrivateKeys(newFullLayout, oldFullLayout); + // For persisting GUI-driven changes in layout + // _preGUI and _tracePreGUI were already copied over in relinkPrivateKeys + if(!newFullLayout._preGUI) newFullLayout._preGUI = {}; + // track trace GUI changes by uid rather than by trace index + if(!newFullLayout._tracePreGUI) newFullLayout._tracePreGUI = {}; + var tracePreGUI = newFullLayout._tracePreGUI; + var uids = {}; + var uid; + for(uid in tracePreGUI) uids[uid] = 'old'; + for(i = 0; i < newFullData.length; i++) { + uid = newFullData[i]._fullInput.uid; + if(!uids[uid]) tracePreGUI[uid] = {}; + uids[uid] = 'new'; + } + for(uid in uids) { + if(uids[uid] === 'old') delete tracePreGUI[uid]; + } + // TODO may return a promise plots.doAutoMargin(gd); diff --git a/src/plots/polar/polar.js b/src/plots/polar/polar.js index 97142b3a31d..02347fd474a 100644 --- a/src/plots/polar/polar.js +++ b/src/plots/polar/polar.js @@ -864,7 +864,7 @@ proto.updateMainDrag = function(fullLayout) { rl[0] + (r0 - innerRadius) * m, rl[0] + (r1 - innerRadius) * m ]; - Registry.call('relayout', gd, _this.id + '.radialaxis.range', newRng); + Registry.call('_guiRelayout', gd, _this.id + '.radialaxis.range', newRng); } function zoomClick(numClicks, evt) { @@ -880,7 +880,7 @@ proto.updateMainDrag = function(fullLayout) { } gd.emit('plotly_doubleclick', null); - Registry.call('relayout', gd, updateObj); + Registry.call('_guiRelayout', gd, updateObj); } if(clickMode.indexOf('select') > -1 && numClicks === 1) { @@ -1007,9 +1007,9 @@ proto.updateRadialDrag = function(fullLayout, polarLayout, rngIndex) { function doneFn() { if(angle1 !== null) { - Registry.call('relayout', gd, _this.id + '.radialaxis.angle', angle1); + Registry.call('_guiRelayout', gd, _this.id + '.radialaxis.angle', angle1); } else if(rprime !== null) { - Registry.call('relayout', gd, _this.id + '.radialaxis.range[' + rngIndex + ']', rprime); + Registry.call('_guiRelayout', gd, _this.id + '.radialaxis.range[' + rngIndex + ']', rprime); } } @@ -1221,7 +1221,7 @@ proto.updateAngularDrag = function(fullLayout) { updateObj[_this.id + '.radialaxis.angle'] = rrot1; } - Registry.call('relayout', gd, updateObj); + Registry.call('_guiRelayout', gd, updateObj); } dragOpts.prepFn = function(evt, startX, startY) { diff --git a/src/plots/ternary/ternary.js b/src/plots/ternary/ternary.js index a4ec4a7427c..f5563eb8f13 100644 --- a/src/plots/ternary/ternary.js +++ b/src/plots/ternary/ternary.js @@ -527,18 +527,22 @@ proto.initInteractions = function() { var x0, y0, mins0, span0, mins, lum, path0, dimmed, zb, corners; + function makeUpdate(_mins) { + var attrs = {}; + attrs[_this.id + '.aaxis.min'] = _mins.a; + attrs[_this.id + '.baxis.min'] = _mins.b; + attrs[_this.id + '.caxis.min'] = _mins.c; + return attrs; + } + function clickZoomPan(numClicks, evt) { var clickMode = gd._fullLayout.clickmode; removeZoombox(gd); if(numClicks === 2) { - var attrs = {}; - attrs[_this.id + '.aaxis.min'] = 0; - attrs[_this.id + '.baxis.min'] = 0; - attrs[_this.id + '.caxis.min'] = 0; gd.emit('plotly_doubleclick', null); - Registry.call('relayout', gd, attrs); + Registry.call('_guiRelayout', gd, makeUpdate({a: 0, b: 0, c: 0})); } if(clickMode.indexOf('select') > -1 && numClicks === 1) { @@ -642,12 +646,7 @@ proto.initInteractions = function() { if(mins === mins0) return; - var attrs = {}; - attrs[_this.id + '.aaxis.min'] = mins.a; - attrs[_this.id + '.baxis.min'] = mins.b; - attrs[_this.id + '.caxis.min'] = mins.c; - - Registry.call('relayout', gd, attrs); + Registry.call('_guiRelayout', gd, makeUpdate(mins)); if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { Lib.notifier(_(gd, 'Double-click to zoom back out'), 'long'); @@ -721,12 +720,7 @@ proto.initInteractions = function() { } function dragDone() { - var attrs = {}; - attrs[_this.id + '.aaxis.min'] = mins.a; - attrs[_this.id + '.baxis.min'] = mins.b; - attrs[_this.id + '.caxis.min'] = mins.c; - - Registry.call('relayout', gd, attrs); + Registry.call('_guiRelayout', gd, makeUpdate(mins)); } // finally, set up hover and click diff --git a/src/traces/parcoords/plot.js b/src/traces/parcoords/plot.js index aef8c9581c4..3d280905c9b 100644 --- a/src/traces/parcoords/plot.js +++ b/src/traces/parcoords/plot.js @@ -8,6 +8,8 @@ 'use strict'; +var Registry = require('../../registry'); + var parcoords = require('./parcoords'); var prepareRegl = require('../../lib/prepare_regl'); @@ -22,12 +24,17 @@ module.exports = function plot(gd, cdparcoords) { var gdDimensions = {}; var gdDimensionsOriginalOrder = {}; + var fullIndices = {}; + var inputIndices = {}; var size = fullLayout._size; cdparcoords.forEach(function(d, i) { - gdDimensions[i] = gd.data[i].dimensions; - gdDimensionsOriginalOrder[i] = gd.data[i].dimensions.slice(); + var trace = d[0].trace; + fullIndices[i] = trace.index; + var iIn = inputIndices[i] = trace._fullInput.index; + gdDimensions[i] = gd.data[iIn].dimensions; + gdDimensionsOriginalOrder[i] = gd.data[iIn].dimensions.slice(); }); var filterChanged = function(i, originalDimensionIndex, newRanges) { @@ -48,10 +55,19 @@ module.exports = function plot(gd, cdparcoords) { newConstraints = [newConstraints]; } - var restyleData = {}; var aStr = 'dimensions[' + originalDimensionIndex + '].constraintrange'; + + var editData = {}; + editData[aStr] = newConstraints && newConstraints[0]; + Registry.call('_storeDirectGUIEdit', + gd.data[inputIndices[i]], + fullLayout._tracePreGUI[gd._fullData[fullIndices[i]]._fullInput.uid], + editData + ); + + var restyleData = {}; restyleData[aStr] = newConstraints; - gd.emit('plotly_restyle', [restyleData, [i]]); + gd.emit('plotly_restyle', [restyleData, [inputIndices[i]]]); }; var hover = function(eventData) { @@ -103,7 +119,17 @@ module.exports = function plot(gd, cdparcoords) { gdDimensions[i].splice(gdDimensionsOriginalOrder[i].indexOf(d), 0, d); // insert at original index }); - gd.emit('plotly_restyle'); + // TODO: we can't really store this part of the interaction state + // directly as below, since it incudes data arrays. If we want to + // persist column order we may have to do something special for this + // case to just store the order itself. + // Registry.call('_storeDirectGUIEdit', + // gd.data[inputIndices[i]], + // fullLayout._tracePreGUI[gd._fullData[fullIndices[i]]._fullInput.uid], + // {dimensions: gdDimensions[i]} + // ); + + gd.emit('plotly_restyle', [{dimensions: [gdDimensions[i]]}, [inputIndices[i]]]); }; parcoords( diff --git a/src/traces/table/plot.js b/src/traces/table/plot.js index 0ac8f2a50db..5e177cb3631 100644 --- a/src/traces/table/plot.js +++ b/src/traces/table/plot.js @@ -588,6 +588,9 @@ function columnMoved(gd, calcdata, indices) { calcdata.columnorder = indices; + // TODO: there's no data here, but also this reordering is not reflected + // in gd.data or even gd._fullData. + // For now I will not attempt to persist this in _preGUI gd.emit('plotly_restyle'); } From 10ddbb9c67c4e9abf1b8a1f51cd0ada340f0f7db Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Tue, 6 Nov 2018 17:31:10 -0500 Subject: [PATCH 08/33] fix and :lock: problem with dragging colorbars in sub-containers --- src/components/colorbar/draw.js | 26 +++++++++-------- test/jasmine/tests/colorbar_test.js | 45 +++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 12 deletions(-) diff --git a/src/components/colorbar/draw.js b/src/components/colorbar/draw.js index 71c5b9dd7ff..be1088c2246 100644 --- a/src/components/colorbar/draw.js +++ b/src/components/colorbar/draw.js @@ -467,15 +467,10 @@ module.exports = function draw(gd, id) { } function drawTitle(titleClass, titleOpts) { - var trace = getTrace(); - var propName = 'colorbar.title'; - var containerName = trace._module.colorbar.container; - if(containerName) propName = containerName + '.' + propName; - var dfltTitleOpts = { propContainer: cbAxisOut, - propName: propName, - traceIndex: trace.index, + propName: getPropName('title'), + traceIndex: getTrace().index, placeholder: fullLayout._dfltTitle.colorbar, containerGroup: container.select('.cbtitle') }; @@ -627,11 +622,10 @@ module.exports = function draw(gd, id) { setCursor(container); if(xf !== undefined && yf !== undefined) { - Registry.call('_guiRestyle', - gd, - {'colorbar.x': xf, 'colorbar.y': yf}, - getTrace().index - ); + var update = {}; + update[getPropName('x')] = xf; + update[getPropName('y')] = yf; + Registry.call('_guiRestyle', gd, update, getTrace().index); } } }); @@ -649,6 +643,14 @@ module.exports = function draw(gd, id) { } } + function getPropName(suffix) { + var trace = getTrace(); + var propName = 'colorbar.'; + var containerName = trace._module.colorbar.container; + if(containerName) propName = containerName + '.' + propName; + return propName + suffix; + } + // setter/getters for every item defined in opts Object.keys(opts).forEach(function(name) { component[name] = function(v) { diff --git a/test/jasmine/tests/colorbar_test.js b/test/jasmine/tests/colorbar_test.js index 6456ea4eb1d..1a4b2239078 100644 --- a/test/jasmine/tests/colorbar_test.js +++ b/test/jasmine/tests/colorbar_test.js @@ -8,6 +8,7 @@ var destroyGraphDiv = require('../assets/destroy_graph_div'); var failTest = require('../assets/fail_test'); var supplyAllDefaults = require('../assets/supply_defaults'); var assertPlotSize = require('../assets/custom_assertions').assertPlotSize; +var drag = require('../assets/drag'); describe('Test colorbar:', function() { @@ -354,5 +355,49 @@ describe('Test colorbar:', function() { .catch(failTest) .then(done); }); + + function getCBNode() { + return document.querySelector('.colorbar'); + } + + it('can drag root-level colorbars in editable mode', function(done) { + Plotly.newPlot(gd, + [{z: [[1, 2], [3, 4]], type: 'heatmap'}], + {width: 400, height: 400}, + {editable: true} + ) + .then(function() { + expect(gd.data[0].colorbar).toBeUndefined(); + expect(gd._fullData[0].colorbar.x).toBe(1.02); + expect(gd._fullData[0].colorbar.y).toBe(0.5); + return drag(getCBNode(), -100, 100); + }) + .then(function() { + expect(gd.data[0].colorbar.x).toBeWithin(0.591, 0.01); + expect(gd.data[0].colorbar.y).toBeWithin(0.045, 0.01); + }) + .catch(failTest) + .then(done); + }); + + it('can drag marker-level colorbars in editable mode', function(done) { + Plotly.newPlot(gd, + [{y: [1, 2, 1], marker: {color: [0, 1, 2], showscale: true}}], + {width: 400, height: 400}, + {editable: true} + ) + .then(function() { + expect(gd.data[0].marker.colorbar).toBeUndefined(); + expect(gd._fullData[0].marker.colorbar.x).toBe(1.02); + expect(gd._fullData[0].marker.colorbar.y).toBe(0.5); + return drag(getCBNode(), -100, 100); + }) + .then(function() { + expect(gd.data[0].marker.colorbar.x).toBeWithin(0.591, 0.01); + expect(gd.data[0].marker.colorbar.y).toBeWithin(0.045, 0.01); + }) + .catch(failTest) + .then(done); + }); }); }); From 4af2bf8b6e8b190b3f253934cee51ec7a90f7acd Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Thu, 8 Nov 2018 16:38:34 -0500 Subject: [PATCH 09/33] add and coerce uirevision attributes --- src/components/legend/attributes.js | 9 +++++ src/components/legend/defaults.js | 6 +++- src/plots/attributes.js | 12 +++++++ src/plots/cartesian/layout_attributes.js | 10 ++++++ src/plots/cartesian/layout_defaults.js | 2 ++ src/plots/geo/layout/layout_attributes.js | 13 ++++++- src/plots/gl3d/layout/layout_attributes.js | 9 +++++ src/plots/layout_attributes.js | 42 ++++++++++++++++++++++ src/plots/mapbox/layout_attributes.js | 13 ++++++- src/plots/plots.js | 5 +++ src/plots/polar/layout_attributes.js | 32 +++++++++++++++++ src/plots/polar/layout_defaults.js | 2 ++ src/plots/subplot_defaults.js | 6 ++++ src/plots/ternary/layout_attributes.js | 25 ++++++++++++- src/plots/ternary/layout_defaults.js | 6 ++-- 15 files changed, 186 insertions(+), 6 deletions(-) diff --git a/src/components/legend/attributes.js b/src/components/legend/attributes.js index a42e324f010..7d0006d8c00 100644 --- a/src/components/legend/attributes.js +++ b/src/components/legend/attributes.js @@ -120,5 +120,14 @@ module.exports = { 'or *bottom* of the legend.' ].join(' ') }, + uirevision: { + valType: 'any', + role: 'info', + editType: 'none', + description: [ + 'Controls persistence of legend-driven changes in trace and pie label', + 'visibility. Defaults to `layout.uirevision`.' + ].join(' ') + }, editType: 'legend' }; diff --git a/src/components/legend/defaults.js b/src/components/legend/defaults.js index c82d175951f..cd9097f0422 100644 --- a/src/components/legend/defaults.js +++ b/src/components/legend/defaults.js @@ -66,7 +66,7 @@ module.exports = function legendDefaults(layoutIn, layoutOut, fullData) { basePlotLayoutAttributes, 'showlegend', legendReallyHasATrace && legendTraceCount > 1); - if(showLegend === false) return; + if(showLegend === false && !containerIn.uirevision) return; var containerOut = Template.newContainer(layoutOut, 'legend'); @@ -74,6 +74,10 @@ module.exports = function legendDefaults(layoutIn, layoutOut, fullData) { return Lib.coerce(containerIn, containerOut, attributes, attr, dflt); } + coerce('uirevision', layoutOut.uirevision); + + if(showLegend === false) return; + coerce('bgcolor', layoutOut.paper_bgcolor); coerce('bordercolor'); coerce('borderwidth'); diff --git a/src/plots/attributes.js b/src/plots/attributes.js index 653176fd260..113cc11a537 100644 --- a/src/plots/attributes.js +++ b/src/plots/attributes.js @@ -164,5 +164,17 @@ module.exports = { 'An array of operations that manipulate the trace data,', 'for example filtering or sorting the data arrays.' ].join(' ') + }, + uirevision: { + valType: 'any', + role: 'info', + editType: 'none', + description: [ + 'Controls persistence of user-driven changes to the trace:', + 'interactions like `selectedpoints` and type-specific ones such as', + '`constraintrange` in `parcoords` traces, as well as some', + '`editable: true` modifications such as `name` and `colorbar.title`.', + 'Defaults to `layout.uirevision`.' + ].join(' ') } }; diff --git a/src/plots/cartesian/layout_attributes.js b/src/plots/cartesian/layout_attributes.js index 404f023eb71..64722e535b6 100644 --- a/src/plots/cartesian/layout_attributes.js +++ b/src/plots/cartesian/layout_attributes.js @@ -766,6 +766,16 @@ module.exports = { 'Used with `categoryorder`.' ].join(' ') }, + uirevision: { + valType: 'any', + role: 'info', + editType: 'none', + description: [ + 'Controls persistence of user-driven changes in axis `range`,', + '`autorange`, and `title` if in `editable: true` configuration.', + 'Defaults to `layout.uirevision`.' + ].join(' ') + }, editType: 'calc', _deprecated: { diff --git a/src/plots/cartesian/layout_defaults.js b/src/plots/cartesian/layout_defaults.js index 63abbc2364b..c56c64c2145 100644 --- a/src/plots/cartesian/layout_defaults.js +++ b/src/plots/cartesian/layout_defaults.js @@ -176,6 +176,8 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { splomStash: ((layoutOut._splomAxes || {})[axLetter] || {})[id] }; + coerce('uirevision', layoutOut.uirevision); + handleTypeDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions); handleAxisDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); diff --git a/src/plots/geo/layout/layout_attributes.js b/src/plots/geo/layout/layout_attributes.js index f326c816550..848aa52038e 100644 --- a/src/plots/geo/layout/layout_attributes.js +++ b/src/plots/geo/layout/layout_attributes.js @@ -65,7 +65,7 @@ var geoAxesAttrs = { } }; -module.exports = overrideAll({ +var attrs = module.exports = overrideAll({ domain: domainAttrs({name: 'geo'}, { description: [ 'Note that geo subplots are constrained by domain.', @@ -311,3 +311,14 @@ module.exports = overrideAll({ lonaxis: geoAxesAttrs, lataxis: geoAxesAttrs }, 'plot', 'from-root'); + +// set uirevision outside of overrideAll so it can be `editType: 'none'` +attrs.uirevision = { + valType: 'any', + role: 'info', + editType: 'none', + description: [ + 'Controls persistence of user-driven changes in the view', + '(projection and center). Defaults to `layout.uirevision`.' + ].join(' ') +}; diff --git a/src/plots/gl3d/layout/layout_attributes.js b/src/plots/gl3d/layout/layout_attributes.js index 870eca0151c..22475483437 100644 --- a/src/plots/gl3d/layout/layout_attributes.js +++ b/src/plots/gl3d/layout/layout_attributes.js @@ -156,6 +156,15 @@ module.exports = { 'Determines the mode of hover interactions for this scene.' ].join(' ') }, + uirevision: { + valType: 'any', + role: 'info', + editType: 'none', + description: [ + 'Controls persistence of user-driven changes in camera attributes.', + 'Defaults to `layout.uirevision`.' + ].join(' ') + }, editType: 'plot', _deprecated: { diff --git a/src/plots/layout_attributes.js b/src/plots/layout_attributes.js index 103a0b234f7..78b829e47ae 100644 --- a/src/plots/layout_attributes.js +++ b/src/plots/layout_attributes.js @@ -202,6 +202,38 @@ module.exports = { 'different identity from its predecessor contains new data.' ].join(' ') }, + uirevision: { + valType: 'any', + role: 'info', + editType: 'none', + description: [ + 'Used to allow user interactions with the plot to persist after', + '`Plotly.react` calls that are unaware of these interactions.', + 'If `uirevision` is omitted, or if it is given and it changed from', + 'the previous `Plotly.react` call, the exact new figure is used.', + 'If `uirevision` is truthy and did NOT change, any attribute', + 'that has been affected by user interactions and did not receive a', + 'different value in the new figure will keep the interaction value.', + '`layout.uirevision` attribute serves as the default for', + '`uirevision` attributes in various sub-containers. For finer', + 'control you can set these sub-attributes directly. For example,', + 'if your app separately controls the data on the x and y axes you', + 'might set `xaxis.uirevision=*time*` and `yaxis.uirevision=*cost*`.', + 'Then if only the y data is changed, you can update', + '`yaxis.uirevision=*quantity*` and the y axis range will reset but', + 'the x axis range will retain any user-driven zoom.' + ].join(' ') + }, + editrevision: { + valType: 'any', + role: 'info', + editType: 'none', + description: [ + 'Controls persistence of user-driven changes in `editable: true`', + 'configuration, other than trace names and axis titles.', + 'Defaults to `layout.uirevision`.' + ].join(' ') + }, template: { valType: 'any', role: 'info', @@ -252,6 +284,16 @@ module.exports = { editType: 'modebar', description: 'Sets the color of the active or hovered on icons in the modebar.' }, + uirevision: { + valType: 'any', + role: 'info', + editType: 'none', + description: [ + 'Controls persistence of user-driven changes related to the modebar,', + 'including `hovermode`, `dragmode`, and `showspikes` at both the', + 'root level and inside subplots. Defaults to `layout.uirevision`.' + ].join(' ') + }, editType: 'modebar' } }; diff --git a/src/plots/mapbox/layout_attributes.js b/src/plots/mapbox/layout_attributes.js index 4d59225f208..e07767b913d 100644 --- a/src/plots/mapbox/layout_attributes.js +++ b/src/plots/mapbox/layout_attributes.js @@ -25,7 +25,7 @@ var fontAttr = fontAttrs({ }); fontAttr.family.dflt = 'Open Sans Regular, Arial Unicode MS Regular'; -module.exports = overrideAll({ +var attrs = module.exports = overrideAll({ _arrayAttrRegexps: [Lib.counterRegex('mapbox', '.layers', true)], domain: domainAttrs({name: 'mapbox'}), @@ -245,3 +245,14 @@ module.exports = overrideAll({ } }) }, 'plot', 'from-root'); + +// set uirevision outside of overrideAll so it can be `editType: 'none'` +attrs.uirevision = { + valType: 'any', + role: 'info', + editType: 'none', + description: [ + 'Controls persistence of user-driven changes in the view:', + '`center`, `zoom`, `bearing`, `pitch`. Defaults to `layout.uirevision`.' + ].join(' ') +}; diff --git a/src/plots/plots.js b/src/plots/plots.js index c053b8c9c6f..92ca7dd53e5 100644 --- a/src/plots/plots.js +++ b/src/plots/plots.js @@ -1140,6 +1140,8 @@ plots.supplyTraceDefaults = function(traceIn, traceOut, colorIndex, layout, trac coerce('type'); coerce('name', layout._traceWord + ' ' + traceInIndex); + coerce('uirevision', layout.uirevision); + // we want even invisible traces to make their would-be subplots visible // so coerce the subplot id(s) now no matter what var _module = plots.getModule(traceOut); @@ -1382,12 +1384,15 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { coerce('colorway'); coerce('datarevision'); + var uirevision = coerce('uirevision'); + coerce('editrevision', uirevision); coerce('modebar.orientation'); coerce('modebar.bgcolor', Color.addOpacity(layoutOut.paper_bgcolor, 0.5)); var modebarDefaultColor = Color.contrast(Color.rgb(layoutOut.modebar.bgcolor)); coerce('modebar.color', Color.addOpacity(modebarDefaultColor, 0.3)); coerce('modebar.activecolor', Color.addOpacity(modebarDefaultColor, 0.7)); + coerce('modebar.uirevision', uirevision); Registry.getComponentMethod( 'calendars', diff --git a/src/plots/polar/layout_attributes.js b/src/plots/polar/layout_attributes.js index 8334b0c3d96..94cffb496ca 100644 --- a/src/plots/polar/layout_attributes.js +++ b/src/plots/polar/layout_attributes.js @@ -118,6 +118,17 @@ var radialAxisAttrs = { hoverformat: axesAttrs.hoverformat, + uirevision: { + valType: 'any', + role: 'info', + editType: 'none', + description: [ + 'Controls persistence of user-driven changes in axis `range`,', + '`autorange`, `angle`, and `title` if in `editable: true` configuration.', + 'Defaults to `polar.uirevision`.' + ].join(' ') + }, + editType: 'calc' }; @@ -215,6 +226,16 @@ var angularAxisAttrs = { hoverformat: axesAttrs.hoverformat, + uirevision: { + valType: 'any', + role: 'info', + editType: 'none', + description: [ + 'Controls persistence of user-driven changes in axis `rotation`.', + 'Defaults to `polar.uirevision`.' + ].join(' ') + }, + editType: 'calc' }; @@ -294,5 +315,16 @@ module.exports = { // TODO maybe? // annotations: + uirevision: { + valType: 'any', + role: 'info', + editType: 'none', + description: [ + 'Controls persistence of user-driven changes in axis attributes,', + 'if not overridden in the individual axes.', + 'Defaults to `layout.uirevision`.' + ].join(' ') + }, + editType: 'calc' }; diff --git a/src/plots/polar/layout_defaults.js b/src/plots/polar/layout_defaults.js index 32bf5afff4b..b5cef9b77ce 100644 --- a/src/plots/polar/layout_defaults.js +++ b/src/plots/polar/layout_defaults.js @@ -66,6 +66,8 @@ function handleDefaults(contIn, contOut, coerce, opts) { var visible = coerceAxis('visible'); setConvert(axOut, contOut, layoutOut); + coerceAxis('uirevision', contOut.uirevision); + var dfltColor; var dfltFontColor; diff --git a/src/plots/subplot_defaults.js b/src/plots/subplot_defaults.js index 9e83049b773..98f55abeeef 100644 --- a/src/plots/subplot_defaults.js +++ b/src/plots/subplot_defaults.js @@ -67,6 +67,12 @@ module.exports = function handleSubplotDefaults(layoutIn, layoutOut, fullData, o subplotLayoutOut = Template.newContainer(layoutOut, id, baseId); + // All subplot containers get a `uirevision` inheriting from the base. + // Currently all subplots containers have some user interaction + // attributes, but if we ever add one that doesn't, we would need an + // option to skip this step. + coerce('uirevision', layoutOut.uirevision); + var dfltDomains = {}; dfltDomains[partition] = [i / idsLength, (i + 1) / idsLength]; handleDomainDefaults(subplotLayoutOut, layoutOut, coerce, dfltDomains); diff --git a/src/plots/ternary/layout_attributes.js b/src/plots/ternary/layout_attributes.js index 72397f0f876..cd310143ba2 100644 --- a/src/plots/ternary/layout_attributes.js +++ b/src/plots/ternary/layout_attributes.js @@ -66,7 +66,7 @@ var ternaryAxesAttrs = { } }; -module.exports = overrideAll({ +var attrs = module.exports = overrideAll({ domain: domainAttrs({name: 'ternary'}), bgcolor: { @@ -89,3 +89,26 @@ module.exports = overrideAll({ baxis: ternaryAxesAttrs, caxis: ternaryAxesAttrs }, 'plot', 'from-root'); + +// set uirevisions outside of `overrideAll` so we can get `editType: none` +attrs.uirevision = { + valType: 'any', + role: 'info', + editType: 'none', + description: [ + 'Controls persistence of user-driven changes in axis `min` and `title`,', + 'if not overridden in the individual axes.', + 'Defaults to `layout.uirevision`.' + ].join(' ') +}; + +attrs.aaxis.uirevision = attrs.baxis.uirevision = attrs.caxis.uirevision = { + valType: 'any', + role: 'info', + editType: 'none', + description: [ + 'Controls persistence of user-driven changes in axis `min`,', + 'and `title` if in `editable: true` configuration.', + 'Defaults to `ternary.uirevision`.' + ].join(' ') +}; diff --git a/src/plots/ternary/layout_defaults.js b/src/plots/ternary/layout_defaults.js index 7952a4559a5..451255856f2 100644 --- a/src/plots/ternary/layout_defaults.js +++ b/src/plots/ternary/layout_defaults.js @@ -46,7 +46,7 @@ function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, option containerOut = Template.newContainer(ternaryLayoutOut, axName); containerOut._name = axName; - handleAxisDefaults(containerIn, containerOut, options); + handleAxisDefaults(containerIn, containerOut, options, ternaryLayoutOut); } // if the min values contradict each other, set them all to default (0) @@ -65,13 +65,15 @@ function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, option } } -function handleAxisDefaults(containerIn, containerOut, options) { +function handleAxisDefaults(containerIn, containerOut, options, ternaryLayoutOut) { var axAttrs = layoutAttributes[containerOut._name]; function coerce(attr, dflt) { return Lib.coerce(containerIn, containerOut, axAttrs, attr, dflt); } + coerce('uirevision', ternaryLayoutOut.uirevision); + containerOut.type = 'linear'; // no other types allowed for ternary var dfltColor = coerce('color'); From 03baca7efe26c130fbcc559e9724930b79bbbc77 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Thu, 8 Nov 2018 21:31:32 -0500 Subject: [PATCH 10/33] use uirevisions in Plotly.react to preserve ui state --- src/plot_api/plot_api.js | 189 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 189 insertions(+) diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index f9c907fa8e5..2457dee04be 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -2362,6 +2362,193 @@ exports._guiRestyle = guiEdit(restyle); exports._guiRelayout = guiEdit(relayout); exports._guiUpdate = guiEdit(update); +// For connecting edited layout attributes to uirevision attrs +// If no `attr` we use `match[1] + '.uirevision'` +// Ordered by most common edits first, to minimize our search time +var layoutUIControlPatterns = [ + {pattern: /^hiddenlabels/, attr: 'legend.uirevision'}, + {pattern: /^((x|y)axis\d*)\.((auto)?range|title)/, autofill: true}, + + // showspikes and modes include those nested inside scenes + {pattern: /axis\d*\.showspikes$/, attr: 'modebar.uirevision'}, + {pattern: /(hover|drag)mode$/, attr: 'modebar.uirevision'}, + + {pattern: /^(scene\d*)\.camera/}, + {pattern: /^(geo\d*)\.(projection|center)/}, + {pattern: /^(ternary\d*\.[abc]axis)\.(min|title)$/}, + {pattern: /^(polar\d*\.(radial|angular)axis)\./}, + {pattern: /^(mapbox\d*)\.(center|zoom|bearing|pitch)/}, + + {pattern: /^legend\.(x|y)$/, attr: 'editrevision'}, + {pattern: /^(shapes|annotations)/, attr: 'editrevision'}, + {pattern: /^title$/, attr: 'editrevision'} +]; + +// same for trace attributes: if `attr` is given it's in layout, +// or with no `attr` we use `trace.uirevision` +var traceUIControlPatterns = [ + // "visible" includes trace.transforms[i].styles[j].value.visible + {pattern: /(^|value\.)visible$/, attr: 'legend.uirevision'}, + {pattern: /^dimensions\[\d+\]\.constraintrange/}, + + // below this you must be in editable: true mode + // TODO: I still put name and title with `trace.uirevision` + // reasonable or should these be `editrevision`? + // Also applies to axis titles up in the layout section + + // "name" also includes transform.styles + {pattern: /(^|value\.)name$/}, + // including nested colorbar attributes (ie marker.colorbar) + {pattern: /colorbar\.title$/}, + {pattern: /colorbar\.(x|y)$/, attr: 'editrevision'} +]; + +function findUIPattern(key, patternSpecs) { + for(var i = 0; i < patternSpecs.length; i++) { + var spec = patternSpecs[i]; + var match = key.match(spec.pattern); + if(match) { + return {head: match[1], attr: spec.attr, autofill: spec.autofill}; + } + } +} + +// We're finding the new uirevision before supplyDefaults, so do the +// inheritance manually. Note that only `undefined` inherits - other +// falsy values are returned. +function getNewRev(revAttr, container) { + var newRev = nestedProperty(container, revAttr).get(); + if(newRev !== undefined) return newRev; + + var parts = revAttr.split('.'); + parts.pop(); + while(parts.length > 1) { + parts.pop(); + newRev = nestedProperty(container, parts.join('.') + '.uirevision').get(); + if(newRev !== undefined) return newRev; + } + + return container.uirevision; +} + +function getFullTraceIndexFromUid(uid, fullData) { + for(var i = 0; i < fullData.length; i++) { + if(fullData[i]._fullInput.uid === uid) return i; + } + return -1; +} + +function getTraceIndexFromUid(uid, data, tracei) { + for(var i = 0; i < data.length; i++) { + if(data[i].uid === uid) return i; + } + // fall back on trace order, but only if user didn't provide a uid for that trace + return data[tracei].uid ? -1 : tracei; +} + +function applyUIRevisions(data, layout, oldFullData, oldFullLayout) { + var layoutPreGUI = oldFullLayout._preGUI; + var key, revAttr, oldRev, newRev, match, preGUIVal, newNP, newVal; + for(key in layoutPreGUI) { + match = findUIPattern(key, layoutUIControlPatterns); + if(match) { + revAttr = match.attr || (match.head + '.uirevision'); + oldRev = nestedProperty(oldFullLayout, revAttr).get(); + newRev = oldRev && getNewRev(revAttr, layout); + if(newRev && (newRev === oldRev)) { + preGUIVal = layoutPreGUI[key]; + if(preGUIVal === null) preGUIVal = undefined; + newNP = nestedProperty(layout, key); + newVal = newNP.get(); + // TODO: This test for undefined is to account for the case where + // the value was filled in automatically in gd.layout, + // like axis.range/autorange. In principle though, if the initial + // plot had a value and the new plot removed that value, we would + // want the removal to override the GUI edit and generate a new + // auto value. But that would require figuring out what value was + // in gd.layout *before* the auto values were filled in, and + // storing *that* in preGUI... oh well, for now at least I limit + // this to attributes that get autofilled, which AFAICT among + // the GUI-editable attributes is just axis.range/autorange. + if(newVal === preGUIVal || (match.autofill && newVal === undefined)) { + newNP.set(nestedProperty(oldFullLayout, key).get()); + continue; + } + } + } + else { + Lib.warn('unrecognized GUI edit: ' + key); + } + // if we got this far, the new value was accepted as the new starting + // point (either because it changed or revision changed) + // so remove it from _preGUI for next time. + delete layoutPreGUI[key]; + } + + // Now traces - try to match them up by uid (in case we added/deleted in + // the middle), then fall back on index. + // var tracei = -1; + // for(var fulli = 0; fulli < oldFullData.length; fulli++) { + var allTracePreGUI = oldFullLayout._tracePreGUI; + for(var uid in allTracePreGUI) { + var tracePreGUI = allTracePreGUI[uid]; + var newTrace = null; + var fullInput; + for(key in tracePreGUI) { + // wait until we know we have preGUI values to look for traces + // but if we don't find both, stop looking at this uid + if(!newTrace) { + var fulli = getFullTraceIndexFromUid(uid, oldFullData); + if(fulli < 0) { + // Somehow we didn't even have this trace in oldFullData... + // I guess this could happen with `deleteTraces` or something + delete allTracePreGUI[uid]; + break; + } + var fullTrace = oldFullData[fulli]; + fullInput = fullTrace._fullInput; + + var newTracei = getTraceIndexFromUid(uid, data, fullInput.index); + if(newTracei < 0) { + // No match in new data + delete allTracePreGUI[uid]; + break; + } + newTrace = data[newTracei]; + } + + match = findUIPattern(key, traceUIControlPatterns); + if(match) { + if(match.attr) { + oldRev = nestedProperty(oldFullLayout, match.attr).get(); + newRev = oldRev && getNewRev(match.attr, layout); + } + else { + oldRev = fullInput.uirevision; + // inheritance for trace.uirevision is simple, just layout.uirevision + newRev = newTrace.uirevision; + if(newRev === undefined) newRev = layout.uirevision; + } + + if(newRev && newRev === oldRev) { + preGUIVal = tracePreGUI[key]; + if(preGUIVal === null) preGUIVal = undefined; + newNP = nestedProperty(newTrace, key); + newVal = newNP.get(); + if(newVal === preGUIVal || (match.autofill && newVal === undefined)) { + newNP.set(nestedProperty(fullInput, key).get()); + continue; + } + } + } + else { + Lib.warn('unrecognized GUI edit: ' + key + ' in trace uid ' + uid); + } + delete tracePreGUI[key]; + } + } +} + /** * Plotly.react: * A plot/update method that takes the full plot state (same API as plot/newPlot) @@ -2424,6 +2611,8 @@ exports.react = function(gd, data, layout, config) { gd.layout = layout || {}; helpers.cleanLayout(gd.layout); + applyUIRevisions(gd.data, gd.layout, oldFullData, oldFullLayout); + // "true" skips updating calcdata and remapping arrays from calcTransforms, // which supplyDefaults usually does at the end, but we may need to NOT do // if the diff (which we haven't determined yet) says we'll recalc From 6a9d0d78e9d7da0882ec8d9fa8214f4fc805cf69 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Fri, 9 Nov 2018 15:27:51 -0500 Subject: [PATCH 11/33] add selectedpoints to uirevision framework --- src/plot_api/plot_api.js | 1 + src/plots/cartesian/select.js | 9 +++++++++ src/plots/layout_attributes.js | 9 +++++++++ src/plots/plots.js | 1 + 4 files changed, 20 insertions(+) diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 2457dee04be..b26724e7069 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -2387,6 +2387,7 @@ var layoutUIControlPatterns = [ // same for trace attributes: if `attr` is given it's in layout, // or with no `attr` we use `trace.uirevision` var traceUIControlPatterns = [ + {pattern: /^selectedpoints$/, attr: 'selectionrevision'}, // "visible" includes trace.transforms[i].styles[j].value.visible {pattern: /(^|value\.)visible$/, attr: 'legend.uirevision'}, {pattern: /^dimensions\[\d+\]\.constraintrange/}, diff --git a/src/plots/cartesian/select.js b/src/plots/cartesian/select.js index 35d39d285a6..ce6e40c4028 100644 --- a/src/plots/cartesian/select.js +++ b/src/plots/cartesian/select.js @@ -666,6 +666,15 @@ function isOnlyOnePointSelected(searchTraces) { function updateSelectedState(gd, searchTraces, eventData) { var i, searchInfo, cd, trace; + // before anything else, update preGUI if necessary + for(i = 0; i < searchTraces.length; i++) { + var fullInputTrace = searchTraces[i].cd[0].trace._fullInput; + var tracePreGUI = gd._fullLayout._tracePreGUI[fullInputTrace.uid]; + if(tracePreGUI.selectedpoints === undefined) { + tracePreGUI.selectedpoints = fullInputTrace._input.selectedpoints || null; + } + } + if(eventData) { var pts = eventData.points || []; diff --git a/src/plots/layout_attributes.js b/src/plots/layout_attributes.js index 78b829e47ae..b91470a534a 100644 --- a/src/plots/layout_attributes.js +++ b/src/plots/layout_attributes.js @@ -234,6 +234,15 @@ module.exports = { 'Defaults to `layout.uirevision`.' ].join(' ') }, + selectionrevision: { + valType: 'any', + role: 'info', + editType: 'none', + description: [ + 'Controls persistence of user-driven changes in selected points', + 'from all traces.' + ].join(' ') + }, template: { valType: 'any', role: 'info', diff --git a/src/plots/plots.js b/src/plots/plots.js index 92ca7dd53e5..6e51b41d85a 100644 --- a/src/plots/plots.js +++ b/src/plots/plots.js @@ -1386,6 +1386,7 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { coerce('datarevision'); var uirevision = coerce('uirevision'); coerce('editrevision', uirevision); + coerce('selectionrevision', uirevision); coerce('modebar.orientation'); coerce('modebar.bgcolor', Color.addOpacity(layoutOut.paper_bgcolor, 0.5)); From a4437472023bbe49f22e0b33f7d50561227ba766 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Fri, 9 Nov 2018 12:16:30 -0500 Subject: [PATCH 12/33] break Plotly.react tests out of plot_api_test into plot_api_react_test --- test/jasmine/tests/plot_api_react_test.js | 888 ++++++++++++++++++++++ test/jasmine/tests/plot_api_test.js | 877 --------------------- 2 files changed, 888 insertions(+), 877 deletions(-) create mode 100644 test/jasmine/tests/plot_api_react_test.js diff --git a/test/jasmine/tests/plot_api_react_test.js b/test/jasmine/tests/plot_api_react_test.js new file mode 100644 index 00000000000..9a3694ceab2 --- /dev/null +++ b/test/jasmine/tests/plot_api_react_test.js @@ -0,0 +1,888 @@ +var Plotly = require('@lib/index'); +var plotApi = require('@src/plot_api/plot_api'); +var Lib = require('@src/lib'); +var Axes = require('@src/plots/cartesian/axes'); +var subroutines = require('@src/plot_api/subroutines'); +var annotations = require('@src/components/annotations'); +var images = require('@src/components/images'); +var Registry = require('@src/registry'); + +var d3 = require('d3'); +var createGraphDiv = require('../assets/create_graph_div'); +var destroyGraphDiv = require('../assets/destroy_graph_div'); +var failTest = require('../assets/fail_test'); +var supplyAllDefaults = require('../assets/supply_defaults'); +var mockLists = require('../assets/mock_lists'); + +describe('@noCIdep Plotly.react', function() { + var mockedMethods = [ + 'doTraceStyle', + 'doColorBars', + 'doLegend', + 'layoutStyles', + 'doTicksRelayout', + 'doModeBar', + 'doCamera' + ]; + + var gd; + var afterPlotCnt; + + beforeEach(function() { + gd = createGraphDiv(); + + spyOn(plotApi, 'plot').and.callThrough(); + spyOn(Registry, 'call').and.callThrough(); + + mockedMethods.forEach(function(m) { + spyOn(subroutines, m).and.callThrough(); + subroutines[m].calls.reset(); + }); + + spyOn(annotations, 'drawOne').and.callThrough(); + spyOn(annotations, 'draw').and.callThrough(); + spyOn(images, 'draw').and.callThrough(); + spyOn(Axes, 'doTicks').and.callThrough(); + }); + + afterEach(destroyGraphDiv); + + function countPlots() { + plotApi.plot.calls.reset(); + subroutines.layoutStyles.calls.reset(); + annotations.draw.calls.reset(); + annotations.drawOne.calls.reset(); + images.draw.calls.reset(); + + afterPlotCnt = 0; + gd.on('plotly_afterplot', function() { afterPlotCnt++; }); + } + + function countCalls(counts) { + var callsFinal = Lib.extendFlat({}, counts); + callsFinal.layoutStyles = (counts.layoutStyles || 0) + (counts.plot || 0); + + mockedMethods.forEach(function(m) { + expect(subroutines[m]).toHaveBeenCalledTimes(callsFinal[m] || 0); + subroutines[m].calls.reset(); + }); + + // calls to Plotly.plot via plot_api.js or Registry.call('plot') + var plotCalls = plotApi.plot.calls.count() + + Registry.call.calls.all() + .filter(function(d) { return d.args[0] === 'plot'; }) + .length; + expect(plotCalls).toBe(counts.plot || 0, 'Plotly.plot calls'); + plotApi.plot.calls.reset(); + Registry.call.calls.reset(); + + // only consider annotation and image draw calls if we *don't* do a full plot. + if(!counts.plot) { + expect(annotations.draw).toHaveBeenCalledTimes(counts.annotationDraw || 0); + expect(annotations.drawOne).toHaveBeenCalledTimes(counts.annotationDrawOne || 0); + expect(images.draw).toHaveBeenCalledTimes(counts.imageDraw || 0); + } + annotations.draw.calls.reset(); + annotations.drawOne.calls.reset(); + images.draw.calls.reset(); + + expect(afterPlotCnt).toBe(1, 'plotly_afterplot should be called only once per edit'); + afterPlotCnt = 0; + } + + it('can add / remove traces', function(done) { + var data1 = [{y: [1, 2, 3], mode: 'markers'}]; + var data2 = [data1[0], {y: [2, 3, 1], mode: 'markers'}]; + var layout = {}; + Plotly.newPlot(gd, data1, layout) + .then(countPlots) + .then(function() { + expect(d3.selectAll('.point').size()).toBe(3); + + return Plotly.react(gd, data2, layout); + }) + .then(function() { + expect(d3.selectAll('.point').size()).toBe(6); + + return Plotly.react(gd, data1, layout); + }) + .then(function() { + expect(d3.selectAll('.point').size()).toBe(3); + }) + .catch(failTest) + .then(done); + }); + + it('should notice new data by ===, without layout.datarevision', function(done) { + var data = [{y: [1, 2, 3], mode: 'markers'}]; + var layout = {}; + + Plotly.newPlot(gd, data, layout) + .then(countPlots) + .then(function() { + expect(d3.selectAll('.point').size()).toBe(3); + + data[0].y.push(4); + return Plotly.react(gd, data, layout); + }) + .then(function() { + // didn't pick it up, as we modified in place!!! + expect(d3.selectAll('.point').size()).toBe(3); + countCalls({plot: 0}); + + data[0].y = [1, 2, 3, 4, 5]; + return Plotly.react(gd, data, layout); + }) + .then(function() { + // new object, we picked it up! + expect(d3.selectAll('.point').size()).toBe(5); + countCalls({plot: 1}); + }) + .catch(failTest) + .then(done); + }); + + it('should notice new layout.datarevision', function(done) { + var data = [{y: [1, 2, 3], mode: 'markers'}]; + var layout = {datarevision: 1}; + + Plotly.newPlot(gd, data, layout) + .then(countPlots) + .then(function() { + expect(d3.selectAll('.point').size()).toBe(3); + + data[0].y.push(4); + return Plotly.react(gd, data, layout); + }) + .then(function() { + // didn't pick it up, as we didn't modify datarevision + expect(d3.selectAll('.point').size()).toBe(3); + countCalls({plot: 0}); + + data[0].y.push(5); + layout.datarevision = 'bananas'; + return Plotly.react(gd, data, layout); + }) + .then(function() { + // new revision, we picked it up! + expect(d3.selectAll('.point').size()).toBe(5); + + countCalls({plot: 1}); + }) + .catch(failTest) + .then(done); + }); + + it('picks up partial redraws', function(done) { + var data = [{y: [1, 2, 3], mode: 'markers'}]; + var layout = {}; + + Plotly.newPlot(gd, data, layout) + .then(countPlots) + .then(function() { + layout.title = 'XXXXX'; + layout.hovermode = 'closest'; + data[0].marker = {color: 'rgb(0, 100, 200)'}; + return Plotly.react(gd, data, layout); + }) + .then(function() { + countCalls({layoutStyles: 1, doTraceStyle: 1, doModeBar: 1}); + expect(d3.select('.gtitle').text()).toBe('XXXXX'); + var points = d3.selectAll('.point'); + expect(points.size()).toBe(3); + points.each(function() { + expect(window.getComputedStyle(this).fill).toBe('rgb(0, 100, 200)'); + }); + + layout.showlegend = true; + layout.xaxis.tick0 = 0.1; + layout.xaxis.dtick = 0.3; + return Plotly.react(gd, data, layout); + }) + .then(function() { + // legend and ticks get called initially, but then plot gets added during automargin + countCalls({doLegend: 1, doTicksRelayout: 1, plot: 1}); + + data = [{z: [[1, 2], [3, 4]], type: 'surface'}]; + layout = {}; + + return Plotly.react(gd, data, layout); + }) + .then(function() { + // we get an extra call to layoutStyles from marginPushersAgain due to the colorbar. + // Really need to simplify that pipeline... + countCalls({plot: 1, layoutStyles: 1}); + + layout.scene.camera = {up: {x: 1, y: -1, z: 0}}; + + return Plotly.react(gd, data, layout); + }) + .then(function() { + countCalls({doCamera: 1}); + + data[0].type = 'heatmap'; + delete layout.scene; + return Plotly.react(gd, data, layout); + }) + .then(function() { + countCalls({plot: 1}); + + // ideally we'd just do this with `surface` but colorbar attrs have editType 'calc' there + // TODO: can we drop them to type: 'colorbars' even for the 3D types? + data[0].colorbar = {len: 0.6}; + return Plotly.react(gd, data, layout); + }) + .then(function() { + countCalls({doColorBars: 1, plot: 1}); + }) + .catch(failTest) + .then(done); + }); + + it('picks up special dtick geo case', function(done) { + var data = [{type: 'scattergeo'}]; + var layout = {}; + + function countLines() { + var path = d3.select(gd).select('.lataxis > path'); + return path.attr('d').split('M').length; + } + + Plotly.react(gd, data) + .then(countPlots) + .then(function() { + layout.geo = {lataxis: {showgrid: true, dtick: 10}}; + return Plotly.react(gd, data, layout); + }) + .then(function() { + countCalls({plot: 1}); + expect(countLines()).toBe(18); + }) + .then(function() { + layout.geo.lataxis.dtick = 30; + return Plotly.react(gd, data, layout); + }) + .then(function() { + countCalls({plot: 1}); + expect(countLines()).toBe(6); + }) + .catch(failTest) + .then(done); + }); + + it('picks up minimal sequence for cartesian axis range updates', function(done) { + var data = [{y: [1, 2, 1]}]; + var layout = {xaxis: {range: [1, 2]}}; + var layout2 = {xaxis: {range: [0, 1]}}; + + Plotly.newPlot(gd, data, layout) + .then(countPlots) + .then(function() { + expect(Axes.doTicks).toHaveBeenCalledWith(gd, ''); + return Plotly.react(gd, data, layout2); + }) + .then(function() { + expect(Axes.doTicks).toHaveBeenCalledWith(gd, 'redraw'); + expect(subroutines.layoutStyles).not.toHaveBeenCalled(); + }) + .catch(failTest) + .then(done); + }); + + it('redraws annotations one at a time', function(done) { + var data = [{y: [1, 2, 3], mode: 'markers'}]; + var layout = {}; + var ymax; + + Plotly.newPlot(gd, data, layout) + .then(countPlots) + .then(function() { + ymax = layout.yaxis.range[1]; + + layout.annotations = [{ + x: 1, + y: 4, + text: 'Way up high', + showarrow: false + }, { + x: 1, + y: 2, + text: 'On the data', + showarrow: false + }]; + return Plotly.react(gd, data, layout); + }) + .then(function() { + // autoranged - so we get a full replot + countCalls({plot: 1}); + expect(d3.selectAll('.annotation').size()).toBe(2); + + layout.annotations[1].bgcolor = 'rgb(200, 100, 0)'; + return Plotly.react(gd, data, layout); + }) + .then(function() { + countCalls({annotationDrawOne: 1}); + expect(window.getComputedStyle(d3.select('.annotation[data-index="1"] .bg').node()).fill) + .toBe('rgb(200, 100, 0)'); + expect(layout.yaxis.range[1]).not.toBeCloseTo(ymax, 0); + + layout.annotations[0].font = {color: 'rgb(0, 255, 0)'}; + layout.annotations[1].bgcolor = 'rgb(0, 0, 255)'; + return Plotly.react(gd, data, layout); + }) + .then(function() { + countCalls({annotationDrawOne: 2}); + expect(window.getComputedStyle(d3.select('.annotation[data-index="0"] text').node()).fill) + .toBe('rgb(0, 255, 0)'); + expect(window.getComputedStyle(d3.select('.annotation[data-index="1"] .bg').node()).fill) + .toBe('rgb(0, 0, 255)'); + + Lib.extendFlat(layout.annotations[0], {yref: 'paper', y: 0.8}); + + return Plotly.react(gd, data, layout); + }) + .then(function() { + countCalls({plot: 1}); + expect(layout.yaxis.range[1]).toBeCloseTo(ymax, 0); + }) + .catch(failTest) + .then(done); + }); + + it('redraws images all at once', function(done) { + var data = [{y: [1, 2, 3], mode: 'markers'}]; + var layout = {}; + var jsLogo = 'https://images.plot.ly/language-icons/api-home/js-logo.png'; + + var x, y, height, width; + + Plotly.newPlot(gd, data, layout) + .then(countPlots) + .then(function() { + layout.images = [{ + source: jsLogo, + xref: 'paper', + yref: 'paper', + x: 0.1, + y: 0.1, + sizex: 0.2, + sizey: 0.2 + }, { + source: jsLogo, + xref: 'x', + yref: 'y', + x: 1, + y: 2, + sizex: 1, + sizey: 1 + }]; + return Plotly.react(gd, data, layout); + }) + .then(function() { + countCalls({imageDraw: 1}); + expect(d3.selectAll('image').size()).toBe(2); + + var n = d3.selectAll('image').node(); + x = n.attributes.x.value; + y = n.attributes.y.value; + height = n.attributes.height.value; + width = n.attributes.width.value; + + layout.images[0].y = 0.8; + layout.images[0].sizey = 0.4; + return Plotly.react(gd, data, layout); + }) + .then(function() { + countCalls({imageDraw: 1}); + var n = d3.selectAll('image').node(); + expect(n.attributes.x.value).toBe(x); + expect(n.attributes.width.value).toBe(width); + expect(n.attributes.y.value).not.toBe(y); + expect(n.attributes.height.value).not.toBe(height); + }) + .catch(failTest) + .then(done); + }); + + it('can change config, and always redraws', function(done) { + var data = [{y: [1, 2, 3]}]; + var layout = {}; + + Plotly.newPlot(gd, data, layout) + .then(countPlots) + .then(function() { + expect(d3.selectAll('.drag').size()).toBe(11); + expect(d3.selectAll('.gtitle').size()).toBe(0); + + return Plotly.react(gd, data, layout, {editable: true}); + }) + .then(function() { + expect(d3.selectAll('.drag').size()).toBe(11); + expect(d3.selectAll('.gtitle').text()).toBe('Click to enter Plot title'); + countCalls({plot: 1}); + + return Plotly.react(gd, data, layout, {staticPlot: true}); + }) + .then(function() { + expect(d3.selectAll('.drag').size()).toBe(0); + expect(d3.selectAll('.gtitle').size()).toBe(0); + countCalls({plot: 1}); + + return Plotly.react(gd, data, layout, {}); + }) + .then(function() { + expect(d3.selectAll('.drag').size()).toBe(11); + expect(d3.selectAll('.gtitle').size()).toBe(0); + countCalls({plot: 1}); + }) + .catch(failTest) + .then(done); + }); + + it('can put polar plots into staticPlot mode', function(done) { + // tested separately since some of the relevant code is actually + // in cartesian/graph_interact... hopefully we'll fix that + // sometime and the test will still pass. + var data = [{r: [1, 2, 3], theta: [0, 120, 240], type: 'scatterpolar'}]; + var layout = {}; + + Plotly.newPlot(gd, data, layout) + .then(countPlots) + .then(function() { + expect(d3.select(gd).selectAll('.drag').size()).toBe(4); + + return Plotly.react(gd, data, layout, {staticPlot: true}); + }) + .then(function() { + expect(d3.select(gd).selectAll('.drag').size()).toBe(0); + + return Plotly.react(gd, data, layout, {}); + }) + .then(function() { + expect(d3.select(gd).selectAll('.drag').size()).toBe(4); + }) + .catch(failTest) + .then(done); + }); + + it('can change data in candlesticks multiple times', function(done) { + // test that we've fixed the original issue in + // https://github.com/plotly/plotly.js/issues/2510 + + function assertCalc(open, high, low, close) { + expect(gd.calcdata[0][0]).toEqual(jasmine.objectContaining({ + min: low, + max: high, + med: close, + q1: Math.min(open, close), + q3: Math.max(open, close), + dir: close >= open ? 'increasing' : 'decreasing' + })); + } + var trace = { + type: 'candlestick', + low: [1], + open: [2], + close: [3], + high: [4] + }; + Plotly.newPlot(gd, [trace]) + .then(function() { + assertCalc(2, 4, 1, 3); + + trace.low = [0]; + return Plotly.react(gd, [trace]); + }) + .then(function() { + assertCalc(2, 4, 0, 3); + + trace.low = [-1]; + return Plotly.react(gd, [trace]); + }) + .then(function() { + assertCalc(2, 4, -1, 3); + + trace.close = [1]; + return Plotly.react(gd, [trace]); + }) + .then(function() { + assertCalc(2, 4, -1, 1); + }) + .catch(failTest) + .then(done); + }); + + function aggregatedPie(i) { + var labels = i <= 1 ? + ['A', 'B', 'A', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A'] : + ['X', 'Y', 'Z', 'Z', 'Y', 'Z', 'X', 'Z', 'Y', 'Z', 'X']; + var trace = { + type: 'pie', + values: [4, 1, 4, 4, 1, 4, 4, 2, 1, 1, 15], + labels: labels, + transforms: [{ + type: 'aggregate', + groups: labels, + aggregations: [{target: 'values', func: 'sum'}] + }] + }; + return { + data: [trace], + layout: { + datarevision: i, + colorway: ['red', 'orange', 'yellow', 'green', 'blue', 'violet'] + } + }; + } + + var aggPie1CD = [[ + {v: 26, label: 'A', color: 'red', i: 0}, + {v: 9, label: 'C', color: 'orange', i: 2}, + {v: 6, label: 'B', color: 'yellow', i: 1} + ]]; + + var aggPie2CD = [[ + {v: 23, label: 'X', color: 'red', i: 0}, + {v: 15, label: 'Z', color: 'orange', i: 2}, + {v: 3, label: 'Y', color: 'yellow', i: 1} + ]]; + + function aggregatedScatter(i) { + return { + data: [{ + x: [1, 2, 3, 4, 6, 5], + y: [2, 1, 3, 5, 6, 4], + transforms: [{ + type: 'aggregate', + groups: [1, -1, 1, -1, 1, -1], + aggregations: i > 1 ? [{func: 'last', target: 'x'}] : [] + }] + }], + layout: {daterevision: i + 10} + }; + } + + var aggScatter1CD = [[ + {x: 1, y: 2, i: 0}, + {x: 2, y: 1, i: 1} + ]]; + + var aggScatter2CD = [[ + {x: 6, y: 2, i: 0}, + {x: 5, y: 1, i: 1} + ]]; + + function aggregatedParcoords(i) { + return { + data: [{ + type: 'parcoords', + dimensions: [ + {label: 'A', values: [1, 2, 3, 4]}, + {label: 'B', values: [4, 3, 2, 1]} + ], + transforms: i ? [{ + type: 'aggregate', + groups: [1, 2, 1, 2], + aggregations: [ + {target: 'dimensions[0].values', func: i > 1 ? 'avg' : 'first'}, + {target: 'dimensions[1].values', func: i > 1 ? 'first' : 'avg'} + ] + }] : + [] + }] + }; + } + + var aggParcoords0Vals = [[1, 2, 3, 4], [4, 3, 2, 1]]; + var aggParcoords1Vals = [[1, 2], [3, 2]]; + var aggParcoords2Vals = [[2, 3], [4, 3]]; + + function checkCalcData(expectedCD) { + return function() { + expect(gd.calcdata.length).toBe(expectedCD.length); + expectedCD.forEach(function(expectedCDi, i) { + var cdi = gd.calcdata[i]; + expect(cdi.length).toBe(expectedCDi.length, i); + expectedCDi.forEach(function(expectedij, j) { + expect(cdi[j]).toEqual(jasmine.objectContaining(expectedij)); + }); + }); + }; + } + + function checkValues(expectedVals) { + return function() { + expect(gd._fullData.length).toBe(1); + var dims = gd._fullData[0].dimensions; + expect(dims.length).toBe(expectedVals.length); + expectedVals.forEach(function(expected, i) { + expect(dims[i].values).toEqual(expected); + }); + }; + } + + function reactTo(fig) { + return function() { return Plotly.react(gd, fig); }; + } + + it('can change pie aggregations', function(done) { + Plotly.newPlot(gd, aggregatedPie(1)) + .then(checkCalcData(aggPie1CD)) + + .then(reactTo(aggregatedPie(2))) + .then(checkCalcData(aggPie2CD)) + + .then(reactTo(aggregatedPie(1))) + .then(checkCalcData(aggPie1CD)) + .catch(failTest) + .then(done); + }); + + it('can change scatter aggregations', function(done) { + Plotly.newPlot(gd, aggregatedScatter(1)) + .then(checkCalcData(aggScatter1CD)) + + .then(reactTo(aggregatedScatter(2))) + .then(checkCalcData(aggScatter2CD)) + + .then(reactTo(aggregatedScatter(1))) + .then(checkCalcData(aggScatter1CD)) + .catch(failTest) + .then(done); + }); + + it('can change parcoords aggregations', function(done) { + Plotly.newPlot(gd, aggregatedParcoords(0)) + .then(checkValues(aggParcoords0Vals)) + + .then(reactTo(aggregatedParcoords(1))) + .then(checkValues(aggParcoords1Vals)) + + .then(reactTo(aggregatedParcoords(2))) + .then(checkValues(aggParcoords2Vals)) + + .then(reactTo(aggregatedParcoords(0))) + .then(checkValues(aggParcoords0Vals)) + + .catch(failTest) + .then(done); + }); + + it('can change type with aggregations', function(done) { + Plotly.newPlot(gd, aggregatedScatter(1)) + .then(checkCalcData(aggScatter1CD)) + + .then(reactTo(aggregatedPie(1))) + .then(checkCalcData(aggPie1CD)) + + .then(reactTo(aggregatedParcoords(1))) + .then(checkValues(aggParcoords1Vals)) + + .then(reactTo(aggregatedScatter(1))) + .then(checkCalcData(aggScatter1CD)) + + .then(reactTo(aggregatedParcoords(2))) + .then(checkValues(aggParcoords2Vals)) + + .then(reactTo(aggregatedPie(2))) + .then(checkCalcData(aggPie2CD)) + + .then(reactTo(aggregatedScatter(2))) + .then(checkCalcData(aggScatter2CD)) + + .then(reactTo(aggregatedParcoords(0))) + .then(checkValues(aggParcoords0Vals)) + .catch(failTest) + .then(done); + }); + + it('can change frames without redrawing', function(done) { + var data = [{y: [1, 2, 3]}]; + var layout = {}; + var frames = [{name: 'frame1'}]; + + Plotly.newPlot(gd, {data: data, layout: layout, frames: frames}) + .then(countPlots) + .then(function() { + var frameData = gd._transitionData._frames; + expect(frameData.length).toBe(1); + expect(frameData[0].name).toBe('frame1'); + + frames[0].name = 'frame2'; + return Plotly.react(gd, {data: data, layout: layout, frames: frames}); + }) + .then(function() { + countCalls({}); + var frameData = gd._transitionData._frames; + expect(frameData.length).toBe(1); + expect(frameData[0].name).toBe('frame2'); + }) + .catch(failTest) + .then(done); + }); + + // make sure we've included every trace type in this suite + var typesTested = {}; + var itemType; + for(itemType in Registry.modules) { typesTested[itemType] = 0; } + for(itemType in Registry.transformsRegistry) { typesTested[itemType] = 0; } + + // Not really being supported... This isn't part of the main bundle, and it's pretty broken, + // but it gets registered and used by a couple of the gl2d tests. + delete typesTested.contourgl; + + function _runReactMock(mockSpec, done) { + var mock = mockSpec[1]; + var initialJson; + + function fullJson() { + var out = JSON.parse(Plotly.Plots.graphJson({ + data: gd._fullData.map(function(trace) { return trace._fullInput; }), + layout: gd._fullLayout + })); + + // TODO: does it matter that ax.tick0/dtick/range and zmin/zmax + // are often not regenerated without a calc step? + // in as far as editor and others rely on _full, I think the + // answer must be yes, but I'm not sure about within plotly.js + [ + 'xaxis', 'xaxis2', 'xaxis3', 'xaxis4', 'xaxis5', + 'yaxis', 'yaxis2', 'yaxis3', 'yaxis4', + 'zaxis' + ].forEach(function(axName) { + var ax = out.layout[axName]; + if(ax) { + delete ax.dtick; + delete ax.tick0; + + // TODO this one I don't understand and can't reproduce + // in the dashboard but it's needed here? + delete ax.range; + } + if(out.layout.scene) { + ax = out.layout.scene[axName]; + if(ax) { + delete ax.dtick; + delete ax.tick0; + // TODO: this is the only one now that uses '_input_' + key + // as a hack to tell Plotly.react to ignore changes. + // Can we kill this? + delete ax.range; + } + } + }); + out.data.forEach(function(trace) { + if(trace.type === 'contourcarpet') { + delete trace.zmin; + delete trace.zmax; + } + }); + + return out; + } + + // Make sure we define `_length` in every trace *in supplyDefaults*. + // This is only relevant for traces that *have* a 1D concept of length, + // and in addition to simplifying calc/plot logic later on, ths serves + // as a signal to transforms about how they should operate. For traces + // that do NOT have a 1D length, `_length` should be `null`. + var mockGD = Lib.extendDeep({}, mock); + supplyAllDefaults(mockGD); + expect(mockGD._fullData.length).not.toBeLessThan((mock.data || []).length, mockSpec[0]); + mockGD._fullData.forEach(function(trace, i) { + var len = trace._length; + if(trace.visible !== false && len !== null) { + expect(typeof len).toBe('number', mockSpec[0] + ' trace ' + i + ': type=' + trace.type); + } + + typesTested[trace.type]++; + + if(trace.transforms) { + trace.transforms.forEach(function(transform) { + typesTested[transform.type]++; + }); + } + }); + + Plotly.newPlot(gd, mock) + .then(countPlots) + .then(function() { + initialJson = fullJson(); + + return Plotly.react(gd, mock); + }) + .then(function() { + expect(fullJson()).toEqual(initialJson); + countCalls({}); + }) + .catch(failTest) + .then(done); + } + + mockLists.svg.forEach(function(mockSpec) { + it('can redraw "' + mockSpec[0] + '" with no changes as a noop (svg mocks)', function(done) { + _runReactMock(mockSpec, done); + }); + }); + + mockLists.gl.forEach(function(mockSpec) { + it('can redraw "' + mockSpec[0] + '" with no changes as a noop (gl mocks)', function(done) { + _runReactMock(mockSpec, done); + }); + }); + + mockLists.mapbox.forEach(function(mockSpec) { + it('@noCI can redraw "' + mockSpec[0] + '" with no changes as a noop (mapbpox mocks)', function(done) { + Plotly.setPlotConfig({ + mapboxAccessToken: require('@build/credentials.json').MAPBOX_ACCESS_TOKEN + }); + _runReactMock(mockSpec, done); + }); + }); + + // since CI breaks up gl/svg types, and drops scattermapbox, this test won't work there + // but I should hope that if someone is doing something as major as adding a new type, + // they'll run the full test suite locally! + it('@noCI tested every trace & transform type at least once', function() { + for(var itemType in typesTested) { + expect(typesTested[itemType]).toBeGreaterThan(0, itemType + ' was not tested'); + } + }); +}); + +describe('resizing with Plotly.relayout and Plotly.react', function() { + var gd; + + beforeEach(function() { + gd = createGraphDiv(); + }); + + afterEach(destroyGraphDiv); + + it('recalculates autoranges when height/width change', function(done) { + Plotly.newPlot(gd, + [{y: [1, 2], marker: {size: 100}}], + {width: 400, height: 400, margin: {l: 100, r: 100, t: 100, b: 100}} + ) + .then(function() { + expect(gd.layout.xaxis.range).toBeCloseToArray([-1.31818, 2.31818], 3); + expect(gd.layout.yaxis.range).toBeCloseToArray([-0.31818, 3.31818], 3); + + return Plotly.relayout(gd, {height: 800, width: 800}); + }) + .then(function() { + expect(gd.layout.xaxis.range).toBeCloseToArray([-0.22289, 1.22289], 3); + expect(gd.layout.yaxis.range).toBeCloseToArray([0.77711, 2.22289], 3); + + gd.layout.width = 500; + gd.layout.height = 500; + return Plotly.react(gd, gd.data, gd.layout); + }) + .then(function() { + expect(gd.layout.xaxis.range).toBeCloseToArray([-0.53448, 1.53448], 3); + expect(gd.layout.yaxis.range).toBeCloseToArray([0.46552, 2.53448], 3); + }) + .catch(failTest) + .then(done); + }); +}); diff --git a/test/jasmine/tests/plot_api_test.js b/test/jasmine/tests/plot_api_test.js index 8f72baf0bb0..d0b8514fcd6 100644 --- a/test/jasmine/tests/plot_api_test.js +++ b/test/jasmine/tests/plot_api_test.js @@ -11,9 +11,6 @@ var pkg = require('../../../package.json'); var subroutines = require('@src/plot_api/subroutines'); var helpers = require('@src/plot_api/helpers'); var editTypes = require('@src/plot_api/edit_types'); -var annotations = require('@src/components/annotations'); -var images = require('@src/components/images'); -var Registry = require('@src/registry'); var d3 = require('d3'); var createGraphDiv = require('../assets/create_graph_div'); @@ -21,7 +18,6 @@ var destroyGraphDiv = require('../assets/destroy_graph_div'); var failTest = require('../assets/fail_test'); var checkTicks = require('../assets/custom_assertions').checkTicks; var supplyAllDefaults = require('../assets/supply_defaults'); -var mockLists = require('../assets/mock_lists'); describe('Test plot api', function() { 'use strict'; @@ -2659,879 +2655,6 @@ describe('Test plot api', function() { Plotly.update(gd, {'type': 'scatter', 'marker.color': 'red'}, {}, [1]); }); }); - - describe('@noCIdep Plotly.react', function() { - var mockedMethods = [ - 'doTraceStyle', - 'doColorBars', - 'doLegend', - 'layoutStyles', - 'doTicksRelayout', - 'doModeBar', - 'doCamera' - ]; - - var gd; - var afterPlotCnt; - - beforeEach(function() { - gd = createGraphDiv(); - - spyOn(plotApi, 'plot').and.callThrough(); - spyOn(Registry, 'call').and.callThrough(); - - mockedMethods.forEach(function(m) { - spyOn(subroutines, m).and.callThrough(); - subroutines[m].calls.reset(); - }); - - spyOn(annotations, 'drawOne').and.callThrough(); - spyOn(annotations, 'draw').and.callThrough(); - spyOn(images, 'draw').and.callThrough(); - spyOn(Axes, 'doTicks').and.callThrough(); - }); - - afterEach(destroyGraphDiv); - - function countPlots() { - plotApi.plot.calls.reset(); - subroutines.layoutStyles.calls.reset(); - annotations.draw.calls.reset(); - annotations.drawOne.calls.reset(); - images.draw.calls.reset(); - - afterPlotCnt = 0; - gd.on('plotly_afterplot', function() { afterPlotCnt++; }); - } - - function countCalls(counts) { - var callsFinal = Lib.extendFlat({}, counts); - callsFinal.layoutStyles = (counts.layoutStyles || 0) + (counts.plot || 0); - - mockedMethods.forEach(function(m) { - expect(subroutines[m]).toHaveBeenCalledTimes(callsFinal[m] || 0); - subroutines[m].calls.reset(); - }); - - // calls to Plotly.plot via plot_api.js or Registry.call('plot') - var plotCalls = plotApi.plot.calls.count() + - Registry.call.calls.all() - .filter(function(d) { return d.args[0] === 'plot'; }) - .length; - expect(plotCalls).toBe(counts.plot || 0, 'Plotly.plot calls'); - plotApi.plot.calls.reset(); - Registry.call.calls.reset(); - - // only consider annotation and image draw calls if we *don't* do a full plot. - if(!counts.plot) { - expect(annotations.draw).toHaveBeenCalledTimes(counts.annotationDraw || 0); - expect(annotations.drawOne).toHaveBeenCalledTimes(counts.annotationDrawOne || 0); - expect(images.draw).toHaveBeenCalledTimes(counts.imageDraw || 0); - } - annotations.draw.calls.reset(); - annotations.drawOne.calls.reset(); - images.draw.calls.reset(); - - expect(afterPlotCnt).toBe(1, 'plotly_afterplot should be called only once per edit'); - afterPlotCnt = 0; - } - - it('can add / remove traces', function(done) { - var data1 = [{y: [1, 2, 3], mode: 'markers'}]; - var data2 = [data1[0], {y: [2, 3, 1], mode: 'markers'}]; - var layout = {}; - Plotly.newPlot(gd, data1, layout) - .then(countPlots) - .then(function() { - expect(d3.selectAll('.point').size()).toBe(3); - - return Plotly.react(gd, data2, layout); - }) - .then(function() { - expect(d3.selectAll('.point').size()).toBe(6); - - return Plotly.react(gd, data1, layout); - }) - .then(function() { - expect(d3.selectAll('.point').size()).toBe(3); - }) - .catch(failTest) - .then(done); - }); - - it('should notice new data by ===, without layout.datarevision', function(done) { - var data = [{y: [1, 2, 3], mode: 'markers'}]; - var layout = {}; - - Plotly.newPlot(gd, data, layout) - .then(countPlots) - .then(function() { - expect(d3.selectAll('.point').size()).toBe(3); - - data[0].y.push(4); - return Plotly.react(gd, data, layout); - }) - .then(function() { - // didn't pick it up, as we modified in place!!! - expect(d3.selectAll('.point').size()).toBe(3); - countCalls({plot: 0}); - - data[0].y = [1, 2, 3, 4, 5]; - return Plotly.react(gd, data, layout); - }) - .then(function() { - // new object, we picked it up! - expect(d3.selectAll('.point').size()).toBe(5); - countCalls({plot: 1}); - }) - .catch(failTest) - .then(done); - }); - - it('should notice new layout.datarevision', function(done) { - var data = [{y: [1, 2, 3], mode: 'markers'}]; - var layout = {datarevision: 1}; - - Plotly.newPlot(gd, data, layout) - .then(countPlots) - .then(function() { - expect(d3.selectAll('.point').size()).toBe(3); - - data[0].y.push(4); - return Plotly.react(gd, data, layout); - }) - .then(function() { - // didn't pick it up, as we didn't modify datarevision - expect(d3.selectAll('.point').size()).toBe(3); - countCalls({plot: 0}); - - data[0].y.push(5); - layout.datarevision = 'bananas'; - return Plotly.react(gd, data, layout); - }) - .then(function() { - // new revision, we picked it up! - expect(d3.selectAll('.point').size()).toBe(5); - - countCalls({plot: 1}); - }) - .catch(failTest) - .then(done); - }); - - it('picks up partial redraws', function(done) { - var data = [{y: [1, 2, 3], mode: 'markers'}]; - var layout = {}; - - Plotly.newPlot(gd, data, layout) - .then(countPlots) - .then(function() { - layout.title = 'XXXXX'; - layout.hovermode = 'closest'; - data[0].marker = {color: 'rgb(0, 100, 200)'}; - return Plotly.react(gd, data, layout); - }) - .then(function() { - countCalls({layoutStyles: 1, doTraceStyle: 1, doModeBar: 1}); - expect(d3.select('.gtitle').text()).toBe('XXXXX'); - var points = d3.selectAll('.point'); - expect(points.size()).toBe(3); - points.each(function() { - expect(window.getComputedStyle(this).fill).toBe('rgb(0, 100, 200)'); - }); - - layout.showlegend = true; - layout.xaxis.tick0 = 0.1; - layout.xaxis.dtick = 0.3; - return Plotly.react(gd, data, layout); - }) - .then(function() { - // legend and ticks get called initially, but then plot gets added during automargin - countCalls({doLegend: 1, doTicksRelayout: 1, plot: 1}); - - data = [{z: [[1, 2], [3, 4]], type: 'surface'}]; - layout = {}; - - return Plotly.react(gd, data, layout); - }) - .then(function() { - // we get an extra call to layoutStyles from marginPushersAgain due to the colorbar. - // Really need to simplify that pipeline... - countCalls({plot: 1, layoutStyles: 1}); - - layout.scene.camera = {up: {x: 1, y: -1, z: 0}}; - - return Plotly.react(gd, data, layout); - }) - .then(function() { - countCalls({doCamera: 1}); - - data[0].type = 'heatmap'; - delete layout.scene; - return Plotly.react(gd, data, layout); - }) - .then(function() { - countCalls({plot: 1}); - - // ideally we'd just do this with `surface` but colorbar attrs have editType 'calc' there - // TODO: can we drop them to type: 'colorbars' even for the 3D types? - data[0].colorbar = {len: 0.6}; - return Plotly.react(gd, data, layout); - }) - .then(function() { - countCalls({doColorBars: 1, plot: 1}); - }) - .catch(failTest) - .then(done); - }); - - it('picks up special dtick geo case', function(done) { - var data = [{type: 'scattergeo'}]; - var layout = {}; - - function countLines() { - var path = d3.select(gd).select('.lataxis > path'); - return path.attr('d').split('M').length; - } - - Plotly.react(gd, data) - .then(countPlots) - .then(function() { - layout.geo = {lataxis: {showgrid: true, dtick: 10}}; - return Plotly.react(gd, data, layout); - }) - .then(function() { - countCalls({plot: 1}); - expect(countLines()).toBe(18); - }) - .then(function() { - layout.geo.lataxis.dtick = 30; - return Plotly.react(gd, data, layout); - }) - .then(function() { - countCalls({plot: 1}); - expect(countLines()).toBe(6); - }) - .catch(failTest) - .then(done); - }); - - it('picks up minimal sequence for cartesian axis range updates', function(done) { - var data = [{y: [1, 2, 1]}]; - var layout = {xaxis: {range: [1, 2]}}; - var layout2 = {xaxis: {range: [0, 1]}}; - - Plotly.newPlot(gd, data, layout) - .then(countPlots) - .then(function() { - expect(Axes.doTicks).toHaveBeenCalledWith(gd, ''); - return Plotly.react(gd, data, layout2); - }) - .then(function() { - expect(Axes.doTicks).toHaveBeenCalledWith(gd, 'redraw'); - expect(subroutines.layoutStyles).not.toHaveBeenCalled(); - }) - .catch(failTest) - .then(done); - }); - - it('redraws annotations one at a time', function(done) { - var data = [{y: [1, 2, 3], mode: 'markers'}]; - var layout = {}; - var ymax; - - Plotly.newPlot(gd, data, layout) - .then(countPlots) - .then(function() { - ymax = layout.yaxis.range[1]; - - layout.annotations = [{ - x: 1, - y: 4, - text: 'Way up high', - showarrow: false - }, { - x: 1, - y: 2, - text: 'On the data', - showarrow: false - }]; - return Plotly.react(gd, data, layout); - }) - .then(function() { - // autoranged - so we get a full replot - countCalls({plot: 1}); - expect(d3.selectAll('.annotation').size()).toBe(2); - - layout.annotations[1].bgcolor = 'rgb(200, 100, 0)'; - return Plotly.react(gd, data, layout); - }) - .then(function() { - countCalls({annotationDrawOne: 1}); - expect(window.getComputedStyle(d3.select('.annotation[data-index="1"] .bg').node()).fill) - .toBe('rgb(200, 100, 0)'); - expect(layout.yaxis.range[1]).not.toBeCloseTo(ymax, 0); - - layout.annotations[0].font = {color: 'rgb(0, 255, 0)'}; - layout.annotations[1].bgcolor = 'rgb(0, 0, 255)'; - return Plotly.react(gd, data, layout); - }) - .then(function() { - countCalls({annotationDrawOne: 2}); - expect(window.getComputedStyle(d3.select('.annotation[data-index="0"] text').node()).fill) - .toBe('rgb(0, 255, 0)'); - expect(window.getComputedStyle(d3.select('.annotation[data-index="1"] .bg').node()).fill) - .toBe('rgb(0, 0, 255)'); - - Lib.extendFlat(layout.annotations[0], {yref: 'paper', y: 0.8}); - - return Plotly.react(gd, data, layout); - }) - .then(function() { - countCalls({plot: 1}); - expect(layout.yaxis.range[1]).toBeCloseTo(ymax, 0); - }) - .catch(failTest) - .then(done); - }); - - it('redraws images all at once', function(done) { - var data = [{y: [1, 2, 3], mode: 'markers'}]; - var layout = {}; - var jsLogo = 'https://images.plot.ly/language-icons/api-home/js-logo.png'; - - var x, y, height, width; - - Plotly.newPlot(gd, data, layout) - .then(countPlots) - .then(function() { - layout.images = [{ - source: jsLogo, - xref: 'paper', - yref: 'paper', - x: 0.1, - y: 0.1, - sizex: 0.2, - sizey: 0.2 - }, { - source: jsLogo, - xref: 'x', - yref: 'y', - x: 1, - y: 2, - sizex: 1, - sizey: 1 - }]; - return Plotly.react(gd, data, layout); - }) - .then(function() { - countCalls({imageDraw: 1}); - expect(d3.selectAll('image').size()).toBe(2); - - var n = d3.selectAll('image').node(); - x = n.attributes.x.value; - y = n.attributes.y.value; - height = n.attributes.height.value; - width = n.attributes.width.value; - - layout.images[0].y = 0.8; - layout.images[0].sizey = 0.4; - return Plotly.react(gd, data, layout); - }) - .then(function() { - countCalls({imageDraw: 1}); - var n = d3.selectAll('image').node(); - expect(n.attributes.x.value).toBe(x); - expect(n.attributes.width.value).toBe(width); - expect(n.attributes.y.value).not.toBe(y); - expect(n.attributes.height.value).not.toBe(height); - }) - .catch(failTest) - .then(done); - }); - - it('can change config, and always redraws', function(done) { - var data = [{y: [1, 2, 3]}]; - var layout = {}; - - Plotly.newPlot(gd, data, layout) - .then(countPlots) - .then(function() { - expect(d3.selectAll('.drag').size()).toBe(11); - expect(d3.selectAll('.gtitle').size()).toBe(0); - - return Plotly.react(gd, data, layout, {editable: true}); - }) - .then(function() { - expect(d3.selectAll('.drag').size()).toBe(11); - expect(d3.selectAll('.gtitle').text()).toBe('Click to enter Plot title'); - countCalls({plot: 1}); - - return Plotly.react(gd, data, layout, {staticPlot: true}); - }) - .then(function() { - expect(d3.selectAll('.drag').size()).toBe(0); - expect(d3.selectAll('.gtitle').size()).toBe(0); - countCalls({plot: 1}); - - return Plotly.react(gd, data, layout, {}); - }) - .then(function() { - expect(d3.selectAll('.drag').size()).toBe(11); - expect(d3.selectAll('.gtitle').size()).toBe(0); - countCalls({plot: 1}); - }) - .catch(failTest) - .then(done); - }); - - it('can put polar plots into staticPlot mode', function(done) { - // tested separately since some of the relevant code is actually - // in cartesian/graph_interact... hopefully we'll fix that - // sometime and the test will still pass. - var data = [{r: [1, 2, 3], theta: [0, 120, 240], type: 'scatterpolar'}]; - var layout = {}; - - Plotly.newPlot(gd, data, layout) - .then(countPlots) - .then(function() { - expect(d3.select(gd).selectAll('.drag').size()).toBe(4); - - return Plotly.react(gd, data, layout, {staticPlot: true}); - }) - .then(function() { - expect(d3.select(gd).selectAll('.drag').size()).toBe(0); - - return Plotly.react(gd, data, layout, {}); - }) - .then(function() { - expect(d3.select(gd).selectAll('.drag').size()).toBe(4); - }) - .catch(failTest) - .then(done); - }); - - it('can change data in candlesticks multiple times', function(done) { - // test that we've fixed the original issue in - // https://github.com/plotly/plotly.js/issues/2510 - - function assertCalc(open, high, low, close) { - expect(gd.calcdata[0][0]).toEqual(jasmine.objectContaining({ - min: low, - max: high, - med: close, - q1: Math.min(open, close), - q3: Math.max(open, close), - dir: close >= open ? 'increasing' : 'decreasing' - })); - } - var trace = { - type: 'candlestick', - low: [1], - open: [2], - close: [3], - high: [4] - }; - Plotly.newPlot(gd, [trace]) - .then(function() { - assertCalc(2, 4, 1, 3); - - trace.low = [0]; - return Plotly.react(gd, [trace]); - }) - .then(function() { - assertCalc(2, 4, 0, 3); - - trace.low = [-1]; - return Plotly.react(gd, [trace]); - }) - .then(function() { - assertCalc(2, 4, -1, 3); - - trace.close = [1]; - return Plotly.react(gd, [trace]); - }) - .then(function() { - assertCalc(2, 4, -1, 1); - }) - .catch(failTest) - .then(done); - }); - - function aggregatedPie(i) { - var labels = i <= 1 ? - ['A', 'B', 'A', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A'] : - ['X', 'Y', 'Z', 'Z', 'Y', 'Z', 'X', 'Z', 'Y', 'Z', 'X']; - var trace = { - type: 'pie', - values: [4, 1, 4, 4, 1, 4, 4, 2, 1, 1, 15], - labels: labels, - transforms: [{ - type: 'aggregate', - groups: labels, - aggregations: [{target: 'values', func: 'sum'}] - }] - }; - return { - data: [trace], - layout: { - datarevision: i, - colorway: ['red', 'orange', 'yellow', 'green', 'blue', 'violet'] - } - }; - } - - var aggPie1CD = [[ - {v: 26, label: 'A', color: 'red', i: 0}, - {v: 9, label: 'C', color: 'orange', i: 2}, - {v: 6, label: 'B', color: 'yellow', i: 1} - ]]; - - var aggPie2CD = [[ - {v: 23, label: 'X', color: 'red', i: 0}, - {v: 15, label: 'Z', color: 'orange', i: 2}, - {v: 3, label: 'Y', color: 'yellow', i: 1} - ]]; - - function aggregatedScatter(i) { - return { - data: [{ - x: [1, 2, 3, 4, 6, 5], - y: [2, 1, 3, 5, 6, 4], - transforms: [{ - type: 'aggregate', - groups: [1, -1, 1, -1, 1, -1], - aggregations: i > 1 ? [{func: 'last', target: 'x'}] : [] - }] - }], - layout: {daterevision: i + 10} - }; - } - - var aggScatter1CD = [[ - {x: 1, y: 2, i: 0}, - {x: 2, y: 1, i: 1} - ]]; - - var aggScatter2CD = [[ - {x: 6, y: 2, i: 0}, - {x: 5, y: 1, i: 1} - ]]; - - function aggregatedParcoords(i) { - return { - data: [{ - type: 'parcoords', - dimensions: [ - {label: 'A', values: [1, 2, 3, 4]}, - {label: 'B', values: [4, 3, 2, 1]} - ], - transforms: i ? [{ - type: 'aggregate', - groups: [1, 2, 1, 2], - aggregations: [ - {target: 'dimensions[0].values', func: i > 1 ? 'avg' : 'first'}, - {target: 'dimensions[1].values', func: i > 1 ? 'first' : 'avg'} - ] - }] : - [] - }] - }; - } - - var aggParcoords0Vals = [[1, 2, 3, 4], [4, 3, 2, 1]]; - var aggParcoords1Vals = [[1, 2], [3, 2]]; - var aggParcoords2Vals = [[2, 3], [4, 3]]; - - function checkCalcData(expectedCD) { - return function() { - expect(gd.calcdata.length).toBe(expectedCD.length); - expectedCD.forEach(function(expectedCDi, i) { - var cdi = gd.calcdata[i]; - expect(cdi.length).toBe(expectedCDi.length, i); - expectedCDi.forEach(function(expectedij, j) { - expect(cdi[j]).toEqual(jasmine.objectContaining(expectedij)); - }); - }); - }; - } - - function checkValues(expectedVals) { - return function() { - expect(gd._fullData.length).toBe(1); - var dims = gd._fullData[0].dimensions; - expect(dims.length).toBe(expectedVals.length); - expectedVals.forEach(function(expected, i) { - expect(dims[i].values).toEqual(expected); - }); - }; - } - - function reactTo(fig) { - return function() { return Plotly.react(gd, fig); }; - } - - it('can change pie aggregations', function(done) { - Plotly.newPlot(gd, aggregatedPie(1)) - .then(checkCalcData(aggPie1CD)) - - .then(reactTo(aggregatedPie(2))) - .then(checkCalcData(aggPie2CD)) - - .then(reactTo(aggregatedPie(1))) - .then(checkCalcData(aggPie1CD)) - .catch(failTest) - .then(done); - }); - - it('can change scatter aggregations', function(done) { - Plotly.newPlot(gd, aggregatedScatter(1)) - .then(checkCalcData(aggScatter1CD)) - - .then(reactTo(aggregatedScatter(2))) - .then(checkCalcData(aggScatter2CD)) - - .then(reactTo(aggregatedScatter(1))) - .then(checkCalcData(aggScatter1CD)) - .catch(failTest) - .then(done); - }); - - it('can change parcoords aggregations', function(done) { - Plotly.newPlot(gd, aggregatedParcoords(0)) - .then(checkValues(aggParcoords0Vals)) - - .then(reactTo(aggregatedParcoords(1))) - .then(checkValues(aggParcoords1Vals)) - - .then(reactTo(aggregatedParcoords(2))) - .then(checkValues(aggParcoords2Vals)) - - .then(reactTo(aggregatedParcoords(0))) - .then(checkValues(aggParcoords0Vals)) - - .catch(failTest) - .then(done); - }); - - it('can change type with aggregations', function(done) { - Plotly.newPlot(gd, aggregatedScatter(1)) - .then(checkCalcData(aggScatter1CD)) - - .then(reactTo(aggregatedPie(1))) - .then(checkCalcData(aggPie1CD)) - - .then(reactTo(aggregatedParcoords(1))) - .then(checkValues(aggParcoords1Vals)) - - .then(reactTo(aggregatedScatter(1))) - .then(checkCalcData(aggScatter1CD)) - - .then(reactTo(aggregatedParcoords(2))) - .then(checkValues(aggParcoords2Vals)) - - .then(reactTo(aggregatedPie(2))) - .then(checkCalcData(aggPie2CD)) - - .then(reactTo(aggregatedScatter(2))) - .then(checkCalcData(aggScatter2CD)) - - .then(reactTo(aggregatedParcoords(0))) - .then(checkValues(aggParcoords0Vals)) - .catch(failTest) - .then(done); - }); - - it('can change frames without redrawing', function(done) { - var data = [{y: [1, 2, 3]}]; - var layout = {}; - var frames = [{name: 'frame1'}]; - - Plotly.newPlot(gd, {data: data, layout: layout, frames: frames}) - .then(countPlots) - .then(function() { - var frameData = gd._transitionData._frames; - expect(frameData.length).toBe(1); - expect(frameData[0].name).toBe('frame1'); - - frames[0].name = 'frame2'; - return Plotly.react(gd, {data: data, layout: layout, frames: frames}); - }) - .then(function() { - countCalls({}); - var frameData = gd._transitionData._frames; - expect(frameData.length).toBe(1); - expect(frameData[0].name).toBe('frame2'); - }) - .catch(failTest) - .then(done); - }); - - // make sure we've included every trace type in this suite - var typesTested = {}; - var itemType; - for(itemType in Registry.modules) { typesTested[itemType] = 0; } - for(itemType in Registry.transformsRegistry) { typesTested[itemType] = 0; } - - // Not really being supported... This isn't part of the main bundle, and it's pretty broken, - // but it gets registered and used by a couple of the gl2d tests. - delete typesTested.contourgl; - - function _runReactMock(mockSpec, done) { - var mock = mockSpec[1]; - var initialJson; - - function fullJson() { - var out = JSON.parse(Plotly.Plots.graphJson({ - data: gd._fullData.map(function(trace) { return trace._fullInput; }), - layout: gd._fullLayout - })); - - // TODO: does it matter that ax.tick0/dtick/range and zmin/zmax - // are often not regenerated without a calc step? - // in as far as editor and others rely on _full, I think the - // answer must be yes, but I'm not sure about within plotly.js - [ - 'xaxis', 'xaxis2', 'xaxis3', 'xaxis4', 'xaxis5', - 'yaxis', 'yaxis2', 'yaxis3', 'yaxis4', - 'zaxis' - ].forEach(function(axName) { - var ax = out.layout[axName]; - if(ax) { - delete ax.dtick; - delete ax.tick0; - - // TODO this one I don't understand and can't reproduce - // in the dashboard but it's needed here? - delete ax.range; - } - if(out.layout.scene) { - ax = out.layout.scene[axName]; - if(ax) { - delete ax.dtick; - delete ax.tick0; - // TODO: this is the only one now that uses '_input_' + key - // as a hack to tell Plotly.react to ignore changes. - // Can we kill this? - delete ax.range; - } - } - }); - out.data.forEach(function(trace) { - if(trace.type === 'contourcarpet') { - delete trace.zmin; - delete trace.zmax; - } - }); - - return out; - } - - // Make sure we define `_length` in every trace *in supplyDefaults*. - // This is only relevant for traces that *have* a 1D concept of length, - // and in addition to simplifying calc/plot logic later on, ths serves - // as a signal to transforms about how they should operate. For traces - // that do NOT have a 1D length, `_length` should be `null`. - var mockGD = Lib.extendDeep({}, mock); - supplyAllDefaults(mockGD); - expect(mockGD._fullData.length).not.toBeLessThan((mock.data || []).length, mockSpec[0]); - mockGD._fullData.forEach(function(trace, i) { - var len = trace._length; - if(trace.visible !== false && len !== null) { - expect(typeof len).toBe('number', mockSpec[0] + ' trace ' + i + ': type=' + trace.type); - } - - typesTested[trace.type]++; - - if(trace.transforms) { - trace.transforms.forEach(function(transform) { - typesTested[transform.type]++; - }); - } - }); - - Plotly.newPlot(gd, mock) - .then(countPlots) - .then(function() { - initialJson = fullJson(); - - return Plotly.react(gd, mock); - }) - .then(function() { - expect(fullJson()).toEqual(initialJson); - countCalls({}); - }) - .catch(failTest) - .then(done); - } - - mockLists.svg.forEach(function(mockSpec) { - it('can redraw "' + mockSpec[0] + '" with no changes as a noop (svg mocks)', function(done) { - _runReactMock(mockSpec, done); - }); - }); - - mockLists.gl.forEach(function(mockSpec) { - it('can redraw "' + mockSpec[0] + '" with no changes as a noop (gl mocks)', function(done) { - _runReactMock(mockSpec, done); - }); - }); - - mockLists.mapbox.forEach(function(mockSpec) { - it('@noCI can redraw "' + mockSpec[0] + '" with no changes as a noop (mapbpox mocks)', function(done) { - Plotly.setPlotConfig({ - mapboxAccessToken: require('@build/credentials.json').MAPBOX_ACCESS_TOKEN - }); - _runReactMock(mockSpec, done); - }); - }); - - // since CI breaks up gl/svg types, and drops scattermapbox, this test won't work there - // but I should hope that if someone is doing something as major as adding a new type, - // they'll run the full test suite locally! - it('@noCI tested every trace & transform type at least once', function() { - for(var itemType in typesTested) { - expect(typesTested[itemType]).toBeGreaterThan(0, itemType + ' was not tested'); - } - }); - }); - - describe('resizing with Plotly.relayout and Plotly.react', function() { - var gd; - - beforeEach(function() { - gd = createGraphDiv(); - }); - - afterEach(destroyGraphDiv); - - it('recalculates autoranges when height/width change', function(done) { - Plotly.newPlot(gd, - [{y: [1, 2], marker: {size: 100}}], - {width: 400, height: 400, margin: {l: 100, r: 100, t: 100, b: 100}} - ) - .then(function() { - expect(gd.layout.xaxis.range).toBeCloseToArray([-1.31818, 2.31818], 3); - expect(gd.layout.yaxis.range).toBeCloseToArray([-0.31818, 3.31818], 3); - - return Plotly.relayout(gd, {height: 800, width: 800}); - }) - .then(function() { - expect(gd.layout.xaxis.range).toBeCloseToArray([-0.22289, 1.22289], 3); - expect(gd.layout.yaxis.range).toBeCloseToArray([0.77711, 2.22289], 3); - - gd.layout.width = 500; - gd.layout.height = 500; - return Plotly.react(gd, gd.data, gd.layout); - }) - .then(function() { - expect(gd.layout.xaxis.range).toBeCloseToArray([-0.53448, 1.53448], 3); - expect(gd.layout.yaxis.range).toBeCloseToArray([0.46552, 2.53448], 3); - }) - .catch(failTest) - .then(done); - }); - }); }); describe('plot_api helpers', function() { From 54304b40aee7c97a81b64964b67123ac05b5eb82 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Fri, 9 Nov 2018 16:10:53 -0500 Subject: [PATCH 13/33] test uirevision + react logic --- test/jasmine/tests/plot_api_react_test.js | 488 ++++++++++++++++++++++ 1 file changed, 488 insertions(+) diff --git a/test/jasmine/tests/plot_api_react_test.js b/test/jasmine/tests/plot_api_react_test.js index 9a3694ceab2..242d343ed33 100644 --- a/test/jasmine/tests/plot_api_react_test.js +++ b/test/jasmine/tests/plot_api_react_test.js @@ -13,6 +13,7 @@ var destroyGraphDiv = require('../assets/destroy_graph_div'); var failTest = require('../assets/fail_test'); var supplyAllDefaults = require('../assets/supply_defaults'); var mockLists = require('../assets/mock_lists'); +var drag = require('../assets/drag'); describe('@noCIdep Plotly.react', function() { var mockedMethods = [ @@ -886,3 +887,490 @@ describe('resizing with Plotly.relayout and Plotly.react', function() { .then(done); }); }); + + +describe('Plotly.react and uirevision attributes', function() { + var gd; + + beforeEach(function() { + gd = createGraphDiv(); + }); + + afterEach(destroyGraphDiv); + + function checkState(dataKeys, layoutKeys, msg) { + var np = Lib.nestedProperty; + return function() { + dataKeys.forEach(function(traceKeys, i) { + var trace = gd.data[i]; + var fullTrace = gd._fullData.filter(function(ft) { + return ft._fullInput.index === i; + })[0]._fullInput; + + for(var key in traceKeys) { + var val = traceKeys[key]; + var valIn = Array.isArray(val) ? val[0] : val; + var valOut = Array.isArray(val) ? val[val.length - 1] : val; + expect(np(trace, key).get()).toEqual(valIn, msg + ': data[' + i + '].' + key); + expect(np(fullTrace, key).get()).toEqual(valOut, msg + ': _fullData[' + i + '].' + key); + } + }); + + for(var key in (layoutKeys || {})) { + var val = layoutKeys[key]; + var valIn = Array.isArray(val) ? val[0] : val; + var valOut = Array.isArray(val) ? val[val.length - 1] : val; + expect(np(gd.layout, key).get()).toEqual(valIn, msg + ': layout.' + key); + expect(np(gd._fullLayout, key).get()).toEqual(valOut, msg + ': _fullLayout.' + key); + } + }; + } + + function _react(fig) { + return function() { + return Plotly.react(gd, fig); + }; + } + + it('preserves zoom and trace visibility state until uirevision changes', function(done) { + var checkNoEdits = checkState([{ + }, { + visible: [undefined, true] + }], { + 'xaxis.autorange': true, + 'yaxis.autorange': true + }, 'initial'); + + var checkHasEdits = checkState([{ + }, { + visible: 'legendonly' + }], { + 'xaxis.range[0]': 0, + 'xaxis.range[1]': 1, + 'xaxis.autorange': false, + 'yaxis.range[0]': 1, + 'yaxis.range[1]': 2, + 'yaxis.autorange': false + }, 'with GUI edits'); + + var i = 0; + function fig(rev) { + i++; + return { + data: [{y: [1, 3, i]}, {y: [2, 1, i + 1]}], + layout: {uirevision: rev} + }; + } + + function setEdits() { + return Registry.call('_guiRelayout', gd, { + 'xaxis.range': [0, 1], + 'yaxis.range': [1, 2] + }) + .then(function() { + return Registry.call('_guiRestyle', gd, 'visible', 'legendonly', [1]); + }); + } + + Plotly.newPlot(gd, fig('something')) + .then(checkNoEdits) + .then(setEdits) + .then(checkHasEdits) + .then(_react(fig('something'))) + .then(checkHasEdits) + .then(_react(fig('something else!'))) + .then(checkNoEdits) + .then(_react(fig('something'))) + // back to the first uirevision, but the changes are gone forever + .then(checkNoEdits) + // falsy uirevision - does not preserve edits + .then(_react(fig(false))) + .then(checkNoEdits) + .then(setEdits) + .then(checkHasEdits) + .then(_react(fig(false))) + .then(checkNoEdits) + .catch(failTest) + .then(done); + }); + + it('moves trace visibility with uid', function(done) { + Plotly.newPlot(gd, + [{y: [1, 3, 1], uid: 'a'}, {y: [2, 1, 2], uid: 'b'}], + {uirevision: 'something'} + ) + .then(function() { + return Registry.call('_guiRestyle', gd, 'visible', 'legendonly', [1]); + }) + // we hid the second trace, with uid b + .then(checkState([{visible: [undefined, true]}, {visible: 'legendonly'}])) + .then(_react({ + data: [{y: [1, 3, 1], uid: 'b'}, {y: [2, 1, 2], uid: 'a'}], + layout: {uirevision: 'something'} + })) + // now the first trace is hidden, because it has uid b now! + .then(checkState([{visible: 'legendonly'}, {visible: [undefined, true]}])) + .catch(failTest) + .then(done); + }); + + it('controls axis edits with axis.uirevision', function(done) { + function fig(mainRev, xRev, yRev, x2Rev, y2Rev) { + return { + data: [{y: [1, 2, 1]}, {y: [3, 4, 3], xaxis: 'x2', yaxis: 'y2'}], + layout: { + uirevision: mainRev, + grid: {columns: 2, pattern: 'independent'}, + xaxis: {uirevision: xRev}, + yaxis: {uirevision: yRev}, + xaxis2: {uirevision: x2Rev}, + yaxis2: {uirevision: y2Rev} + } + }; + } + + function checkAutoRange(x, y, x2, y2, msg) { + return checkState([], { + 'xaxis.autorange': x, + 'yaxis.autorange': y, + 'xaxis2.autorange': x2, + 'yaxis2.autorange': y2 + }, msg); + } + + function setExplicitRanges() { + return Registry.call('_guiRelayout', gd, { + 'xaxis.range': [1, 2], + 'yaxis.range': [2, 3], + 'xaxis2.range': [3, 4], + 'yaxis2.range': [4, 5] + }); + } + + Plotly.newPlot(gd, fig('a', 'x1a', 'y1a', 'x2a', 'y2a')) + .then(checkAutoRange(true, true, true, true)) + .then(setExplicitRanges) + .then(checkAutoRange(false, false, false, false)) + // change main rev (no effect) and y1 and x2 + .then(_react(fig('b', 'x1a', 'y1b', 'x2b', 'y2a'))) + .then(checkAutoRange(false, true, true, false)) + // now reset with falsy revisions for x2 & y2 but undefined for x1 & y1 + // to show that falsy says "never persist changes here" but undefined + // will be inherited + .then(_react(fig('a', undefined, undefined, false, ''))) + .then(checkAutoRange(true, true, true, true)) + .then(setExplicitRanges) + .then(checkAutoRange(false, false, false, false)) + .then(_react(fig('a', undefined, undefined, false, ''))) + .then(checkAutoRange(false, false, true, true)) + .then(_react(fig('b', undefined, undefined, false, ''))) + .then(checkAutoRange(true, true, true, true)) + .catch(failTest) + .then(done); + }); + + it('controls trace and pie label visibility from legend.uirevision', function(done) { + function checkVisible(traces, hiddenlabels, msg) { + return checkState( + traces.map(function(v) { + return {visible: v ? [undefined, true] : 'legendonly'}; + }), + {hiddenlabels: hiddenlabels}, + msg + ); + } + + function fig(mainRev, legendRev) { + return { + data: [ + {y: [1, 2]}, + {y: [2, 1]}, + {type: 'pie', labels: ['a', 'b', 'c'], values: [1, 2, 3]} + ], + layout: { + uirevision: mainRev, + legend: {uirevision: legendRev} + } + }; + } + + Plotly.newPlot(gd, fig('main a', 'legend a')) + .then(checkVisible([true, true], undefined, 'initial')) + .then(function() { + return Registry.call('_guiUpdate', gd, + {visible: 'legendonly'}, + {hiddenlabels: ['b', 'c']}, + [0] + ); + }) + // wrap [b, c] in another array to distinguish it from + // [layout, fullLayout] + .then(checkVisible([false, true], [['b', 'c']], 'gui')) + .then(_react(fig('main b', 'legend a'))) + .then(checkVisible([false, true], [['b', 'c']], 'change main rev')) + .then(_react(fig('main b', 'legend b'))) + .then(checkVisible([true, true], undefined, 'change legend rev')) + .catch(failTest) + .then(done); + }); + + it('preserves groupby group visibility', function(done) { + // TODO: there's a known problem if the groups change... unlike + // traces we will keep visibility by group in order, not by group value + + function checkVisible(groups, extraTrace) { + var trace0edits = {}; + groups.forEach(function(visi, i) { + var attr = 'transforms[0].styles[' + i + '].value.visible'; + trace0edits[attr] = visi ? undefined : 'legendonly'; + }); + return checkState([ + trace0edits, + {visible: extraTrace ? [undefined, true] : 'legendonly'} + ]); + } + + function fig(mainRev, legendRev) { + return { + data: [{ + y: [1, 2, 3, 4, 5, 6], + transforms: [{ + type: 'groupby', + groups: ['a', 'b', 'c', 'a', 'b', 'c'] + }] + }, { + y: [7, 8] + }], + layout: { + uirevision: mainRev, + legend: {uirevision: legendRev} + } + }; + } + + Plotly.newPlot(gd, fig('main a', 'legend a')) + .then(checkVisible([true, true, true], true)) + .then(function() { + return Registry.call('_guiRestyle', gd, { + 'transforms[0].styles[0].value.visible': 'legendonly', + 'transforms[0].styles[2].value.visible': 'legendonly' + }, [0]) + .then(function() { + return Registry.call('_guiRestyle', gd, 'visible', 'legendonly', [1]); + }); + }) + .then(checkVisible([false, true, false], false)) + .then(_react(fig('main b', 'legend a'))) + .then(checkVisible([false, true, false], false)) + .then(_react(fig('main b', 'legend b'))) + .then(checkVisible([true, true, true], true)) + .catch(failTest) + .then(done); + }); + + it('@gl preserves modebar interactions using modebar.uirevision', function(done) { + function fig(mainRev, modebarRev) { + return { + data: [ + {type: 'surface', z: [[1, 2], [3, 4]]}, + {y: [1, 2]} + ], + layout: { + scene: { + domain: {x: [0, 0.4]}, + hovermode: 'closest', + dragmode: 'zoom' + }, + xaxis: {domain: [0.6, 1], showspikes: true}, + yaxis: {showspikes: true}, + uirevision: mainRev, + modebar: {uirevision: modebarRev}, + hovermode: 'closest', + dragmode: 'zoom' + } + }; + } + + function editModes() { + return Registry.call('_guiRelayout', gd, { + dragmode: 'pan', + hovermode: false, + 'xaxis.showspikes': false, + 'yaxis.showspikes': false, + 'scene.dragmode': 'pan', + 'scene.hovermode': false, + 'scene.xaxis.showspikes': false, + 'scene.yaxis.showspikes': false, + 'scene.zaxis.showspikes': false + }); + } + + function _checkModes(original) { + var dragmode = original ? 'zoom' : 'pan'; + var hovermode = original ? 'closest' : false; + var spikes = original ? true : false; + var spikes3D = original ? [undefined, true] : false; + return checkState([], { + dragmode: dragmode, + hovermode: hovermode, + 'xaxis.showspikes': spikes, + 'yaxis.showspikes': spikes, + 'scene.dragmode': dragmode, + 'scene.hovermode': hovermode, + 'scene.xaxis.showspikes': spikes3D, + 'scene.yaxis.showspikes': spikes3D, + 'scene.zaxis.showspikes': spikes3D + }); + } + var checkOriginalModes = _checkModes(true); + var checkEditedModes = _checkModes(false); + + Plotly.newPlot(gd, fig('main a', 'modebar a')) + .then(checkOriginalModes) + .then(editModes) + .then(checkEditedModes) + .then(_react(fig('main b', 'modebar a'))) + .then(checkEditedModes) + .then(_react(fig('main b', 'modebar b'))) + .then(checkOriginalModes) + .catch(failTest) + .then(done); + }); + + it('preserves geo viewport changes using geo.uirevision', function(done) { + function fig(mainRev, geoRev) { + return { + data: [{ + type: 'scattergeo', lon: [0, -75], lat: [0, 45] + }], + layout: { + uirevision: mainRev, + geo: {uirevision: geoRev} + } + }; + } + + function editView() { + return Registry.call('_guiRelayout', gd, { + 'geo.projection.scale': 3, + 'geo.projection.rotation.lon': -45, + 'geo.center.lat': 22, + 'geo.center.lon': -45 + }); + } + + function _checkView(original) { + return checkState([], { + 'geo.projection.scale': original ? [undefined, 1] : 3, + 'geo.projection.rotation.lon': original ? [undefined, 0] : -45, + 'geo.center.lat': original ? [undefined, 0] : 22, + 'geo.center.lon': original ? [undefined, 0] : -45 + }); + } + var checkOriginalView = _checkView(true); + var checkEditedView = _checkView(false); + + Plotly.newPlot(gd, fig('main a', 'geo a')) + .then(checkOriginalView) + .then(editView) + .then(checkEditedView) + .then(_react(fig('main b', 'geo a'))) + .then(checkEditedView) + .then(_react(fig('main b', 'geo b'))) + .then(checkOriginalView) + .catch(failTest) + .then(done); + }); + + it('@gl preserves 3d camera changes using scene.uirevision', function(done) { + function fig(mainRev, sceneRev) { + return { + data: [{type: 'surface', z: [[1, 2], [3, 4]]}], + layout: { + uirevision: mainRev, + scene: {uirevision: sceneRev} + } + }; + } + + function editCamera() { + return Registry.call('_guiRelayout', gd, { + 'scene.camera': { + center: {x: 1, y: 2, z: 3}, + eye: {x: 2, y: 3, z: 4}, + up: {x: 0, y: 0, z: 1} + } + }); + } + + function _checkCamera(original) { + return checkState([], { + 'scene.camera.center.x': original ? [undefined, 0] : 1, + 'scene.camera.center.y': original ? [undefined, 0] : 2, + 'scene.camera.center.z': original ? [undefined, 0] : 3, + 'scene.camera.eye.x': original ? [undefined, 1.25] : 2, + 'scene.camera.eye.y': original ? [undefined, 1.25] : 3, + 'scene.camera.eye.z': original ? [undefined, 1.25] : 4, + 'scene.camera.up.x': original ? [undefined, 0] : 0, + 'scene.camera.up.y': original ? [undefined, 0] : 0, + 'scene.camera.up.z': original ? [undefined, 1] : 1 + }); + } + var checkOriginalCamera = _checkCamera(true); + var checkEditedCamera = _checkCamera(false); + + Plotly.newPlot(gd, fig('main a', 'scene a')) + .then(checkOriginalCamera) + .then(editCamera) + .then(checkEditedCamera) + .then(_react(fig('main b', 'scene a'))) + .then(checkEditedCamera) + .then(_react(fig('main b', 'scene b'))) + .then(checkOriginalCamera) + .catch(failTest) + .then(done); + }); + + it('preserves selectedpoints using selectionrevision', function(done) { + function fig(mainRev, selectionRev) { + return { + data: [{y: [1, 3, 1]}, {y: [2, 1, 3]}], + layout: { + uirevision: mainRev, + selectionrevision: selectionRev, + dragmode: 'select', + width: 400, + height: 400, + margin: {l: 100, t: 100, r: 100, b: 100} + } + }; + } + + function editSelection() { + // drag across the upper right quadrant, so we'll select + // curve 0 point 1 and curve 1 point 2 + return drag(document.querySelector('.nsewdrag'), + 148, 100, '', 150, 102); + } + + var checkNoSelection = checkState([ + {selectedpoints: undefined}, + {selectedpoints: undefined} + ]); + var checkSelection = checkState([ + {selectedpoints: [[1]]}, + {selectedpoints: [[2]]} + ]); + + Plotly.newPlot(gd, fig('main a', 'selection a')) + .then(checkNoSelection) + .then(editSelection) + .then(checkSelection) + .then(_react(fig('main b', 'selection a'))) + .then(checkSelection) + .then(_react(fig('main b', 'selection b'))) + .then(checkNoSelection) + .catch(failTest) + .then(done); + }); +}); From 86b90d4e00ca98d2e0aa7d689d561548c258c7ff Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Sat, 10 Nov 2018 08:39:12 -0500 Subject: [PATCH 14/33] remove `apply` arg from _storeDirectGUIEdit --- src/plot_api/plot_api.js | 11 +++++------ src/plots/gl2d/scene2d.js | 16 +++++++++++++--- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index b26724e7069..c8394ca8095 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1438,22 +1438,21 @@ function storeCurrent(attr, val, newVal, preGUI) { } } -/* +/** * storeDirectGUIEdit: for routines that skip restyle/relayout and mock it * by emitting a plotly_restyle or plotly_relayout event, this routine - * applies the changes to the input objects and keeps track of the initial state - * in _preGUI for use by uirevision + * keeps track of the initial state in _preGUI for use by uirevision + * Does *not* apply these changes to data/layout - that's the responsibility + * of the calling routine. * * @param {object} container: the input attributes container (eg `layout` or a `trace`) * @param {object} fullContainer: the full partner to `container` * @param {object} edits: the {attr: val} object as normally passed to `relayout` etc - * @param {boolean} apply: should we apply these changes to the input object? */ -exports._storeDirectGUIEdit = function(container, preGUI, edits, apply) { +exports._storeDirectGUIEdit = function(container, preGUI, edits) { for(var attr in edits) { var np = nestedProperty(container, attr); storeCurrent(attr, np.get(), edits[attr], preGUI); - if(apply) np.set(edits[attr]); } }; diff --git a/src/plots/gl2d/scene2d.js b/src/plots/gl2d/scene2d.js index d406125e4bf..6e9a2753cdb 100644 --- a/src/plots/gl2d/scene2d.js +++ b/src/plots/gl2d/scene2d.js @@ -316,15 +316,25 @@ proto.relayoutCallback = function() { var graphDiv = this.graphDiv; var xaxis = this.xaxis; var yaxis = this.yaxis; + var layout = graphDiv.layout; // make a meaningful value to be passed on to possible 'plotly_relayout' subscriber(s) var update = {}; - update[xaxis._name + '.range'] = xaxis.range.slice(); - update[yaxis._name + '.range'] = yaxis.range.slice(); + var xrange = update[xaxis._name + '.range'] = xaxis.range.slice(); + var yrange = update[yaxis._name + '.range'] = yaxis.range.slice(); update[xaxis._name + '.autorange'] = xaxis.autorange; update[yaxis._name + '.autorange'] = yaxis.autorange; - Registry.call('_storeDirectGUIEdit', graphDiv.layout, graphDiv._fullLayout._preGUI, update, true); + Registry.call('_storeDirectGUIEdit', graphDiv.layout, graphDiv._fullLayout._preGUI, update); + + // update the input layout + var xaIn = layout[xaxis._name]; + xaIn.range = xrange; + xaIn.autorange = xaxis.autorange; + + var yaIn = layout[yaxis._name]; + yaIn.range = yrange; + yaIn.autorange = yaxis.autorange; // lastInputTime helps determine which one is the latest input (if async) update.lastInputTime = this.camera.lastInputTime; From 502082f0414e1025a41a1503575aef6f4f4b7405 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Sat, 10 Nov 2018 15:57:23 -0500 Subject: [PATCH 15/33] :palm_tree: uirevision tests --- test/jasmine/tests/plot_api_react_test.js | 137 +++++++++------------- 1 file changed, 53 insertions(+), 84 deletions(-) diff --git a/test/jasmine/tests/plot_api_react_test.js b/test/jasmine/tests/plot_api_react_test.js index 242d343ed33..ede0c311ce0 100644 --- a/test/jasmine/tests/plot_api_react_test.js +++ b/test/jasmine/tests/plot_api_react_test.js @@ -1069,17 +1069,23 @@ describe('Plotly.react and uirevision attributes', function() { .then(done); }); - it('controls trace and pie label visibility from legend.uirevision', function(done) { - function checkVisible(traces, hiddenlabels, msg) { - return checkState( - traces.map(function(v) { - return {visible: v ? [undefined, true] : 'legendonly'}; - }), - {hiddenlabels: hiddenlabels}, - msg - ); - } + function _run(figFn, editFn, checkInitial, checkEdited, done) { + // figFn should take 2 args (main uirevision and partial uirevision) + // and return a figure {data, layout} + // editFn, checkInitial, checkEdited are functions of no args + Plotly.newPlot(gd, figFn('main a', 'part a')) + .then(checkInitial) + .then(editFn) + .then(checkEdited) + .then(_react(figFn('main b', 'part a'))) + .then(checkEdited) + .then(_react(figFn('main b', 'part b'))) + .then(checkInitial) + .catch(failTest) + .then(done); + } + it('controls trace and pie label visibility from legend.uirevision', function(done) { function fig(mainRev, legendRev) { return { data: [ @@ -1094,42 +1100,34 @@ describe('Plotly.react and uirevision attributes', function() { }; } - Plotly.newPlot(gd, fig('main a', 'legend a')) - .then(checkVisible([true, true], undefined, 'initial')) - .then(function() { + function hideSome() { return Registry.call('_guiUpdate', gd, {visible: 'legendonly'}, {hiddenlabels: ['b', 'c']}, [0] ); - }) + } + + function checkVisible(traces, hiddenlabels) { + return checkState( + traces.map(function(v) { + return {visible: v ? [undefined, true] : 'legendonly'}; + }), + {hiddenlabels: hiddenlabels} + ); + } + var checkAllVisible = checkVisible([true, true], undefined); // wrap [b, c] in another array to distinguish it from // [layout, fullLayout] - .then(checkVisible([false, true], [['b', 'c']], 'gui')) - .then(_react(fig('main b', 'legend a'))) - .then(checkVisible([false, true], [['b', 'c']], 'change main rev')) - .then(_react(fig('main b', 'legend b'))) - .then(checkVisible([true, true], undefined, 'change legend rev')) - .catch(failTest) - .then(done); + var checkSomeHidden = checkVisible([false, true], [['b', 'c']]); + + _run(fig, hideSome, checkAllVisible, checkSomeHidden, done); }); it('preserves groupby group visibility', function(done) { // TODO: there's a known problem if the groups change... unlike // traces we will keep visibility by group in order, not by group value - function checkVisible(groups, extraTrace) { - var trace0edits = {}; - groups.forEach(function(visi, i) { - var attr = 'transforms[0].styles[' + i + '].value.visible'; - trace0edits[attr] = visi ? undefined : 'legendonly'; - }); - return checkState([ - trace0edits, - {visible: extraTrace ? [undefined, true] : 'legendonly'} - ]); - } - function fig(mainRev, legendRev) { return { data: [{ @@ -1148,9 +1146,7 @@ describe('Plotly.react and uirevision attributes', function() { }; } - Plotly.newPlot(gd, fig('main a', 'legend a')) - .then(checkVisible([true, true, true], true)) - .then(function() { + function hideSome() { return Registry.call('_guiRestyle', gd, { 'transforms[0].styles[0].value.visible': 'legendonly', 'transforms[0].styles[2].value.visible': 'legendonly' @@ -1158,14 +1154,23 @@ describe('Plotly.react and uirevision attributes', function() { .then(function() { return Registry.call('_guiRestyle', gd, 'visible', 'legendonly', [1]); }); - }) - .then(checkVisible([false, true, false], false)) - .then(_react(fig('main b', 'legend a'))) - .then(checkVisible([false, true, false], false)) - .then(_react(fig('main b', 'legend b'))) - .then(checkVisible([true, true, true], true)) - .catch(failTest) - .then(done); + } + + function checkVisible(groups, extraTrace) { + var trace0edits = {}; + groups.forEach(function(visi, i) { + var attr = 'transforms[0].styles[' + i + '].value.visible'; + trace0edits[attr] = visi ? undefined : 'legendonly'; + }); + return checkState([ + trace0edits, + {visible: extraTrace ? [undefined, true] : 'legendonly'} + ]); + } + var checkAllVisible = checkVisible([true, true, true], true); + var checkSomeHidden = checkVisible([false, true, false], false); + + _run(fig, hideSome, checkAllVisible, checkSomeHidden, done); }); it('@gl preserves modebar interactions using modebar.uirevision', function(done) { @@ -1225,16 +1230,7 @@ describe('Plotly.react and uirevision attributes', function() { var checkOriginalModes = _checkModes(true); var checkEditedModes = _checkModes(false); - Plotly.newPlot(gd, fig('main a', 'modebar a')) - .then(checkOriginalModes) - .then(editModes) - .then(checkEditedModes) - .then(_react(fig('main b', 'modebar a'))) - .then(checkEditedModes) - .then(_react(fig('main b', 'modebar b'))) - .then(checkOriginalModes) - .catch(failTest) - .then(done); + _run(fig, editModes, checkOriginalModes, checkEditedModes, done); }); it('preserves geo viewport changes using geo.uirevision', function(done) { @@ -1270,16 +1266,7 @@ describe('Plotly.react and uirevision attributes', function() { var checkOriginalView = _checkView(true); var checkEditedView = _checkView(false); - Plotly.newPlot(gd, fig('main a', 'geo a')) - .then(checkOriginalView) - .then(editView) - .then(checkEditedView) - .then(_react(fig('main b', 'geo a'))) - .then(checkEditedView) - .then(_react(fig('main b', 'geo b'))) - .then(checkOriginalView) - .catch(failTest) - .then(done); + _run(fig, editView, checkOriginalView, checkEditedView, done); }); it('@gl preserves 3d camera changes using scene.uirevision', function(done) { @@ -1319,16 +1306,7 @@ describe('Plotly.react and uirevision attributes', function() { var checkOriginalCamera = _checkCamera(true); var checkEditedCamera = _checkCamera(false); - Plotly.newPlot(gd, fig('main a', 'scene a')) - .then(checkOriginalCamera) - .then(editCamera) - .then(checkEditedCamera) - .then(_react(fig('main b', 'scene a'))) - .then(checkEditedCamera) - .then(_react(fig('main b', 'scene b'))) - .then(checkOriginalCamera) - .catch(failTest) - .then(done); + _run(fig, editCamera, checkOriginalCamera, checkEditedCamera, done); }); it('preserves selectedpoints using selectionrevision', function(done) { @@ -1362,15 +1340,6 @@ describe('Plotly.react and uirevision attributes', function() { {selectedpoints: [[2]]} ]); - Plotly.newPlot(gd, fig('main a', 'selection a')) - .then(checkNoSelection) - .then(editSelection) - .then(checkSelection) - .then(_react(fig('main b', 'selection a'))) - .then(checkSelection) - .then(_react(fig('main b', 'selection b'))) - .then(checkNoSelection) - .catch(failTest) - .then(done); + _run(fig, editSelection, checkNoSelection, checkSelection, done); }); }); From 5182f6a7032e9ecf544783760f25ecf8c431f5e2 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Sat, 10 Nov 2018 16:37:12 -0500 Subject: [PATCH 16/33] fix and :lock: polar uirevisions --- src/plot_api/plot_api.js | 4 +- test/jasmine/tests/plot_api_react_test.js | 68 +++++++++++++++++++---- 2 files changed, 61 insertions(+), 11 deletions(-) diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index c8394ca8095..36a175e27fe 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -2375,7 +2375,9 @@ var layoutUIControlPatterns = [ {pattern: /^(scene\d*)\.camera/}, {pattern: /^(geo\d*)\.(projection|center)/}, {pattern: /^(ternary\d*\.[abc]axis)\.(min|title)$/}, - {pattern: /^(polar\d*\.(radial|angular)axis)\./}, + {pattern: /^(polar\d*\.radialaxis)\.(auto)?range/, autofill: true}, + {pattern: /^(polar\d*\.radialaxis)\.angle/}, + {pattern: /^(polar\d*\.angularaxis)\.rotation/}, {pattern: /^(mapbox\d*)\.(center|zoom|bearing|pitch)/}, {pattern: /^legend\.(x|y)$/, attr: 'editrevision'}, diff --git a/test/jasmine/tests/plot_api_react_test.js b/test/jasmine/tests/plot_api_react_test.js index ede0c311ce0..ea221d5060a 100644 --- a/test/jasmine/tests/plot_api_react_test.js +++ b/test/jasmine/tests/plot_api_react_test.js @@ -1069,11 +1069,11 @@ describe('Plotly.react and uirevision attributes', function() { .then(done); }); - function _run(figFn, editFn, checkInitial, checkEdited, done) { + function _run(figFn, editFn, checkInitial, checkEdited) { // figFn should take 2 args (main uirevision and partial uirevision) // and return a figure {data, layout} // editFn, checkInitial, checkEdited are functions of no args - Plotly.newPlot(gd, figFn('main a', 'part a')) + return Plotly.newPlot(gd, figFn('main a', 'part a')) .then(checkInitial) .then(editFn) .then(checkEdited) @@ -1081,8 +1081,7 @@ describe('Plotly.react and uirevision attributes', function() { .then(checkEdited) .then(_react(figFn('main b', 'part b'))) .then(checkInitial) - .catch(failTest) - .then(done); + .catch(failTest); } it('controls trace and pie label visibility from legend.uirevision', function(done) { @@ -1121,7 +1120,7 @@ describe('Plotly.react and uirevision attributes', function() { // [layout, fullLayout] var checkSomeHidden = checkVisible([false, true], [['b', 'c']]); - _run(fig, hideSome, checkAllVisible, checkSomeHidden, done); + _run(fig, hideSome, checkAllVisible, checkSomeHidden).then(done); }); it('preserves groupby group visibility', function(done) { @@ -1170,7 +1169,7 @@ describe('Plotly.react and uirevision attributes', function() { var checkAllVisible = checkVisible([true, true, true], true); var checkSomeHidden = checkVisible([false, true, false], false); - _run(fig, hideSome, checkAllVisible, checkSomeHidden, done); + _run(fig, hideSome, checkAllVisible, checkSomeHidden).then(done); }); it('@gl preserves modebar interactions using modebar.uirevision', function(done) { @@ -1230,7 +1229,7 @@ describe('Plotly.react and uirevision attributes', function() { var checkOriginalModes = _checkModes(true); var checkEditedModes = _checkModes(false); - _run(fig, editModes, checkOriginalModes, checkEditedModes, done); + _run(fig, editModes, checkOriginalModes, checkEditedModes).then(done); }); it('preserves geo viewport changes using geo.uirevision', function(done) { @@ -1266,7 +1265,7 @@ describe('Plotly.react and uirevision attributes', function() { var checkOriginalView = _checkView(true); var checkEditedView = _checkView(false); - _run(fig, editView, checkOriginalView, checkEditedView, done); + _run(fig, editView, checkOriginalView, checkEditedView).then(done); }); it('@gl preserves 3d camera changes using scene.uirevision', function(done) { @@ -1306,7 +1305,7 @@ describe('Plotly.react and uirevision attributes', function() { var checkOriginalCamera = _checkCamera(true); var checkEditedCamera = _checkCamera(false); - _run(fig, editCamera, checkOriginalCamera, checkEditedCamera, done); + _run(fig, editCamera, checkOriginalCamera, checkEditedCamera).then(done); }); it('preserves selectedpoints using selectionrevision', function(done) { @@ -1340,6 +1339,55 @@ describe('Plotly.react and uirevision attributes', function() { {selectedpoints: [[2]]} ]); - _run(fig, editSelection, checkNoSelection, checkSelection, done); + _run(fig, editSelection, checkNoSelection, checkSelection).then(done); + }); + + it('preserves polar view changes using polar.uirevision', function(done) { + // polar you can control either at the subplot or the axis level + function fig(mainRev, polarRev) { + return { + data: [{r: [1, 2], theta: [1, 2], type: 'scatterpolar', mode: 'lines'}], + layout: { + uirevision: mainRev, + polar: {uirevision: polarRev} + } + }; + } + + function fig2(mainRev, polarRev) { + return { + data: [{r: [1, 2], theta: [1, 2], type: 'scatterpolar', mode: 'lines'}], + layout: { + uirevision: mainRev, + polar: { + angularaxis: {uirevision: polarRev}, + radialaxis: {uirevision: polarRev} + } + } + }; + } + + function editPolar() { + return Registry.call('_guiRelayout', gd, { + 'polar.radialaxis.range': [-2, 4], + 'polar.radialaxis.angle': 45, + 'polar.angularaxis.rotation': -90 + }); + } + + function checkPolar(original) { + return checkState([], { + 'polar.radialaxis.range[0]': original ? 0 : -2, + 'polar.radialaxis.range[1]': original ? 2 : 4, + 'polar.radialaxis.angle': original ? [undefined, 0] : 45, + 'polar.angularaxis.rotation': original ? [undefined, 0] : -90 + }); + } + + _run(fig, editPolar, checkPolar(true), checkPolar()) + .then(function() { + return _run(fig2, editPolar, checkPolar(true), checkPolar()); + }) + .then(done); }); }); From 89dde84b65c4bf8279da2f519e492822080c0e5b Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Sat, 10 Nov 2018 16:47:53 -0500 Subject: [PATCH 17/33] :lock: ternary uirevisions --- test/jasmine/tests/plot_api_react_test.js | 48 +++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/test/jasmine/tests/plot_api_react_test.js b/test/jasmine/tests/plot_api_react_test.js index ea221d5060a..9b577a033b4 100644 --- a/test/jasmine/tests/plot_api_react_test.js +++ b/test/jasmine/tests/plot_api_react_test.js @@ -1390,4 +1390,52 @@ describe('Plotly.react and uirevision attributes', function() { }) .then(done); }); + + it('preserves ternary view changes using ternary.uirevision', function(done) { + function fig(mainRev, ternaryRev) { + return { + data: [{a: [1, 2, 3], b: [2, 3, 1], c: [3, 1, 2], type: 'scatterternary'}], + layout: { + uirevision: mainRev, + ternary: {uirevision: ternaryRev} + } + }; + } + + function fig2(mainRev, ternaryRev) { + return { + data: [{a: [1, 2, 3], b: [2, 3, 1], c: [3, 1, 2], type: 'scatterternary'}], + layout: { + uirevision: mainRev, + ternary: { + aaxis: {uirevision: ternaryRev}, + baxis: {uirevision: ternaryRev}, + caxis: {uirevision: ternaryRev} + } + } + }; + } + + function editTernary() { + return Registry.call('_guiRelayout', gd, { + 'ternary.aaxis.min': 0.1, + 'ternary.baxis.min': 0.2, + 'ternary.caxis.min': 0.3 + }); + } + + function checkTernary(original) { + return checkState([], { + 'ternary.aaxis.min': original ? [undefined, 0] : 0.1, + 'ternary.baxis.min': original ? [undefined, 0] : 0.2, + 'ternary.caxis.min': original ? [undefined, 0] : 0.3, + }); + } + + _run(fig, editTernary, checkTernary(true), checkTernary()) + .then(function() { + return _run(fig2, editTernary, checkTernary(true), checkTernary()); + }) + .then(done); + }); }); From 778ec15926f7c89019e4f84fbdbc698c03cd56d4 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Sat, 10 Nov 2018 18:36:07 -0500 Subject: [PATCH 18/33] fix and :lock: mapbox uirevisions --- src/plots/mapbox/mapbox.js | 22 ++++++------ test/jasmine/tests/plot_api_react_test.js | 42 ++++++++++++++++++++++- 2 files changed, 52 insertions(+), 12 deletions(-) diff --git a/src/plots/mapbox/mapbox.js b/src/plots/mapbox/mapbox.js index f3b745cacdd..f1ddfdb01dc 100644 --- a/src/plots/mapbox/mapbox.js +++ b/src/plots/mapbox/mapbox.js @@ -138,22 +138,22 @@ proto.createMap = function(calcData, fullLayout, resolve, reject) { map.on('moveend', function(eventData) { if(!self.map) return; - var view = self.getView(); - - opts._input.center = opts.center = view.center; - opts._input.zoom = opts.zoom = view.zoom; - opts._input.bearing = opts.bearing = view.bearing; - opts._input.pitch = opts.pitch = view.pitch; - // 'moveend' gets triggered by map.setCenter, map.setZoom, // map.setBearing and map.setPitch. // - // Here, we make sure that 'plotly_relayout' is - // triggered here only when the 'moveend' originates from a + // Here, we make sure that state updates amd 'plotly_relayout' + // are triggered only when the 'moveend' originates from a // mouse target (filtering out API calls) to not // duplicate 'plotly_relayout' events. if(eventData.originalEvent || wheeling) { + var view = self.getView(); + + opts._input.center = opts.center = view.center; + opts._input.zoom = opts.zoom = view.zoom; + opts._input.bearing = opts.bearing = view.bearing; + opts._input.pitch = opts.pitch = view.pitch; + emitRelayoutFromView(view); } wheeling = false; @@ -308,8 +308,8 @@ proto.updateData = function(calcData) { }; proto.updateLayout = function(fullLayout) { - var map = this.map, - opts = this.opts; + var map = this.map; + var opts = this.opts; map.setCenter(convertCenter(opts.center)); map.setZoom(opts.zoom); diff --git a/test/jasmine/tests/plot_api_react_test.js b/test/jasmine/tests/plot_api_react_test.js index 9b577a033b4..00a869d5613 100644 --- a/test/jasmine/tests/plot_api_react_test.js +++ b/test/jasmine/tests/plot_api_react_test.js @@ -15,6 +15,8 @@ var supplyAllDefaults = require('../assets/supply_defaults'); var mockLists = require('../assets/mock_lists'); var drag = require('../assets/drag'); +var MAPBOX_ACCESS_TOKEN = require('@build/credentials.json').MAPBOX_ACCESS_TOKEN; + describe('@noCIdep Plotly.react', function() { var mockedMethods = [ 'doTraceStyle', @@ -835,7 +837,7 @@ describe('@noCIdep Plotly.react', function() { mockLists.mapbox.forEach(function(mockSpec) { it('@noCI can redraw "' + mockSpec[0] + '" with no changes as a noop (mapbpox mocks)', function(done) { Plotly.setPlotConfig({ - mapboxAccessToken: require('@build/credentials.json').MAPBOX_ACCESS_TOKEN + mapboxAccessToken: MAPBOX_ACCESS_TOKEN }); _runReactMock(mockSpec, done); }); @@ -1438,4 +1440,42 @@ describe('Plotly.react and uirevision attributes', function() { }) .then(done); }); + + it('@gl preserves mapbox view changes using mapbox.uirevision', function(done) { + function fig(mainRev, mapboxRev) { + return { + data: [{lat: [1, 2], lon: [1, 2], type: 'scattermapbox'}], + layout: { + uirevision: mainRev, + mapbox: {uirevision: mapboxRev} + } + }; + } + + function editMap() { + return Registry.call('_guiRelayout', gd, { + 'mapbox.center.lat': 1, + 'mapbox.center.lon': 2, + 'mapbox.zoom': 3, + 'mapbox.bearing': 4, + 'mapbox.pitch': 5 + }); + } + + function checkMapbox(original) { + return checkState([], { + 'mapbox.center.lat': original ? [undefined, 0] : 1, + 'mapbox.center.lon': original ? [undefined, 0] : 2, + 'mapbox.zoom': original ? [undefined, 1] : 3, + 'mapbox.bearing': original ? [undefined, 0] : 4, + 'mapbox.pitch': original ? [undefined, 0] : 5 + }); + } + + Plotly.setPlotConfig({ + mapboxAccessToken: MAPBOX_ACCESS_TOKEN + }); + + _run(fig, editMap, checkMapbox(true), checkMapbox()).then(done); + }); }); From 21f5db55cc880c5a8199b281cc58040c7e11eb02 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Sat, 10 Nov 2018 20:34:35 -0500 Subject: [PATCH 19/33] fix and :lock: editable shapes & annotations uirevision --- src/plot_api/manage_arrays.js | 15 +++++--- src/plot_api/plot_api.js | 47 ++++++++++++----------- test/jasmine/tests/plot_api_react_test.js | 39 +++++++++++++++++++ 3 files changed, 73 insertions(+), 28 deletions(-) diff --git a/src/plot_api/manage_arrays.js b/src/plot_api/manage_arrays.js index 6c84a5b1c67..99def8f1508 100644 --- a/src/plot_api/manage_arrays.js +++ b/src/plot_api/manage_arrays.js @@ -9,7 +9,6 @@ 'use strict'; -var nestedProperty = require('../lib/nested_property'); var isPlainObject = require('../lib/is_plain_object'); var noop = require('../lib/noop'); var Loggers = require('../lib/loggers'); @@ -66,11 +65,15 @@ var isRemoveVal = exports.isRemoveVal = function isRemoveVal(val) { * the flags for which actions we're going to perform to display these (and * any other) changes. If we're already `recalc`ing, we don't need to redraw * individual items + * @param {function} _nestedProperty + * a (possibly modified for gui edits) nestedProperty constructor + * The modified version takes a 3rd argument, for a prefix to the attribute + * string necessary for storing GUI edits * * @returns {bool} `true` if it managed to complete drawing of the changes * `false` would mean the parent should replot. */ -exports.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { +exports.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags, _nestedProperty) { var componentType = np.astr, supplyComponentDefaults = Registry.getComponentMethod(componentType, 'supplyLayoutDefaults'), draw = Registry.getComponentMethod(componentType, 'draw'), @@ -110,7 +113,7 @@ exports.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, // redoing supplyDefaults // TODO: this assumes componentArray is in gd.layout - which will not be // true after we extend this to restyle - componentArrayFull = nestedProperty(fullLayout, componentType).get(); + componentArrayFull = _nestedProperty(fullLayout, componentType).get(); var deletes = [], firstIndexChange = -1, @@ -121,7 +124,7 @@ exports.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, objEdits, objKeys, objVal, - adding; + adding, prefix; // first make the add and edit changes for(i = 0; i < componentNums.length; i++) { @@ -160,7 +163,9 @@ exports.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, } else { for(j = 0; j < objKeys.length; j++) { - nestedProperty(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); + prefix = componentType + '[' + componentNum + '].'; + _nestedProperty(componentArray[componentNum], objKeys[j], prefix) + .set(objEdits[objKeys[j]]); } } } diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 36a175e27fe..8f9e9f210e4 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1396,24 +1396,23 @@ function undefinedToNull(val) { } /** - * modified Lib.nestedProperty to also record GUI edits + * Factory function to wrap nestedProperty with GUI edits if necessary + * with GUI edits we add an optional prefix to the nestedProperty constructor + * to prepend to the attribute string in the preGUI store. */ -function npWithGuiEdits(container, attr, preGUI, guiEditFlag) { - var np = nestedProperty(container, attr); +function makeNP(preGUI, guiEditFlag) { + if(!guiEditFlag) return nestedProperty; - var npSet = np.set; - function setWithGuiEdits(val) { - // preGUI is not nested, it's flat with attribute strings - // flatten it the rest of the way, even if currentVal is nested - storeCurrent(attr, np.get(), val, preGUI); - npSet(val); - } - - if(guiEditFlag) { - np.set = setWithGuiEdits; - } - - return np; + return function(container, attr, prefix) { + var np = nestedProperty(container, attr); + var npSet = np.set; + np.set = function(val) { + var fullAttr = (prefix || '') + attr; + storeCurrent(fullAttr, np.get(), val, preGUI); + npSet(val); + }; + return np; + }; } function storeCurrent(attr, val, newVal, preGUI) { @@ -1461,6 +1460,7 @@ function _restyle(gd, aobj, traces) { var fullData = gd._fullData; var data = gd.data; var guiEditFlag = fullLayout._guiEditing; + var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag); var i; // initialize flags @@ -1510,11 +1510,11 @@ function _restyle(gd, aobj, traces) { var extraparam; if(attr.substr(0, 6) === 'LAYOUT') { - extraparam = npWithGuiEdits(gd.layout, attr.replace('LAYOUT', ''), fullLayout._preGUI, guiEditFlag); + extraparam = layoutNP(gd.layout, attr.replace('LAYOUT', '')); } else { var tracei = traces[i]; var preGUI = fullLayout._tracePreGUI[getFullTrace(tracei)._fullInput.uid]; - extraparam = npWithGuiEdits(data[tracei], attr, preGUI, guiEditFlag); + extraparam = makeNP(preGUI, guiEditFlag)(data[tracei], attr); } if(!(attr in undoit)) { @@ -1569,7 +1569,7 @@ function _restyle(gd, aobj, traces) { redoit[ai] = vi; if(ai.substr(0, 6) === 'LAYOUT') { - param = npWithGuiEdits(gd.layout, ai.replace('LAYOUT', ''), fullLayout._preGUI, guiEditFlag); + param = layoutNP(gd.layout, ai.replace('LAYOUT', '')); undoit[ai] = [undefinedToNull(param.get())]; // since we're allowing val to be an array, allow it here too, // even though that's meaningless @@ -1586,7 +1586,7 @@ function _restyle(gd, aobj, traces) { cont = data[traces[i]]; contFull = getFullTrace(traces[i]); var preGUI = fullLayout._tracePreGUI[contFull._fullInput.uid]; - param = npWithGuiEdits(cont, ai, preGUI, guiEditFlag); + param = makeNP(preGUI, guiEditFlag)(cont, ai); oldVal = param.get(); newVal = Array.isArray(vi) ? vi[i % vi.length] : vi; @@ -1896,6 +1896,7 @@ function _relayout(gd, aobj) { var layout = gd.layout; var fullLayout = gd._fullLayout; var guiEditFlag = fullLayout._guiEditing; + var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag); var keys = Object.keys(aobj); var axes = Axes.list(gd); var arrayEdits = {}; @@ -1940,7 +1941,7 @@ function _relayout(gd, aobj) { // via a parent) do not override with this auto-generated extra if(attr in aobj || helpers.hasParent(aobj, attr)) return; - var p = npWithGuiEdits(layout, attr, fullLayout._preGUI, guiEditFlag); + var p = layoutNP(layout, attr); if(!(attr in undoit)) { undoit[attr] = undefinedToNull(p.get()); } @@ -1965,7 +1966,7 @@ function _relayout(gd, aobj) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } - var p = npWithGuiEdits(layout, ai, fullLayout._preGUI, guiEditFlag); + var p = layoutNP(layout, ai); var vi = aobj[ai]; var plen = p.parts.length; // p.parts may end with an index integer if the property is an array @@ -2183,7 +2184,7 @@ function _relayout(gd, aobj) { // now we've collected component edits - execute them all together for(arrayStr in arrayEdits) { var finished = manageArrays.applyContainerArrayChanges(gd, - nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); + layoutNP(layout, arrayStr), arrayEdits[arrayStr], flags, layoutNP); if(!finished) flags.plot = true; } diff --git a/test/jasmine/tests/plot_api_react_test.js b/test/jasmine/tests/plot_api_react_test.js index 00a869d5613..614087f172f 100644 --- a/test/jasmine/tests/plot_api_react_test.js +++ b/test/jasmine/tests/plot_api_react_test.js @@ -1478,4 +1478,43 @@ describe('Plotly.react and uirevision attributes', function() { _run(fig, editMap, checkMapbox(true), checkMapbox()).then(done); }); + + it('preserves editable: true shape & annotation edits using editrevision', function(done) { + function fig(mainRev, editRev) { + return {layout: { + shapes: [{x0: 0, x1: 0.5, y0: 0, y1: 0.5}], + annotations: [ + {x: 1, y: 0, text: 'hi'}, + {x: 1, y: 1, text: 'bye', showarrow: true, ax: -20, ay: 20} + ], + xaxis: {range: [0, 1]}, + yaxis: {range: [0, 1]}, + uirevision: mainRev, + editrevision: editRev + }}; + } + + function attrs(original) { + return { + 'shapes[0].x0': original ? 0 : 0.1, + 'shapes[0].x1': original ? 0.5 : 0.2, + 'shapes[0].y0': original ? 0 : 0.3, + 'shapes[0].y1': original ? 0.5 : 0.4, + 'annotations[1].x': original ? 1 : 0.5, + 'annotations[1].y': original ? 1 : 0.6, + 'annotations[1].ax': original ? -20 : -30, + 'annotations[1].ay': original ? 20 : 30, + 'annotations[1].text': original ? 'bye' : 'buy' + }; + } + + function editComponents() { + return Registry.call('_guiRelayout', gd, attrs()); + } + + var checkInitial = checkState([], attrs(true)); + var checkEdited = checkState([], attrs()); + + _run(fig, editComponents, checkInitial, checkEdited).then(done); + }); }); From 8f0f075dda8297baf3c2990a9b2ebf2515834cce Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Sat, 10 Nov 2018 20:47:11 -0500 Subject: [PATCH 20/33] :palm_tree: uirevision tests --- test/jasmine/tests/plot_api_react_test.js | 128 ++++++++++------------ 1 file changed, 55 insertions(+), 73 deletions(-) diff --git a/test/jasmine/tests/plot_api_react_test.js b/test/jasmine/tests/plot_api_react_test.js index 614087f172f..8dd65e39e3e 100644 --- a/test/jasmine/tests/plot_api_react_test.js +++ b/test/jasmine/tests/plot_api_react_test.js @@ -1197,26 +1197,12 @@ describe('Plotly.react and uirevision attributes', function() { }; } - function editModes() { - return Registry.call('_guiRelayout', gd, { - dragmode: 'pan', - hovermode: false, - 'xaxis.showspikes': false, - 'yaxis.showspikes': false, - 'scene.dragmode': 'pan', - 'scene.hovermode': false, - 'scene.xaxis.showspikes': false, - 'scene.yaxis.showspikes': false, - 'scene.zaxis.showspikes': false - }); - } - - function _checkModes(original) { + function attrs(original) { var dragmode = original ? 'zoom' : 'pan'; var hovermode = original ? 'closest' : false; var spikes = original ? true : false; var spikes3D = original ? [undefined, true] : false; - return checkState([], { + return { dragmode: dragmode, hovermode: hovermode, 'xaxis.showspikes': spikes, @@ -1226,10 +1212,15 @@ describe('Plotly.react and uirevision attributes', function() { 'scene.xaxis.showspikes': spikes3D, 'scene.yaxis.showspikes': spikes3D, 'scene.zaxis.showspikes': spikes3D - }); + }; } - var checkOriginalModes = _checkModes(true); - var checkEditedModes = _checkModes(false); + + function editModes() { + return Registry.call('_guiRelayout', gd, attrs()); + } + + var checkOriginalModes = checkState([], attrs(true)); + var checkEditedModes = checkState([], attrs()); _run(fig, editModes, checkOriginalModes, checkEditedModes).then(done); }); @@ -1247,25 +1238,21 @@ describe('Plotly.react and uirevision attributes', function() { }; } - function editView() { - return Registry.call('_guiRelayout', gd, { - 'geo.projection.scale': 3, - 'geo.projection.rotation.lon': -45, - 'geo.center.lat': 22, - 'geo.center.lon': -45 - }); - } - - function _checkView(original) { - return checkState([], { + function attrs(original) { + return { 'geo.projection.scale': original ? [undefined, 1] : 3, 'geo.projection.rotation.lon': original ? [undefined, 0] : -45, 'geo.center.lat': original ? [undefined, 0] : 22, 'geo.center.lon': original ? [undefined, 0] : -45 - }); + }; + } + + function editView() { + return Registry.call('_guiRelayout', gd, attrs()); } - var checkOriginalView = _checkView(true); - var checkEditedView = _checkView(false); + + var checkOriginalView = checkState([], attrs(true)); + var checkEditedView = checkState([], attrs()); _run(fig, editView, checkOriginalView, checkEditedView).then(done); }); @@ -1369,26 +1356,25 @@ describe('Plotly.react and uirevision attributes', function() { }; } - function editPolar() { - return Registry.call('_guiRelayout', gd, { - 'polar.radialaxis.range': [-2, 4], - 'polar.radialaxis.angle': 45, - 'polar.angularaxis.rotation': -90 - }); - } - - function checkPolar(original) { - return checkState([], { + function attrs(original) { + return { 'polar.radialaxis.range[0]': original ? 0 : -2, 'polar.radialaxis.range[1]': original ? 2 : 4, 'polar.radialaxis.angle': original ? [undefined, 0] : 45, 'polar.angularaxis.rotation': original ? [undefined, 0] : -90 - }); + }; } - _run(fig, editPolar, checkPolar(true), checkPolar()) + function editPolar() { + return Registry.call('_guiRelayout', gd, attrs()); + } + + var checkInitial = checkState([], attrs(true)); + var checkEdited = checkState([], attrs()); + + _run(fig, editPolar, checkInitial, checkEdited) .then(function() { - return _run(fig2, editPolar, checkPolar(true), checkPolar()); + return _run(fig2, editPolar, checkInitial, checkEdited); }) .then(done); }); @@ -1418,25 +1404,24 @@ describe('Plotly.react and uirevision attributes', function() { }; } - function editTernary() { - return Registry.call('_guiRelayout', gd, { - 'ternary.aaxis.min': 0.1, - 'ternary.baxis.min': 0.2, - 'ternary.caxis.min': 0.3 - }); - } - - function checkTernary(original) { - return checkState([], { + function attrs(original) { + return { 'ternary.aaxis.min': original ? [undefined, 0] : 0.1, 'ternary.baxis.min': original ? [undefined, 0] : 0.2, 'ternary.caxis.min': original ? [undefined, 0] : 0.3, - }); + }; + } + + function editTernary() { + return Registry.call('_guiRelayout', gd, attrs()); } - _run(fig, editTernary, checkTernary(true), checkTernary()) + var checkInitial = checkState([], attrs(true)); + var checkEdited = checkState([], attrs()); + + _run(fig, editTernary, checkInitial, checkEdited) .then(function() { - return _run(fig2, editTernary, checkTernary(true), checkTernary()); + return _run(fig2, editTernary, checkInitial, checkEdited); }) .then(done); }); @@ -1452,31 +1437,28 @@ describe('Plotly.react and uirevision attributes', function() { }; } - function editMap() { - return Registry.call('_guiRelayout', gd, { - 'mapbox.center.lat': 1, - 'mapbox.center.lon': 2, - 'mapbox.zoom': 3, - 'mapbox.bearing': 4, - 'mapbox.pitch': 5 - }); - } - - function checkMapbox(original) { - return checkState([], { + function attrs(original) { + return { 'mapbox.center.lat': original ? [undefined, 0] : 1, 'mapbox.center.lon': original ? [undefined, 0] : 2, 'mapbox.zoom': original ? [undefined, 1] : 3, 'mapbox.bearing': original ? [undefined, 0] : 4, 'mapbox.pitch': original ? [undefined, 0] : 5 - }); + }; + } + + function editMap() { + return Registry.call('_guiRelayout', gd, attrs()); } + var checkInitial = checkState([], attrs(true)); + var checkEdited = checkState([], attrs()); + Plotly.setPlotConfig({ mapboxAccessToken: MAPBOX_ACCESS_TOKEN }); - _run(fig, editMap, checkMapbox(true), checkMapbox()).then(done); + _run(fig, editMap, checkInitial, checkEdited).then(done); }); it('preserves editable: true shape & annotation edits using editrevision', function(done) { From eb728fed8bf012cc380f4b58314f6e2f78db1919 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Sat, 10 Nov 2018 23:43:40 -0500 Subject: [PATCH 21/33] fix and :lock: editable: true uirevisions --- src/plot_api/plot_api.js | 18 ++- src/traces/parcoords/plot.js | 28 ++-- test/jasmine/assets/drag.js | 7 +- test/jasmine/tests/plot_api_react_test.js | 157 +++++++++++++++++++++- 4 files changed, 188 insertions(+), 22 deletions(-) diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 8f9e9f210e4..9b40e6b7fae 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -2377,7 +2377,7 @@ var layoutUIControlPatterns = [ {pattern: /^(geo\d*)\.(projection|center)/}, {pattern: /^(ternary\d*\.[abc]axis)\.(min|title)$/}, {pattern: /^(polar\d*\.radialaxis)\.(auto)?range/, autofill: true}, - {pattern: /^(polar\d*\.radialaxis)\.angle/}, + {pattern: /^(polar\d*\.radialaxis)\.(angle|title)/}, {pattern: /^(polar\d*\.angularaxis)\.rotation/}, {pattern: /^(mapbox\d*)\.(center|zoom|bearing|pitch)/}, @@ -2449,6 +2449,18 @@ function getTraceIndexFromUid(uid, data, tracei) { return data[tracei].uid ? -1 : tracei; } +function valsMatch(v1, v2) { + var v1IsObj = Lib.isPlainObject(v1); + var v1IsArray = Array.isArray(v1); + if(v1IsObj || v1IsArray) { + return ( + (v1IsObj && Lib.isPlainObject(v2)) || + (v1IsArray && Array.isArray(v2)) + ) && JSON.stringify(v1) === JSON.stringify(v2); + } + return v1 === v2; +} + function applyUIRevisions(data, layout, oldFullData, oldFullLayout) { var layoutPreGUI = oldFullLayout._preGUI; var key, revAttr, oldRev, newRev, match, preGUIVal, newNP, newVal; @@ -2473,7 +2485,7 @@ function applyUIRevisions(data, layout, oldFullData, oldFullLayout) { // storing *that* in preGUI... oh well, for now at least I limit // this to attributes that get autofilled, which AFAICT among // the GUI-editable attributes is just axis.range/autorange. - if(newVal === preGUIVal || (match.autofill && newVal === undefined)) { + if(valsMatch(newVal, preGUIVal) || (match.autofill && newVal === undefined)) { newNP.set(nestedProperty(oldFullLayout, key).get()); continue; } @@ -2538,7 +2550,7 @@ function applyUIRevisions(data, layout, oldFullData, oldFullLayout) { if(preGUIVal === null) preGUIVal = undefined; newNP = nestedProperty(newTrace, key); newVal = newNP.get(); - if(newVal === preGUIVal || (match.autofill && newVal === undefined)) { + if(valsMatch(newVal, preGUIVal) || (match.autofill && newVal === undefined)) { newNP.set(nestedProperty(fullInput, key).get()); continue; } diff --git a/src/traces/parcoords/plot.js b/src/traces/parcoords/plot.js index 3d280905c9b..3607ec6091a 100644 --- a/src/traces/parcoords/plot.js +++ b/src/traces/parcoords/plot.js @@ -8,8 +8,6 @@ 'use strict'; -var Registry = require('../../registry'); - var parcoords = require('./parcoords'); var prepareRegl = require('../../lib/prepare_regl'); @@ -44,27 +42,33 @@ module.exports = function plot(gd, cdparcoords) { var gdDimension = gdDimensionsOriginalOrder[i][originalDimensionIndex]; var newConstraints = newRanges.map(function(r) { return r.slice(); }); + + // Store constraint range in preGUI + // This one doesn't work if it's stored in pieces in _storeDirectGUIEdit + // because it's an array of variable dimensionality. So store the whole + // thing at once manually. + var aStr = 'dimensions[' + originalDimensionIndex + '].constraintrange'; + var preGUI = fullLayout._tracePreGUI[gd._fullData[fullIndices[i]]._fullInput.uid]; + if(preGUI[aStr] === undefined) { + var initialVal = gdDimension.constraintrange; + preGUI[aStr] = initialVal || null; + } + + var fullDimension = gd._fullData[fullIndices[i]].dimensions[originalDimensionIndex]; + if(!newConstraints.length) { delete gdDimension.constraintrange; + delete fullDimension.constraintrange; newConstraints = null; } else { if(newConstraints.length === 1) newConstraints = newConstraints[0]; gdDimension.constraintrange = newConstraints; + fullDimension.constraintrange = newConstraints.slice(); // wrap in another array for restyle event data newConstraints = [newConstraints]; } - var aStr = 'dimensions[' + originalDimensionIndex + '].constraintrange'; - - var editData = {}; - editData[aStr] = newConstraints && newConstraints[0]; - Registry.call('_storeDirectGUIEdit', - gd.data[inputIndices[i]], - fullLayout._tracePreGUI[gd._fullData[fullIndices[i]]._fullInput.uid], - editData - ); - var restyleData = {}; restyleData[aStr] = newConstraints; gd.emit('plotly_restyle', [restyleData, [inputIndices[i]]]); diff --git a/test/jasmine/assets/drag.js b/test/jasmine/assets/drag.js index 10c8320ce91..1658ca9a288 100644 --- a/test/jasmine/assets/drag.js +++ b/test/jasmine/assets/drag.js @@ -7,7 +7,7 @@ var getNodeCoords = require('./get_node_coords'); * optionally specify an edge ('n', 'se', 'w' etc) * to grab it by an edge or corner (otherwise the middle is used) */ -function drag(node, dx, dy, edge, x0, y0, nsteps) { +function drag(node, dx, dy, edge, x0, y0, nsteps, noCover) { nsteps = nsteps || 1; var coords = getNodeCoords(node, edge); @@ -17,7 +17,8 @@ function drag(node, dx, dy, edge, x0, y0, nsteps) { mouseEvent('mousemove', fromX, fromY, {element: node}); mouseEvent('mousedown', fromX, fromY, {element: node}); - var promise = waitForDragCover().then(function(dragCoverNode) { + var promise = (noCover ? Promise.resolve(node) : waitForDragCover()) + .then(function(dragCoverNode) { var toX; var toY; @@ -28,7 +29,7 @@ function drag(node, dx, dy, edge, x0, y0, nsteps) { } mouseEvent('mouseup', toX, toY, {element: dragCoverNode}); - return waitForDragCoverRemoval(); + return noCover || waitForDragCoverRemoval(); }); return promise; diff --git a/test/jasmine/tests/plot_api_react_test.js b/test/jasmine/tests/plot_api_react_test.js index 8dd65e39e3e..14530e5bd2b 100644 --- a/test/jasmine/tests/plot_api_react_test.js +++ b/test/jasmine/tests/plot_api_react_test.js @@ -900,6 +900,20 @@ describe('Plotly.react and uirevision attributes', function() { afterEach(destroyGraphDiv); + function checkCloseIfArray(val1, val2, msg) { + if(Array.isArray(val1) && Array.isArray(val2)) { + if(Array.isArray(val1[0]) && Array.isArray(val2[0])) { + expect(val1).toBeCloseTo2DArray(val2, 2, msg); + } + else { + expect(val1).toBeCloseToArray(val2, 2, msg); + } + } + else { + expect(val1).toBe(val2, msg); + } + } + function checkState(dataKeys, layoutKeys, msg) { var np = Lib.nestedProperty; return function() { @@ -913,8 +927,10 @@ describe('Plotly.react and uirevision attributes', function() { var val = traceKeys[key]; var valIn = Array.isArray(val) ? val[0] : val; var valOut = Array.isArray(val) ? val[val.length - 1] : val; - expect(np(trace, key).get()).toEqual(valIn, msg + ': data[' + i + '].' + key); - expect(np(fullTrace, key).get()).toEqual(valOut, msg + ': _fullData[' + i + '].' + key); + checkCloseIfArray(np(trace, key).get(), valIn, msg + ': data[' + i + '].' + key); + checkCloseIfArray(np(fullTrace, key).get(), valOut, msg + ': _fullData[' + i + '].' + key); + checkCloseIfArray(np(trace, key).get(), valIn, msg + ': data[' + i + '].' + key); + checkCloseIfArray(np(fullTrace, key).get(), valOut, msg + ': _fullData[' + i + '].' + key); } }); @@ -922,8 +938,8 @@ describe('Plotly.react and uirevision attributes', function() { var val = layoutKeys[key]; var valIn = Array.isArray(val) ? val[0] : val; var valOut = Array.isArray(val) ? val[val.length - 1] : val; - expect(np(gd.layout, key).get()).toEqual(valIn, msg + ': layout.' + key); - expect(np(gd._fullLayout, key).get()).toEqual(valOut, msg + ': _fullLayout.' + key); + checkCloseIfArray(np(gd.layout, key).get(), valIn, msg + ': layout.' + key); + checkCloseIfArray(np(gd._fullLayout, key).get(), valOut, msg + ': _fullLayout.' + key); } }; } @@ -1499,4 +1515,137 @@ describe('Plotly.react and uirevision attributes', function() { _run(fig, editComponents, checkInitial, checkEdited).then(done); }); + + it('preserves editable: true plot title and legend & colorbar positions using editrevision', function(done) { + function fig(mainRev, editRev) { + return { + data: [{y: [1, 2]}, {y: [2, 1]}, {z: [[1, 2], [3, 4]], type: 'heatmap'}], + layout: { + uirevision: mainRev, + editrevision: editRev + }, + config: {editable: true} + }; + } + + function editEditable() { + return Registry.call('_guiUpdate', gd, + {'colorbar.x': 0.8, 'colorbar.y': 0.6}, + {title: 'yep', 'legend.x': 1.1, 'legend.y': 0.9}, + [2] + ); + } + + function checkAttrs(original) { + return checkState([{}, {}, { + 'colorbar.x': original ? [undefined, 1.02] : 0.8, + 'colorbar.y': original ? [undefined, 0.5] : 0.6 + }], { + title: original ? [undefined, 'Click to enter Plot title'] : 'yep', + 'legend.x': original ? [undefined, 1.02] : 1.1, + 'legend.y': original ? [undefined, 1] : 0.9 + }); + } + + _run(fig, editEditable, checkAttrs(true), checkAttrs).then(done); + }); + + it('preserves editable: true name, colorbar title and parcoords constraint range via trace.uirevision', function(done) { + function fig(mainRev, traceRev) { + return { + data: [{ + type: 'parcoords', + dimensions: [ + {label: 'a', values: [1, 2, 3, 5], constraintrange: [2.5, 3.5]}, + {label: 'b', values: [7, 9, 5, 6]} + ], + line: {showscale: true, color: [1, 2, 3, 4]}, + uirevision: traceRev + }], + layout: { + uirevision: mainRev, + width: 400, + height: 400, + margin: {l: 100, r: 100, t: 100, b: 100} + }, + config: {editable: true} + }; + } + + function attrs(original) { + return { + 'dimensions[0].constraintrange': original ? [[2.5, 3.5]] : [[[1.5, 2.5], [2.938, 3.979]]], + 'dimensions[1].constraintrange': original ? undefined : [[6.937, 7.979]], + 'line.colorbar.title': original ? [undefined, 'Click to enter Colorscale title'] : 'color', + name: original ? [undefined, 'trace 0'] : 'name' + }; + } + + function axisDragNode(i) { + return document.querySelectorAll('.axis-brush .background')[i]; + } + + function editTrace() { + var _; + return Registry.call('_guiRestyle', gd, + {'line.colorbar.title': 'color', name: 'name'}, + [0] + ) + .then(function() { + return drag(axisDragNode(0), 0, 50, _, _, _, _, true); + }) + .then(function() { + return drag(axisDragNode(0), 0, -50, _, _, _, _, true); + }) + .then(function() { + return drag(axisDragNode(1), 0, -50, _, _, _, _, true); + }); + } + + _run(fig, editTrace, checkState([attrs(true)]), checkState([attrs()])).then(done); + }); + + it('preserves editable: true axis titles using the axis uirevisions', function(done) { + function fig(mainRev, axRev) { + return { + data: [ + {y: [1, 2]}, + {a: [1, 2], b: [2, 1], c: [1, 1], type: 'scatterternary'}, + {r: [1, 2], theta: [1, 2], type: 'scatterpolar'} + ], + layout: { + uirevision: mainRev, + xaxis: {uirevision: axRev}, + yaxis: {uirevision: axRev}, + ternary: { + aaxis: {uirevision: axRev}, + baxis: {uirevision: axRev}, + caxis: {uirevision: axRev} + }, + polar: {radialaxis: {uirevision: axRev}} + }, + config: {editable: true} + }; + } + + function attrs(original) { + return { + 'xaxis.title': original ? [undefined, 'Click to enter X axis title'] : 'XXX', + 'yaxis.title': original ? [undefined, 'Click to enter Y axis title'] : 'YYY', + 'ternary.aaxis.title': original ? [undefined, 'Component A'] : 'AAA', + 'ternary.baxis.title': original ? [undefined, 'Component B'] : 'BBB', + 'ternary.caxis.title': original ? [undefined, 'Component C'] : 'CCC', + 'polar.radialaxis.title': original ? [undefined, ''] : 'RRR' + }; + } + + function editComponents() { + return Registry.call('_guiRelayout', gd, attrs()); + } + + var checkInitial = checkState([], attrs(true)); + var checkEdited = checkState([], attrs()); + + _run(fig, editComponents, checkInitial, checkEdited).then(done); + }); }); From c95ae07b6e05887476d0cb0e69a2820259e5c184 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Mon, 12 Nov 2018 12:04:40 -0500 Subject: [PATCH 22/33] revert form of rangeslider relayout call (but it's still _guiRelayout) so the event data still has {range: [min, max]} not {range[0]: min, ...} for backward compatibility. Note the latter form is no longer needed for guiEdits to work consistently --- src/components/rangeslider/draw.js | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/components/rangeslider/draw.js b/src/components/rangeslider/draw.js index 5d0bf72f23e..08f7a68eeba 100644 --- a/src/components/rangeslider/draw.js +++ b/src/components/rangeslider/draw.js @@ -286,10 +286,7 @@ function setDataRange(rangeSlider, gd, axisOpts, opts) { dataMax = clamp(opts.p2d(opts._pixelMax)); window.requestAnimationFrame(function() { - var update = {}; - update[axisOpts._name + '.range[0]'] = dataMin; - update[axisOpts._name + '.range[1]'] = dataMax; - Registry.call('_guiRelayout', gd, update); + Registry.call('_guiRelayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); }); } From 7ab8630689019e6162cbbc49a374668390713774 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Mon, 12 Nov 2018 12:24:21 -0500 Subject: [PATCH 23/33] comment on uirevision<->uid in trace.uirevision attribute description --- src/plots/attributes.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/plots/attributes.js b/src/plots/attributes.js index 113cc11a537..6aea41b1c0b 100644 --- a/src/plots/attributes.js +++ b/src/plots/attributes.js @@ -174,7 +174,12 @@ module.exports = { 'interactions like `selectedpoints` and type-specific ones such as', '`constraintrange` in `parcoords` traces, as well as some', '`editable: true` modifications such as `name` and `colorbar.title`.', - 'Defaults to `layout.uirevision`.' + 'Defaults to `layout.uirevision`.', + 'Trace changes are tracked by `uid`, which only falls back on trace', + 'index if no `uid` is provided. So if your app can add/remove traces', + 'before the end of the `data` array, such that the same trace has a', + 'different index, you can still preserve user-driven changes if you', + 'give each trace a `uid` that stays with it as it moves.' ].join(' ') } }; From 756308fe843b9a10dcfb30646ff5a14d7b3e0624 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Mon, 12 Nov 2018 22:53:24 -0500 Subject: [PATCH 24/33] record real initial axis (auto)range so we can update to autorange --- src/plot_api/plot_api.js | 41 +++++++++---- src/plots/cartesian/autorange.js | 8 +++ src/plots/cartesian/layout_defaults.js | 2 +- src/plots/polar/layout_defaults.js | 1 + test/jasmine/tests/plot_api_react_test.js | 71 +++++++++++++++++++++++ 5 files changed, 111 insertions(+), 12 deletions(-) diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 9b40e6b7fae..2334cefab31 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1445,7 +1445,8 @@ function storeCurrent(attr, val, newVal, preGUI) { * of the calling routine. * * @param {object} container: the input attributes container (eg `layout` or a `trace`) - * @param {object} fullContainer: the full partner to `container` + * @param {object} preGUI: where original values should be stored, either + * `layout._preGUI` or `layout._tracePreGUI[uid]` * @param {object} edits: the {attr: val} object as normally passed to `relayout` etc */ exports._storeDirectGUIEdit = function(container, preGUI, edits) { @@ -2367,7 +2368,7 @@ exports._guiUpdate = guiEdit(update); // Ordered by most common edits first, to minimize our search time var layoutUIControlPatterns = [ {pattern: /^hiddenlabels/, attr: 'legend.uirevision'}, - {pattern: /^((x|y)axis\d*)\.((auto)?range|title)/, autofill: true}, + {pattern: /^((x|y)axis\d*)\.((auto)?range|title)/}, // showspikes and modes include those nested inside scenes {pattern: /axis\d*\.showspikes$/, attr: 'modebar.uirevision'}, @@ -2376,8 +2377,7 @@ var layoutUIControlPatterns = [ {pattern: /^(scene\d*)\.camera/}, {pattern: /^(geo\d*)\.(projection|center)/}, {pattern: /^(ternary\d*\.[abc]axis)\.(min|title)$/}, - {pattern: /^(polar\d*\.radialaxis)\.(auto)?range/, autofill: true}, - {pattern: /^(polar\d*\.radialaxis)\.(angle|title)/}, + {pattern: /^(polar\d*\.radialaxis)\.((auto)?range|angle|title)/}, {pattern: /^(polar\d*\.angularaxis)\.rotation/}, {pattern: /^(mapbox\d*)\.(center|zoom|bearing|pitch)/}, @@ -2411,7 +2411,7 @@ function findUIPattern(key, patternSpecs) { var spec = patternSpecs[i]; var match = key.match(spec.pattern); if(match) { - return {head: match[1], attr: spec.attr, autofill: spec.autofill}; + return {head: match[1], attr: spec.attr}; } } } @@ -2464,6 +2464,8 @@ function valsMatch(v1, v2) { function applyUIRevisions(data, layout, oldFullData, oldFullLayout) { var layoutPreGUI = oldFullLayout._preGUI; var key, revAttr, oldRev, newRev, match, preGUIVal, newNP, newVal; + var bothInheritAutorange = []; + var newRangeAccepted = {}; for(key in layoutPreGUI) { match = findUIPattern(key, layoutUIControlPatterns); if(match) { @@ -2485,8 +2487,11 @@ function applyUIRevisions(data, layout, oldFullData, oldFullLayout) { // storing *that* in preGUI... oh well, for now at least I limit // this to attributes that get autofilled, which AFAICT among // the GUI-editable attributes is just axis.range/autorange. - if(valsMatch(newVal, preGUIVal) || (match.autofill && newVal === undefined)) { - newNP.set(nestedProperty(oldFullLayout, key).get()); + if(valsMatch(newVal, preGUIVal)) { + if(newVal === undefined && key.substr(key.length - 9) === 'autorange') { + bothInheritAutorange.push(key.substr(0, key.length - 10)); + } + newNP.set(undefinedToNull(nestedProperty(oldFullLayout, key).get())); continue; } } @@ -2498,12 +2503,26 @@ function applyUIRevisions(data, layout, oldFullData, oldFullLayout) { // point (either because it changed or revision changed) // so remove it from _preGUI for next time. delete layoutPreGUI[key]; + + if(key.substr(key.length - 8, 6) === 'range[') { + newRangeAccepted[key.substr(0, key.length - 9)] = 1; + } + } + + // Special logic for `autorange`, since it interacts with `range`: + // If the new figure's matching `range` was kept, and `autorange` + // wasn't supplied explicitly in either the original or the new figure, + // we shouldn't alter that - but we may just have done that, so fix it. + for(var i = 0; i < bothInheritAutorange.length; i++) { + var axAttr = bothInheritAutorange[i]; + if(newRangeAccepted[axAttr]) { + var newAx = nestedProperty(layout, axAttr).get(); + if(newAx) delete newAx.autorange; + } } // Now traces - try to match them up by uid (in case we added/deleted in // the middle), then fall back on index. - // var tracei = -1; - // for(var fulli = 0; fulli < oldFullData.length; fulli++) { var allTracePreGUI = oldFullLayout._tracePreGUI; for(var uid in allTracePreGUI) { var tracePreGUI = allTracePreGUI[uid]; @@ -2550,8 +2569,8 @@ function applyUIRevisions(data, layout, oldFullData, oldFullLayout) { if(preGUIVal === null) preGUIVal = undefined; newNP = nestedProperty(newTrace, key); newVal = newNP.get(); - if(valsMatch(newVal, preGUIVal) || (match.autofill && newVal === undefined)) { - newNP.set(nestedProperty(fullInput, key).get()); + if(valsMatch(newVal, preGUIVal)) { + newNP.set(undefinedToNull(nestedProperty(fullInput, key).get())); continue; } } diff --git a/src/plots/cartesian/autorange.js b/src/plots/cartesian/autorange.js index 3343fb4a899..3fe613d5e7d 100644 --- a/src/plots/cartesian/autorange.js +++ b/src/plots/cartesian/autorange.js @@ -12,6 +12,7 @@ var isNumeric = require('fast-isnumeric'); var Lib = require('../../lib'); var FP_SAFE = require('../../constants/numerical').FP_SAFE; +var Registry = require('../../registry'); module.exports = { getAutoRange: getAutoRange, @@ -250,6 +251,13 @@ function doAutoRange(gd, ax) { // but we want to report its results back to layout axIn = ax._input; + + // before we edit _input, store preGUI values + var edits = {}; + edits[ax._attr + '.range'] = ax.range; + edits[ax._attr + '.autorange'] = ax.autorange; + Registry.call('_storeDirectGUIEdit', gd.layout, gd._fullLayout._preGUI, edits); + axIn.range = ax.range.slice(); axIn.autorange = ax.autorange; } diff --git a/src/plots/cartesian/layout_defaults.js b/src/plots/cartesian/layout_defaults.js index c56c64c2145..e0e6e18dc08 100644 --- a/src/plots/cartesian/layout_defaults.js +++ b/src/plots/cartesian/layout_defaults.js @@ -158,7 +158,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { axLayoutOut._shapeIndices = []; // set up some private properties - axLayoutOut._name = axName; + axLayoutOut._name = axLayoutOut._attr = axName; var id = axLayoutOut._id = name2id(axName); var overlayableAxes = getOverlayableAxes(axLetter, axName); diff --git a/src/plots/polar/layout_defaults.js b/src/plots/polar/layout_defaults.js index b5cef9b77ce..d0c0b5da31f 100644 --- a/src/plots/polar/layout_defaults.js +++ b/src/plots/polar/layout_defaults.js @@ -53,6 +53,7 @@ function handleDefaults(contIn, contOut, coerce, opts) { var axIn = contIn[axName]; var axOut = Template.newContainer(contOut, axName); axOut._id = axOut._name = axName; + axOut._attr = opts.id + '.' + axName; axOut._traceIndices = subplotData.map(function(t) { return t._expandedIndex; }); var dataAttr = constants.axisName2dataArray[axName]; diff --git a/test/jasmine/tests/plot_api_react_test.js b/test/jasmine/tests/plot_api_react_test.js index 14530e5bd2b..acffa755fae 100644 --- a/test/jasmine/tests/plot_api_react_test.js +++ b/test/jasmine/tests/plot_api_react_test.js @@ -1087,6 +1087,77 @@ describe('Plotly.react and uirevision attributes', function() { .then(done); }); + it('respects reverting an explicit cartesian axis range to auto', function(done) { + function fig(xRange, yRange) { + return { + data: [{z: [[1, 2], [3, 4]], type: 'heatmap', x: [0, 1, 2], y: [3, 4, 5]}], + layout: { + xaxis: {range: xRange}, + yaxis: {range: yRange}, + uirevision: 'a' + } + }; + } + + function setRanges(xRange, yRange) { + return function() { + return Registry.call('_guiRelayout', gd, { + 'xaxis.range': xRange, + 'yaxis.range': yRange + }); + }; + } + + function checkRanges(xRange, yRange) { + return checkState([], { + 'xaxis.range': [xRange], + 'yaxis.range': [yRange] + }); + } + + Plotly.newPlot(gd, fig([1, 3], [4, 6])) + .then(checkRanges([1, 3], [4, 6])) + .then(setRanges([2, 4], [5, 7])) + .then(checkRanges([2, 4], [5, 7])) + .then(_react(fig(undefined, undefined))) + .then(checkRanges([0, 2], [3, 5])) + .catch(failTest) + .then(done); + }); + + it('respects reverting an explicit polar axis range to auto', function(done) { + function fig(range) { + return { + data: [{type: 'barpolar', r: [1, 1], theta: [0, 90]}], + layout: { + polar: {radialaxis: {range: range}}, + uirevision: 'a' + } + }; + } + + function setRange(range) { + return function() { + return Registry.call('_guiRelayout', gd, { + 'polar.radialaxis.range': range + }); + }; + } + + function checkRange(range) { + return checkState([], {'polar.radialaxis.range': [range]}); + } + + Plotly.newPlot(gd, fig([1, 3])) + .then(checkRange([1, 3])) + .then(setRange([2, 4])) + .then(checkRange([2, 4])) + .then(_react(fig(undefined))) + .then(checkRange([0, 1.05263])) + .catch(failTest) + .then(done); + }); + function _run(figFn, editFn, checkInitial, checkEdited) { // figFn should take 2 args (main uirevision and partial uirevision) // and return a figure {data, layout} From 874a72aa86778ef223a65d8ce77b1af8b761fdd0 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Mon, 12 Nov 2018 22:58:15 -0500 Subject: [PATCH 25/33] remove now-obsolete comment about autorange/autofill --- src/plot_api/plot_api.js | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 2334cefab31..88cd185447a 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -2477,16 +2477,6 @@ function applyUIRevisions(data, layout, oldFullData, oldFullLayout) { if(preGUIVal === null) preGUIVal = undefined; newNP = nestedProperty(layout, key); newVal = newNP.get(); - // TODO: This test for undefined is to account for the case where - // the value was filled in automatically in gd.layout, - // like axis.range/autorange. In principle though, if the initial - // plot had a value and the new plot removed that value, we would - // want the removal to override the GUI edit and generate a new - // auto value. But that would require figuring out what value was - // in gd.layout *before* the auto values were filled in, and - // storing *that* in preGUI... oh well, for now at least I limit - // this to attributes that get autofilled, which AFAICT among - // the GUI-editable attributes is just axis.range/autorange. if(valsMatch(newVal, preGUIVal)) { if(newVal === undefined && key.substr(key.length - 9) === 'autorange') { bothInheritAutorange.push(key.substr(0, key.length - 10)); From 090231bce09a0ee064b0741ec261b9b1d10de9b3 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Tue, 13 Nov 2018 13:42:35 -0500 Subject: [PATCH 26/33] fix and :lock: selectionrevision with groupby --- src/plots/cartesian/select.js | 15 ++++++--- test/jasmine/tests/plot_api_react_test.js | 41 +++++++++++++++++++++++ 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/src/plots/cartesian/select.js b/src/plots/cartesian/select.js index ce6e40c4028..f1efad89e54 100644 --- a/src/plots/cartesian/select.js +++ b/src/plots/cartesian/select.js @@ -680,8 +680,8 @@ function updateSelectedState(gd, searchTraces, eventData) { for(i = 0; i < searchTraces.length; i++) { trace = searchTraces[i].cd[0].trace; - trace.selectedpoints = []; - trace._input.selectedpoints = []; + trace._input.selectedpoints = trace._fullInput.selectedpoints = []; + if(trace._fullInput !== trace) trace.selectedpoints = []; } for(i = 0; i < pts.length; i++) { @@ -691,10 +691,14 @@ function updateSelectedState(gd, searchTraces, eventData) { if(pt.pointIndices) { [].push.apply(data.selectedpoints, pt.pointIndices); - [].push.apply(fullData.selectedpoints, pt.pointIndices); + if(trace._fullInput !== trace) { + [].push.apply(fullData.selectedpoints, pt.pointIndices); + } } else { data.selectedpoints.push(pt.pointIndex); - fullData.selectedpoints.push(pt.pointIndex); + if(trace._fullInput !== trace) { + fullData.selectedpoints.push(pt.pointIndex); + } } } } @@ -703,6 +707,9 @@ function updateSelectedState(gd, searchTraces, eventData) { trace = searchTraces[i].cd[0].trace; delete trace.selectedpoints; delete trace._input.selectedpoints; + if(trace._fullInput !== trace) { + delete trace._fullInput.selectedpoints; + } } } diff --git a/test/jasmine/tests/plot_api_react_test.js b/test/jasmine/tests/plot_api_react_test.js index acffa755fae..937d8f07e39 100644 --- a/test/jasmine/tests/plot_api_react_test.js +++ b/test/jasmine/tests/plot_api_react_test.js @@ -1418,6 +1418,47 @@ describe('Plotly.react and uirevision attributes', function() { _run(fig, editSelection, checkNoSelection, checkSelection).then(done); }); + it('preserves selectedpoints using selectedrevision (groupby case)', function(done) { + function fig(mainRev, selectionRev) { + return { + data: [{ + x: [1, 2, 3, 1, 2, 3, 1, 2, 3], + y: [1, 1, 1, 2, 2, 2, 3, 3, 3], + mode: 'markers', + marker: {size: 20}, + transforms: [{ + type: 'groupby', + groups: [1, 2, 3, 2, 3, 1, 3, 1, 2] + }] + }], + layout: { + uirevision: mainRev, + selectionrevision: selectionRev, + dragmode: 'select', + width: 400, + height: 400, + margin: {l: 100, t: 100, r: 100, b: 100} + } + }; + } + + function editSelection() { + // drag across the upper right quadrant, so we'll select + // curve 0 point 1 and curve 1 point 2 + return drag(document.querySelector('.nsewdrag'), + 148, 148, '', 150, 102); + } + + var checkNoSelection = checkState([{selectedpoints: undefined}]); + // the funny point order here is from the grouping: + // points 5 & 7 come first as they're in group 1 + // point 8 is next, in group 2 + // point 4 is last, in group 3 + var checkSelection = checkState([{selectedpoints: [[5, 7, 8, 4]]}]); + + _run(fig, editSelection, checkNoSelection, checkSelection).then(done); + }); + it('preserves polar view changes using polar.uirevision', function(done) { // polar you can control either at the subplot or the axis level function fig(mainRev, polarRev) { From 5a27c0043e46342d73b8d986f9ce995fc48ead60 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Tue, 13 Nov 2018 13:56:05 -0500 Subject: [PATCH 27/33] update trace.uirevision description with what it does/doesn't control --- src/plots/attributes.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/plots/attributes.js b/src/plots/attributes.js index 6aea41b1c0b..b6db8871022 100644 --- a/src/plots/attributes.js +++ b/src/plots/attributes.js @@ -170,11 +170,16 @@ module.exports = { role: 'info', editType: 'none', description: [ - 'Controls persistence of user-driven changes to the trace:', - 'interactions like `selectedpoints` and type-specific ones such as', + 'Controls persistence of some user-driven changes to the trace:', '`constraintrange` in `parcoords` traces, as well as some', '`editable: true` modifications such as `name` and `colorbar.title`.', 'Defaults to `layout.uirevision`.', + 'Note that other user-driven trace attribute changes are controlled', + 'by `layout` attributes:', + '`trace.visible` is controlled by `layout.legend.uirevision`,', + '`selectedpoints` is controlled by `layout.selectionrevision`,', + 'and `colorbar.(x|y)` (accessible with `config: {editable: true}`)', + 'is controlled by `layout.editrevision`.', 'Trace changes are tracked by `uid`, which only falls back on trace', 'index if no `uid` is provided. So if your app can add/remove traces', 'before the end of the `data` array, such that the same trace has a', From 2034941580dec9ca618b20c2eb64944109756cfb Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Mon, 19 Nov 2018 12:12:50 -0500 Subject: [PATCH 28/33] partial preGUI fix for 3D camera --- src/plots/gl3d/scene.js | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/src/plots/gl3d/scene.js b/src/plots/gl3d/scene.js index 8b1e7eb8ed8..ccc6fcb9d74 100644 --- a/src/plots/gl3d/scene.js +++ b/src/plots/gl3d/scene.js @@ -222,7 +222,6 @@ function initializeGLPlot(scene, fullLayout, canvas, gl) { var update = {}; update[scene.id + '.camera'] = getLayoutCamera(scene.camera); - Registry.call('_storeDirectGUIEdit', gd.layout, gd._fullLayout._preGUI, update); scene.saveCamera(gd.layout); scene.graphDiv.emit('plotly_relayout', update); }; @@ -702,10 +701,10 @@ proto.setCamera = function setCamera(cameraData) { // save camera to user layout (i.e. gd.layout) proto.saveCamera = function saveCamera(layout) { - var cameraData = this.getCamera(), - cameraNestedProp = Lib.nestedProperty(layout, this.id + '.camera'), - cameraDataLastSave = cameraNestedProp.get(), - hasChanged = false; + var cameraData = this.getCamera(); + var cameraNestedProp = Lib.nestedProperty(layout, this.id + '.camera'); + var cameraDataLastSave = cameraNestedProp.get(); + var hasChanged = false; function same(x, y, i, j) { var vectors = ['up', 'center', 'eye'], @@ -725,7 +724,14 @@ proto.saveCamera = function saveCamera(layout) { } } - if(hasChanged) cameraNestedProp.set(cameraData); + if(hasChanged) { + cameraNestedProp.set(cameraData); + + var fullLayout = this.fullLayout; + var cameraFullNP = Lib.nestedProperty(fullLayout, this.id + '.camera'); + cameraFullNP.set(cameraData); + Registry.call('_storeDirectGUIEdit', layout, fullLayout._preGUI, cameraData); + } return hasChanged; }; @@ -744,6 +750,19 @@ proto.updateFx = function(dragmode, hovermode) { camera.mode = 'turntable'; camera.keyBindingMode = 'rotate'; + // The setter for camera.mode animates the transition to z-up, + // but only if we *don't* explicitly set z-up earlier via the + // relayout. So push `up` back to layout & fullLayout manually now. + var gd = this.graphDiv; + var layout = gd.layout; + var fullLayout = gd._fullLayout; + var attr = this.id + '.camera.up'; + var edits = {}; + var zUp = {x: 0, y: 0, z: 1}; + edits[attr] = zUp; + Registry.call('_storeDirectGUIEdit', layout, fullLayout._preGUI, edits); + this.fullSceneLayout.camera.up = zUp; + Lib.nestedProperty(gd.layout, attr).set(zUp); } else { // none rotation modes [pan or zoom] From 8d119855da2adce3f60b28a9bc1e7b22d14896b7 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Wed, 28 Nov 2018 21:21:33 -0500 Subject: [PATCH 29/33] write camera.up back to layout only when necessary interaction between previous changes in this PR and #3256 --- src/plots/gl3d/scene.js | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/plots/gl3d/scene.js b/src/plots/gl3d/scene.js index c04aeb5f718..cfc7eee11bc 100644 --- a/src/plots/gl3d/scene.js +++ b/src/plots/gl3d/scene.js @@ -754,15 +754,22 @@ proto.updateFx = function(dragmode, hovermode) { // but only if we *don't* explicitly set z-up earlier via the // relayout. So push `up` back to layout & fullLayout manually now. var gd = this.graphDiv; - var layout = gd.layout; var fullLayout = gd._fullLayout; + var fullCamera = this.fullSceneLayout.camera; + var x = fullCamera.up.x; + var y = fullCamera.up.y; + var z = fullCamera.up.z; + // only push `up` back to (full)layout if it's going to change + if(z / Math.sqrt(x * x + y * y + z * z) > 0.999) return; + var attr = this.id + '.camera.up'; - var edits = {}; var zUp = {x: 0, y: 0, z: 1}; + var edits = {}; edits[attr] = zUp; + var layout = gd.layout; Registry.call('_storeDirectGUIEdit', layout, fullLayout._preGUI, edits); - this.fullSceneLayout.camera.up = zUp; - Lib.nestedProperty(gd.layout, attr).set(zUp); + fullCamera.up = zUp; + Lib.nestedProperty(layout, attr).set(zUp); } else { // none rotation modes [pan or zoom] From 0621e43f7264657c265f94fdb17e1662b30d2a01 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Thu, 29 Nov 2018 21:23:36 -0500 Subject: [PATCH 30/33] update uirevisions for new title attribute structure #3276 --- src/plot_api/plot_api.js | 10 +++++----- src/plots/polar/layout_attributes.js | 3 +++ test/jasmine/tests/plot_api_react_test.js | 20 ++++++++++---------- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index fb95d1be99c..828797411f2 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -2427,7 +2427,7 @@ exports._guiUpdate = guiEdit(update); // Ordered by most common edits first, to minimize our search time var layoutUIControlPatterns = [ {pattern: /^hiddenlabels/, attr: 'legend.uirevision'}, - {pattern: /^((x|y)axis\d*)\.((auto)?range|title)/}, + {pattern: /^((x|y)axis\d*)\.((auto)?range|title\.text)/}, // showspikes and modes include those nested inside scenes {pattern: /axis\d*\.showspikes$/, attr: 'modebar.uirevision'}, @@ -2435,14 +2435,14 @@ var layoutUIControlPatterns = [ {pattern: /^(scene\d*)\.camera/}, {pattern: /^(geo\d*)\.(projection|center)/}, - {pattern: /^(ternary\d*\.[abc]axis)\.(min|title)$/}, - {pattern: /^(polar\d*\.radialaxis)\.((auto)?range|angle|title)/}, + {pattern: /^(ternary\d*\.[abc]axis)\.(min|title\.text)$/}, + {pattern: /^(polar\d*\.radialaxis)\.((auto)?range|angle|title\.text)/}, {pattern: /^(polar\d*\.angularaxis)\.rotation/}, {pattern: /^(mapbox\d*)\.(center|zoom|bearing|pitch)/}, {pattern: /^legend\.(x|y)$/, attr: 'editrevision'}, {pattern: /^(shapes|annotations)/, attr: 'editrevision'}, - {pattern: /^title$/, attr: 'editrevision'} + {pattern: /^title\.text$/, attr: 'editrevision'} ]; // same for trace attributes: if `attr` is given it's in layout, @@ -2461,7 +2461,7 @@ var traceUIControlPatterns = [ // "name" also includes transform.styles {pattern: /(^|value\.)name$/}, // including nested colorbar attributes (ie marker.colorbar) - {pattern: /colorbar\.title$/}, + {pattern: /colorbar\.title\.text$/}, {pattern: /colorbar\.(x|y)$/, attr: 'editrevision'} ]; diff --git a/src/plots/polar/layout_attributes.js b/src/plots/polar/layout_attributes.js index aa7ab38909c..4d878a9fd43 100644 --- a/src/plots/polar/layout_attributes.js +++ b/src/plots/polar/layout_attributes.js @@ -136,6 +136,9 @@ var radialAxisAttrs = { } }; +// radial title is not gui-editable, so it needs dflt: '', similar to carpet axes. +radialAxisAttrs.title.text.dflt = ''; + extendFlat( radialAxisAttrs, diff --git a/test/jasmine/tests/plot_api_react_test.js b/test/jasmine/tests/plot_api_react_test.js index 838f29ecb4c..812eb6f63e5 100644 --- a/test/jasmine/tests/plot_api_react_test.js +++ b/test/jasmine/tests/plot_api_react_test.js @@ -1643,7 +1643,7 @@ describe('Plotly.react and uirevision attributes', function() { function editEditable() { return Registry.call('_guiUpdate', gd, {'colorbar.x': 0.8, 'colorbar.y': 0.6}, - {title: 'yep', 'legend.x': 1.1, 'legend.y': 0.9}, + {'title.text': 'yep', 'legend.x': 1.1, 'legend.y': 0.9}, [2] ); } @@ -1653,7 +1653,7 @@ describe('Plotly.react and uirevision attributes', function() { 'colorbar.x': original ? [undefined, 1.02] : 0.8, 'colorbar.y': original ? [undefined, 0.5] : 0.6 }], { - title: original ? [undefined, 'Click to enter Plot title'] : 'yep', + 'title.text': original ? [undefined, 'Click to enter Plot title'] : 'yep', 'legend.x': original ? [undefined, 1.02] : 1.1, 'legend.y': original ? [undefined, 1] : 0.9 }); @@ -1688,7 +1688,7 @@ describe('Plotly.react and uirevision attributes', function() { return { 'dimensions[0].constraintrange': original ? [[2.5, 3.5]] : [[[1.5, 2.5], [2.938, 3.979]]], 'dimensions[1].constraintrange': original ? undefined : [[6.937, 7.979]], - 'line.colorbar.title': original ? [undefined, 'Click to enter Colorscale title'] : 'color', + 'line.colorbar.title.text': original ? [undefined, 'Click to enter Colorscale title'] : 'color', name: original ? [undefined, 'trace 0'] : 'name' }; } @@ -1700,7 +1700,7 @@ describe('Plotly.react and uirevision attributes', function() { function editTrace() { var _; return Registry.call('_guiRestyle', gd, - {'line.colorbar.title': 'color', name: 'name'}, + {'line.colorbar.title.text': 'color', name: 'name'}, [0] ) .then(function() { @@ -1742,12 +1742,12 @@ describe('Plotly.react and uirevision attributes', function() { function attrs(original) { return { - 'xaxis.title': original ? [undefined, 'Click to enter X axis title'] : 'XXX', - 'yaxis.title': original ? [undefined, 'Click to enter Y axis title'] : 'YYY', - 'ternary.aaxis.title': original ? [undefined, 'Component A'] : 'AAA', - 'ternary.baxis.title': original ? [undefined, 'Component B'] : 'BBB', - 'ternary.caxis.title': original ? [undefined, 'Component C'] : 'CCC', - 'polar.radialaxis.title': original ? [undefined, ''] : 'RRR' + 'xaxis.title.text': original ? [undefined, 'Click to enter X axis title'] : 'XXX', + 'yaxis.title.text': original ? [undefined, 'Click to enter Y axis title'] : 'YYY', + 'ternary.aaxis.title.text': original ? [undefined, 'Component A'] : 'AAA', + 'ternary.baxis.title.text': original ? [undefined, 'Component B'] : 'BBB', + 'ternary.caxis.title.text': original ? [undefined, 'Component C'] : 'CCC', + 'polar.radialaxis.title.text': original ? [undefined, ''] : 'RRR' }; } From bdef7d334b19e5af52925f183c0233c554766a49 Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Thu, 29 Nov 2018 21:50:30 -0500 Subject: [PATCH 31/33] more permissive tickson rotation test for AJ's machine --- test/jasmine/tests/axes_test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/jasmine/tests/axes_test.js b/test/jasmine/tests/axes_test.js index 3d502b3dfb5..fc05081c879 100644 --- a/test/jasmine/tests/axes_test.js +++ b/test/jasmine/tests/axes_test.js @@ -3212,7 +3212,7 @@ describe('Test axes', function() { angle: [90, 90, 90] }); - return Plotly.relayout(gd, 'xaxis.range', [-0.5, 1.5]); + return Plotly.relayout(gd, 'xaxis.range', [-0.4, 1.4]); }) .then(function() { _assert('narrower range - unrotated', { From 2b77911fcc30cce6906f756102dd48af74b0bbcf Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Fri, 30 Nov 2018 11:18:36 -0500 Subject: [PATCH 32/33] looser acceptance for title centering, to work on AJ's machine --- test/jasmine/tests/titles_test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/jasmine/tests/titles_test.js b/test/jasmine/tests/titles_test.js index 2dd4ba2230f..6696cda814c 100644 --- a/test/jasmine/tests/titles_test.js +++ b/test/jasmine/tests/titles_test.js @@ -528,7 +528,7 @@ describe('Plot title', function() { var topDistance = titleBB.top - refElemBB.top; var bottomDistance = refElemBB.bottom - titleBB.bottom; - var tolerance = 1.1; + var tolerance = 1.3; var msg = 'Title centered vertically within ' + elemSelector.desc; expect(topDistance).toBeWithin(bottomDistance, tolerance, msg); } From 067bd7dd1f5e762185c641c49f29208a444e0b1f Mon Sep 17 00:00:00 2001 From: alexcjohnson Date: Fri, 30 Nov 2018 11:31:57 -0500 Subject: [PATCH 33/33] biger tickwidth difference in tickson rotation test --- test/jasmine/tests/axes_test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/jasmine/tests/axes_test.js b/test/jasmine/tests/axes_test.js index fc05081c879..39969dd2f57 100644 --- a/test/jasmine/tests/axes_test.js +++ b/test/jasmine/tests/axes_test.js @@ -3219,7 +3219,7 @@ describe('Test axes', function() { angle: [0, 0] }); - return Plotly.relayout(gd, 'xaxis.tickwidth', 10); + return Plotly.relayout(gd, 'xaxis.tickwidth', 30); }) .then(function() { _assert('narrow range / wide ticks - rotated', {