Skip to content

sankey: implement node grouping via mouse selection #3712

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 8 commits into from
Apr 8, 2019
11 changes: 11 additions & 0 deletions src/components/modebar/buttons.js
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,17 @@ function toggleHover(gd) {
Registry.call('_guiRelayout', gd, 'hovermode', newHover);
}

modeBarButtons.resetSankeyGroup = {
name: 'resetSankeyGroup',
title: function(gd) { return _(gd, 'Ungroup all nodes'); },
icon: Icons.home,
click: function(gd) {
Registry.call('restyle', gd, {
'node.groups': [[]],
Copy link
Contributor

@etpinard etpinard Apr 4, 2019

Choose a reason for hiding this comment

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

As we discussed in person, it might be better to restyle back to the "initial" view rather than to just remove all the groups.

To do so:

  • stash the 'initial' node.(x|y) and groups in fullData[i] (see mapbox example)
  • call restyle with the values in that stash each in the modebar button handler (see example)

Copy link
Contributor

@etpinard etpinard Apr 8, 2019

Choose a reason for hiding this comment

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

@antoinerg let me know if you need help implementing this 😄

Copy link
Contributor Author

Choose a reason for hiding this comment

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

call restyle with the values in that stash each in the modebar button handler (see example)

I don't think I can reuse resetView because it does a relayout whereas we need a restyle.

Copy link
Contributor

Choose a reason for hiding this comment

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

Right, no need to use resetView() found in modebar/buttons.js, but you should try to replicate the same pattern.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done in commit 506da4c! Let me know if it is satisfactory.

I will now write Jasmine tests for the reset button. Is there anything else you would like me to add?

Copy link
Contributor

Choose a reason for hiding this comment

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

I will now write Jasmine tests for the reset button. Is there anything else you would like me to add?

Nop, once that jasmine test is in, this one will be good to go!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done in f8a4073

});
}
};

// buttons when more then one plot types are present

modeBarButtons.toggleHover = {
Expand Down
4 changes: 4 additions & 0 deletions src/components/modebar/manage.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ function getButtonGroups(gd, buttonsToRemove, buttonsToAdd, showSendToCloud) {
var hasTernary = fullLayout._has('ternary');
var hasMapbox = fullLayout._has('mapbox');
var hasPolar = fullLayout._has('polar');
var hasSankey = fullLayout._has('sankey');
var allAxesFixed = areAllAxesFixed(fullLayout);

var groups = [];
Expand Down Expand Up @@ -139,6 +140,9 @@ function getButtonGroups(gd, buttonsToRemove, buttonsToAdd, showSendToCloud) {
else if(hasPie) {
hoverGroup = ['hoverClosestPie'];
}
else if(hasSankey) {
hoverGroup = ['resetSankeyGroup'];
}
else { // hasPolar, hasTernary
// always show at least one hover icon.
hoverGroup = ['toggleHover'];
Expand Down
9 changes: 9 additions & 0 deletions src/plots/cartesian/select.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ function prepSelect(e, startX, startY, dragOptions, mode) {
var allAxes = dragOptions.xaxes.concat(dragOptions.yaxes);
var subtract = e.altKey;

var doneFnCompleted = dragOptions.doneFnCompleted;

var filterPoly, selectionTester, mergedPolygons, currentPolygon;
var i, searchInfo, eventData;

Expand Down Expand Up @@ -284,6 +286,8 @@ function prepSelect(e, startX, startY, dragOptions, mode) {
dragOptions.mergedPolygons.length = 0;
[].push.apply(dragOptions.mergedPolygons, mergedPolygons);
}

doneFnCompleted(selection);
Copy link
Contributor

Choose a reason for hiding this comment

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

I like this solution a lot. Very clean 🥇

});
};
}
Expand Down Expand Up @@ -519,6 +523,11 @@ function determineSearchTraces(gd, xAxes, yAxes, subplot) {
var info = createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]);
info.scene = gd._fullLayout._splomScenes[trace.uid];
searchTraces.push(info);
} else if(
trace.type === 'sankey'
) {
var sankeyInfo = createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]);
searchTraces.push(sankeyInfo);
} else {
if(xAxisIds.indexOf(trace.xaxis) === -1) continue;
if(yAxisIds.indexOf(trace.yaxis) === -1) continue;
Expand Down
97 changes: 97 additions & 0 deletions src/traces/sankey/base_plot.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ var getModuleCalcData = require('../../plots/get_data').getModuleCalcData;
var plot = require('./plot');
var fxAttrs = require('../../components/fx/layout_attributes');

var setCursor = require('../../lib/setcursor');
var dragElement = require('../../components/dragelement');
var prepSelect = require('../../plots/cartesian/select').prepSelect;
var Lib = require('../../lib');
var Registry = require('../../registry');

var SANKEY = 'sankey';

exports.name = SANKEY;
Expand All @@ -34,3 +40,94 @@ exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout)
oldFullLayout._paperdiv.selectAll('.sankey').remove();
}
};

exports.updateFx = function(gd) {
for(var i = 0; i < gd._fullData.length; i++) {
subplotUpdateFx(gd, i);
}
};

var dragOptions = [];
function subplotUpdateFx(gd, index) {
var i = index;
var fullData = gd._fullData[i];
var fullLayout = gd._fullLayout;

var dragMode = fullLayout.dragmode;
var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair';
var bgRect = fullData._bgRect;

setCursor(bgRect, cursor);

var xaxis = {
_id: 'x',
c2p: function(v) { return v; },
_offset: fullData._sankey.translateX,
_length: fullData._sankey.width
};
var yaxis = {
_id: 'y',
c2p: function(v) { return v; },
_offset: fullData._sankey.translateY,
_length: fullData._sankey.height
};

// Note: dragOptions is needed to be declared for all dragmodes because
// it's the object that holds persistent selection state.
dragOptions[i] = {
gd: gd,
element: bgRect.node(),
plotinfo: {
id: i,
xaxis: xaxis,
yaxis: yaxis,
fillRangeItems: Lib.noop
},
subplot: i,
// create mock x/y axes for hover routine
xaxes: [xaxis],
yaxes: [yaxis],
doneFnCompleted: function(selection) {
var newGroups;
var oldGroups = gd._fullData[i].node.groups.slice();
var newGroup = [];

function findNode(pt) {
return gd._fullData[i]._sankey.graph.nodes.find(function(n) {
return n.pointNumber === pt;
});
}

for(var j = 0; j < selection.length; j++) {
var node = findNode(selection[j].pointNumber);
if(!node) continue;

// If the node represents a group
if(node.group) {
// Add all its children to the current selection
for(var k = 0; k < node.childrenNodes.length; k++) {
newGroup.push(node.childrenNodes[k].pointNumber);
}
// Flag group for removal from existing list of groups
oldGroups[node.pointNumber - fullData.node._count] = false;
} else {
newGroup.push(node.pointNumber);
}
}

newGroups = oldGroups
.filter(function(g) { return g; })
.concat([newGroup]);

Registry.call('_guiRestyle', gd, {
'node.groups': [ newGroups ]
}, i).catch(Lib.noop); // TODO will this ever fail?
}
};

dragOptions[i].prepFn = function(e, startX, startY) {
prepSelect(e, startX, startY, dragOptions[i], dragMode);
Copy link
Contributor

Choose a reason for hiding this comment

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

... and I guess prepSelect does the right thing when dragmode isn't select nor lasso?

Copy link
Contributor

Choose a reason for hiding this comment

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

Ahh. This is tricky actually for sankey, dragmode values zoom and pan don't really make sense. I'm not sure if we can do anything about it in v1. Would it be ok to have zoom and pan correspond to the current "drag-on-nodes" behaviour?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Would it be ok to have zoom and pan correspond to the current "drag-on-nodes" behavior?

Yes, I think it would be OK. I will return early in subplotUpdateFx when dragMode is either zoom or pan.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done in aa17f1b

};

dragElement.init(dragOptions[i]);
}
1 change: 1 addition & 0 deletions src/traces/sankey/calc.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ function convertToD3Sankey(trace) {
if(linkSpec.target[i] > maxNodeId) maxNodeId = linkSpec.target[i];
}
var nodeCount = maxNodeId + 1;
trace.node._count = nodeCount;

// Group nodes
var j;
Expand Down
1 change: 1 addition & 0 deletions src/traces/sankey/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Plot.plot = require('./plot');
Plot.moduleType = 'trace';
Plot.name = 'sankey';
Plot.basePlotModule = require('./base_plot');
Plot.selectPoints = require('./select.js');
Plot.categories = ['noOpacity'];
Plot.meta = {
description: [
Expand Down
17 changes: 17 additions & 0 deletions src/traces/sankey/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,23 @@ module.exports = function(gd, svg, calcData, layout, callbacks) {
.style('pointer-events', 'auto')
.attr('transform', sankeyTransform);

sankey.each(function(d, i) {
gd._fullData[i]._sankey = d;

// Draw dragbox
Lib.ensureSingle(gd._fullLayout._draggers, 'rect', 'bg-' + i, function(el) {
el
.style('pointer-events', 'all')
.attr('width', d.width)
.attr('height', d.height)
.attr('x', d.translateX)
.attr('y', d.translateY)
.style({fill: 'transparent', 'stroke-width': 0});

gd._fullData[i]._bgRect = el;
});
});

sankey.transition()
.ease(c.ease).duration(c.duration)
.attr('transform', sankeyTransform);
Expand Down
36 changes: 36 additions & 0 deletions src/traces/sankey/select.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* Copyright 2012-2019, 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';

module.exports = function selectPoints(searchInfo, selectionTester) {
var cd = searchInfo.cd;
var selection = [];
var fullData = cd[0].trace;

var nodes = fullData._sankey.graph.nodes;

for(var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if(node.partOfGroup) continue; // Those are invisible

// TODO: decide on selection criteria, using centroid for now
var pos = [(node.x0 + node.x1) / 2, (node.y0 + node.y1) / 2];
Copy link
Contributor

Choose a reason for hiding this comment

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

Voting 👍 on centroid.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ok 👍 I 🔪 the TODO in 20d8c92

Maybe we should add a visual cue to let the user know a given node is now part of a selection 🤔 This could also be added later on.


// Swap x and y if trace is vertical
if(fullData.orientation === 'v') pos.reverse();

if(selectionTester.contains(pos, false, i, searchInfo)) {
selection.push({
pointNumber: node.pointNumber
// TODO: add eventData
});
}
}
return selection;
};