"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}`;
});
let gradeSeq = 0; // supersedes an in-flight load when the user picks a new spot/date
async function runGrade() {
if (!selected) return;
updateHash();
placeholder.hidden = true;
results.hidden = false;
const seq = ++gradeSeq;
// Delay the spinner: a cache-served render lands in a few ms, so blanking the
// panel immediately would just flash. Only a genuinely slow (network) load
// ever shows it.
const spin = setTimeout(() => {
if (seq === gradeSeq) results.innerHTML = `
Fetching decades of climate history…
`;
}, 150);
// 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 {
// Stale-while-revalidate: a stale cached copy renders immediately and the
// update callback repaints if the background revalidation finds new data.
data = await window.Thermograph.getJSON(url, window.Thermograph.TTL.grade, false, (upd) => {
if (seq === gradeSeq) render(upd);
});
} catch (err) {
clearTimeout(spin);
if (seq !== gradeSeq) return;
results.innerHTML = `
${err.message}
`;
return;
}
clearTimeout(spin);
if (seq !== gradeSeq) return;
render(data);
}
// Temps flow through the shared unit formatter (°F from the API, shown in the
// active unit); the others are unit-agnostic.
const fmtTemp = (v) => window.Thermograph.fmtTemp(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). Dry days label the running dry streak
// (see precipCell) rather than the rain amount.
const cTemp = (v) => window.Thermograph.fmtTemp(v); // active unit, bare degree
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 grade = g
? `${g.grade}`
: "";
return `
`;
}
// ---- 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
// Repaint everything in the newly-picked unit, preserving the already-loaded
// forecast (render() clears it and refetches from cache; restore it right away).
window.Thermograph.onUnitChange(() => {
if (!recentData) return;
const fc = forecastData;
render(recentData);
if (fc) { forecastData = fc; renderSeries(); }
});
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 = `
${svg}
`;
document.getElementById("chart-toggle").addEventListener("click", (e) => {
const b = e.target.closest("button[data-metric]");
if (!b || b.dataset.metric === chartMetric) return;
chartMetric = b.dataset.metric;
try { localStorage.setItem("thermograph:chartMetric", chartMetric); } catch (e) {}
buildChart(data);
});
attachChartHover(wrap);
}
// Per-series display meta for the diverging-scale metrics. `sfx` is the unit
// appended to axis + point labels ("°"); wind carries its unit in the subtitle
// instead of on every point to keep the plot uncluttered.
const SERIES = {
tmax: (C) => ({ color: C.hi, label: "Daily high", sfx: "°" }),
tmin: (C) => ({ color: C.lo, label: "Daily low", sfx: "°" }),
feels: (C) => ({ color: C.feels, label: "Feels like", sfx: "°" }),
humid: (C) => ({ color: C.humid, label: "Absolute humidity (g/m³)", sfx: "" }),
wind: (C) => ({ color: C.wind, label: "Wind speed (mph)", sfx: "" }),
gust: (C) => ({ color: C.gust, label: "Wind gust (mph)", sfx: "" }),
};
// Percentile "fan" tiers — bands between successive percentile marks, colored to
// match the calendar. Temperature is diverging (cold→green→hot); precipitation
// uses the sequential rain-intensity ramp.
const TEMP_FAN = [
["p90", "p99", "very-hot"], ["p75", "p90", "hot"], ["p60", "p75", "warm"],
["p40", "p60", "normal"], ["p25", "p40", "cool"], ["p10", "p25", "cold"], ["p1", "p10", "very-cold"],
];
const RAIN_FAN = [
["p90", "p99", "wet-8"], ["p75", "p90", "wet-7"], ["p60", "p75", "wet-6"],
["p40", "p60", "wet-5"], ["p25", "p40", "wet-4"], ["p10", "p25", "wet-3"], ["p1", "p10", "wet-2"],
];
// Shared line-series chart: an optional shaded percentile fan + dashed median, the
// value line with dots, and labeled points — so temperature, wind, humidity,
// precipitation and dry streak all read in one consistent style.
function lineChart(cfg) {
const { days, n, xFor, C, key, color, fan, hasNormals, baseZero,
getVal, getPct, dotColor, fmtAxis, fmtLabel, labelOn,
subtitle, legend, aria } = cfg;
// y-range: the plotted values plus the fan extremes (p1/p99) when present.
const vals = [];
days.forEach((d) => {
const v = getVal(d); if (v != null && !isNaN(v)) vals.push(v);
if (hasNormals && d.normals && d.normals[key]) {
const u = pget(d.normals[key], "p99"), l = pget(d.normals[key], "p1");
if (u != null) vals.push(u); if (l != null) vals.push(l);
}
});
let finite = vals.filter((v) => v != null && !isNaN(v));
if (!finite.length) finite = [0, 1];
let lo = Math.min(...finite), hi = Math.max(...finite);
if (baseZero) lo = Math.min(lo, 0);
if (hi <= lo) hi = lo + 1;
const pad = baseZero ? Math.max((hi - lo) * 0.12, 0.01) : Math.max((hi - lo) * 0.08, 3);
hi += pad; if (!baseZero) lo -= pad;
const yT = (v) => plotBot - ((v - lo) / (hi - lo)) * (plotBot - plotTop);
let grid = "";
for (let t = 0; t <= 4; t++) {
const v = lo + ((hi - lo) * t) / 4, y = yT(v).toFixed(1);
grid += ``;
grid += `${fmtAxis(v)}`;
}
// Shaded fan bands between percentile marks (the "highlights"), same as the calendar tiers.
const band = (dnKey, upKey, cls) => {
let top = "", bot = "";
days.forEach((d, i) => { const u = d.normals && pget(d.normals[key], upKey); if (u == null) return;
top += (top ? "L" : "M") + xFor(i).toFixed(1) + " " + yT(u).toFixed(1) + " "; });
for (let i = n - 1; i >= 0; i--) { const dd = days[i].normals && pget(days[i].normals[key], dnKey); if (dd == null) continue;
bot += "L" + xFor(i).toFixed(1) + " " + yT(dd).toFixed(1) + " "; }
return top ? `` : "";
};
const fanSvg = (hasNormals && fan) ? fan.map((t) => band(t[0], t[1], t[2])).join("") : "";
const normTrace = (pctKey) => {
let p = "", st = false;
days.forEach((d, i) => { const v = d.normals && pget(d.normals[key], pctKey); if (v == null) return;
p += (st ? "L" : "M") + xFor(i).toFixed(1) + " " + yT(v).toFixed(1) + " "; st = true; });
return p;
};
const valTrace = () => {
let p = "", st = false;
days.forEach((d, i) => { const v = getVal(d); if (v == null || isNaN(v)) { st = false; return; }
p += (st ? "L" : "M") + xFor(i).toFixed(1) + " " + yT(v).toFixed(1) + " "; st = true; });
return p;
};
const medianSvg = hasNormals
? `` : "";
const dots = days.map((d, i) => {
const v = getVal(d); if (v == null || isNaN(v)) return "";
return ``;
}).join("");
const labels = days.map((d, i) => {
const v = getVal(d); if (v == null || isNaN(v)) return "";
if (labelOn && !labelOn(v, d)) return "";
const x = xFor(i).toFixed(1), y = yT(v);
const vy = (y - plotTop < 26 ? y + 15 : y - 15).toFixed(1); // flip below near the top
const pv = getPct ? getPct(d) : null;
const pct = pv == null ? "" :
`${ord(pv)}`;
return `${fmtLabel(v)}${pct}`;
}).join("");
const content = grid + fanSvg + medianSvg +
`` +
dots + labels;
return { content, legend, color, subtitle, aria };
}
// One temperature-scale series (High/Low/Feels/Wind/Gust).
function tempChart(key, days, n, xFor, C) {
const s = SERIES[key](C);
// Temperature series (° suffix) show in the active unit; wind/gust stay in mph.
// The plot keeps its °F domain — only the labels convert — so positions hold.
const isTemp = s.sfx === "°";
const fmtV = (v) => `${Math.round(isTemp ? window.Thermograph.toUnit(v) : v)}${s.sfx}`;
return lineChart({
days, n, xFor, C, key, color: s.color, fan: TEMP_FAN, hasNormals: true, baseZero: false,
getVal: (d) => (d[key] ? d[key].value : null),
getPct: (d) => (d[key] ? d[key].percentile : null),
fmtAxis: fmtV,
fmtLabel: fmtV,
legend:
`${s.label} (dashed = median)` +
`Band shaded by grade tier` +
`Points labeled value · percentile — grade from the band tier (scale below)`,
subtitle: `${s.label} — recent trend vs normal`,
aria: `Recent ${s.label.toLowerCase()} versus the normal range.`,
});
}
// Precipitation as a line vs its normal range — same fan/median/labels style as
// temperature, so the metrics read consistently. Rain days are labeled; dry days
// sit on the baseline. The fan is the rain-intensity tier ramp.
function precipChart(days, n, xFor, C) {
return lineChart({
days, n, xFor, C, key: "precip", color: C.precip, fan: RAIN_FAN, hasNormals: true, baseZero: true,
getVal: (d) => (d.precip ? d.precip.value : null),
getPct: (d) => (d.precip ? d.precip.percentile : null),
// Rain days take their intensity-tier color; no-rain days warm with the dry
// streak (tan→red) so a dry spell reads as dry, matching the Dry chart.
dotColor: (d) => (d.precip && d.precip.value > 0 ? (TIER_COLORS[d.precip.class] || C.precip) : (drynessColor(d.dsr) || C.precip)),
fmtAxis: (v) => `${v.toFixed(2)}"`,
fmtLabel: (v) => `${v.toFixed(2)}"`,
labelOn: (v) => v > 0, // only label rain days; dry days rest on the baseline
legend:
`Precipitation (dashed = median)` +
`Band shaded by rain-intensity tier` +
`Rain days labeled amount · percentile (rain scale below)`,
subtitle: "Precipitation — daily totals vs normal",
aria: "Daily precipitation totals versus the normal range.",
});
}
// "Days since last rain" dry-streak color: rain days are blue; each dry day warms
// from a light base toward dark red, saturating at 14 consecutive dry days.
// (Mirrors the calendar's dry-streak ramp.)
const DRY_BASE = [247, 217, 176], DRY_MAX = [122, 13, 26], DRY_CAP = 14;
const lerpRgb = (a, b, t) => `rgb(${a.map((x, i) => Math.round(x + (b[i] - x) * t)).join(",")})`;
function drynessColor(dsr) {
if (dsr == null) return "";
if (dsr === 0) return "#2b7bba"; // measurable rain that day
return lerpRgb(DRY_BASE, DRY_MAX, Math.min(dsr, DRY_CAP) / DRY_CAP);
}
// Dry streak as a line: days since last rain, dots warming with the streak; a rain
// day drops the line to 0 with a blue dot. (No climatology fan — it's not graded.)
function dryChart(days, n, xFor, C) {
return lineChart({
days, n, xFor, C, key: "dry", color: drynessColor(9), fan: null, hasNormals: false, baseZero: true,
getVal: (d) => (d.dsr == null ? null : d.dsr),
getPct: () => null,
dotColor: (d) => drynessColor(d.dsr),
fmtAxis: (v) => `${Math.round(v)}d`,
fmtLabel: (v) => `${Math.round(v)}`,
labelOn: (v) => v > 0, // label the streak length; rain days (0) just show the dot
legend:
`Days since last rain — dry streak` +
`Rain that day (streak = 0)`,
subtitle: "Dry streak — days since last measurable rain",
aria: "Days since last measurable rain, as a line.",
});
}
function attachChartHover(wrap) {
const svg = wrap.querySelector("svg");
const tip = wrap.querySelector("#chart-tip");
const cross = wrap.querySelector("#crosshair");
const C = chartPalette();
const pctLine = (label, g, unit, color) => {
if (!g) return `
${label} —
`;
const pct = g.percentile == null ? "" : ` · ${ord(g.percentile)} pct`;
const gc = TIER_COLORS[g.class] || "";
// "°" marks a temperature line — show it in the active unit; others are as-is.
const val = unit === "°" ? Math.round(window.Thermograph.toUnit(g.value)) : g.value;
return `
${label} ${val}${unit}${pct} ${g.grade}
`;
};
// 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 = `