Chart.js labels and ticks with proper locale formatting (#948)

* Use hassUtil to format time in timeline tooltip

* Also format time in timeline ticks

* Use hassUtil.formatTime instead of moment.format
This commit is contained in:
Max Prokhorov 2018-02-28 21:40:38 +03:00 committed by Paulus Schoutsen
parent 5966e872cf
commit 9c6d28fbc4
2 changed files with 36 additions and 6 deletions

View File

@ -200,16 +200,23 @@
} else {
this.set(['tooltip', 'yAlign'], 'no-transform');
}
const title = tooltip.title ? tooltip.title[0] || '' : '';
let str1;
let titleDate = null;
let formattedTitle;
if (title instanceof Date) {
str1 = moment(title).format('L LTS');
titleDate = title;
} else if (title instanceof moment) {
str1 = title.format('L LTS');
} else {
str1 = title;
titleDate = title.toDate();
}
this.set(['tooltip', 'title'], str1);
if (titleDate === null) {
formattedTitle = title;
} else {
formattedTitle = window.hassUtil.formatDateTime(titleDate);
}
this.set(['tooltip', 'title'], formattedTitle);
const bodyLines = tooltip.body.map(n => n.lines);
// Set Text
@ -262,6 +269,13 @@
})));
this.set('unit', this.data.unit);
}
_formatTickValue(value, index, values) {
if (values.length === 0) {
return value;
}
const date = new Date(values[index].value);
return window.hassUtil.formatTime(date);
}
drawChart() {
const data = this.data.data;
const ctx = this.$.chartCanvas;
@ -321,6 +335,7 @@
}
};
options = Chart.helpers.merge(options, this.data.options);
options.scales.xAxes[0].ticks.callback = this._formatTickValue;
if (this.data.type === 'timeline') {
// timeline is not zoomable, so dont capture mouse
this.set('isZoomable', false);

View File

@ -129,9 +129,24 @@ class StateHistoryChartTimeline extends Polymer.Element {
labels.push(entityDisplay);
});
const formatTooltipLabel = function (item, data) {
const values = data.datasets[item.datasetIndex].data[item.index];
const start = window.hassUtil.formatDateTime(values[0]);
const end = window.hassUtil.formatDateTime(values[1]);
const state = values[2];
return [state, start, end];
};
const chartOptions = {
type: 'timeline',
options: {
tooltips: {
callbacks: {
label: formatTooltipLabel
}
},
scales: {
xAxes: [{
ticks: {