Update public/scripts/trends.js

This commit is contained in:
JoshBaneyCS 2025-04-30 10:25:27 +00:00
parent bf1f466f6c
commit f33dad2454

View File

@ -1,5 +1,6 @@
// public/scripts/trends.js
// Timeframes
// Timeframe configurations
const tfConfig = [
{ unit: 'hours', count: 24, label: 'Last 24 Hours' },
{ unit: 'days', count: 7, label: 'Last 7 Days' },
@ -11,7 +12,7 @@ const tfConfig = [
let readings = [];
let chart;
// Helper: subtract time
// Subtract helper
function subtract(date, count, unit) {
const d = new Date(date);
switch (unit) {
@ -24,9 +25,8 @@ function subtract(date, count, unit) {
return d;
}
// On load
document.addEventListener('DOMContentLoaded', () => {
// Grab server-injected data
// 1) Use serverinjected data
const data = window.__INITIAL_READINGS__ || [];
readings = data.map(r => {
@ -56,7 +56,6 @@ document.addEventListener('DOMContentLoaded', () => {
});
function setupUI() {
// Slider
const slider = document.getElementById('timeframe-slider');
const label = document.getElementById('timeframe-label');
slider.addEventListener('input', () => {
@ -65,17 +64,14 @@ function setupUI() {
});
label.textContent = tfConfig[slider.value].label;
// Metric toggles
document.getElementsByName('metric').forEach(cb => {
cb.addEventListener('change', updateView);
});
// Sortable headers
document.querySelectorAll('#trends-table thead th.sortable').forEach(th => {
document.querySelectorAll('#trends-table thead th.sortable')
.forEach(th => {
th.addEventListener('click', () => {
// Determine sort order
const asc = !th.classList.contains('asc');
// Clear other indicators
document.querySelectorAll('#trends-table thead th')
.forEach(h => h.classList.remove('asc','desc'));
th.classList.add(asc ? 'asc' : 'desc');
@ -116,26 +112,22 @@ function initChart() {
function updateView() {
if (!chart) return;
// Determine 'now' based on latest reading
const maxEpoch = Math.max(...readings.map(r => r.dateObj.getTime()));
const nowDate = new Date(maxEpoch);
// Use latest reading time as “now”
const maxEpoch = readings.reduce((m, r) => Math.max(m, r.dateObj.getTime()), 0);
const now = new Date(maxEpoch);
// Compute cutoff
const idx = +document.getElementById('timeframe-slider').value;
const { unit, count } = tfConfig[idx];
const cutoff = idx === 4
const cutoff = (idx === tfConfig.length - 1)
? new Date(0)
: subtract(nowDate, count, unit);
: subtract(now, count, unit);
// Filter data
const filtered = readings.filter(r => r.dateObj >= cutoff);
// Selected metrics
const selected = Array.from(document.getElementsByName('metric'))
.filter(cb => cb.checked)
.map(cb => cb.value);
// Update chart
chart.data.labels = filtered.map(r => r.formattedTs);
chart.data.datasets = [];
if (selected.includes('temperature')) {
@ -161,7 +153,6 @@ function updateView() {
}
chart.update();
// Populate table
const tbody = document.getElementById('trends-table-body');
tbody.innerHTML = '';
filtered.forEach(r => {