Skip to content
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

CategoryScale: automatically add missing labels #8053

Merged
merged 3 commits into from
Nov 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions src/scales/scale.category.js
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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() {
Expand Down
1 change: 0 additions & 1 deletion test/fixtures/controller.bar/bar-skip-null-object-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down
24 changes: 24 additions & 0 deletions test/specs/scale.category.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down