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
This commit is contained in:
Evert Timberg 2020-12-14 05:04:10 -05:00 committed by GitHub
parent 93c3467182
commit e268845c7b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 7 deletions

View File

@ -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) {

View File

@ -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({