Update public/scripts/trends.js

time
This commit is contained in:
JoshBaneyCS 2025-04-30 01:40:12 +00:00
parent 6cdf71f4bc
commit ccc9818242

View File

@ -1,20 +1,20 @@
// public/scripts/trends.js // public/scripts/trends.js
// ─── Configuration ──────────────────────────────────────────────────────────── // ─── Configuration for timeframes ─────────────────────────────────────────────
const tfConfig = [ const tfConfig = [
{ unit: 'hours', count: 24, label: 'Last 24 Hours' }, { unit: 'hours', count: 24, label: 'Last 24 Hours' },
{ unit: 'days', count: 7, label: 'Last 7 Days' }, { unit: 'days', count: 7, label: 'Last 7 Days' },
{ unit: 'weeks', count: 4, label: 'Last 4 Weeks' }, { unit: 'weeks', count: 4, label: 'Last 4 Weeks' },
{ unit: 'months', count: 12, label: 'Last 12 Months' }, { unit: 'months', count: 12, label: 'Last 12 Months' },
{ unit: 'year', count: 1, label: 'All Time' } { unit: 'years', count: 1, label: 'All Time' }
]; ];
// ─── Helpers ────────────────────────────────────────────────────────────────── // ─── Helpers ──────────────────────────────────────────────────────────────────
// Format an EST SQL timestamp ("YYYY-MM-DD HH:mm:ss") to "M/D/YY @HH:mm" // Reformat EST SQL timestamp "YYYY-MM-DD HH:mm:ss" → "M/D/YY @HH:mm"
function formatESTTimestamp(ts) { function formatESTTimestamp(ts) {
const [date, time] = ts.split(' '); const [datePart, timePart] = ts.split(' ');
const [Y, M, D] = date.split('-').map(n=>parseInt(n,10)); const [Y, M, D] = datePart.split('-').map(n => parseInt(n, 10));
const [h, m] = time.split(':'); const [h, m] = timePart.split(':');
const YY = String(Y).slice(-2); const YY = String(Y).slice(-2);
return `${M}/${D}/${YY} @${h.padStart(2,'0')}:${m}`; return `${M}/${D}/${YY} @${h.padStart(2,'0')}:${m}`;
} }
@ -27,7 +27,7 @@ function subtract(date, count, unit) {
case 'days': d.setDate(d.getDate() - count); break; case 'days': d.setDate(d.getDate() - count); break;
case 'weeks': d.setDate(d.getDate() - 7 * count); break; case 'weeks': d.setDate(d.getDate() - 7 * count); break;
case 'months': d.setMonth(d.getMonth() - count); break; case 'months': d.setMonth(d.getMonth() - count); break;
case 'year': d.setFullYear(d.getFullYear() - count); break; case 'years': d.setFullYear(d.getFullYear() - count); break;
} }
return d; return d;
} }
@ -36,15 +36,15 @@ function subtract(date, count, unit) {
let readings = []; let readings = [];
let chart; let chart;
// ─── Initialize ─────────────────────────────────────────────────────────────── // ─── Initialize on page load ─────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', async () => { document.addEventListener('DOMContentLoaded', async () => {
await loadReadings(); await loadReadings();
setupUI(); setupUI();
initChart(); initChart();
updateView(); // initial render updateView();
}); });
// ─── Load data ──────────────────────────────────────────────────────────────── // ─── Load readings from API ───────────────────────────────────────────────────
async function loadReadings() { async function loadReadings() {
const data = await fetch('/api/readings').then(r => r.json()); const data = await fetch('/api/readings').then(r => r.json());
readings = data.map(r => ({ readings = data.map(r => ({
@ -56,7 +56,7 @@ async function loadReadings() {
// ─── UI Wiring ──────────────────────────────────────────────────────────────── // ─── UI Wiring ────────────────────────────────────────────────────────────────
function setupUI() { function setupUI() {
// Timeframe slider // Timeframe slider + label
const slider = document.getElementById('timeframe-slider'); const slider = document.getElementById('timeframe-slider');
const label = document.getElementById('timeframe-label'); const label = document.getElementById('timeframe-label');
slider.addEventListener('input', () => { slider.addEventListener('input', () => {
@ -70,18 +70,19 @@ function setupUI() {
cb.addEventListener('change', updateView); cb.addEventListener('change', updateView);
}); });
// Table sorting (simple toggle asc/desc per column) // Table sorting
document.querySelectorAll('#trends-table thead th.sortable').forEach(th => { document.querySelectorAll('#trends-table thead th.sortable').forEach(th => {
th.addEventListener('click', () => { th.addEventListener('click', () => {
const field = th.dataset.field; const idx = th.cellIndex;
const asc = !th.classList.contains('asc');
const tbody = document.getElementById('trends-table-body'); const tbody = document.getElementById('trends-table-body');
const rows = Array.from(tbody.rows); const rows = Array.from(tbody.rows);
const asc = !th.classList.contains('asc');
rows.sort((a, b) => { rows.sort((a, b) => {
const av = a.cells[th.cellIndex].textContent; const aText = a.cells[idx].textContent;
const bv = b.cells[th.cellIndex].textContent; const bText = b.cells[idx].textContent;
return asc ? av.localeCompare(bv, undefined, {numeric:true}) return asc
: bv.localeCompare(av, undefined, {numeric:true}); ? aText.localeCompare(bText, undefined, { numeric: true })
: bText.localeCompare(aText, undefined, { numeric: true });
}); });
th.classList.toggle('asc', asc); th.classList.toggle('asc', asc);
rows.forEach(r => tbody.appendChild(r)); rows.forEach(r => tbody.appendChild(r));
@ -89,7 +90,7 @@ function setupUI() {
}); });
} }
// ─── Chart Initialization ───────────────────────────────────────────────────── // ─── Initialize Chart.js line chart ───────────────────────────────────────────
function initChart() { function initChart() {
const ctx = document.getElementById('trend-chart').getContext('2d'); const ctx = document.getElementById('trend-chart').getContext('2d');
chart = new Chart(ctx, { chart = new Chart(ctx, {
@ -107,13 +108,14 @@ function initChart() {
}); });
} }
// ─── Update everything on UI change ────────────────────────────────────────── // ─── Update both chart & table based on UI state ─────────────────────────────
function updateView() { function updateView() {
// Determine timeframe cutoff
const idx = +document.getElementById('timeframe-slider').value; const idx = +document.getElementById('timeframe-slider').value;
const { unit, count } = tfConfig[idx]; const { unit, count } = tfConfig[idx];
const cutoff = subtract(new Date(), count, unit); const cutoff = subtract(new Date(), count, unit);
// Filter readings within timeframe // Filter readings
const filtered = readings.filter(r => r.dateObj >= cutoff); const filtered = readings.filter(r => r.dateObj >= cutoff);
// Determine selected metrics // Determine selected metrics
@ -121,15 +123,14 @@ function updateView() {
.filter(cb => cb.checked) .filter(cb => cb.checked)
.map(cb => cb.value); .map(cb => cb.value);
// Prepare chart data // Prepare chart labels & datasets
const labels = filtered.map(r => r.formattedTs); const labels = filtered.map(r => r.formattedTs);
const datasets = []; const datasets = [];
if (selected.includes('temperature')) { if (selected.includes('temperature')) {
datasets.push({ datasets.push({
label: 'Temperature (°F)', label: 'Temperature (°F)',
data: filtered.map(r => r.temperature), data: filtered.map(r => r.temperature),
borderColor: 'rgba(255,99,132,0.8)',
backgroundColor: 'rgba(255,99,132,0.2)',
tension: 0.3 tension: 0.3
}); });
} }
@ -137,8 +138,6 @@ function updateView() {
datasets.push({ datasets.push({
label: 'Humidity (%)', label: 'Humidity (%)',
data: filtered.map(r => r.humidity), data: filtered.map(r => r.humidity),
borderColor: 'rgba(54,162,235,0.8)',
backgroundColor: 'rgba(54,162,235,0.2)',
tension: 0.3 tension: 0.3
}); });
} }
@ -146,22 +145,18 @@ function updateView() {
datasets.push({ datasets.push({
label: 'Heat Index (°F)', label: 'Heat Index (°F)',
data: filtered.map(r => r.heatIndex), data: filtered.map(r => r.heatIndex),
borderColor: 'rgba(255,206,86,0.8)',
backgroundColor: 'rgba(255,206,86,0.2)',
tension: 0.3 tension: 0.3
}); });
} }
// Update chart
chart.data.labels = labels; chart.data.labels = labels;
chart.data.datasets = datasets; chart.data.datasets = datasets;
chart.update(); chart.update();
// Populate table
populateTable(filtered); populateTable(filtered);
} }
// ─── Populate trends table ─────────────────────────────────────────────────── // ─── Populate the trends table ────────────────────────────────────────────────
function populateTable(data) { function populateTable(data) {
const tbody = document.getElementById('trends-table-body'); const tbody = document.getElementById('trends-table-body');
tbody.innerHTML = ''; tbody.innerHTML = '';