Update public/scripts/trends.js

This commit is contained in:
JoshBaneyCS 2025-04-30 05:05:01 +00:00
parent ee378087e1
commit 1a5c73264c

View File

@ -1,6 +1,4 @@
// public/scripts/trends.js // Timeframe configurations
// --- Timeframe options ---
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' },
@ -9,11 +7,10 @@ const tfConfig = [
{ unit: 'years', count: 1, label: 'All Time' } { unit: 'years', count: 1, label: 'All Time' }
]; ];
// --- State ---
let readings = []; let readings = [];
let chart; let chart;
// --- Helpers --- // Subtract a given amount from a Date
function subtract(date, count, unit) { function subtract(date, count, unit) {
const d = new Date(date); const d = new Date(date);
switch (unit) { switch (unit) {
@ -26,12 +23,10 @@ function subtract(date, count, unit) {
return d; return d;
} }
// --- Load & initialize --- document.addEventListener('DOMContentLoaded', () => {
document.addEventListener('DOMContentLoaded', async () => { // 1) Grab embedded data
console.log('📡 Loading readings from /api/readings…'); const data = window.__INITIAL_READINGS__ || [];
try {
const data = await fetch('/api/readings').then(r => r.json());
console.log('✅ Received readings:', data);
readings = data.map(r => ({ readings = data.map(r => ({
stationDockDoor: r.stationDockDoor, stationDockDoor: r.stationDockDoor,
location: r.location, location: r.location,
@ -41,23 +36,22 @@ document.addEventListener('DOMContentLoaded', async () => {
dateObj: new Date(r.epoch_ms), dateObj: new Date(r.epoch_ms),
formattedTs: new Date(r.epoch_ms).toLocaleString('en-US', { formattedTs: new Date(r.epoch_ms).toLocaleString('en-US', {
timeZone: 'America/New_York', timeZone: 'America/New_York',
month:'numeric', day:'numeric', year:'2-digit', month: 'numeric',
hour:'2-digit', minute:'2-digit', hour12:false day: 'numeric',
year: '2-digit',
hour12: false,
hour: '2-digit',
minute: '2-digit'
}).replace(',', ' @') }).replace(',', ' @')
})); }));
console.log('✔ Parsed readings:', readings);
setupUI(); setupUI();
initChart(); initChart();
updateView(); updateView();
} catch (err) {
console.error('❌ Failed to load readings:', err);
}
}); });
// --- UI wiring ---
function setupUI() { function setupUI() {
// Slider // Timeframe slider
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', () => {
@ -66,7 +60,7 @@ function setupUI() {
}); });
label.textContent = tfConfig[slider.value].label; label.textContent = tfConfig[slider.value].label;
// Metrics toggles // Metric toggles
document.getElementsByName('metric').forEach(cb => { document.getElementsByName('metric').forEach(cb => {
cb.addEventListener('change', updateView); cb.addEventListener('change', updateView);
}); });
@ -78,23 +72,20 @@ function setupUI() {
const asc = !th.classList.contains('asc'); const asc = !th.classList.contains('asc');
const tbody = document.getElementById('trends-table-body'); const tbody = document.getElementById('trends-table-body');
Array.from(tbody.rows) Array.from(tbody.rows)
.sort((a,b) => asc .sort((a, b) => {
? a.cells[idx].textContent.localeCompare(b.cells[idx].textContent, undefined, {numeric:true}) const av = a.cells[idx].textContent;
: b.cells[idx].textContent.localeCompare(a.cells[idx].textContent, undefined, {numeric:true}) const bv = b.cells[idx].textContent;
) return asc
? av.localeCompare(bv, undefined, { numeric: true })
: bv.localeCompare(av, undefined, { numeric: true });
})
.forEach(r => tbody.appendChild(r)); .forEach(r => tbody.appendChild(r));
th.classList.toggle('asc', asc); th.classList.toggle('asc', asc);
}); });
}); });
} }
// --- Chart.js init ---
function initChart() { function initChart() {
if (typeof Chart === 'undefined') {
console.error('❌ Chart.js not loaded!');
return;
}
console.log('📊 Initializing Chart.js');
const ctx = document.getElementById('trend-chart').getContext('2d'); const ctx = document.getElementById('trend-chart').getContext('2d');
chart = new Chart(ctx, { chart = new Chart(ctx, {
type: 'line', type: 'line',
@ -111,27 +102,23 @@ function initChart() {
}); });
} }
// --- Render chart & table ---
function updateView() { function updateView() {
if (!chart) return; if (!chart) return;
console.log('🔄 updateView called');
// Timeframe cutoff // Determine 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(Date.now(), count, unit);
console.log(` Showing data since ${cutoff.toISOString()}`);
// Filter readings // Filter readings
const filtered = readings.filter(r => r.dateObj >= cutoff); const filtered = readings.filter(r => r.dateObj >= cutoff);
console.log(` ${filtered.length}/${readings.length} points after filtering`);
// Metrics selected // Determine selected metrics
const selected = Array.from(document.getElementsByName('metric')) const selected = Array.from(document.getElementsByName('metric'))
.filter(cb => cb.checked).map(cb => cb.value); .filter(cb => cb.checked)
console.log(' Metrics selected:', selected); .map(cb => cb.value);
// Update chart // Build chart
chart.data.labels = filtered.map(r => r.formattedTs); chart.data.labels = filtered.map(r => r.formattedTs);
chart.data.datasets = []; chart.data.datasets = [];
if (selected.includes('temperature')) { if (selected.includes('temperature')) {
@ -155,10 +142,9 @@ function updateView() {
tension: 0.3 tension: 0.3
}); });
} }
console.log(' Chart update:', chart.data);
chart.update(); chart.update();
// Update table // Populate table
const tbody = document.getElementById('trends-table-body'); const tbody = document.getElementById('trends-table-body');
tbody.innerHTML = ''; tbody.innerHTML = '';
filtered.forEach(r => { filtered.forEach(r => {
@ -173,5 +159,4 @@ function updateView() {
`; `;
tbody.appendChild(tr); tbody.appendChild(tr);
}); });
console.log(' Table populated with', filtered.length, 'rows');
} }