]> git.ipfire.org Git - thirdparty/Chart.js.git/commitdiff
Category: parse to valid index values only (#8697)
authorJukka Kurkela <jukka.kurkela@gmail.com>
Mon, 22 Mar 2021 21:20:03 +0000 (23:20 +0200)
committerGitHub <noreply@github.com>
Mon, 22 Mar 2021 21:20:03 +0000 (17:20 -0400)
src/scales/scale.category.js
test/specs/scale.category.tests.js

index 175bd3e8fde280b5a838f63f7f8742dfbc679666..28f57b082c9199bb36d5aa0d80dfa9148d639704 100644 (file)
@@ -1,5 +1,5 @@
 import Scale from '../core/core.scale';
-import {isNullOrUndef, valueOrDefault} from '../helpers';
+import {isNullOrUndef, valueOrDefault, _limitValue} from '../helpers';
 
 const addIfString = (labels, raw, index) => typeof raw === 'string'
   ? labels.push(raw) - 1
@@ -14,6 +14,8 @@ function findOrAddLabel(labels, raw, index) {
   return first !== last ? index : first;
 }
 
+const validIndex = (index, max) => index === null ? null : _limitValue(Math.round(index), 0, max);
+
 export default class CategoryScale extends Scale {
 
   constructor(cfg) {
@@ -29,8 +31,9 @@ export default class CategoryScale extends Scale {
       return null;
     }
     const labels = this.getLabels();
-    return isFinite(index) && labels[index] === raw
-      ? index : findOrAddLabel(labels, raw, valueOrDefault(index, raw));
+    index = isFinite(index) && labels[index] === raw ? index
+      : findOrAddLabel(labels, raw, valueOrDefault(index, raw));
+    return validIndex(index, labels.length - 1);
   }
 
   determineDataLimits() {
index 24bcf46b14b9312b04b652059ab1143895125c48..fe3aad52e7439f3003b846f259fd61adefdba9a0 100644 (file)
@@ -20,7 +20,6 @@ describe('Category scale tests', function() {
     });
   });
 
-
   it('Should generate ticks from the data xLabels', function() {
     var labels = ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'];
     var chart = window.acquireChart({
@@ -114,6 +113,42 @@ describe('Category scale tests', function() {
 
   });
 
+  it('should parse only to a valid index', function() {
+    var chart = window.acquireChart({
+      type: 'line',
+      data: {
+        datasets: [{
+          xAxisID: 'x',
+          yAxisID: 'y',
+          data: [10, 5, 0, 25, 78]
+        }],
+        labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5']
+      },
+      options: {
+        scales: {
+          x: {
+            type: 'category',
+            position: 'bottom'
+          },
+          y: {
+            type: 'linear'
+          }
+        }
+      }
+    });
+
+    var scale = chart.scales.x;
+
+    expect(scale.parse(-10)).toEqual(0);
+    expect(scale.parse(-0.1)).toEqual(0);
+    expect(scale.parse(4.1)).toEqual(4);
+    expect(scale.parse(5)).toEqual(4);
+    expect(scale.parse(1)).toEqual(1);
+    expect(scale.parse(1.4)).toEqual(1);
+    expect(scale.parse(1.5)).toEqual(2);
+    expect(scale.parse('tick2')).toEqual(1);
+  });
+
   it('should get the correct label for the index', function() {
     var chart = window.acquireChart({
       type: 'line',