"use strict";
let selected = null; // {lat, lon}
const dateInput = document.getElementById("date-input");
const todayBtn = document.getElementById("today-btn");
const todayISO = () => new Date().toISOString().slice(0, 10);
dateInput.value = todayISO();
dateInput.max = dateInput.value;
// The "Today" chip snaps the target date back to today; it stays lit while the
// target already is today, so it doubles as a "you're viewing now" indicator.
function syncTodayBtn() {
todayBtn.classList.toggle("active", dateInput.value === todayISO());
}
syncTodayBtn();
todayBtn.addEventListener("click", () => {
const t = todayISO();
if (dateInput.value === t) return;
dateInput.value = t;
dateInput.max = t;
syncTodayBtn();
if (selected) runGrade();
});
function selectLocation(lat, lon) {
selected = { lat, lon };
runGrade();
}
// ---- location picker ----
// The Find button opens the shared modal map picker; choosing a spot loads it.
const findBtn = document.getElementById("find-btn");
const locLabel = document.getElementById("loc-label");
findBtn.innerHTML = `${window.LocationPicker.PIN_ICON} Find a location`;
findBtn.addEventListener("click", () => {
window.LocationPicker.open(selected, (lat, lon) => selectLocation(lat, lon));
});
dateInput.addEventListener("change", () => { syncTodayBtn(); selected && runGrade(); });
// ---- grade request + render ----
const placeholder = document.getElementById("placeholder");
const results = document.getElementById("results");
let lastGraded = null; // most recent /api/grade response (for the PNG export)
// Clicking a graded day (any cell or its date header) opens its full breakdown.
results.addEventListener("click", (e) => {
const row = e.target.closest(".rd-grid [data-date]");
if (!row || !selected) return;
location.href = `day#lat=${selected.lat.toFixed(5)}&lon=${selected.lon.toFixed(5)}&date=${row.dataset.date}`;
});
async function runGrade() {
if (!selected) return;
updateHash();
placeholder.hidden = true;
results.hidden = false;
results.innerHTML = `
Fetching decades of climate history…
`;
// Omit the date when it's today, so the URL (and cache key) matches the prefetch
// fired from the other views — a same-tab navigation then reuses the response.
const q = `lat=${selected.lat}&lon=${selected.lon}`;
const url = dateInput.value === todayISO() ? `api/grade?${q}` : `api/grade?${q}&date=${dateInput.value}`;
let data;
try {
data = await window.Thermograph.getJSON(url, window.Thermograph.TTL.grade);
} catch (err) {
results.innerHTML = `
${err.message}
`;
return;
}
render(data);
}
const fmtTemp = (v) => (v == null ? "—" : `${Math.round(v)}°`);
const fmtPrecip = (v) => (v == null ? "—" : `${v.toFixed(2)}"`);
const fmtWind = (v) => (v == null ? "—" : `${Math.round(v)} mph`);
const fmtHumid = (v) => (v == null ? "—" : `${v.toFixed(1)} g/m³`);
// Compact cell formatters for the dense recent/forecast table (units live in the
// column headers, so values stay short). Precip shows a dot for a dry day.
const cTemp = (v) => (v == null ? "—" : `${Math.round(v)}°`);
const cHum = (v) => (v == null ? "—" : `${Math.round(v)}%`);
const cWind = (v) => (v == null ? "—" : `${Math.round(v)}`);
const cRain = (v) => (v == null ? "—" : v > 0 ? v.toFixed(2) : "·");
// Monochrome inline icons (currentColor) so the UI chrome matches the dark theme
// instead of using colorful emoji. Feather-style line paths.
const IC = {
link: ``,
download: ``,
calendar: ``,
};
function placeLabel(data) {
return data.place || `${data.cell.center_lat.toFixed(3)}, ${data.cell.center_lon.toFixed(3)}`;
}
function render(data) {
recentData = data;
forecastData = null; // invalidate any forecast from a previous location/date
// Reflect the chosen place beside the Find button (which becomes "Change").
locLabel.textContent = placeLabel(data);
locLabel.hidden = false;
findBtn.innerHTML = `${window.LocationPicker.PIN_ICON} Change location`;
const c = data.climatology;
const cell = data.cell;
const yrs = c.year_range ? `${c.year_range[0]}–${c.year_range[1]}` : "—";
const coords = `${cell.center_lat.toFixed(3)}, ${cell.center_lon.toFixed(3)}`;
// Each card compares the target day's value to the normal (median) for that
// metric, tinted by its grade, and links to the full single-day breakdown.
const today = data.recent[0] || null;
const dayHref = `day#lat=${selected.lat.toFixed(5)}&lon=${selected.lon.toFixed(5)}&date=${data.target_date}`;
const cmpCard = (label, key, clim, fmt) => {
const g = today ? today[key] : null;
const normalVal = clim ? fmt(clim.p50) : "—";
const cat = g ? (TIER_COLORS[g.class] || "") : "";
const big = g ? fmt(g.value) : normalVal;
const sub = g
? `${g.grade} · normal ${normalVal}`
: `normal ${normalVal}`;
return `
${data.place ? coords + " · " : ""}~${cell.area_sq_mi} sq mi cell · climatology from ${yrs}
(${c.n_samples.toLocaleString()} days in the ±7-day window)
`;
renderSeries(); // fills #series (chart + graded-days timeline) from recent data
fetchForecast(); // merge the 7-day forecast into the timeline when it arrives
window.Thermograph.prefetchViews(selected.lat, selected.lon, "grade"); // warm calendar/forecast
document.getElementById("btn-link").onclick = copyShareLink;
document.getElementById("btn-png").onclick = downloadChartPng;
}
// One tinted value cell: background + value colored by the day's grade tier for
// that metric (the same diverging scale as everywhere else). Carries the date so
// tapping any cell opens that day's full breakdown.
function rdCell(g, fmt, date, isFc, isToday, override) {
const dd = date ? ` data-date="${date}"` : "";
const cls = "rd-c" + (isFc ? " rd-fc" : isToday ? " rd-today" : "");
if (!g) return `—`;
const col = override || TIER_COLORS[g.class] || "";
return `${fmt(g.value)}`;
}
// Compact "graded days" table — a ROW per metric, a COLUMN per day (newest first).
// Wide runs (e.g. 2 weeks) scroll horizontally inside their own container; the
// metric-label column stays pinned. Tapping any cell/day opens that day's detail.
const RD_METRICS = [
["tmax", "Hi", cTemp], ["tmin", "Lo", cTemp], ["feels", "Feel", cTemp],
["humid", "Hum", cHum], ["wind", "Wind", cWind], ["gust", "Gust", cWind], ["precip", "Rain", cRain],
];
function daysTable(rows, todayDate) {
if (!rows.length) return "";
const isFc = (d) => todayDate && d.date > todayDate; // future = forecast columns
const cols = `grid-template-columns: 46px repeat(${rows.length}, minmax(42px, 1fr));`;
const header = `` + rows.map((d) => {
const dt = new Date(d.date + "T00:00:00");
const dow = dt.toLocaleDateString(undefined, { weekday: "short" });
const md = dt.toLocaleDateString(undefined, { month: "numeric", day: "numeric" });
const cls = "rd-colh" + (isFc(d) ? " rd-fc" : d.date === todayDate ? " rd-today" : "");
return `
${dow}${md}
`;
}).join("");
const body = RD_METRICS.map(([key, label, fmt]) =>
`
${label}
` +
rows.map((d) => {
// No-rain days in the Rain row take the dry-streak warmth (tan→red, deepening
// with the streak) — matching the Dry chart and calendar — instead of one flat
// "dry" tint. Falls back to the flat dry color when the streak is unknown.
const dry = key === "precip" && d.precip && d.precip.class === "dry";
const override = dry ? drynessColor(d.dsr) : null;
return rdCell(d[key], fmt, d.date, isFc(d), d.date === todayDate, override);
}).join("")
).join("");
return `
${header}${body}
`;
}
// ---- Recent + Forecast timeline ----
// The header normals stay fixed on the target day; the chart + graded-days table
// below show one continuous timeline: recent history through the 7-day forecast,
// chronological, opened with today at the left edge.
let recentData = null; // /grade response (past) — the base render
let forecastData = null; // /forecast response (next 7 days), fetched in the background
const addDaysISO = (iso, n) => {
const d = new Date(iso + "T00:00:00Z");
d.setUTCDate(d.getUTCDate() + n);
return d.toISOString().slice(0, 10);
};
// Newest-first overall: forecast (furthest→nearest) then past (newest→oldest).
// The forecast is only merged while it *continues* the observed run with no gap —
// so viewing a past week (whose recent days end well before today's live forecast)
// shows just that week instead of a disconnected forecast block after a date gap.
// Bounded to within 13 days of the anchored date and at most a week of forecast.
function combinedDays() {
const past = recentData ? recentData.recent : []; // newest-first; newest = target_date
const rawFut = forecastData ? forecastData.recent : []; // furthest-first (tomorrow…+7 reversed)
if (!rawFut.length || !past.length) return [...rawFut, ...past];
const limit = addDaysISO(recentData.target_date, 13); // forecast must fall within 13 days
let prev = past[0].date; // last observed day (the anchor)
const kept = [];
for (const f of [...rawFut].reverse()) { // walk oldest→newest
if (kept.length >= 7 || f.date > limit) break; // cap a week / 13-day window
if (f.date !== addDaysISO(prev, 1)) break; // a gap — stop merging the forecast
kept.push(f);
prev = f.date;
}
return [...kept.reverse(), ...past]; // restore furthest-first ordering
}
async function fetchForecast() {
if (!selected) return;
const { lat, lon } = selected;
try {
const d = await window.Thermograph.getJSON(`api/v2/forecast?lat=${lat}&lon=${lon}`, window.Thermograph.TTL.forecast);
if (!selected || selected.lat !== lat || selected.lon !== lon) return; // user moved on
forecastData = d;
renderSeries();
} catch (err) { /* forecast is a bonus — keep the recent view on failure */ }
}
function renderSeries() {
const host = document.getElementById("series");
if (!host || !recentData) return;
const combined = combinedDays(); // newest-first
const chartData = { ...recentData, recent: combined };
const today = recentData.target_date;
const hasFc = combined.some((d) => d.date > today); // forecast days actually merged in
host.innerHTML = `
`;
};
// Pointer events cover mouse, touch and pen with one path, so tapping/dragging
// the chart works on phones (mousemove never fires on touchscreens).
const showTip = (r, e) => {
const d = chartDays[+r.dataset.i];
const x = +r.getAttribute("x") + +r.getAttribute("width") / 2;
cross.setAttribute("x1", x); cross.setAttribute("x2", x); cross.setAttribute("opacity", "0.7");
const dt = new Date(d.date + "T00:00:00");
const nt = d.normals.tmax, ni = d.normals.tmin;
tip.innerHTML = `