Skip to content

Transform react #2577

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 26 commits into from
Apr 26, 2018
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
bbe3533
remove no longer needed hack for finance in findArrayAttributes
alexcjohnson Apr 18, 2018
ed24765
_commonLength -> _length
alexcjohnson Apr 18, 2018
fcc459d
fix #2508, fix #2470 - problems with Plotly.react and aggregate trans…
alexcjohnson Apr 18, 2018
7044a13
standardize transforms handling of _length
alexcjohnson Apr 19, 2018
88b7b43
:racehorse: refactor sort transform from O(n^2) to O(n)
alexcjohnson Apr 19, 2018
cf4c9c3
heatmap&carpet/has_columns -> Lib.is1D
alexcjohnson Apr 20, 2018
e84d4b9
close #1410 - yes, stop pruning in nestedProperty
alexcjohnson Apr 20, 2018
b436d52
ensure every trace defines _length in supplyDefaults, and abort trans…
alexcjohnson Apr 22, 2018
2a41f9e
react+transforms PR review edits
alexcjohnson Apr 24, 2018
965bcfb
fixes and test for checklist in #2508
alexcjohnson Apr 24, 2018
6fae229
some fixes and tests for empty data arrays
alexcjohnson Apr 24, 2018
79295f1
rename violins mock that doesn't contain violin traces
alexcjohnson Apr 25, 2018
5e9aa65
transforms mock
alexcjohnson Apr 26, 2018
690eb95
clean up keyedContainer for possibly missing array
alexcjohnson Apr 26, 2018
a244cec
violin should not explicitly set whiskerwidth
alexcjohnson Apr 26, 2018
92bd5d2
add _length and stop slicing in scattercarpet
alexcjohnson Apr 26, 2018
dc6de2f
clean up handling of colorscale defaults
alexcjohnson Apr 26, 2018
03956e1
include count aggregates in _arrayAttrs - so they remap correctly
alexcjohnson Apr 26, 2018
f439e41
in diffData I had _fullInput in the new trace, but not the old!
alexcjohnson Apr 26, 2018
e47e6a9
_compareAsJSON for groupby styles
alexcjohnson Apr 26, 2018
aa30ad6
update plot_api_test to :lock: recent changes in react/transforms etc
alexcjohnson Apr 26, 2018
4c70826
lint
alexcjohnson Apr 26, 2018
7279b55
+shapes & annotations3d in react-noop test
alexcjohnson Apr 26, 2018
3e250df
tweak docs & remove commented-out code
alexcjohnson Apr 26, 2018
cd08479
reactWith -> reactTo
alexcjohnson Apr 26, 2018
0414147
separate svg and gl traces in react-noop tests
alexcjohnson Apr 26, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ lib.ensureArray = require('./ensure_array');
var isArrayModule = require('./is_array');
lib.isTypedArray = isArrayModule.isTypedArray;
lib.isArrayOrTypedArray = isArrayModule.isArrayOrTypedArray;
lib.is1D = isArrayModule.is1D;

var coerceModule = require('./coerce');
lib.valObjectMeta = coerceModule.valObjectMeta;
Expand Down
18 changes: 14 additions & 4 deletions src/lib/is_array.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,20 @@ var dv = (typeof DataView === 'undefined') ?
function() {} :
DataView;

exports.isTypedArray = function(a) {
function isTypedArray(a) {
return ab.isView(a) && !(a instanceof dv);
};
}

function isArrayOrTypedArray(a) {
return Array.isArray(a) || isTypedArray(a);
}

function is1D(a) {
return !isArrayOrTypedArray(a[0]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe isArray1D would be clearer as this assumes that you're passing an array (or at least something you can index in).

We might want to add a comment above about that assumption too, in case someone in the future wants to turn this into:

return Array.isArray(a) && !isArrayOrTypedArray(a[0]);

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2a41f9e -> isArray1D

}

exports.isArrayOrTypedArray = function(a) {
return Array.isArray(a) || exports.isTypedArray(a);
module.exports = {
isTypedArray: isTypedArray,
isArrayOrTypedArray: isArrayOrTypedArray,
is1D: is1D
};
101 changes: 22 additions & 79 deletions src/lib/nested_property.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@

var isNumeric = require('fast-isnumeric');
var isArrayOrTypedArray = require('./is_array').isArrayOrTypedArray;
var isPlainObject = require('./is_plain_object');
var containerArrayMatch = require('../plot_api/container_array_match');

/**
* convert a string s (such as 'xaxis.range[0]')
Expand Down Expand Up @@ -115,44 +113,21 @@ function npGet(cont, parts) {
}

/*
* Can this value be deleted? We can delete any empty object (null, undefined, [], {})
* EXCEPT empty data arrays, {} inside an array, or anything INSIDE an *args* array.
* Can this value be deleted? We can delete `undefined`, and `null` except INSIDE an
* *args* array.
*
* Info arrays can be safely deleted, but not deleting them has no ill effects other
* than leaving a trace or layout object with some cruft in it.
* Previously we also deleted some `{}` and `[]`, in order to try and make set/unset
* a net noop; but this causes far more complication than it's worth, and still had
* lots of exceptions. See https://github.com/plotly/plotly.js/issues/1410
*
* Deleting data arrays can change the meaning of the object, as `[]` means there is
* data for this attribute, it's just empty right now while `undefined` means the data
* should be filled in with defaults to match other data arrays.
*
* `{}` inside an array means "the default object" which is clearly different from
* popping it off the end of the array, or setting it `undefined` inside the array.
*
* *args* arrays get passed directly to API methods and we should respect precisely
* what the user has put there - although if the whole *args* array is empty it's fine
* to delete that.
*
* So we do some simple tests here to find known non-data arrays but don't worry too
* much about not deleting some arrays that would actually be safe to delete.
* *args* arrays get passed directly to API methods and we should respect null if
* the user put it there, but otherwise null is deleted as we use it as code
* in restyle/relayout/update for "delete this value" whereas undefined means
* "ignore this edit"
*/
var INFO_PATTERNS = /(^|\.)((domain|range)(\.[xy])?|args|parallels)$/;
Copy link
Contributor

@etpinard etpinard Apr 23, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO:

  • check that the old toolpanel does not break

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moreover @alexcjohnson, what if in the very unlikely scenario of someone writing in that their app relies on the old pruning behavior, what should we do?

I suspect reverting this commit would break some test(s) added in this PR (which one by the way?), so maybe we could formulate a solution for that hypothetical user?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason I made this commit now was the trace._length = null, which in some cases was getting pruned later on in supplyDefaults by attributes with dflt: null and breaking my redraw all the things test addition. I could have handled this in a few different ways:

  • use something other than null for _length - I considered false but to me that had the implication of "has no length" rather than what I wanted, "(1D) length does not apply." Anyway the whole idea that we're pruning in the middle of supplyDefaults which is really only supposed to be building the _full* objects I wanted to avoid.
  • make a special code path that does no pruning or unsetting - like nestedProperty.onlySet(val) - but that's adding complexity so not ideal.
  • get rid of all dflt: null (and perhaps even enforce that) throughout our attributes. I still think we should do that, but I opted not to do it here.

Anyway, to the question:

what if in the very unlikely scenario of someone writing in that their app relies on the old pruning behavior, what should we do?

If it leads to a visible change in the plot, we should fix it so the API does not contain such a dependence on the existence of empty containers ;)
If it just alters the data structures (data and layout I guess, after a restyle/relayout) I can't really predict why a user would be bothered by this, but we can help them wrap their restyle/relayout with something like if(val === null) { pruneContainersPulledFromThisCommit(...) }

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great answer. Thanks!

var ARGS_PATTERN = /(^|\.)args\[/;
function isDeletable(val, propStr) {
if(!emptyObj(val) ||
(isPlainObject(val) && propStr.charAt(propStr.length - 1) === ']') ||
(propStr.match(ARGS_PATTERN) && val !== undefined)
) {
return false;
}
if(!isArrayOrTypedArray(val)) return true;

if(propStr.match(INFO_PATTERNS)) return true;

var match = containerArrayMatch(propStr);
// if propStr matches the container array itself, index is an empty string
// otherwise we've matched something inside the container array, which may
// still be a data array.
return match && (match.index === '');
return (val === undefined) || (val === null && !propStr.match(ARGS_PATTERN));
}

function npSet(cont, parts, propStr) {
Expand Down Expand Up @@ -194,8 +169,18 @@ function npSet(cont, parts, propStr) {
}

if(toDelete) {
if(i === parts.length - 1) delete curCont[parts[i]];
pruneContainers(containerLevels);
if(i === parts.length - 1) {
delete curCont[parts[i]];

// The one bit of pruning we still do: drop `undefined` from the end of arrays.
// In case someone has already unset previous items, continue until we hit a
// non-undefined value.
if(Array.isArray(curCont) && +parts[i] === curCont.length - 1) {
while(curCont.length && curCont[curCont.length - 1] === undefined) {
curCont.pop();
}
}
}
}
else curCont[parts[i]] = val;
};
Expand Down Expand Up @@ -249,48 +234,6 @@ function checkNewContainer(container, part, nextPart, toDelete) {
return true;
}

function pruneContainers(containerLevels) {
var i,
j,
curCont,
propPart,
keys,
remainingKeys;
for(i = containerLevels.length - 1; i >= 0; i--) {
curCont = containerLevels[i][0];
propPart = containerLevels[i][1];

remainingKeys = false;
if(isArrayOrTypedArray(curCont)) {
for(j = curCont.length - 1; j >= 0; j--) {
if(isDeletable(curCont[j], joinPropStr(propPart, j))) {
if(remainingKeys) curCont[j] = undefined;
else curCont.pop();
}
else remainingKeys = true;
}
}
else if(typeof curCont === 'object' && curCont !== null) {
keys = Object.keys(curCont);
remainingKeys = false;
for(j = keys.length - 1; j >= 0; j--) {
if(isDeletable(curCont[keys[j]], joinPropStr(propPart, keys[j]))) {
delete curCont[keys[j]];
}
else remainingKeys = true;
}
}
if(remainingKeys) return;
}
}

function emptyObj(obj) {
if(obj === undefined || obj === null) return true;
if(typeof obj !== 'object') return false; // any plain value
if(isArrayOrTypedArray(obj)) return !obj.length; // []
return !Object.keys(obj).length; // {}
}

function badContainer(container, propStr, propParts) {
return {
set: function() { throw 'bad container'; },
Expand Down
8 changes: 7 additions & 1 deletion src/plot_api/plot_api.js
Original file line number Diff line number Diff line change
Expand Up @@ -2267,7 +2267,10 @@ exports.react = function(gd, data, layout, config) {
gd.layout = layout || {};
helpers.cleanLayout(gd.layout);

Plots.supplyDefaults(gd);
// "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
Plots.supplyDefaults(gd, true);
Copy link
Contributor

@etpinard etpinard Apr 23, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not a big fan of this pattern.

At the very least we should turn this into Plots.supplyDefaults(gd, {skipDefaultsUpdateCalc: 1}) to make it more readable and extendable.

Personally, I'd vote for removing the newly added Plots.supplyDefaultsUpdateCalc() from Plots.supplyDefaults and call Plotly.supplyDefaultsUpdateCalc after Plots.supplyDefaults in the places that new it.

On master, we have:

image

where the calls in validate.js and rangeslider/draw.js (and maybe more) don't need to update calc.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps the name supplyDefaultsUpdateCalc isn't the best - though you could argue the same about calcTransform, which happens during the calc step but updates the data arrays in _fullData. supplyDefaultsUpdateCalc has one simple function when there are no transforms, to attach the new traces to the old calcdata in case we're not going to run a recalc, but when there are transforms it also (first) pulls the transformed array attributes back from the old fullTrace to the new one. So I think in fact we do need this in most instances, and there are some external callers (like streambed) that depend on this as well.

So I'm going to keep it as part of the default supplyDefaults behavior, but I'm happy to make it into an options object for clarity.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cleaner supplyDefaults API -> 2a41f9e


var newFullData = gd._fullData;
var newFullLayout = gd._fullLayout;
Expand All @@ -2289,6 +2292,9 @@ exports.react = function(gd, data, layout, config) {

// clear calcdata if required
if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined;
// otherwise do the calcdata updates and calcTransform array remaps that we skipped earlier
else Plots.supplyDefaultsUpdateCalc(gd.calcdata, newFullData);

if(relayoutFlags.margins) helpers.clearAxisAutomargins(gd);

// Note: what restyle/relayout use impliedEdits and clearAxisTypes for
Expand Down
56 changes: 33 additions & 23 deletions src/plot_api/plot_schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,12 @@ exports.isValObject = function(obj) {
exports.findArrayAttributes = function(trace) {
var arrayAttributes = [];
var stack = [];
var isArrayStack = [];
var baseContainer, baseAttrName;

function callback(attr, attrName, attrs, level) {
stack = stack.slice(0, level).concat([attrName]);
isArrayStack = isArrayStack.slice(0, level).concat([attr && attr._isLinkedToArray]);

var splittableAttr = (
attr &&
Expand All @@ -190,48 +193,55 @@ exports.findArrayAttributes = function(trace) {

if(!splittableAttr) return;

var astr = toAttrString(stack);
var val = Lib.nestedProperty(trace, astr).get();
if(!Lib.isArrayOrTypedArray(val)) return;

arrayAttributes.push(astr);
crawlIntoTrace(baseContainer, 0, '');
}

function toAttrString(stack) {
return stack.join('.');
function crawlIntoTrace(container, i, astrPartial) {
var item = container[stack[i]];
var newAstrPartial = astrPartial + stack[i];
if(i === stack.length - 1) {
if(Lib.isArrayOrTypedArray(item)) {
arrayAttributes.push(baseAttrName + newAstrPartial);
}
}
else {
if(isArrayStack[i]) {
if(Array.isArray(item)) {
for(var j = 0; j < item.length; j++) {
if(Lib.isPlainObject(item[j])) {
crawlIntoTrace(item[j], i + 1, newAstrPartial + '[' + j + '].');
}
}
}
}
else if(Lib.isPlainObject(item)) {
crawlIntoTrace(item, i + 1, newAstrPartial + '.');
}
}
}

baseContainer = trace;
baseAttrName = '';
exports.crawl(baseAttributes, callback);
if(trace._module && trace._module.attributes) {
exports.crawl(trace._module.attributes, callback);
}

if(trace.transforms) {
var transforms = trace.transforms;

var transforms = trace.transforms;
if(transforms) {
for(var i = 0; i < transforms.length; i++) {
var transform = transforms[i];
var module = transform._module;

if(module) {
stack = ['transforms[' + i + ']'];
baseAttrName = 'transforms[' + i + '].';
baseContainer = transform;

exports.crawl(module.attributes, callback, 1);
exports.crawl(module.attributes, callback);
}
}
}

// Look into the fullInput module attributes for array attributes
// to make sure that 'custom' array attributes are detected.
//
// At the moment, we need this block to make sure that
// ohlc and candlestick 'open', 'high', 'low', 'close' can be
// used with filter and groupby transforms.
if(trace._fullInput && trace._fullInput._module && trace._fullInput._module.attributes) {
exports.crawl(trace._fullInput._module.attributes, callback);
arrayAttributes = Lib.filterUnique(arrayAttributes);
}

return arrayAttributes;
};

Expand Down
2 changes: 1 addition & 1 deletion src/plots/cartesian/type_defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ function getFirstNonEmptyTrace(data, id, axLetter) {
var trace = data[i];

if(trace.type === 'splom' &&
trace._commonLength > 0 &&
trace._length > 0 &&
trace['_' + axLetter + 'axes'][id]
) {
return trace;
Expand Down
35 changes: 22 additions & 13 deletions src/plots/plots.js
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ var extraFormatKeys = [
// gd._fullLayout._transformModules
// is a list of all the transform modules invoked.
//
plots.supplyDefaults = function(gd) {
plots.supplyDefaults = function(gd, skipCalcUpdate) {
var oldFullLayout = gd._fullLayout || {};

if(oldFullLayout._skipDefaults) {
Expand Down Expand Up @@ -458,24 +458,28 @@ plots.supplyDefaults = function(gd) {
}

// update object references in calcdata
if(oldCalcdata.length === newFullData.length) {
for(i = 0; i < newFullData.length; i++) {
var newTrace = newFullData[i];
var cd0 = oldCalcdata[i][0];
if(cd0 && cd0.trace) {
if(cd0.trace._hasCalcTransform) {
remapTransformedArrays(cd0, newTrace);
} else {
cd0.trace = newTrace;
}
}
}
if(!skipCalcUpdate && oldCalcdata.length === newFullData.length) {
plots.supplyDefaultsUpdateCalc(oldCalcdata, newFullData);
}

// sort base plot modules for consistent ordering
newFullLayout._basePlotModules.sort(sortBasePlotModules);
};

plots.supplyDefaultsUpdateCalc = function(oldCalcdata, newFullData) {
for(var i = 0; i < newFullData.length; i++) {
var newTrace = newFullData[i];
var cd0 = oldCalcdata[i][0];
if(cd0 && cd0.trace) {
if(cd0.trace._hasCalcTransform) {
remapTransformedArrays(cd0, newTrace);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remapTransformedArrays is only called from here, maybe we could merge it in here?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merged and 🐎 remapTransformedArrays -> 2a41f9e

} else {
cd0.trace = newTrace;
}
}
}
};

/**
* Make a container for collecting subplots we need to display.
*
Expand Down Expand Up @@ -1174,6 +1178,11 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex)
};

plots.supplyTransformDefaults = function(traceIn, traceOut, layout) {
// For now we only allow transforms on 1D traces, ie those that specify a _length.
// If we were to implement 2D transforms, we'd need to have each transform
// describe its own applicability and disable itself when it doesn't apply.
if(!traceOut._length) return;

var globalTransforms = layout._globalTransforms || [];
var transformModules = layout._transformModules || [];

Expand Down
3 changes: 1 addition & 2 deletions src/traces/box/calc.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,11 @@ module.exports = function calc(gd, trace) {
var dPos = dv.minDiff / 2;
var posBins = makeBins(posDistinct, dPos);

var vLen = val.length;
var pLen = posDistinct.length;
var ptsPerBin = initNestedArray(pLen);

// bin pts info per position bins
for(i = 0; i < vLen; i++) {
for(i = 0; i < trace._length; i++) {
var v = val[i];
if(!isNumeric(v)) continue;

Expand Down
13 changes: 11 additions & 2 deletions src/traces/box/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,28 @@ function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function handleSampleDefaults(traceIn, traceOut, coerce, layout) {
var y = coerce('y');
var x = coerce('x');
var hasX = x && x.length;

var defaultOrientation;
var defaultOrientation, len;

if(y && y.length) {
defaultOrientation = 'v';
if(!x) coerce('x0');
if(hasX) {
len = Math.min(x.length, y.length);
}
else {
coerce('x0');
len = y.length;
}
} else if(x && x.length) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be hasX.

defaultOrientation = 'h';
coerce('y0');
len = x.length;
} else {
traceOut.visible = false;
return;
}
traceOut._length = len;

var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);
Expand Down
Loading