agreg-server/server/frontend/public/assets/js/chart.js

78 lines
2.1 KiB
JavaScript
Raw Normal View History

const PERIOD_FORMATS = {
hour: { hour: "2-digit", minute: "2-digit", day: "2-digit", month: "short" },
day: { day: "2-digit", month: "short" },
week: { day: "2-digit", month: "short" },
month: { month: "short", year: "numeric" },
};
function formatPeriod(isoString, granularity) {
const date = new Date(isoString);
const opts = PERIOD_FORMATS[granularity] ?? PERIOD_FORMATS.day;
return date.toLocaleDateString("fr-FR", opts);
}
function showMessage(message) {
document.getElementById("consumption-chart").hidden = true;
const msg = document.getElementById("chart-message");
msg.textContent = message;
msg.hidden = false;
}
function hideMessage() {
document.getElementById("consumption-chart").hidden = false;
document.getElementById("chart-message").hidden = true;
}
function renderChart(points, granularity) {
if (!points || points.length === 0){
showMessage("Aucune donnée à afficher sur cette période");
return null;
}
hideMessage();
const canvas = document.getElementById("consumption-chart");
const labels = points.map((p) => formatPeriod(p.period, granularity));
2026-05-12 19:05:02 +02:00
const data = points.map((p) => p.delta_m3);
const style = getComputedStyle(document.documentElement);
const accent = style.getPropertyValue('--color-chart').trim();
let chart = new Chart(canvas, {
type: "bar",
data: {
labels,
datasets: [
{
label: "Consommation (m³)",
2026-05-12 19:05:02 +02:00
data,
backgroundColor: accent + 'cc',
borderColor: accent,
borderWidth: 1
},
],
},
options: {
responsive: true,
scales: {
2026-05-12 19:05:02 +02:00
x: {
grid: { display: false },
ticks: {
color: style.getPropertyValue("--color-text-muted").trim()
},
},
y: {
beginAtZero: true,
2026-05-12 19:05:02 +02:00
grid: { color: style.getPropertyValue("--color-border").trim() },
ticks: {
color: style.getPropertyValue("--color-text-muted").trim(),
callback: (v) => v.toFixed(2)
},
},
},
},
});
return chart;
}