Respect min and max when building ticks (#4860)

Generate time scale ticks (`ticks.source: 'auto'`) based on the effective visualized range instead of the actual data range, meaning that the computed units and/or step size may change if the time options min and max are different from the data min and max.
This commit is contained in:
Ben McCann 2017-10-20 00:03:38 -07:00 committed by Simon Brunel
parent 11315fba2b
commit b64fd5db25
2 changed files with 24 additions and 8 deletions

View File

@ -504,8 +504,8 @@ module.exports = function(Chart) {
var me = this;
var chart = me.chart;
var timeOpts = me.options.time;
var min = parse(timeOpts.min, me) || MAX_INTEGER;
var max = parse(timeOpts.max, me) || MIN_INTEGER;
var min = MAX_INTEGER;
var max = MIN_INTEGER;
var timestamps = [];
var datasets = [];
var labels = [];
@ -552,6 +552,9 @@ module.exports = function(Chart) {
max = Math.max(max, timestamps[timestamps.length - 1]);
}
min = parse(timeOpts.min, me) || min;
max = parse(timeOpts.max, me) || max;
// In case there is no valid min/max, let's use today limits
min = min === MAX_INTEGER ? +moment().startOf('day') : min;
max = max === MIN_INTEGER ? +moment().endOf('day') + 1 : max;

View File

@ -376,23 +376,36 @@ describe('Time scale tests', function() {
var config;
beforeEach(function() {
config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('time'));
config.ticks.source = 'labels';
config.time.unit = 'day';
});
it('should use the min option', function() {
config.time.unit = 'day';
it('should use the min option when less than first label for building ticks', function() {
config.time.min = '2014-12-29T04:00:00';
var scale = createScale(mockData, config);
expect(scale.ticks[0]).toEqual('Dec 31');
expect(scale.ticks[0]).toEqual('Jan 1');
});
it('should use the max option', function() {
config.time.unit = 'day';
it('should use the min option when greater than first label for building ticks', function() {
config.time.min = '2015-01-02T04:00:00';
var scale = createScale(mockData, config);
expect(scale.ticks[0]).toEqual('Jan 2');
});
it('should use the max option when greater than last label for building ticks', function() {
config.time.max = '2015-01-05T06:00:00';
var scale = createScale(mockData, config);
expect(scale.ticks[scale.ticks.length - 1]).toEqual('Jan 3');
});
expect(scale.ticks[scale.ticks.length - 1]).toEqual('Jan 5');
it('should use the max option when less than last label for building ticks', function() {
config.time.max = '2015-01-02T23:00:00';
var scale = createScale(mockData, config);
expect(scale.ticks[scale.ticks.length - 1]).toEqual('Jan 2');
});
});