Skip to content

Commit 2cb5f93

Browse files
authored
Fix errors from zero-dimension scales (#544)
Trying to pan a zero-dimension linear scale results in a `RangeError: minimumFractionDigits value is out of range` when LinearBaseScale tries to format its ticks. This can happen a couple of ways: * If a scale is configured with an identical min and max - that seems like a misconfiguration, but Chart.js by itself at least attempts to handle it. * If the browser window is shrunk enough for the chart area to have 0 dimensions The problem occurs because panNumericalScale calculates a newMin and newMax of NaN here. This, in turn, is because getDecimalForPixel (used by getValueForPixel) and getPixelForValue return NaN for 0-dimension scales. Fixes #543
1 parent 75bce9a commit 2cb5f93

2 files changed

Lines changed: 37 additions & 2 deletions

File tree

src/scale.types.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,8 +134,11 @@ function panNumericalScale(scale, delta, limits, canZoom = false) {
134134
const newMin = scale.getValueForPixel(scale.getPixelForValue(prevStart + offset) - delta);
135135
const newMax = scale.getValueForPixel(scale.getPixelForValue(prevEnd + offset) - delta);
136136
const {min: minLimit = -Infinity, max: maxLimit = Infinity} = canZoom && limits && limits[scale.axis] || {};
137-
if ((newMin < minLimit || newMax > maxLimit)) {
138-
return true; // At limit: No change but return true to indicate no need to store the delta.
137+
if (isNaN(newMin) || isNaN(newMax) || newMin < minLimit || newMax > maxLimit) {
138+
// At limit: No change but return true to indicate no need to store the delta.
139+
// NaN can happen for 0-dimension scales (either because they were configured
140+
// with min === max or because the chart has 0 plottable area).
141+
return true;
139142
}
140143
return updateRange(scale, {min: newMin, max: newMax}, limits, canZoom);
141144
}

test/specs/pan.spec.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,38 @@ describe('pan', function() {
9292
expect(scale.min).toBeLessThan(2);
9393
expect(scale.max).toBe(scale.min + 2);
9494
});
95+
96+
it('should handle zero-dimension scales', function() {
97+
const chart = window.acquireChart({
98+
type: 'line',
99+
data,
100+
options: {
101+
plugins: {
102+
zoom: {
103+
pan: {
104+
enabled: true,
105+
mode: 'y',
106+
}
107+
}
108+
},
109+
scales: {
110+
y: {
111+
type: 'linear',
112+
min: 2,
113+
max: 2
114+
}
115+
}
116+
}
117+
});
118+
const scale = chart.scales.y;
119+
expect(scale.min).toBe(2);
120+
expect(scale.max).toBe(2);
121+
chart.pan(50);
122+
expect(scale.min).toBe(2);
123+
expect(scale.max).toBe(2);
124+
expect(scale.options.min).toBe(2);
125+
expect(scale.options.max).toBe(2);
126+
});
95127
});
96128

97129
describe('events', function() {

0 commit comments

Comments
 (0)