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

View File

@ -129,9 +129,24 @@ class StateHistoryChartTimeline extends Polymer.Element {
labels.push(entityDisplay); 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 = { const chartOptions = {
type: 'timeline', type: 'timeline',
options: { options: {
tooltips: {
callbacks: {
label: formatTooltipLabel
}
},
scales: { scales: {
xAxes: [{ xAxes: [{
ticks: { ticks: {