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
stationDockDoor: r.stationDockDoor, readings = data.map(r => {
location: r.location, const dt = new Date(r.epoch_ms);
temperature: r.temperature, return {
humidity: r.humidity, stationDockDoor: r.stationDockDoor,
heatIndex: r.heatIndex, location: r.location,
dateObj: new Date(r.epoch_ms), temperature: r.temperature,
formattedTs: new Date(r.epoch_ms).toLocaleString('en-US', { humidity: r.humidity,
timeZone: 'America/New_York', heatIndex: r.heatIndex,
month: 'numeric', dateObj: dt,
day: 'numeric', formattedTs: dt.toLocaleString('en-US', {
year: '2-digit', timeZone: 'America/New_York',
hour12: false, month: 'numeric',
hour: '2-digit', day: 'numeric',
minute: '2-digit' year: '2-digit',
}).replace(',', ' @') hour: '2-digit',
})); minute: '2-digit',
hour12: false
}).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,40 +109,46 @@ 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 idx = +document.getElementById('timeframe-slider').value; const maxEpoch = Math.max(...readings.map(r => r.dateObj.getTime()));
const { unit, count } = tfConfig[idx]; const nowDate = new Date(maxEpoch);
const cutoff = subtract(Date.now(), count, unit);
// Filter readings // Compute cutoff
const idx = +document.getElementById('timeframe-slider').value;
const { unit, count } = tfConfig[idx];
const cutoff = (idx === 4)
? new Date(0) // "All Time"
: subtract(nowDate, count, unit);
// 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')) {
chart.data.datasets.push({ chart.data.datasets.push({
label: 'Temperature (°F)', label: 'Temperature (°F)',
data: filtered.map(r => r.temperature), data: filtered.map(r => r.temperature),
tension: 0.3 tension: 0.3
}); });
} }
if (selected.includes('humidity')) { if (selected.includes('humidity')) {
chart.data.datasets.push({ chart.data.datasets.push({
label: 'Humidity (%)', label: 'Humidity (%)',
data: filtered.map(r => r.humidity), data: filtered.map(r => r.humidity),
tension: 0.3 tension: 0.3
}); });
} }
if (selected.includes('heatIndex')) { if (selected.includes('heatIndex')) {
chart.data.datasets.push({ chart.data.datasets.push({
label: 'Heat Index (°F)', label: 'Heat Index (°F)',
data: filtered.map(r => r.heatIndex), data: filtered.map(r => r.heatIndex),
tension: 0.3 tension: 0.3
}); });
} }
@ -160,3 +170,4 @@ function updateView() {
tbody.appendChild(tr); tbody.appendChild(tr);
}); });
} }