Update public/scripts/trends.js

This commit is contained in:
JoshBaneyCS 2025-04-30 02:21:43 +00:00
parent 9283a6d31a
commit 1c312ab0a5

View File

@ -1,6 +1,6 @@
// public/scripts/trends.js
// ─── Configuration for timeframes ─────────────────────────────────────────────
// ─── Timeframe options ───────────────────────────────────────────────────────
const tfConfig = [
{ unit:'hours', count:24, label:'Last 24 Hours' },
{ unit:'days', count:7, label:'Last 7 Days' },
@ -9,17 +9,19 @@ const tfConfig = [
{ unit:'years', count:1, label:'All Time' }
];
// ─── Helpers ──────────────────────────────────────────────────────────────────
// Reformat EST SQL timestamp "YYYY-MM-DD HH:mm:ss" → "M/D/YY @HH:mm"
// ─── Helpers ─────────────────────────────────────────────────────────────────
function formatESTTimestamp(ts) {
const [datePart, timePart] = ts.split(' ');
const [Y, M, D] = datePart.split('-').map(n => parseInt(n, 10));
const [h, m] = timePart.split(':');
const YY = String(Y).slice(-2);
return `${M}/${D}/${YY} @${h.padStart(2,'0')}:${m}`;
const [date, time] = ts.split(' ');
const [Y, M, D] = date.split('-').map(n=>parseInt(n,10));
const [h, m] = time.split(':');
return `${M}/${D}/${String(Y).slice(-2)} @${h.padStart(2,'0')}:${m}`;
}
function parseLocalDate(ts) {
const [date, time] = ts.split(' ');
const [Y, M, D] = date.split('-').map(n=>parseInt(n,10));
const [h, m, s] = time.split(':').map(n=>parseInt(n,10));
return new Date(Y, M-1, D, h, m, s);
}
// Subtract count units from a Date
function subtract(date, count, unit) {
const d = new Date(date);
switch(unit) {
@ -32,11 +34,11 @@ function subtract(date, count, unit) {
return d;
}
// ─── State ────────────────────────────────────────────────────────────────────
// ─── State & Chart Ref ───────────────────────────────────────────────────────
let readings = [];
let chart;
// ─── Initialize on page load ─────────────────────────────────────────────────
// ─── On Load ─────────────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', async() => {
await loadReadings();
setupUI();
@ -44,19 +46,19 @@ document.addEventListener('DOMContentLoaded', async () => {
updateView();
});
// ─── Load readings from API ───────────────────────────────────────────────────
// ─── Load & parse readings ───────────────────────────────────────────────────
async function loadReadings() {
const data = await fetch('/api/readings').then(r=>r.json());
readings = data.map(r => ({
...r,
formattedTs: formatESTTimestamp(r.timestamp),
dateObj: new Date(r.timestamp.replace(' ', 'T'))
dateObj: parseLocalDate(r.timestamp)
}));
}
// ─── UI Wiring ────────────────────────────────────────────────────────────────
// ─── UI wiring ───────────────────────────────────────────────────────────────
function setupUI() {
// Timeframe slider + label
// timeframe slider
const slider = document.getElementById('timeframe-slider');
const label = document.getElementById('timeframe-label');
slider.addEventListener('input', ()=>{
@ -65,12 +67,12 @@ function setupUI() {
});
label.textContent = tfConfig[slider.value].label;
// Metric toggles
// metric toggles
document.getElementsByName('metric').forEach(cb => {
cb.addEventListener('change', updateView);
});
// Table sorting
// table sorting
document.querySelectorAll('#trends-table thead th.sortable').forEach(th=>{
th.addEventListener('click', ()=>{
const idx = th.cellIndex;
@ -78,11 +80,11 @@ function setupUI() {
const tbody = document.getElementById('trends-table-body');
const rows = Array.from(tbody.rows);
rows.sort((a,b)=>{
const aText = a.cells[idx].textContent;
const bText = b.cells[idx].textContent;
const av = a.cells[idx].textContent;
const bv = b.cells[idx].textContent;
return asc
? aText.localeCompare(bText, undefined, { numeric: true })
: bText.localeCompare(aText, undefined, { numeric: true });
? av.localeCompare(bv,undefined,{numeric:true})
: bv.localeCompare(av,undefined,{numeric:true});
});
th.classList.toggle('asc', asc);
rows.forEach(r=>tbody.appendChild(r));
@ -90,7 +92,7 @@ function setupUI() {
});
}
// ─── Initialize Chart.js line chart ───────────────────────────────────────────
// ─── Chart.js setup ──────────────────────────────────────────────────────────
function initChart() {
const ctx = document.getElementById('trend-chart').getContext('2d');
chart = new Chart(ctx, {
@ -98,8 +100,8 @@ function initChart() {
data: { labels: [], datasets: [] },
options: {
scales: {
x: { display: true, title: { display: true, text: 'Time (EST)' } },
y: { display: true, title: { display: true, text: 'Value' } }
x: { title: { display:true, text:'Time (EST)' } },
y: { title: { display:true, text:'Value' } }
},
interaction: { mode:'index', intersect:false },
plugins: { legend:{ position:'top' } },
@ -108,45 +110,27 @@ function initChart() {
});
}
// ─── Update both chart & table based on UI state ─────────────────────────────
// ─── Render chart & table ───────────────────────────────────────────────────
function updateView() {
// Determine timeframe cutoff
const idx = +document.getElementById('timeframe-slider').value;
const { unit, count } = tfConfig[idx];
const cutoff = subtract(new Date(), count, unit);
// Filter readings
const filtered = readings.filter(r => r.dateObj >= cutoff);
// Determine selected metrics
const selected = Array.from(document.getElementsByName('metric'))
.filter(cb => cb.checked)
.map(cb => cb.value);
.filter(cb=>cb.checked).map(cb=>cb.value);
// Prepare chart labels & datasets
const labels = filtered.map(r=>r.formattedTs);
const datasets = [];
if (selected.includes('temperature')) {
datasets.push({
label: 'Temperature (°F)',
data: filtered.map(r => r.temperature),
tension: 0.3
});
datasets.push({ label:'Temperature (°F)', data:filtered.map(r=>r.temperature), tension:0.3 });
}
if (selected.includes('humidity')) {
datasets.push({
label: 'Humidity (%)',
data: filtered.map(r => r.humidity),
tension: 0.3
});
datasets.push({ label:'Humidity (%)', data:filtered.map(r=>r.humidity), tension:0.3 });
}
if (selected.includes('heatIndex')) {
datasets.push({
label: 'Heat Index (°F)',
data: filtered.map(r => r.heatIndex),
tension: 0.3
});
datasets.push({ label:'Heat Index (°F)', data:filtered.map(r=>r.heatIndex), tension:0.3 });
}
chart.data.labels = labels;
@ -156,7 +140,7 @@ function updateView() {
populateTable(filtered);
}
// ─── Populate the trends table ────────────────────────────────────────────────
// ─── Populate the table ─────────────────────────────────────────────────────
function populateTable(data) {
const tbody = document.getElementById('trends-table-body');
tbody.innerHTML = '';