Skip to content

Commit

Permalink
Format the label in the time scale tooltip
Browse files Browse the repository at this point in the history
  • Loading branch information
benmccann committed Jan 7, 2018
1 parent 92d033b commit 280de02
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 15 deletions.
42 changes: 29 additions & 13 deletions src/scales/scale.time.js
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,33 @@ function ticksFromTimestamps(values, majorUnit) {
return ticks;
}

function determineLabelFormat(data, timeOpts) {
var i, momentDate, hasMillis, hasTime;

if (timeOpts.tooltipFormat) {
return timeOpts.tooltipFormat;
}

// find the label with the most parts (milliseconds, minutes, etc.)
// format all labels with the same level of detail as the most specific label
for (i = 0; i < data.length; i++) {
momentDate = momentify(data[i], timeOpts);
if (momentDate.millisecond() !== 0) {
hasMillis = true;
break;
}
if (momentDate.second() !== 0 || momentDate.minute() !== 0 || momentDate.hour() !== 0) {
hasTime = true;
}
}
if (hasMillis) {
return 'MMM D, YYYY h:mm:ss.SSS a';
} else if (hasTime) {
return 'MMM D, YYYY h:mm:ss a';
}
return 'MMM D, YYYY';
}

module.exports = function(Chart) {

var defaultConfig = {
Expand Down Expand Up @@ -621,25 +648,14 @@ module.exports = function(Chart) {
me._majorUnit = determineMajorUnit(me._unit);
me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution);
me._offsets = computeOffsets(me._table, ticks, min, max, options);
me._labelFormat = determineLabelFormat(me._timestamps.data, timeOpts);

return ticksFromTimestamps(ticks, me._majorUnit);
},

getLabelForIndex: function(index, datasetIndex) {
var me = this;
var data = me.chart.data;
var timeOpts = me.options.time;
var label = data.labels && index < data.labels.length ? data.labels[index] : '';
var value = data.datasets[datasetIndex].data[index];

if (helpers.isObject(value)) {
label = me.getRightValue(value);
}
if (timeOpts.tooltipFormat) {
label = momentify(label, timeOpts).format(timeOpts.tooltipFormat);
}

return label;
return momentify(me._timestamps.data[index], me.options.time).format(me._labelFormat);
},

/**
Expand Down
4 changes: 2 additions & 2 deletions test/specs/scale.time.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -580,8 +580,8 @@ describe('Time scale tests', function() {

var xScale = chart.scales.xScale0;
expect(xScale.getLabelForIndex(0, 0)).toBeTruthy();
expect(xScale.getLabelForIndex(0, 0)).toBe('2015-01-01T20:00:00');
expect(xScale.getLabelForIndex(6, 0)).toBe('2015-01-10T12:00');
expect(xScale.getLabelForIndex(0, 0)).toBe('Jan 1, 2015 8:00:00 pm');
expect(xScale.getLabelForIndex(6, 0)).toBe('Jan 10, 2015 12:00:00 pm');
});

it('should get the correct pixel for only one data in the dataset', function() {
Expand Down

0 comments on commit 280de02

Please sign in to comment.