diff --git a/draftlogs/8213_fix.md b/draftlogs/8213_fix.md new file mode 100644 index 00000000000..a581763105e --- /dev/null +++ b/draftlogs/8213_fix.md @@ -0,0 +1 @@ +- Fix Sankey traces throwing "Invalid array length" when no link is valid [[#8213](https://github.com/plotly/plotly.js/pull/8213)], with thanks to @Pedroveras-dev for the contribution! diff --git a/src/traces/sankey/render.js b/src/traces/sankey/render.js index a62ad4555ac..91d3d10d075 100644 --- a/src/traces/sankey/render.js +++ b/src/traces/sankey/render.js @@ -88,7 +88,8 @@ function sankeyModel(layout, d, traceIndex) { applyInputSort('link'); applyInputSort('node'); - var graph = sankey(); + // d3-sankey throws on an empty graph + const graph = nodes.length ? sankey() : { nodes: [], links: [] }; if(sankey.nodePadding() < nodePad) { Lib.warn('node.pad was reduced to ', sankey.nodePadding(), ' to fit within the figure.'); diff --git a/test/jasmine/tests/sankey_test.js b/test/jasmine/tests/sankey_test.js index 5e3598002cc..8edc5f90674 100644 --- a/test/jasmine/tests/sankey_test.js +++ b/test/jasmine/tests/sankey_test.js @@ -592,6 +592,53 @@ describe('sankey tests', function () { .then(done, done.fail); }); + it('renders a Sankey trace without valid links', (done) => { + const assertEmpty = () => { + expect(d3SelectAll('.sankey .sankey-node').size()).toBe(0); + expect(d3SelectAll('.sankey .sankey-link').size()).toBe(0); + }; + + Plotly.newPlot(gd, [{ type: 'sankey' }]) + .then(assertEmpty) + .then(() => + Plotly.newPlot(gd, [ + { + type: 'sankey', + node: { label: ['a', 'b'] }, + link: { source: [0], target: [1], value: [0] } + } + ]) + ) + .then(assertEmpty) + .then(done, done.fail); + }); + + it('switches between empty and non-empty Sankey on react', (done) => { + const emptyCopy = Lib.extendDeep({}, mock); + emptyCopy.data[0].link = { source: [], target: [], value: [] }; + + Plotly.newPlot(gd, Lib.extendDeep({}, mock)) + .then(() => { + expect(d3SelectAll('.sankey .sankey-node').size()).toBeGreaterThan(0); + expect(d3SelectAll('.sankey .sankey-link').size()).toBeGreaterThan(0); + + return Plotly.react(gd, emptyCopy); + }) + .then(delay(1000)) + .then(() => { + expect(d3SelectAll('.sankey .sankey-node').size()).toBe(0); + expect(d3SelectAll('.sankey .sankey-link').size()).toBe(0); + + return Plotly.react(gd, Lib.extendDeep({}, mock)); + }) + .then(delay(1000)) + .then(() => { + expect(d3SelectAll('.sankey .sankey-node').size()).toBeGreaterThan(0); + expect(d3SelectAll('.sankey .sankey-link').size()).toBeGreaterThan(0); + }) + .then(done, done.fail); + }); + it('falls back to the default sort for circular Sankey with node.sort set', (done) => { const warnings = []; spyOn(Lib, 'warn').and.callFake((msg) => {