"use strict";
const HOME = "IND";
const S = { data: null, unit: "F", ranges: false, at: HOME, city: null, tz: "America/Indiana/Indianapolis", want: 0 };
try {
S.unit = localStorage.getItem("kind-unit") || "F";
S.ranges = localStorage.getItem("kind-ranges") === "1";
S.at = localStorage.getItem("indra-at") || HOME;
S.city = localStorage.getItem("indra-city");
} catch (e) { /* storage unavailable */ }
const fromUrl = new URLSearchParams(location.search).get("at");
if (fromUrl && /^[A-Za-z0-9]{3}$/.test(fromUrl) && fromUrl.toUpperCase() !== S.at) { S.at = fromUrl.toUpperCase(); S.city = null; }
// Airports used to train, choose or test the model. Elsewhere it hasn't been scored.
const SCORED = new Set("ATL BOS DFW IAH MSP DTW STL MCI SLC LAS SFO LAX PDX BNA CLT TPA MSY OKC ABQ BOI BIS GRB PWM RAP IND PIT MEM SAN OMA JAX RNO CMH ORD DEN MIA SEA PHX BUF BTV RDU SAV MOB AUS ELP ICT FAR BIL GJT SMF".split(" "));
const SOURCE_NAME = { NBS: "National Blend", GFS: "GFS MOS", NAM: "NAM MOS" };
const $ = (s) => document.querySelector(s);
const NS = "http://www.w3.org/2000/svg";
const el = (tag, attrs, parent, text) => {
const n = document.createElementNS(NS, tag);
for (const [k, v] of Object.entries(attrs || {})) n.setAttribute(k, v);
if (text != null) n.textContent = text;
if (parent) parent.appendChild(n);
return n;
};
// ------------------------------------------------------------------ units & formatting
const F = () => S.unit === "F";
const C2F = (c) => c * 9 / 5 + 32;
const U = {
t: (c) => (c == null ? null : F() ? C2F(c) : c),
tF: (f) => (f == null ? null : F() ? f : (f - 32) * 5 / 9),
w: (ms) => (ms == null ? null : F() ? ms * 2.23694 : ms * 3.6),
wMph: (mph) => (mph == null ? null : F() ? mph : mph * 1.609344),
wKt: (kt) => (kt == null ? null : F() ? kt * 1.15078 : kt * 1.852),
p: (hpa) => (hpa == null ? null : F() ? hpa * 0.02953 : hpa),
};
const uT = () => (F() ? "°F" : "°C"), uW = () => (F() ? "mph" : "km/h"), uP = () => (F() ? "inHg" : "hPa"), uR = () => (F() ? "in" : "mm");
const WET_MM = 0.25; // the rain model's "wet hour": at least 0.01 in
const fR = (mm) => (mm == null || mm <= 0 ? "" : mm < WET_MM ? "T" : F() ? (mm / 25.4).toFixed(2).replace(/^0/, "") : mm.toFixed(1));
const r0 = (x) => (x == null || !Number.isFinite(x) ? "" : String(Math.round(x)));
const fP = (x) => (x == null ? "" : F() ? x.toFixed(2) : x.toFixed(0));
const compass = (d) => (d == null ? "calm" : ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"][Math.round(d / 22.5) % 16]);
const fmt = (o) => new Intl.DateTimeFormat("en-US", { timeZone: S.tz, ...o });
let fHr, fDay, fWhen, fTime;
function setZone(tz) {
S.tz = tz;
fHr = fmt({ hour: "numeric" }); fDay = fmt({ weekday: "short", day: "numeric" });
fWhen = fmt({ weekday: "short", hour: "numeric" }); fTime = fmt({ hour: "numeric", minute: "2-digit" });
}
setZone(S.tz);
const hShort = (d) => fHr.format(d).replace(" AM", "a").replace(" PM", "p");
const local = (d) => {
const p = Object.fromEntries(fmt({ year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", hourCycle: "h23" })
.formatToParts(d).map((x) => [x.type, x.value]));
return { key: `${p.year}-${p.month}-${p.day}`, hour: +p.hour };
};
const rh = (t, td) => (t == null || td == null ? null : 100 * Math.exp(17.625 * td / (243.04 + td)) / Math.exp(17.625 * t / (243.04 + t)));
const css = (n) => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
// ------------------------------------------------------------------ hourly rows
function build() {
const d = S.data, o = d.observed;
const obs = o.times.map((t, i) => ({ time: new Date(t), past: true, t: o.t[i], td: o.td[i], wspd: o.wspd[i], wdir: o.wdir?.[i],
gust: o.gust?.[i], mslp: o.mslp[i], sky: o.sky?.[i], precip: o.precip?.[i] }));
const nwsBy = new Map((d.nws?.hourly || []).map((p) => [new Date(p.time).getTime(), p]));
const q = (v, lv, i) => d.forecast[v][lv][i];
const nbs = d.guidance.NBS || {};
const fc = d.times.map((t, i) => {
const time = new Date(t), n = nwsBy.get(time.getTime());
return { time, past: false,
t: q("t", "0.5", i), t05: q("t", "0.05", i), t10: q("t", "0.1", i), t25: q("t", "0.25", i), t75: q("t", "0.75", i), t90: q("t", "0.9", i), t95: q("t", "0.95", i),
td: q("td", "0.5", i), wspd: q("wspd", "0.5", i), w10: q("wspd", "0.1", i), w90: q("wspd", "0.9", i), wdir: d.forecast.wdir[i],
mslp: q("mslp", "0.5", i), gust: nbs.gust?.[i] ?? null, sky: nbs.sky?.[i] ?? null, rain: d.rain?.p?.[i] ?? null,
nws: n ? { tF: n.t_f, mph: n.wspd_mph, pop: n.pop, short: n.short } : null };
});
return { obs, fc, origin: new Date(d.origin) };
}
// ------------------------------------------------------------------ where we differ
function drawDiffer() {
const { fc } = build();
const pairs = fc.filter((p) => p.nws).map((p) => {
const ours = U.t(p.t), nws = U.tF(p.nws.tF);
return { d: ours - nws, out: nws < U.t(p.t10) || nws > U.t(p.t90) };
});
if (!pairs.length) { $("#differ-sum").textContent = ""; return; }
const mean = pairs.reduce((a, x) => a + x.d, 0) / pairs.length;
const big = Math.max(...pairs.map((x) => Math.abs(x.d)));
$("#differ-sum").innerHTML = `ours vs NWS over ${pairs.length} h: average ${mean >= 0 ? "+" : "−"}${Math.abs(mean).toFixed(1)}°, largest gap ${big.toFixed(0)}°` +
(S.ranges ? `, NWS outside our 80% range ${pairs.filter((x) => x.out).length} h` : "");
}
// Monotone cubic curve through points [[x, y] | null, ...]; null breaks the line.
function smooth(pts) {
const segs = []; let cur = [];
for (const p of pts) { if (!p) { if (cur.length) segs.push(cur); cur = []; } else cur.push(p); }
if (cur.length) segs.push(cur);
return segs.map((p) => {
const n = p.length;
if (n < 2) return n ? `M${p[0][0]},${p[0][1]}` : "";
const dx = [], m = [], t = new Array(n);
for (let i = 0; i < n - 1; i++) { dx[i] = p[i + 1][0] - p[i][0]; m[i] = (p[i + 1][1] - p[i][1]) / dx[i]; }
t[0] = m[0]; t[n - 1] = m[n - 2];
for (let i = 1; i < n - 1; i++) t[i] = m[i - 1] * m[i] <= 0 ? 0 : (m[i - 1] + m[i]) / 2;
for (let i = 0; i < n - 1; i++) {
if (m[i] === 0) { t[i] = 0; t[i + 1] = 0; continue; }
const a = t[i] / m[i], b = t[i + 1] / m[i], h = a * a + b * b;
if (h > 9) { const k = 3 / Math.sqrt(h); t[i] = k * a * m[i]; t[i + 1] = k * b * m[i]; }
}
let d = `M${p[0][0]},${p[0][1]}`;
for (let i = 0; i < n - 1; i++) {
const h = dx[i] / 3;
d += `C${p[i][0] + h},${p[i][1] + t[i] * h} ${p[i + 1][0] - h},${p[i + 1][1] - t[i + 1] * h} ${p[i + 1][0]},${p[i + 1][1]}`;
}
return d;
}).join("");
}
// The NWS publishes whole degrees / whole mph, which draws as stair steps. For the line only
// (never the numbers), soften that rounding with two passes of a 1-2-1 filter.
function soften(vals) {
let v = vals.slice();
for (let pass = 0; pass < 2; pass++) {
v = v.map((x, i) => {
if (x == null) return null;
const a = v[i - 1] ?? x, b = v[i + 1] ?? x;
return (a + 2 * x + b) / 4;
});
}
return v;
}
// ------------------------------------------------------------------ the strip
const COL = 42;
function rowsSpec() {
const ourRain = !!S.data.rain?.p; // the hourly rain model is Indianapolis only
return [
{ id: "day", h: 22, label: "" },
{ id: "hour", h: 18, label: "" },
{ id: "fan", h: S.fanH || 300, label: `Temperature ${uT()}
ours NWS
measured
` },
{ id: "t", h: 22, label: innerWidth <= 640 ? "Likely / measured" : "Most likely / measured", strong: true },
{ id: "rng", h: 18, label: "80% range" },
{ id: "nws", h: 18, label: "NWS" },
{ id: "vs", h: 18, label: "NWS vs ours" },
{ id: "sp1", h: 12, label: "" },
{ id: "rchart", h: 96, label: ourRain ? `Rain chance %
ours NWS` : `Rain chance %
NWS` },
...(ourRain ? [{ id: "rain", h: 18, label: "Ours", strong: true }] : []),
{ id: "rnws", h: 18, label: "NWS" },
{ id: "rmeas", h: 18, label: `Measured, ${uR()}` },
{ id: "sp4", h: 12, label: "" },
{ id: "td", h: 18, label: `Dew point ${uT()}` },
{ id: "rh", h: 18, label: "Humidity %" },
{ id: "sp2", h: 12, label: "" },
{ id: "wchart", h: 96, label: `Wind ${uW()}
ours NWS` },
{ id: "arrow", h: 22, label: "Wind from" },
{ id: "w", h: 18, label: innerWidth <= 640 ? "Likely / measured" : "Most likely / measured", strong: true },
{ id: "wr", h: 18, label: "80% range" },
{ id: "g", h: 18, label: "Gust, Blend" },
{ id: "sp3", h: 12, label: "" },
{ id: "p", h: 18, label: `Pressure ${uP()}` },
{ id: "sky", h: 18, label: "Cloud %, Blend" },
{ id: "end", h: 6, label: "" },
].filter((r) => S.ranges || (r.id !== "rng" && r.id !== "wr"));
}
// The temperature chart takes exactly the room the rest of the page leaves, so the page
// itself never scrolls: draw once, measure the overflow, then redraw at the right height.
function fitStrip() {
if (!S.fanH) S.fanH = 300;
drawStrip();
// body height is the content's height, so this also grows the chart when the page is short
const extra = Math.ceil(document.body.getBoundingClientRect().height) - window.innerHeight;
const want = Math.max(180, Math.min(1000, S.fanH - extra));
if (want !== S.fanH) { S.fanH = want; drawStrip(); }
}
function drawStrip() {
const B = build();
const past = B.obs.slice(-24);
const cols = [...past, ...B.fc];
const rows = rowsSpec();
const y = {}; let acc = 0;
for (const r of rows) { y[r.id] = acc; acc += r.h; }
const H = acc, W = cols.length * COL;
$("#strip-labels").innerHTML = rows.map((r) => `
${r.label}
`).join("");
const svg = $("#strip-svg");
svg.innerHTML = "";
svg.setAttribute("width", W); svg.setAttribute("height", H); svg.setAttribute("viewBox", `0 0 ${W} ${H}`);
const cx = (i) => i * COL + COL / 2;
const nPast = past.length;
// backgrounds: past region, night (fan only), day boundaries
const nowX = cx(nPast - 1);
el("rect", { x: 0, y: 0, width: nowX, height: H, fill: css("--past") }, svg);
// our high (8 am–8 pm) and morning low (midnight–9 am) per local day
const dayStats = new Map();
const byDay = new Map();
B.fc.forEach((p) => { const l = local(p.time); if (!byDay.has(l.key)) byDay.set(l.key, []); byDay.get(l.key).push({ t: p.t, hour: l.hour }); });
for (const [k, pts] of byDay) {
const day = pts.filter((p) => p.hour >= 8 && p.hour <= 20), morn = pts.filter((p) => p.hour <= 9);
dayStats.set(k, { hi: day.length >= 8 ? Math.max(...day.map((p) => p.t)) : null, lo: morn.length >= 6 ? Math.min(...morn.map((p) => p.t)) : null });
}
const dayStarts = [];
cols.forEach((p, i) => { if (i === 0 || local(p.time).hour === 0) dayStarts.push(i); });
for (const i of dayStarts) {
if (i) el("line", { x1: i * COL, x2: i * COL, y1: 0, y2: H, class: "c-grid" }, svg);
const t = el("text", { x: i * COL + 5, y: y.day + 15, class: "c-day" }, svg, fDay.format(cols[i].time));
const st = dayStats.get(local(cols[i].time).key);
if (st) el("tspan", { class: "c-dim", dx: 10 }, t, [st.hi != null ? `high ${r0(U.t(st.hi))}°` : "", st.lo != null ? `low ${r0(U.t(st.lo))}°` : ""].filter(Boolean).join(" "));
}
cols.forEach((p, i) => el("text", { x: cx(i), y: y.hour + 13, "text-anchor": "middle", class: "c-dim" }, svg, hShort(p.time)));
// fan chart
const fanTop = y.fan + 8, fanBot = y.fan + S.fanH - 8;
// forecasts made 24 h before "now", for the past columns
const po = S.data.past_ours, pn = S.data.past_nws;
const pastOurs = new Map((po?.times || []).map((t, k) => [new Date(t).getTime(), po.t[k]]));
const pastNws = new Map((pn?.hourly || []).map((h) => [new Date(h.time).getTime(), h.t_f]));
const thenOurs = (p) => { const v = pastOurs.get(p.time.getTime()); return v == null ? null : U.t(v); };
const thenNws = (p) => { const v = pastNws.get(p.time.getTime()); return v == null ? null : U.tF(v); };
const vals = [...past.map((p) => U.t(p.t)),
...B.fc.flatMap((p) => [U.t(p.t), S.ranges ? U.t(p.t10) : null, S.ranges ? U.t(p.t90) : null, p.nws ? U.tF(p.nws.tF) : null])].filter((v) => v != null);
let lo = Math.min(...vals), hi = Math.max(...vals);
const pad = (hi - lo) * 0.06 || 1; lo -= pad; hi += pad;
const Y = (v) => fanTop + (hi - v) / (hi - lo) * (fanBot - fanTop);
const step = (hi - lo) > 40 ? 10 : (hi - lo) > 16 ? 5 : 2;
for (let v = Math.ceil(lo / step) * step; v <= hi; v += step) {
el("line", { x1: 0, x2: W, y1: Y(v), y2: Y(v), class: "c-grid", "stroke-dasharray": "2 4" }, svg);
for (const i of dayStarts) el("text", { x: i * COL + 4, y: Y(v) - 3, class: "c-axis" }, svg, `${v}°`);
}
const ours = css("--ours");
const fcX = (k) => cx(nPast + k);
const band = (a, b) => {
const top = B.fc.map((p, k) => [fcX(k), Y(U.t(p[b]))]);
const bot = B.fc.map((p, k) => [fcX(k), Y(U.t(p[a]))]).reverse();
return "M" + [...top, ...bot].map((p) => p.join(",")).join("L") + "Z";
};
if (S.ranges) {
el("path", { d: band("t10", "t90"), fill: ours, opacity: 0.2 }, svg);
el("path", { d: band("t25", "t75"), fill: ours, opacity: 0.22 }, svg);
}
const ink = css("--ink"), nws = css("--nws");
const linear = (pts) => { let d = "", pen = false; for (const p of pts) { if (!p) { pen = false; continue; } d += `${pen ? "L" : "M"}${p[0]},${p[1]}`; pen = true; } return d; };
const line = (pts, color, w, op = 1) => el("path", { d: linear(pts), fill: "none", stroke: color, "stroke-width": w, "stroke-linejoin": "round", "stroke-linecap": "round", opacity: op }, svg);
// ahead: the current forecasts. Ours starts from the last measurement.
const nwsAtNow = (S.data.nws?.hourly || []).find((h) => new Date(h.time).getTime() === B.origin.getTime());
const nwsNow = [nwsAtNow ? U.tF(nwsAtNow.t_f) : null, ...B.fc.map((p) => (p.nws ? U.tF(p.nws.tF) : null))];
line(nwsNow.map((v, k) => (v != null ? [cx(nPast - 1 + k), Y(v)] : null)), nws, 2.25);
const lastObs = past.filter((p) => p.t != null).slice(-1)[0];
line([...(lastObs ? [[cx(past.indexOf(lastObs)), Y(U.t(lastObs.t))]] : []), ...B.fc.map((p, k) => [fcX(k), Y(U.t(p.t))])], ours, 3);
// flag hours where the NWS falls outside our 80% range
B.fc.forEach((p, k) => {
if (!p.nws || !S.ranges) return;
const n = U.tF(p.nws.tF);
if (n < U.t(p.t10) || n > U.t(p.t90)) el("circle", { cx: fcX(k), cy: Y(n), r: 3.5, fill: css("--bg"), stroke: css("--flag"), "stroke-width": 2 }, svg);
});
line(past.map((p, i) => (p.t != null ? [cx(i), Y(U.t(p.t))] : null)), ink, 1.5);
past.forEach((p, i) => { if (p.t != null) el("circle", { cx: cx(i), cy: Y(U.t(p.t)), r: 3, fill: ink }, svg); });
// wind chart: ours vs NWS ahead, measured (and ours from 24 h earlier) behind
const pastW = new Map((po?.times || []).map((t, k) => [new Date(t).getTime(), po.wspd?.[k]]));
const wTop = y.wchart + 8, wBot = y.wchart + 96 - 6;
const wv = [...past.map((p) => U.w(p.wspd)), ...B.fc.flatMap((p) => [U.w(p.wspd), p.nws ? U.wMph(p.nws.mph) : null])].filter((v) => v != null);
const wHi = Math.max(5, ...wv) * 1.1;
const YW = (v) => wBot - v / wHi * (wBot - wTop);
const wStep = wHi > 40 ? 20 : wHi > 16 ? 10 : 5;
for (let v = 0; v <= wHi; v += wStep) {
el("line", { x1: 0, x2: W, y1: YW(v), y2: YW(v), class: "c-grid", "stroke-dasharray": "2 4" }, svg);
for (const i of dayStarts) el("text", { x: i * COL + 4, y: YW(v) - 3, class: "c-axis" }, svg, String(v));
}
const wOurs = css("--w-ours"), wNws = css("--w-nws");
const lastW = past.filter((p) => p.wspd != null).slice(-1)[0];
const oursW = [...(lastW ? [[cx(past.indexOf(lastW)), YW(U.w(lastW.wspd))]] : []), ...B.fc.map((p, k) => [fcX(k), YW(U.w(p.wspd))])];
line(oursW, wOurs, 2.5);
const nwsWv = [nwsAtNow?.wspd_mph != null ? U.wMph(nwsAtNow.wspd_mph) : null, ...B.fc.map((p) => (p.nws?.mph != null ? U.wMph(p.nws.mph) : null))];
line(nwsWv.map((v, k) => (v != null ? [cx(nPast - 1 + k), YW(v)] : null)), wNws, 2.25);
line(past.map((p, i) => (p.wspd != null ? [cx(i), YW(U.w(p.wspd))] : null)), ink, 1.25, 0.8);
past.forEach((p, i) => { if (p.wspd != null) el("circle", { cx: cx(i), cy: YW(U.w(p.wspd)), r: 2.5, fill: ink }, svg); });
// rain chart: our hourly chance as bars, NWS as a line, wet hours as dots along the top.
// Behind the now line, both show what was forecast 24 h earlier.
const pastRain = new Map((S.data.rain?.past?.times || []).map((t, k) => [new Date(t).getTime(), S.data.rain.past.p[k]]));
const pastPop = new Map((pn?.hourly || []).map((h) => [new Date(h.time).getTime(), "pop" in h ? h.pop ?? 0 : null])); // older saves have no rain chance
const rainAt = (p) => (p.past ? pastRain.get(p.time.getTime()) ?? null : p.rain);
const popAt = (p) => (p.past ? pastPop.get(p.time.getTime()) ?? null : p.nws ? p.nws.pop ?? 0 : null);
const rTop = y.rchart + 12, rBot = y.rchart + 96 - 4, YR = (v) => rBot - v / 100 * (rBot - rTop);
for (const v of [0, 50, 100]) {
el("line", { x1: 0, x2: W, y1: YR(v), y2: YR(v), class: "c-grid", "stroke-dasharray": v ? "2 4" : "" }, svg);
if (v) for (const i of dayStarts) el("text", { x: i * COL + 4, y: YR(v) - 3, class: "c-axis" }, svg, String(v));
}
const rOurs = css("--r-ours");
cols.forEach((p, i) => {
const v = rainAt(p);
if (v == null || v < 0.5) return;
const a = cx(i) - 11, b = cx(i) + 11, top = YR(v), rd = Math.min(3, rBot - top);
el("path", { d: `M${a},${rBot}V${top + rd}Q${a},${top} ${a + rd},${top}H${b - rd}Q${b},${top} ${b},${top + rd}V${rBot}Z`, fill: rOurs, opacity: p.past ? 0.5 : 1 }, svg);
});
line(cols.map((p, i) => { const v = popAt(p); return v == null ? null : [cx(i), YR(v)]; }), css("--r-nws"), 2.25);
past.forEach((p, i) => { if (p.precip >= WET_MM) el("circle", { cx: cx(i), cy: y.rchart + 6, r: 3, fill: ink }, svg); });
// number rows
const txt = (i, row, s, cls = "c-num") => s !== "" && row in y && el("text", { x: cx(i), y: y[row] + rows.find((r) => r.id === row).h - 5, "text-anchor": "middle", class: cls }, svg, s);
cols.forEach((p, i) => {
txt(i, "t", r0(U.t(p.t)), p.past ? "c-num" : "c-strong");
txt(i, "td", r0(U.t(p.td)));
txt(i, "rh", r0(rh(p.t, p.td)));
txt(i, "w", r0(U.w(p.wspd)), p.past ? "c-num" : "c-strong");
txt(i, "g", p.gust != null && (!p.past || p.gust > p.wspd + 0.5) ? r0(U.w(p.gust)) : "");
txt(i, "p", fP(U.p(p.mslp)), "c-num");
txt(i, "sky", r0(p.sky), "c-dim");
txt(i, "rain", r0(rainAt(p)), p.past ? "c-num" : "c-strong");
txt(i, "rnws", r0(popAt(p)), "c-dim");
if (p.past) txt(i, "rmeas", fR(p.precip), "c-num");
if (p.wdir != null) {
const g = el("g", { transform: `translate(${cx(i)},${y.arrow + 11}) rotate(${p.wdir})` }, svg);
el("path", { d: "M0,-7 L0,7 M-4,2.5 L0,7 L4,2.5", stroke: p.past ? ink : ours, "stroke-width": 1.6, fill: "none", "stroke-linecap": "round", "stroke-linejoin": "round" }, g);
}
if (!p.past) {
txt(i, "rng", `${r0(U.t(p.t10))}–${r0(U.t(p.t90))}`, "c-dim");
txt(i, "wr", `${r0(U.w(p.w10))}–${r0(U.w(p.w90))}`, "c-dim");
if (p.nws) {
const n = U.tF(p.nws.tF), d = Math.round(n) - Math.round(U.t(p.t));
txt(i, "nws", r0(n));
const out = S.ranges && (n < U.t(p.t10) || n > U.t(p.t90));
txt(i, "vs", d === 0 ? "0" : `${d > 0 ? "+" : "−"}${Math.abs(d)}`, out ? "c-num c-flag" : "c-dim");
}
}
});
// now line + hover columns
el("line", { x1: nowX, x2: nowX, y1: y.fan, y2: y.fan + S.fanH, class: "c-now" }, svg);
el("line", { x1: nowX, x2: nowX, y1: y.wchart, y2: y.wchart + 96, class: "c-now" }, svg);
el("line", { x1: nowX, x2: nowX, y1: y.rchart, y2: y.rchart + 96, class: "c-now" }, svg);
el("text", { x: nowX + 5, y: y.fan + 12, class: "c-dim" }, svg, "now");
cols.forEach((p, i) => {
const r = el("rect", { x: i * COL, y: 0, width: COL, height: H, class: "c-col", fill: "transparent" }, svg);
const tip = p.past ? `measured ${r0(U.t(p.t))}°`
: `ours ${r0(U.t(p.t))}°` + (p.nws ? `, NWS ${r0(U.tF(p.nws.tF))}°` : "");
const rv = rainAt(p), nv = popAt(p);
const rainTip = rv == null && nv == null ? "" : `. Rain chance${p.past ? " forecast a day earlier" : ""}: ${rv == null ? "" : `ours ${r0(rv)}%`}${rv != null && nv != null ? ", " : ""}${nv == null ? "" : `NWS ${r0(nv)}%`}`;
el("title", {}, r, `${fWhen.format(p.time)}: ${tip}${rainTip}`);
});
const sc = $("#strip-scroll");
if (!S.scrolled) { sc.scrollLeft = Math.max(0, (nPast - 12) * COL); S.scrolled = true; }
// one line on how yesterday's forecasts did over the past 24 hours
const miss = (get) => {
const e = past.map((p) => (p.t != null && get(p) != null ? Math.abs(get(p) - U.t(p.t)) : null)).filter((x) => x != null);
return e.length >= 12 ? e.reduce((a, b) => a + b, 0) / e.length : null;
};
const mO = miss(thenOurs), mN = miss(thenNws);
const home = where().id === HOME;
$("#yesterday").innerHTML = mO == null ? "" : `Yesterday's forecasts for the last 24 hours: ours was off by ${mO.toFixed(1)}° on average` +
(mN != null ? `, the NWS by ${mN.toFixed(1)}°.` : home ? ". The NWS comparison appears once a day of its forecasts has been saved." : ".");
}
function where() {
const st = S.data?.station;
return st || { id: HOME, name: "Indianapolis International", state: "IN", tz: "America/Indiana/Indianapolis" };
}
function drawPlace() {
const st = where(), d = S.data;
const airport = `${st.name} (${st.id})`;
$("#where").textContent = S.city ? `${S.city}: ${airport}` : airport;
document.title = `${S.city ? S.city.split(",")[0] : st.name} forecast: Indra`;
const notes = [];
if (!SCORED.has(st.id)) notes.push("Indra-3M hasn't been scored at this airport. At 18 airports it never trained on, its temperature error averaged about 12% below the National Blend.");
const gone = (d.missing_guidance || []).map((k) => SOURCE_NAME[k] || k);
if (gone.length) notes.push(`This airport has no ${gone.join(" or ")} forecasts, which the model expects, so it may be less accurate here.`);
if (!d.rain?.p) notes.push("Our hourly rain model is Indianapolis only, so rain here is the NWS forecast.");
$("#place-note").textContent = notes.join(" ");
}
function drawInputs() {
const d = S.data, now = Date.now();
const age = (now - new Date(d.generated)) / 36e5, up = $("#updated");
up.textContent = age > 2 ? `Not updated since ${fWhen.format(new Date(d.generated))}` : `computed on this device at ${fTime.format(new Date(d.generated))}`;
up.classList.toggle("stale", age > 2);
$("#units").textContent = F() ? "°F, mph" : "°C, km/h";
}
function render() {
if (!S.data) return;
drawPlace(); drawDiffer(); drawInputs(); fitStrip();
}
// ------------------------------------------------------------------ getting a forecast
// The bar jumps as each step starts, then creeps toward the next step's start, so it never looks stuck.
const BAR = { value: 0, ceiling: 0, timer: null };
function paintBar() {
$("#bar i").style.width = `${(BAR.value * 100).toFixed(1)}%`;
$("#bar").setAttribute("aria-valuenow", Math.round(BAR.value * 100));
}
function showStatus(text, value, ceiling) {
$("#status-text").textContent = text;
$("#status").hidden = !text;
$("#forecast").hidden = !!text;
const running = !!text && value !== undefined;
$("#bar").hidden = !running;
if (!running) {
clearInterval(BAR.timer);
BAR.timer = null;
return;
}
BAR.value = Math.max(BAR.value, value);
BAR.ceiling = Math.max(ceiling ?? value, BAR.value);
paintBar();
if (!BAR.timer) BAR.timer = setInterval(() => { BAR.value += (BAR.ceiling - BAR.value) * 0.03; paintBar(); }, 150);
}
async function load(quiet) {
const ask = ++S.want, id = S.at;
const say = (text, value, ceiling) => { if (!quiet && ask === S.want) showStatus(text, value, ceiling); };
if (!quiet) {
$("#where").textContent = S.city || id;
$("#place-note").textContent = "";
$("#differ-sum").textContent = "";
BAR.value = 0;
showStatus(`Getting the forecast for ${S.city || id}.`, 0.01, 0.02);
}
try {
await places();
const i = P.byId.get(id);
if (i === undefined) { if (!quiet) showStatus("We don't have that airport. Try a city name."); return; }
const [sid, name, state, tz, lat, lon] = P.stations[i];
const d = await Engine.forecast({ id: sid, name, state, tz, lat, lon }, say);
if (ask !== S.want) return;
if (id === HOME) await addIndianapolisRain(d);
if (ask !== S.want) return;
S.data = d; S.ran = Date.now();
setZone(tz);
showStatus("");
render();
} catch (e) {
if (ask === S.want && !quiet) showStatus(e.message || "Something went wrong. Please try again.");
}
}
// Indianapolis also has our separate hourly rain model, computed ahead of time.
async function addIndianapolisRain(d) {
try {
const j = await (await fetch("/forecast.json", { cache: "no-store" })).json();
if (j.rain?.p) {
const shift = Math.round((new Date(d.origin) - new Date(j.origin)) / 36e5);
d.rain = { ...j.rain, p: d.times.map((_, i) => j.rain.p[i + shift] ?? null) };
}
d.past_nws = j.past_nws ?? null;
if (!d.nws.hourly.length && j.nws) d.nws = j.nws;
} catch (e) { /* the forecast stands without it */ }
}
function go(id, city) {
S.at = id; S.city = city || null; S.scrolled = false;
try {
localStorage.setItem("indra-at", id);
if (city) localStorage.setItem("indra-city", city); else localStorage.removeItem("indra-city");
} catch (e) { /* ignore */ }
history.replaceState(null, "", id === HOME ? location.pathname : `?at=${id}`);
load();
}
// ------------------------------------------------------------------ choosing a place
const P = { list: null, hits: [], active: -1 };
const plain = (x) => x.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/\bsaint\b/g, "st").replace(/[.']/g, "");
async function places() {
if (P.list) return P.list;
const d = await (await fetch("/places.json")).json();
P.stations = d.stations;
P.list = d.cities.map(([name, state, s, mi]) => ({ name, state, s, mi, key: plain(name) }));
P.byId = new Map(d.stations.map((x, i) => [x[0], i]));
P.airports = d.stations.map((x, i) => ({ i, key: plain(x[1]) }));
return P.list;
}
function search(text) {
const words = plain(text).replace(/,/g, " ").split(/\s+/).filter(Boolean);
if (!words.length || !P.list) return [];
const out = [];
const code = text.trim().toUpperCase();
if (P.byId.has(code)) {
const x = P.stations[P.byId.get(code)];
out.push({ id: x[0], city: null, text: `${x[1]} (${x[0]})`, sub: x[2] });
}
const state = words.length > 1 && /^[a-z]{2}$/.test(words[words.length - 1]) ? words[words.length - 1].toUpperCase() : null;
const q = (state ? words.slice(0, -1) : words).join(" ");
const tryCity = (test) => {
for (const c of P.list) {
if (out.length >= 8) return;
if (state && c.state !== state) continue;
if (!test(c.key)) continue;
const a = P.stations[c.s], city = `${c.name}, ${c.state}`;
if (!out.some((o) => o.city === city)) out.push({ id: a[0], city, text: city, sub: `${a[1]} (${a[0]}), ${c.mi} mi away` });
}
};
tryCity((k) => k.startsWith(q));
tryCity((k) => k.includes(` ${q}`));
for (const a of P.airports) {
if (out.length >= 8) break;
if (a.key.includes(q)) {
const x = P.stations[a.i];
if (!out.some((o) => o.id === x[0])) out.push({ id: x[0], city: null, text: `${x[1]} (${x[0]})`, sub: x[2] });
}
}
return out;
}
function drawHits() {
const box = $("#place-list"), input = $("#place");
box.innerHTML = "";
P.hits.forEach((h, i) => {
const li = document.createElement("li");
li.id = `hit-${i}`; li.setAttribute("role", "option"); li.setAttribute("aria-selected", i === P.active ? "true" : "false");
const a = document.createElement("span"); a.textContent = h.text;
const b = document.createElement("span"); b.className = "dim"; b.textContent = h.sub;
li.append(a, b);
li.addEventListener("pointerdown", (e) => { e.preventDefault(); pick(i); });
box.appendChild(li);
});
const open = P.hits.length > 0;
box.hidden = !open;
input.setAttribute("aria-expanded", open ? "true" : "false");
if (P.active >= 0) input.setAttribute("aria-activedescendant", `hit-${P.active}`); else input.removeAttribute("aria-activedescendant");
}
function pick(i) {
const h = P.hits[i];
if (!h) return;
P.hits = []; P.active = -1; drawHits();
$("#place").value = ""; $("#place").blur();
go(h.id, h.city);
}
$("#place").addEventListener("focus", () => { places().catch(() => {}); });
$("#place").addEventListener("input", async (e) => {
const text = e.target.value;
if (text.trim().length < 2) { P.hits = []; P.active = -1; drawHits(); return; }
try { await places(); } catch (err) { return; }
if (e.target.value !== text) return;
P.hits = search(text); P.active = P.hits.length ? 0 : -1; drawHits();
});
$("#place").addEventListener("keydown", (e) => {
if (e.key === "ArrowDown" && P.hits.length) { e.preventDefault(); P.active = (P.active + 1) % P.hits.length; drawHits(); }
else if (e.key === "ArrowUp" && P.hits.length) { e.preventDefault(); P.active = (P.active - 1 + P.hits.length) % P.hits.length; drawHits(); }
else if (e.key === "Escape") { P.hits = []; P.active = -1; drawHits(); }
});
$("#place-form").addEventListener("submit", (e) => { e.preventDefault(); if (P.active >= 0) pick(P.active); });
$("#place").addEventListener("blur", () => { setTimeout(() => { P.hits = []; P.active = -1; drawHits(); }, 100); });
$("#units").addEventListener("click", () => {
S.unit = F() ? "C" : "F";
try { localStorage.setItem("kind-unit", S.unit); } catch (e) { /* ignore */ }
render();
});
// The checkbox lives in the row labels, which are rebuilt on every draw.
$("#strip-labels").addEventListener("change", (e) => {
if (e.target.id !== "ranges") return;
S.ranges = e.target.checked;
try { localStorage.setItem("kind-ranges", S.ranges ? "1" : "0"); } catch (err) { /* ignore */ }
render();
$("#ranges").focus();
});
// The strip scrolls sideways with the mouse wheel, and by click-and-drag.
const sc = $("#strip-scroll");
sc.addEventListener("wheel", (e) => {
if (Math.abs(e.deltaX) > Math.abs(e.deltaY)) return; // trackpads already scroll sideways
const max = sc.scrollWidth - sc.clientWidth;
if ((e.deltaY < 0 && sc.scrollLeft <= 0) || (e.deltaY > 0 && sc.scrollLeft >= max)) return; // at an end: let the page scroll
e.preventDefault();
sc.scrollLeft += e.deltaMode === 1 ? e.deltaY * 40 : e.deltaY;
}, { passive: false });
let drag = null;
sc.addEventListener("pointerdown", (e) => { if (e.pointerType === "mouse" && e.button === 0) { drag = { x: e.clientX, left: sc.scrollLeft, moved: false }; } });
window.addEventListener("pointermove", (e) => {
if (!drag) return;
const dx = e.clientX - drag.x;
if (Math.abs(dx) > 3) { drag.moved = true; sc.classList.add("dragging"); }
sc.scrollLeft = drag.left - dx;
});
window.addEventListener("pointerup", () => { drag = null; sc.classList.remove("dragging"); });
let rT;
window.addEventListener("resize", () => { clearTimeout(rT); rT = setTimeout(() => S.data && fitStrip(), 150); });
setInterval(() => { if (!document.hidden && S.ran && Date.now() - S.ran > 30 * 60e3) load(true); }, 5 * 60e3);
load();