Update public/scripts/trends.js

This commit is contained in:
JoshBaneyCS 2025-04-30 05:56:08 +00:00
parent 8b64a043b7
commit cc1c77930b

View File

@ -1,49 +1,56 @@
// Timeframe configurations // 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: 'years', count: 1, label: 'All Time' } { unit:'years', count:1, label:'All Time' }
]; ];
let readings = []; let readings = [];
let chart; let chart;
// Subtract a given amount from a Date // Subtract helper
function subtract(date, count, unit) { function subtract(date, count, unit) {
const d = new Date(date); const d = new Date(date);
switch (unit) { switch(unit) {
case 'hours': d.setHours(d.getHours() - count); break; case 'hours': d.setHours(d.getHours() - count); break;
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 'years': d.setFullYear(d.getFullYear() - count);break; case 'years': d.setFullYear(d.getFullYear() - count); break;
} }
return d; return d;
} }
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
// 1) Grab embedded data // 1) Grab the serverinjected readings
const data = window.__INITIAL_READINGS__ || []; const data = window.__INITIAL_READINGS__ || [];
if (!data.length) {
console.warn('No initial readings found.');
}
readings = data.map(r => ({ // 2) Map into local array with Date objs & formatted strings
readings = data.map(r => {
const dt = new Date(r.epoch_ms);
return {
stationDockDoor: r.stationDockDoor, stationDockDoor: r.stationDockDoor,
location: r.location, location: r.location,
temperature: r.temperature, temperature: r.temperature,
humidity: r.humidity, humidity: r.humidity,
heatIndex: r.heatIndex, heatIndex: r.heatIndex,
dateObj: new Date(r.epoch_ms), dateObj: dt,
formattedTs: new Date(r.epoch_ms).toLocaleString('en-US', { formattedTs: dt.toLocaleString('en-US', {
timeZone: 'America/New_York', timeZone: 'America/New_York',
month: 'numeric', month: 'numeric',
day: 'numeric', day: 'numeric',
year: '2-digit', year: '2-digit',
hour12: false,
hour: '2-digit', hour: '2-digit',
minute: '2-digit' minute: '2-digit',
hour12: false
}).replace(',', ' @') }).replace(',', ' @')
})); };
});
setupUI(); setupUI();
initChart(); initChart();
@ -51,7 +58,7 @@ document.addEventListener('DOMContentLoaded', () => {
}); });
function setupUI() { function setupUI() {
// Timeframe slider // 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', () => {
@ -60,7 +67,7 @@ function setupUI() {
}); });
label.textContent = tfConfig[slider.value].label; label.textContent = tfConfig[slider.value].label;
// Metric toggles // Metric checkboxes
document.getElementsByName('metric').forEach(cb => { document.getElementsByName('metric').forEach(cb => {
cb.addEventListener('change', updateView); cb.addEventListener('change', updateView);
}); });
@ -72,13 +79,10 @@ 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) => { .sort((a,b) => asc
const av = a.cells[idx].textContent; ? a.cells[idx].textContent.localeCompare(b.cells[idx].textContent, undefined, {numeric:true})
const bv = b.cells[idx].textContent; : b.cells[idx].textContent.localeCompare(a.cells[idx].textContent, undefined, {numeric:true})
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);
}); });
@ -92,11 +96,11 @@ function initChart() {
data: { labels: [], datasets: [] }, data: { labels: [], datasets: [] },
options: { options: {
scales: { scales: {
x: { title: { display: true, text: 'Time (EST)' } }, x: { title: { display:true, text:'Time (EST)' } },
y: { title: { display: true, text: 'Value' } } y: { title: { display:true, text:'Value' } }
}, },
interaction: { mode: 'index', intersect: false }, interaction: { mode:'index', intersect:false },
plugins: { legend: { position: 'top' } }, plugins: { legend:{ position:'top' } },
maintainAspectRatio: false maintainAspectRatio: false
} }
}); });
@ -105,20 +109,26 @@ function initChart() {
function updateView() { function updateView() {
if (!chart) return; if (!chart) return;
// Determine cutoff // Determine "now" from the latest reading, not the browser clock
const maxEpoch = Math.max(...readings.map(r => r.dateObj.getTime()));
const nowDate = new Date(maxEpoch);
// Compute 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(Date.now(), count, unit); const cutoff = (idx === 4)
? new Date(0) // "All Time"
: subtract(nowDate, count, unit);
// Filter readings // Filter
const filtered = readings.filter(r => r.dateObj >= cutoff); const filtered = readings.filter(r => r.dateObj >= cutoff);
// Determine selected metrics // Which metrics?
const selected = Array.from(document.getElementsByName('metric')) const selected = Array.from(document.getElementsByName('metric'))
.filter(cb => cb.checked) .filter(cb => cb.checked)
.map(cb => cb.value); .map(cb => cb.value);
// Build chart // Update 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')) {
@ -160,3 +170,4 @@ function updateView() {
tbody.appendChild(tr); tbody.appendChild(tr);
}); });
} }