From: Evert Timberg Date: Mon, 14 Dec 2020 10:04:10 +0000 (-0500) Subject: Quick exit the legend fit function when the legend is not displayed (#8161) X-Git-Tag: v3.0.0-beta.8~69 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=e268845c7ba2a01529619c0ec70c5b5dae7211e8;p=thirdparty%2FChart.js.git Quick exit the legend fit function when the legend is not displayed (#8161) When the legend is not displayed, there are no guarantees that the format of the options dictionary is correct. Rather than performing computations and then exiting without using the results, we can instead exit quickly since the size of the legend will be (0, 0) if not displayed --- diff --git a/src/plugins/plugin.legend.js b/src/plugins/plugin.legend.js index 529f82a77..e90e58816 100644 --- a/src/plugins/plugin.legend.js +++ b/src/plugins/plugin.legend.js @@ -183,6 +183,16 @@ export class Legend extends Element { const labelOpts = opts.labels; const display = opts.display; + // The legend may not be displayed for a variety of reasons including + // the fact that the defaults got set to `false`. + // When the legend is not displayed, there are no guarantees that the options + // are correctly formatted so we need to bail out as early as possible. + const minSize = me._minSize; + if (!display) { + me.width = minSize.width = me.height = minSize.height = 0; + return; + } + const ctx = me.ctx; const labelFont = toFont(labelOpts.font, me.chart.options.font); const fontSize = labelFont.size; @@ -192,8 +202,6 @@ export class Legend extends Element { // Reset hit boxes const hitboxes = me.legendHitBoxes = []; - - const minSize = me._minSize; const isHorizontal = me.isHorizontal(); const titleHeight = me._computeTitleHeight(); @@ -205,11 +213,6 @@ export class Legend extends Element { minSize.height = me.maxHeight; // fill all the height } - // Increase sizes here - if (!display) { - me.width = minSize.width = me.height = minSize.height = 0; - return; - } ctx.font = labelFont.string; if (isHorizontal) { diff --git a/test/specs/plugin.legend.tests.js b/test/specs/plugin.legend.tests.js index 36a3439f4..2a333fed4 100644 --- a/test/specs/plugin.legend.tests.js +++ b/test/specs/plugin.legend.tests.js @@ -706,6 +706,34 @@ describe('Legend block tests', function() { }]); }); + it('should not crash when the legend defaults are false', function() { + const oldDefaults = Chart.defaults.plugins.legend; + + Chart.defaults.set({ + plugins: { + legend: false, + }, + }); + + var chart = window.acquireChart({ + type: 'doughnut', + data: { + datasets: [{ + label: 'dataset1', + data: [1, 2, 3, 4] + }], + labels: ['', '', '', ''] + }, + }); + expect(chart).toBeDefined(); + + Chart.defaults.set({ + plugins: { + legend: oldDefaults, + }, + }); + }); + describe('config update', function() { it ('should update the options', function() { var chart = acquireChart({