Update public/scripts/trends.js
This commit is contained in:
parent
9e169cd742
commit
67e036df63
@ -1,26 +1,22 @@
|
|||||||
// public/scripts/trends.js
|
// public/scripts/trends.js
|
||||||
|
|
||||||
// ─── Timeframes ──────────────────────────────────────────────────────────────
|
// --- 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' },
|
||||||
{ 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' }
|
||||||
];
|
];
|
||||||
|
|
||||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
// --- State ---
|
||||||
function formatESTTimestamp(ts) {
|
let readings = [];
|
||||||
// ts is "YYYY-MM-DD HH:mm:ss" or ISO → we assume you converted to "M/D/YY @HH:mm"
|
let chart;
|
||||||
return ts; // adjust if you need to parse differently
|
|
||||||
}
|
// --- Helpers ---
|
||||||
function parseLocalDate(ts) {
|
|
||||||
// if you have epoch_ms, convert: return new Date(epoch_ms)
|
|
||||||
return new Date(ts.replace(' ', 'T'));
|
|
||||||
}
|
|
||||||
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;
|
||||||
@ -30,37 +26,36 @@ function subtract(date, count, unit) {
|
|||||||
return d;
|
return d;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── State & Chart Ref ───────────────────────────────────────────────────────
|
// --- Load & initialize ---
|
||||||
let readings = [];
|
|
||||||
let chart;
|
|
||||||
|
|
||||||
// ─── Initialize ───────────────────────────────────────────────────────────────
|
|
||||||
document.addEventListener('DOMContentLoaded', async () => {
|
document.addEventListener('DOMContentLoaded', async () => {
|
||||||
await loadReadings();
|
console.log('📡 Loading readings from /api/readings…');
|
||||||
setupUI();
|
try {
|
||||||
initChart();
|
const data = await fetch('/api/readings').then(r => r.json());
|
||||||
updateView();
|
console.log('✅ Received readings:', data);
|
||||||
|
readings = data.map(r => ({
|
||||||
|
stationDockDoor: r.stationDockDoor,
|
||||||
|
location: r.location,
|
||||||
|
temperature: r.temperature,
|
||||||
|
humidity: r.humidity,
|
||||||
|
heatIndex: r.heatIndex,
|
||||||
|
dateObj: new Date(r.epoch_ms),
|
||||||
|
formattedTs: new Date(r.epoch_ms).toLocaleString('en-US', {
|
||||||
|
timeZone:'America/New_York',
|
||||||
|
month:'numeric', day:'numeric', year:'2-digit',
|
||||||
|
hour:'2-digit', minute:'2-digit', hour12:false
|
||||||
|
}).replace(',',' @')
|
||||||
|
}));
|
||||||
|
console.log('✔ Parsed readings:', readings);
|
||||||
|
|
||||||
|
setupUI();
|
||||||
|
initChart();
|
||||||
|
updateView();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('❌ Failed to load readings:', err);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ─── Load data ────────────────────────────────────────────────────────────────
|
// --- UI wiring ---
|
||||||
async function loadReadings() {
|
|
||||||
const data = await fetch('/api/readings').then(r=>r.json());
|
|
||||||
readings = data.map(r => ({
|
|
||||||
stationDockDoor: r.stationDockDoor,
|
|
||||||
location: r.location,
|
|
||||||
temperature: r.temperature,
|
|
||||||
humidity: r.humidity,
|
|
||||||
heatIndex: r.heatIndex,
|
|
||||||
formattedTs: new Date(r.epoch_ms).toLocaleString('en-US', {
|
|
||||||
timeZone:'America/New_York',
|
|
||||||
month:'numeric', day:'numeric', year:'2-digit',
|
|
||||||
hour12: false, hour:'2-digit', minute:'2-digit'
|
|
||||||
}).replace(',',' @'),
|
|
||||||
dateObj: new Date(r.epoch_ms)
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── UI Wiring ────────────────────────────────────────────────────────────────
|
|
||||||
function setupUI() {
|
function setupUI() {
|
||||||
// Slider
|
// Slider
|
||||||
const slider = document.getElementById('timeframe-slider');
|
const slider = document.getElementById('timeframe-slider');
|
||||||
@ -71,14 +66,14 @@ function setupUI() {
|
|||||||
});
|
});
|
||||||
label.textContent = tfConfig[slider.value].label;
|
label.textContent = tfConfig[slider.value].label;
|
||||||
|
|
||||||
// Metric checkboxes
|
// Metrics toggles
|
||||||
document.getElementsByName('metric').forEach(cb => {
|
document.getElementsByName('metric').forEach(cb => {
|
||||||
cb.addEventListener('change', updateView);
|
cb.addEventListener('change', updateView);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Table sorting
|
// 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 idx = th.cellIndex;
|
const idx = th.cellIndex;
|
||||||
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');
|
||||||
@ -87,70 +82,83 @@ function setupUI() {
|
|||||||
? a.cells[idx].textContent.localeCompare(b.cells[idx].textContent, undefined, {numeric:true})
|
? a.cells[idx].textContent.localeCompare(b.cells[idx].textContent, undefined, {numeric:true})
|
||||||
: b.cells[idx].textContent.localeCompare(a.cells[idx].textContent, undefined, {numeric:true})
|
: b.cells[idx].textContent.localeCompare(a.cells[idx].textContent, 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 Initialization ──────────────────────────────────────────────────
|
// --- 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',
|
||||||
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
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Update chart & table ────────────────────────────────────────────────────
|
// --- Render chart & table ---
|
||||||
function updateView() {
|
function updateView() {
|
||||||
const idx = +document.getElementById('timeframe-slider').value;
|
if (!chart) return;
|
||||||
const {unit,count} = tfConfig[idx];
|
console.log('🔄 updateView called');
|
||||||
const cutoff = subtract(new Date(), count, unit);
|
|
||||||
|
|
||||||
// Filter
|
// Timeframe cutoff
|
||||||
|
const idx = +document.getElementById('timeframe-slider').value;
|
||||||
|
const { unit, count } = tfConfig[idx];
|
||||||
|
const cutoff = subtract(new Date(), count, unit);
|
||||||
|
console.log(` Showing data since ${cutoff.toISOString()}`);
|
||||||
|
|
||||||
|
// 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
|
// Metrics selected
|
||||||
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).map(cb => cb.value);
|
||||||
|
console.log(' Metrics selected:', selected);
|
||||||
|
|
||||||
// Chart data
|
// 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
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
console.log(' Chart update:', chart.data);
|
||||||
chart.update();
|
chart.update();
|
||||||
|
|
||||||
// Table
|
// Update 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 => {
|
||||||
@ -165,4 +173,5 @@ function updateView() {
|
|||||||
`;
|
`;
|
||||||
tbody.appendChild(tr);
|
tbody.appendChild(tr);
|
||||||
});
|
});
|
||||||
|
console.log(' Table populated with', filtered.length, 'rows');
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user