thermograph/frontend/static/climate.js
Emi Griffith d6df04eab2 Subtree-merge thermograph-frontend (origin/main) into frontend/
git-subtree-dir: frontend
git-subtree-mainline: a4be7066e5
git-subtree-split: 3a98146da4
2026-07-22 22:01:11 -07:00

33 lines
1.5 KiB
JavaScript

// Client-side unit converter for the server-rendered climate/city/record pages.
// Those pages render every measurement as a span carrying the imperial value —
// `<span class="temp" data-temp-f="72.3">23°C</span>`, `.precip[data-precip-in]`,
// `.wind[data-wind-mph]` (see content.py `_temp`/`_precip`/`_wind`) — so the number
// is real in the HTML for crawlers and no-JS visitors, already in the city's own
// convention. Here we rewrite each span to the active unit on load and whenever the
// toggle changes, reusing the same unit machinery as the interactive pages.
// Importing units.js also boots its toggle-injection IIFE, so this one script gives
// the pages a working toggle.
//
// Absolute humidity is g/m³ in both systems, so it is rendered as plain text with
// no span and nothing to repaint here.
import { fmtTemp, fmtPrecip, fmtWind, onUnitChange } from "./units.js";
// [selector, data attribute, formatter] — the attribute is always the imperial
// value, which is what makes repainting idempotent.
const PAINTERS = [
[".temp[data-temp-f]", "tempF", (v, el) => fmtTemp(v, !el.hasAttribute("data-bare"))],
[".precip[data-precip-in]", "precipIn", (v) => fmtPrecip(v)],
[".wind[data-wind-mph]", "windMph", (v) => fmtWind(v)],
];
function paint() {
for (const [sel, attr, fmt] of PAINTERS) {
for (const el of document.querySelectorAll(sel)) {
const v = parseFloat(el.dataset[attr]);
if (!Number.isNaN(v)) el.textContent = fmt(v, el);
}
}
}
paint();
onUnitChange(paint);