Skip to content

Automargin fixes #2681

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 17 commits into from
Jun 6, 2018
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
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
85 changes: 85 additions & 0 deletions src/components/colorbar/connect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');

var aggNums = require('../../lib').aggNums;
var Colorscale = require('../colorscale');
var drawColorbar = require('./draw');

/**
* connectColorbar: create a colorbar from a trace, using its module to
* describe the connection.
*
* @param {DOM element} gd
*
* @param {Array} cd
* calcdata entry for this trace. cd[0].trace is the trace itself, and the
* colorbar object will be stashed in cd[0].t.cb
*
* @param {object|function} moduleOpts
* may be a function(gd, cd) to override the standard handling below. If
* an object, should have these keys:
* @param {Optional(string)} moduleOpts.container
* name of the container inside the trace where the colorbar and colorscale
* attributes live (ie 'marker', 'line') - omit if they're at the trace root.
* @param {string} moduleOpts.min
* name of the attribute holding the value of the minimum color
* @param {string} moduleOpts.max
* name of the attribute holding the value of the maximum color
* @param {Optional(string)} moduleOpts.vals
* name of the attribute holding the (numeric) color data
* used only if min/max fail. May be omitted if these are always
* pre-calculated.
*/
module.exports = function connectColorbar(gd, cd, moduleOpts) {
if(typeof moduleOpts === 'function') return moduleOpts(gd, cd);
Copy link
Contributor

Choose a reason for hiding this comment

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

Copy link
Contributor

Choose a reason for hiding this comment

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

... and that's the only exception?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yes, contour and those that inherit from it (contourcarpet, contourgl, histogram2dcontour).

I should note that there's one other place module.colorbar gets used, that's in colorbar.draw for getting the nestedProperty string for title editing. If contour colorbars weren't at the module root we'd need to set a container property of the function which would be a bit hacky... alternatively we could either a) make this function be module.colorbar.func, or b) incorporate contour into this routine directly, triggered by some other property of module.colorbar.

Copy link
Contributor

Choose a reason for hiding this comment

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

alternatively we could either a) make this function be module.colorbar.func

This sounds cleaner to me. But no need to do this in this PR.


var trace = cd[0].trace;
var cbId = 'cb' + trace.uid;
var containerName = moduleOpts.container;
var container = containerName ? trace[containerName] : trace;

gd._fullLayout._infolayer.selectAll('.' + cbId).remove();
if(!container || !container.showscale) return;

var zmin = container[moduleOpts.min];
var zmax = container[moduleOpts.max];

var valAttr = moduleOpts.vals;
var vals;
if(Array.isArray(valAttr)) {
for(var i = 0; i < valAttr.length; i++) {
vals = container[valAttr[i]];
if(vals) break;
}
}
else vals = container[valAttr];

if(vals) {
Copy link
Contributor

Choose a reason for hiding this comment

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

(Non-blocking) I'm curious to see what would happen (i.e. which tests would fail if any) if we drop the logic around vals here. cmin/cmax or zmin/zmax should always be computed during the calc step which should happen before this block.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

yeah, looks like calculating the range while drawing the colorbar is obsolete, good call! Though I can't seem to run the image tests all the way through locally anymore, so we'll see in a few minutes -> f9fbbc6

Copy link
Contributor

Choose a reason for hiding this comment

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

image

✅ nice!

if(!isNumeric(zmin)) zmin = aggNums(Math.min, null, vals);
if(!isNumeric(zmax)) zmax = aggNums(Math.max, null, vals);
}

var cb = cd[0].t.cb = drawColorbar(gd, cbId);
var sclFunc = Colorscale.makeColorScaleFunc(
Colorscale.extractScale(
container.colorscale,
zmin,
zmax
),
{ noNumericCheck: true }
);

cb.fillcolor(sclFunc)
.filllevels({start: zmin, end: zmax, size: (zmax - zmin) / 254})
.options(container.colorbar)();
};
10 changes: 4 additions & 6 deletions src/components/colorbar/draw.js
Original file line number Diff line number Diff line change
Expand Up @@ -447,12 +447,10 @@ module.exports = function draw(gd, id) {
}

function drawTitle(titleClass, titleOpts) {
var trace = getTrace(),
propName;
if(Registry.traceIs(trace, 'markerColorscale')) {
propName = 'marker.colorbar.title';
}
else propName = 'colorbar.title';
var trace = getTrace();
var propName = 'colorbar.title';
var containerName = trace._module.colorbar.container;
if(containerName) propName = containerName + '.' + propName;

var dfltTitleOpts = {
propContainer: cbAxisOut,
Expand Down
4 changes: 1 addition & 3 deletions src/components/colorbar/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@


exports.attributes = require('./attributes');

exports.supplyDefaults = require('./defaults');

exports.connect = require('./connect');
exports.draw = require('./draw');

exports.hasColorbar = require('./has_colorbar');
23 changes: 2 additions & 21 deletions src/components/rangeslider/draw.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,9 @@ module.exports = function(gd) {

// remove exiting sliders and their corresponding clip paths
rangeSliders.exit().each(function(axisOpts) {
var rangeSlider = d3.select(this),
opts = axisOpts[constants.name];

rangeSlider.remove();
var opts = axisOpts[constants.name];
fullLayout._topdefs.select('#' + opts._clipId).remove();
});

// remove push margin object(s)
if(rangeSliders.exit().size()) clearPushMargins(gd);
}).remove();
Copy link
Contributor

Choose a reason for hiding this comment

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

Ha exit().each() returns the exit selection, good to know.


// return early if no range slider is visible
if(rangeSliderData.length === 0) return;
Expand Down Expand Up @@ -602,16 +596,3 @@ function drawGrabbers(rangeSlider, gd, axisOpts, opts) {
});
grabAreaMax.attr('height', opts._height);
}

function clearPushMargins(gd) {
var pushMargins = gd._fullLayout._pushmargin || {},
keys = Object.keys(pushMargins);

for(var i = 0; i < keys.length; i++) {
var k = keys[i];

if(k.indexOf(constants.name) !== -1) {
Plots.autoMargin(gd, k);
}
}
}
70 changes: 28 additions & 42 deletions src/components/updatemenus/draw.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ module.exports = function draw(gd) {
* ...
*/

function clearAutoMargin(menuOpts) {
Plots.autoMargin(gd, autoMarginId(menuOpts));
}

// draw update menu container
var menus = fullLayout._menulayer
.selectAll('g.' + constants.containerClassName)
Expand All @@ -63,10 +67,15 @@ module.exports = function draw(gd) {
.classed(constants.containerClassName, true)
.style('cursor', 'pointer');

menus.exit().remove();

// remove push margin object(s)
if(menus.exit().size()) clearPushMargins(gd);
menus.exit().each(function() {
// Most components don't need to explicitly remove autoMargin, because
// marginPushers does this - but updatemenu updates don't go through
Copy link
Contributor

Choose a reason for hiding this comment

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

Why is this the case? Is it because updatemenus attributes are under the "arraydraw" edit type? But then, in this case layout sliders should also have the same problem.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Oh man, I missed sliders in this PR but sure enough, they still have the older pattern - thanks, I'll take a look at those.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Updated sliders in 3deab4c

// a full replot so we need to explicitly remove it.
// This is for removing *all* updatemenus, removing individuals is
// handled below, in hederGroups.exit
d3.select(this).selectAll('g.' + constants.headerGroupClassName)
.each(clearAutoMargin);
}).remove();

// return early if no update menus are visible
if(menuData.length === 0) return;
Expand Down Expand Up @@ -97,21 +106,13 @@ module.exports = function draw(gd) {
if(headerGroups.enter().size()) {
// make sure gButton is on top of all headers
gButton.node().parentNode.appendChild(gButton.node());

gButton
.call(removeAllButtons)
.attr(constants.menuIndexAttrName, '-1');
gButton.call(removeAllButtons);
}

headerGroups.exit().each(function(menuOpts) {
d3.select(this).remove();

gButton
.call(removeAllButtons)
.attr(constants.menuIndexAttrName, '-1');

Plots.autoMargin(gd, constants.autoMarginIdRoot + menuOpts._index);
});
gButton.call(removeAllButtons);
clearAutoMargin(menuOpts);
}).remove();

// draw headers!
headerGroups.each(function(menuOpts) {
Expand Down Expand Up @@ -219,16 +220,8 @@ function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) {
});

header.on('click', function() {
gButton.call(removeAllButtons);


// if this menu is active, fold the dropdown container
// otherwise, make this menu active
gButton.attr(
constants.menuIndexAttrName,
isActive(gButton, menuOpts) ?
-1 :
String(menuOpts._index)
gButton.call(removeAllButtons,
String(isActive(gButton, menuOpts) ? -1 : menuOpts._index)
);

drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
Expand Down Expand Up @@ -608,7 +601,7 @@ function findDimensions(gd, menuOpts) {
dims.lx = Math.round(dims.lx);
dims.ly = Math.round(dims.ly);

Plots.autoMargin(gd, constants.autoMarginIdRoot + menuOpts._index, {
Plots.autoMargin(gd, autoMarginId(menuOpts), {
x: menuOpts.x,
y: menuOpts.y,
l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0),
Expand All @@ -618,6 +611,10 @@ function findDimensions(gd, menuOpts) {
});
}

function autoMarginId(menuOpts) {
return constants.autoMarginIdRoot + menuOpts._index;
}

// set item positions (mutates posOpts)
function setItemPosition(item, menuOpts, posOpts, overrideOpts) {
overrideOpts = overrideOpts || {};
Expand Down Expand Up @@ -655,19 +652,8 @@ function setItemPosition(item, menuOpts, posOpts, overrideOpts) {
posOpts.index++;
}

function removeAllButtons(gButton) {
gButton.selectAll('g.' + constants.dropdownButtonClassName).remove();
}

function clearPushMargins(gd) {
var pushMargins = gd._fullLayout._pushmargin || {};
var keys = Object.keys(pushMargins);

for(var i = 0; i < keys.length; i++) {
var k = keys[i];

if(k.indexOf(constants.autoMarginIdRoot) !== -1) {
Plots.autoMargin(gd, k);
}
}
function removeAllButtons(gButton, newMenuIndexAttr) {
gButton
.attr(constants.menuIndexAttrName, newMenuIndexAttr || '-1')
.selectAll('g.' + constants.dropdownButtonClassName).remove();
}
33 changes: 20 additions & 13 deletions src/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -217,21 +217,24 @@ lib.simpleMap = function(array, func, x1, x2) {
return out;
};

// random string generator
lib.randstr = function randstr(existing, bits, base) {
/*
* Include number of bits, the base of the string you want
* and an optional array of existing strings to avoid.
*/
/**
* Random string generator
*
* @param {object} existing
* pass in strings to avoid as keys with truthy values
* @param {int} bits
* bits of information in the output string, default 24
* @param {int} base
* base of string representation, default 16. Should be a power of 2.
*/
lib.randstr = function randstr(existing, bits, base, _recursion) {
if(!base) base = 16;
if(bits === undefined) bits = 24;
if(bits <= 0) return '0';

var digits = Math.log(Math.pow(2, bits)) / Math.log(base),
res = '',
i,
b,
x;
var digits = Math.log(Math.pow(2, bits)) / Math.log(base);
var res = '';
var i, b, x;

for(i = 2; digits === Infinity; i *= 2) {
digits = Math.log(Math.pow(2, bits / i)) / Math.log(base) * i;
Expand All @@ -251,9 +254,13 @@ lib.randstr = function randstr(existing, bits, base) {
}

var parsed = parseInt(res, base);
if((existing && (existing.indexOf(res) > -1)) ||
if((existing && existing[res]) ||
(parsed !== Infinity && parsed >= Math.pow(2, bits))) {
return randstr(existing, bits, base);
if(_recursion > 10) {
lib.warn('randstr failed uniqueness');
return res;
}
return randstr(existing, bits, base, (_recursion || 0) + 1);
}
else return res;
};
Expand Down
2 changes: 1 addition & 1 deletion src/lib/svg_text_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ function cleanEscapesForTex(s) {
}

function texToSVG(_texString, _config, _callback) {
var randomID = 'math-output-' + Lib.randstr([], 64);
var randomID = 'math-output-' + Lib.randstr({}, 64);
var tmpDiv = d3.select('body').append('div')
.attr({id: randomID})
.style({visibility: 'hidden', position: 'absolute'})
Expand Down
3 changes: 1 addition & 2 deletions src/plot_api/edit_types.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ var layoutOpts = {
valType: 'flaglist',
extras: ['none'],
flags: [
'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'axrange', 'margins',
'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'axrange',
'layoutstyle', 'modebar', 'camera', 'arraydraw'
],
description: [
Expand All @@ -47,7 +47,6 @@ var layoutOpts = {
'*plot* calls `Plotly.plot` but without first clearing `gd.calcdata`.',
'*legend* only redraws the legend.',
'*ticks* only redraws axis ticks, labels, and gridlines.',
'*margins* recomputes ticklabel automargins.',
'*axrange* minimal sequence when updating axis ranges.',
'*layoutstyle* reapplies global and SVG cartesian axis styles.',
'*modebar* just updates the modebar.',
Expand Down
Loading