From: Jukka Kurkela Date: Sat, 14 Nov 2020 22:00:17 +0000 (+0200) Subject: CategoryScale: automatically add missing labels (#8053) X-Git-Tag: v3.0.0-beta.7~41 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=ef89abb84b66f1d738d48c30bfad3ceed56b0b28;p=thirdparty%2FChart.js.git CategoryScale: automatically add missing labels (#8053) CategoryScale: automatically add missing labels --- diff --git a/src/scales/scale.category.js b/src/scales/scale.category.js index 1c8c93328..d61d4c5ff 100644 --- a/src/scales/scale.category.js +++ b/src/scales/scale.category.js @@ -1,5 +1,14 @@ import Scale from '../core/core.scale'; +function findOrAddLabel(labels, raw, index) { + const first = labels.indexOf(raw); + if (first === -1) { + return typeof raw === 'string' ? labels.push(raw) - 1 : index; + } + const last = labels.lastIndexOf(raw); + return first !== last ? index : first; +} + export default class CategoryScale extends Scale { constructor(cfg) { @@ -12,12 +21,8 @@ export default class CategoryScale extends Scale { parse(raw, index) { const labels = this.getLabels(); - if (labels[index] === raw) { - return index; - } - const first = labels.indexOf(raw); - const last = labels.lastIndexOf(raw); - return first === -1 || first !== last ? index : first; + return isFinite(index) && labels[index] === raw + ? index : findOrAddLabel(labels, raw, index); } determineDataLimits() { diff --git a/test/fixtures/controller.bar/bar-skip-null-object-data.js b/test/fixtures/controller.bar/bar-skip-null-object-data.js index 3be0fc964..8690aec27 100644 --- a/test/fixtures/controller.bar/bar-skip-null-object-data.js +++ b/test/fixtures/controller.bar/bar-skip-null-object-data.js @@ -2,7 +2,6 @@ module.exports = { config: { type: 'bar', data: { - labels: [0, 1, 3, 4], datasets: [ { data: {0: 5, 1: 20, 2: 1, 3: 10}, diff --git a/test/specs/scale.category.tests.js b/test/specs/scale.category.tests.js index fe9c74c68..97183a822 100644 --- a/test/specs/scale.category.tests.js +++ b/test/specs/scale.category.tests.js @@ -90,6 +90,30 @@ describe('Category scale tests', function() { expect(getLabels(scale)).toEqual(labels); }); + it('Should generate missing labels', function() { + var labels = ['a', 'b', 'c', 'd']; + var chart = window.acquireChart({ + type: 'line', + data: { + datasets: [{ + data: {a: 1, b: 3, c: -1, d: 10} + }] + }, + options: { + scales: { + x: { + type: 'category', + labels: ['a'] + } + } + } + }); + + var scale = chart.scales.x; + expect(getLabels(scale)).toEqual(labels); + + }); + it('should get the correct label for the index', function() { var chart = window.acquireChart({ type: 'line',