// ════════════════════════════════════════════════════════════════════════ // SUNSCOPE — single-file Preact app, no build step required. // ════════════════════════════════════════════════════════════════════════ // // QUICK MAP — where to find common things to change // ────────────────────────────────────────────────────────────────────── // // Forecast length .............. fetch URL contains &forecast_days=14 // Free tier day limit .......... const FREE_DAYS = 3 // Preview the Pro view ......... useState(false) on isPro → flip to true // Confidence band colours ...... function confidenceBand() (hex codes) // Sky-circle colours ........... function skyFillForElev() (by elev°) // UTCI thermal-stress colours .. function utciCategory() // Big UTCI dial design ......... function ScopeReticle() // Small sun/moon circle ........ function SkyScope() // Rain/snow penalty curve ...... function precipPenalty() // Default columns shown ........ useState({...}) on visibleCols // Page tagline / about copy .... search for "utci-tagline" or "utci-about-text" // Starting location ............ useState({...}) on `location` near top of main // // HTM SYNTAX QUIRKS (the html`...` template literals look weird at first) // ────────────────────────────────────────────────────────────────────── // • Inside backticks, ${value} inserts a JS value // • Use <${MyComponent}> instead of for custom components // • style=${{ color: 'red' }} double braces (CSS as a JS object) // • class="x" or class=${cond ? 'a' : 'b'} both work // • Conditionals: ${cond && html`
shown when true
`} // // AFTER EDITING // ────────────────────────────────────────────────────────────────────── // 1. Save the file. // 2. Hard-refresh the page (Ctrl+F5 on Windows · Cmd+Shift+R on Mac). // 3. To force every visitor to get the fresh version, bump the cache // buster in index.html: sunscope.js?v=14d-local → ?v=14e // 4. Open the browser console (F12 → Console) to see any errors — // they always include the line number that broke. // // SAFETY TIP — before a big change, copy this file to sunscope.js.bak. // If something breaks, just rename the backup back. // ════════════════════════════════════════════════════════════════════════ // Tiny framework imports — these are the only three "outside" dependencies. // All three live in assets/vendor/ so the site has no external requests. import { h, render, Fragment } from './vendor/preact.js'; import { useState, useEffect, useLayoutEffect, useRef } from './vendor/preact-hooks.js'; import htm from './vendor/htm.js'; // `html` is the magic tagged-template function. Use it like: // html`
${someValue}
` const html = htm.bind(h); // ═══════════════════════════════════════════════════════════════════ // PHYSICAL CONSTANTS // ─────────────────────────────────────────────────────────────────── // These are real-world physics values — don't change them unless you // have a peer-reviewed reason. They're used by calcTmrt() below to // work out how much heat your skin actually absorbs from the sun. // SIGMA — Stefan–Boltzmann constant (radiates heat) // EPSILON_P — emissivity of human skin (~0.97) // A_K — short-wave absorption coefficient for clothing // ALBEDO_GRASS — how much sun grass reflects back at you (23%) // ═══════════════════════════════════════════════════════════════════ const SIGMA = 5.670374419e-8; const EPSILON_P = 0.97; const A_K = 0.7; const ALBEDO_GRASS = 0.23; // Vapour pressure (Magnus → hPa) function vaporPressureHpa(Ta, RH) { const es = 6.105 * Math.exp((17.27 * Ta) / (237.7 + Ta)); return es * (RH / 100); } // Solar elevation (NOAA simplified, degrees) function solarElevationDeg(lat, lon, dateUTC) { const start = Date.UTC(dateUTC.getUTCFullYear(), 0, 0); const diff = dateUTC - start; const DOY = Math.floor(diff / 86400000); const hourUTC = dateUTC.getUTCHours() + dateUTC.getUTCMinutes() / 60 + dateUTC.getUTCSeconds() / 3600; const gamma = ((2 * Math.PI) / 365) * (DOY - 1 + (hourUTC - 12) / 24); const eqtime = 229.18 * (0.000075 + 0.001868 * Math.cos(gamma) - 0.032077 * Math.sin(gamma) - 0.014615 * Math.cos(2 * gamma) - 0.040849 * Math.sin(2 * gamma)); const decl = 0.006918 - 0.399912 * Math.cos(gamma) + 0.070257 * Math.sin(gamma) - 0.006758 * Math.cos(2 * gamma) + 0.000907 * Math.sin(2 * gamma) - 0.002697 * Math.cos(3 * gamma) + 0.00148 * Math.sin(3 * gamma); const timeOffset = eqtime + 4 * lon; const tst = hourUTC * 60 + timeOffset; const ha = (((tst / 4) - 180) * Math.PI) / 180; const latRad = (lat * Math.PI) / 180; const cosZenith = Math.sin(latRad) * Math.sin(decl) + Math.cos(latRad) * Math.cos(decl) * Math.cos(ha); const zenith = Math.acos(Math.max(-1, Math.min(1, cosZenith))); return (Math.PI / 2 - zenith) * (180 / Math.PI); } // Mean radiant temperature function calcTmrt(Ta, dirRad, diffRad, globalRad, solElev) { const TaK = Ta + 273.15; let fp = 0; if (solElev > 0) { const h2 = solElev; fp = 0.308 * Math.cos((Math.PI / 180) * h2 * (0.998 - (h2 * h2) / 50000)); } let DNI = 0; if (solElev > 1) { DNI = dirRad / Math.sin((solElev * Math.PI) / 180); DNI = Math.min(DNI, 1100); } const Sshort = A_K * (fp * DNI + 0.5 * diffRad + 0.5 * ALBEDO_GRASS * globalRad); const Slong = EPSILON_P * SIGMA * Math.pow(TaK, 4); const TmrtK = Math.pow((Sshort + Slong) / (EPSILON_P * SIGMA), 0.25); return TmrtK - 273.15; } // ═══════════════════════════════════════════════════════════════════ // UTCI POLYNOMIAL — DO NOT EDIT (or be VERY careful if you do) // ─────────────────────────────────────────────────────────────────── // This is the official 210-term Bröde et al. (2012) approximation. // It takes air temp, mean radiant temp, wind, and humidity and returns // the "felt" temperature. Every number is a peer-reviewed coefficient. // Scroll past it — there's nothing here you'll want to change. // ═══════════════════════════════════════════════════════════════════ // UTCI 210-term polynomial (Bröde et al. 2012) function utciApprox(Ta, Tmrt, va10, ehPa) { const va = Math.max(0.5, Math.min(17, va10)); const D_Tmrt = Tmrt - Ta; const Pa = ehPa / 10; const T = Ta, V = va, D = D_Tmrt, P = Pa; const T2=T*T, T3=T2*T, T4=T3*T, T5=T4*T, T6=T5*T; const V2=V*V, V3=V2*V, V4=V3*V, V5=V4*V, V6=V5*V; const D2=D*D, D3=D2*D, D4=D3*D, D5=D4*D, D6=D5*D; const P2=P*P, P3=P2*P, P4=P3*P, P5=P4*P, P6=P5*P; return T + 6.07562052e-1 + -2.27712343e-2 * T + 8.06470249e-4 * T2 + -1.54271372e-4 * T3 + -3.24651735e-6 * T4 + 7.32602852e-8 * T5 + 1.35959073e-9 * T6 + -2.25836520e0 * V + 8.80326035e-2 * T*V + 2.16844454e-3 * T2*V + -1.53347087e-5 * T3*V + -5.72983704e-7 * T4*V + -2.55090145e-9 * T5*V + -7.51269505e-1 * V2 + -4.08350271e-3 * T*V2 + -5.21670675e-5 * T2*V2 + 1.94544667e-6 * T3*V2 + 1.14099531e-8 * T4*V2 + 1.58137256e-1 * V3 + -6.57263143e-5 * T*V3 + 2.22697524e-7 * T2*V3 + -4.16117031e-8 * T3*V3 + -1.27762753e-2 * V4 + 9.66891875e-6 * T*V4 + 2.52785852e-9 * T2*V4 + 4.56306672e-4 * V5 + -1.74202546e-7 * T*V5 + -5.91491269e-6 * V6 + 3.98374029e-1 * D + 1.83945314e-4 * T*D + -1.73754510e-4 * T2*D + -7.60781159e-7 * T3*D + 3.77830287e-8 * T4*D + 5.43079673e-10 * T5*D + -2.00518269e-2 * V*D + 8.92859837e-4 * T*V*D + 3.45433048e-6 * T2*V*D + -3.77925774e-7 * T3*V*D + -1.69699377e-9 * T4*V*D + 1.69992415e-4 * V2*D + -4.99204314e-5 * T*V2*D + 2.47417178e-7 * T2*V2*D + 1.07596466e-8 * T3*V2*D + 8.49242932e-5 * V3*D + 1.35191328e-6 * T*V3*D + -6.21531254e-9 * T2*V3*D + -4.99410301e-6 * V4*D + -1.89489258e-8 * T*V4*D + 8.15300114e-8 * V5*D + 7.55043090e-4 * D2 + -5.65095215e-5 * T*D2 + -4.52166564e-7 * T2*D2 + 2.46688878e-8 * T3*D2 + 2.42674348e-10 * T4*D2 + 1.54547250e-4 * V*D2 + 5.24110970e-6 * T*V*D2 + -8.75874982e-8 * T2*V*D2 + -1.50743064e-9 * T3*V*D2 + -1.56236307e-5 * V2*D2 + -1.33895614e-7 * T*V2*D2 + 2.49709824e-9 * T2*V2*D2 + 6.51711721e-7 * V3*D2 + 1.94960053e-9 * T*V3*D2 + -1.00361113e-8 * V4*D2 + -1.21206673e-5 * D3 + -2.18203660e-7 * T*D3 + 7.51269482e-9 * T2*D3 + 9.79063848e-11 * T3*D3 + 1.25006734e-6 * V*D3 + -1.81584736e-9 * T*V*D3 + -3.52197671e-10 * T2*V*D3 + -3.36514630e-8 * V2*D3 + 1.35908359e-10 * T*V2*D3 + 4.17032620e-10 * V3*D3 + -1.30369025e-9 * D4 + 4.13908461e-10 * T*D4 + 9.22652254e-12 * T2*D4 + -5.08220384e-9 * V*D4 + -2.24730961e-11 * T*V*D4 + 1.17139133e-10 * V2*D4 + 6.62154879e-10 * D5 + 4.03863260e-13 * T*D5 + 1.95087203e-12 * V*D5 + -4.73602469e-12 * D6 + 5.12733497e0 * P + -3.12788561e-1 * T*P + -1.96701861e-2 * T2*P + 9.99690870e-4 * T3*P + 9.51738512e-6 * T4*P + -4.66426341e-7 * T5*P + 5.48050612e-1 * V*P + -3.30552823e-3 * T*V*P + -1.64119440e-3 * T2*V*P + -5.16670694e-6 * T3*V*P + 9.52692432e-7 * T4*V*P + -4.29223622e-2 * V2*P + 5.00845667e-3 * T*V2*P + 1.00601257e-6 * T2*V2*P + -1.81748644e-6 * T3*V2*P + -1.25813502e-3 * V3*P + -1.79330391e-4 * T*V3*P + 2.34994441e-6 * T2*V3*P + 1.29735808e-4 * V4*P + 1.29064870e-6 * T*V4*P + -2.28558686e-6 * V5*P + -3.69476348e-2 * D*P + 1.62325322e-3 * T*D*P + -3.14279680e-5 * T2*D*P + 2.59835559e-6 * T3*D*P + -4.77136523e-8 * T4*D*P + 8.64203390e-3 * V*D*P + -6.87405181e-4 * T*V*D*P + -9.13863872e-6 * T2*V*D*P + 5.15916806e-7 * T3*V*D*P + -3.59217476e-5 * V2*D*P + 3.28696511e-5 * T*V2*D*P + -7.10542454e-7 * T2*V2*D*P + -1.24382300e-5 * V3*D*P + -7.38584400e-9 * T*V3*D*P + 2.20609296e-7 * V4*D*P + -7.32469180e-4 * D2*P + -1.87381964e-5 * T*D2*P + 4.80925239e-6 * T2*D2*P + -8.75492040e-8 * T3*D2*P + 2.77862930e-5 * V*D2*P + -5.06004592e-6 * T*V*D2*P + 1.14325367e-7 * T2*V*D2*P + 2.53016723e-6 * V2*D2*P + -1.72857035e-8 * T*V2*D2*P + -3.95079398e-8 * V3*D2*P + -3.59413173e-7 * D3*P + 7.04388046e-7 * T*D3*P + -1.89309167e-8 * T2*D3*P + -4.79768731e-7 * V*D3*P + 7.96079978e-9 * T*V*D3*P + 1.62897058e-9 * V2*D3*P + 3.94367674e-8 * D4*P + -1.18566247e-9 * T*D4*P + 3.34678041e-10 * V*D4*P + -1.15606447e-10 * D5*P + -2.80626406e0 * P2 + 5.48712484e-1 * T*P2 + -3.99428410e-3 * T2*P2 + -9.54009191e-4 * T3*P2 + 1.93090978e-5 * T4*P2 + -3.08806365e-1 * V*P2 + 1.16952364e-2 * T*V*P2 + 4.95271903e-4 * T2*V*P2 + -1.90710882e-5 * T3*V*P2 + 2.10787756e-3 * V2*P2 + -6.98445738e-4 * T*V2*P2 + 2.30109073e-5 * T2*V2*P2 + 4.17856590e-4 * V3*P2 + -1.27043871e-5 * T*V3*P2 + -3.04620472e-6 * V4*P2 + 5.14507424e-2 * D*P2 + -4.32510997e-3 * T*D*P2 + 8.99281156e-5 * T2*D*P2 + -7.14663943e-7 * T3*D*P2 + -2.66016305e-4 * V*D*P2 + 2.63789586e-4 * T*V*D*P2 + -7.01199003e-6 * T2*V*D*P2 + -1.06823306e-4 * V2*D*P2 + 3.61341136e-6 * T*V2*D*P2 + 2.29748967e-7 * V3*D*P2 + 3.04788893e-4 * D2*P2 + -6.42070836e-5 * T*D2*P2 + 1.16257971e-6 * T2*D2*P2 + 7.68023384e-6 * V*D2*P2 + -5.47446896e-7 * T*V*D2*P2 + -3.59937910e-8 * V2*D2*P2 + -4.36497725e-6 * D3*P2 + 1.68737969e-7 * T*D3*P2 + 2.67489271e-8 * V*D3*P2 + 3.23926897e-9 * D4*P2 + -3.53874123e-2 * P3 + -2.21201190e-1 * T*P3 + 1.55126038e-2 * T2*P3 + -2.63917279e-4 * T3*P3 + 4.53433455e-2 * V*P3 + -4.32943862e-3 * T*V*P3 + 1.45389826e-4 * T2*V*P3 + 2.17508610e-4 * V2*P3 + -6.66724702e-5 * T*V2*P3 + 3.33217140e-5 * V3*P3 + -2.26921615e-3 * D*P3 + 3.80261982e-4 * T*D*P3 + -5.45314314e-9 * T2*D*P3 + -7.96355448e-4 * V*D*P3 + 2.53458034e-5 * T*V*D*P3 + -6.31223658e-6 * V2*D*P3 + 3.02122035e-4 * D2*P3 + -4.77403547e-6 * T*D2*P3 + 1.73825715e-6 * V*D2*P3 + -4.09087898e-7 * D3*P3 + 6.14155345e-1 * P4 + -6.16755931e-2 * T*P4 + 1.33374846e-3 * T2*P4 + 3.55375387e-3 * V*P4 + -5.13027851e-4 * T*V*P4 + 1.02449757e-4 * V2*P4 + -1.48526421e-3 * D*P4 + -4.11469183e-5 * T*D*P4 + -6.80434415e-6 * V*D*P4 + -9.77675906e-6 * D2*P4 + 8.82773108e-2 * P5 + -3.01859306e-3 * T*P5 + 1.04452989e-3 * V*P5 + 2.47090539e-4 * D*P5 + 1.48348065e-3 * P6; } // ═══════════════════════════════════════════════════════════════════ // UTCI THERMAL STRESS BANDS — the coloured pills in the table. // ─────────────────────────────────────────────────────────────────── // To recolour any band, change its bg/fg hex code. To shift the // boundary between bands (e.g. make "Comfortable" wider), change the // `if (u < …)` thresholds. Order matters — they're checked top-down. // ═══════════════════════════════════════════════════════════════════ // UTCI stress bands function utciCategory(u) { if (u < -40) return { label: 'Extreme cold', bg: '#1a1438', fg: '#fff' }; if (u < -27) return { label: 'Very strong cold', bg: '#23408f', fg: '#fff' }; if (u < -13) return { label: 'Arctic', bg: '#3f73c4', fg: '#fff' }; if (u < 0) return { label: 'Freezing', bg: '#7eb0e0', fg: '#1a1612' }; if (u < 9) return { label: 'Cold', bg: '#bcd9ec', fg: '#1a1612' }; if (u < 18) return { label: 'Chilled', bg: '#c8dcc0', fg: '#1a1612' }; if (u < 26) return { label: 'Comfortable', bg: '#6ab05a', fg: '#fff' }; if (u < 32) return { label: 'Moderate heat', bg: '#e8c547', fg: '#1a1612' }; if (u < 38) return { label: 'Strong heat', bg: '#dc8a3a', fg: '#1a1612' }; if (u < 46) return { label: 'Very strong heat', bg: '#c44a3a', fg: '#fff' }; return { label: 'Extreme heat', bg: '#7a1a1a', fg: '#fff' }; } // ═══════════════════════════════════════════════════════════════════ // SOAK-FACTOR — SunScope's original rain/snow penalty. // ─────────────────────────────────────────────────────────────────── // This is what makes "UTCI+P" different from plain UTCI. It subtracts // extra felt-temperature for rain (wet clothing = evaporative chill) // and snow (wet snow is brutal). Wind amplifies the rain penalty. // Calibrated by feel — adjust the multipliers if you find it too // strong/weak. The big number "7" caps the max rain penalty so a // freak 50mm/h reading can't make UTCI nonsensical. // ═══════════════════════════════════════════════════════════════════ // Precipitation penalty (the SunScope soak-factor) function precipPenalty(precipMm, snowCmH, windMs) { let penalty = 0; if (precipMm > 0) { const base = Math.min(7, 1.4 * Math.pow(precipMm, 0.55) + precipMm * 0.28); const windMult = 1 + Math.min(0.35, windMs * 0.025); penalty += base * windMult; } if (snowCmH > 0) penalty += Math.min(6, 2.2 + snowCmH * 1.6); return -Math.round(penalty * 10) / 10; } // ═══════════════════════════════════════════════════════════════════ // WIND COMPASS — meteorological bearing (deg FROM) → 8-point label. // ─────────────────────────────────────────────────────────────────── // 0/360 = wind FROM north. The pointer in WindVane should rotate so // the arrow's tail points to this bearing (i.e. shows where the wind // comes from), matching how real weather vanes behave. // ═══════════════════════════════════════════════════════════════════ function windCompass8(deg) { if (deg == null || isNaN(deg)) return { label: '—', snapped: 0 }; const dirs = ['N','NE','E','SE','S','SW','W','NW']; const idx = Math.round(((deg % 360) + 360) % 360 / 45) % 8; return { label: dirs[idx], snapped: idx * 45 }; } // ═══════════════════════════════════════════════════════════════════ // UV-A / UV-B SPLIT (estimate, not measurement). // ─────────────────────────────────────────────────────────────────── // Open-Meteo gives a total erythemal UV index. UV-A reaches the // surface much more reliably than UV-B; UV-B is far more sensitive // to solar elevation because of atmospheric path length. // // Cheap model: // At noon (sun overhead) the UV-B share of total UV index is ~15%, // UV-A about 85%. Below ~10° solar elevation, UV-B falls off fast. // We return two pseudo-"index" numbers so the columns are in the // same units the user already understands. // Label these as estimates in the UI. // ═══════════════════════════════════════════════════════════════════ function uvSplit(uv, elevDeg) { if (!uv || uv <= 0 || elevDeg <= 0) return { uvA: 0, uvB: 0 }; const sinE = Math.sin(elevDeg * Math.PI / 180); const uvbFr = Math.max(0.005, Math.min(0.15, 0.15 * Math.pow(sinE, 1.6))); const uvaFr = 1 - uvbFr; return { uvA: uv * uvaFr, uvB: uv * uvbFr }; } // ═══════════════════════════════════════════════════════════════════ // SUNBURN TIME — minutes to MED for the chosen Fitzpatrick skin type. // ─────────────────────────────────────────────────────────────────── // Standard erythemal model: time_min ≈ base_minutes[type] / UV_index. // Numbers are the well-known "unprotected, midday, no sunscreen" // reference times at UV = 1. Returns Infinity when UV is 0 (night). // ═══════════════════════════════════════════════════════════════════ const SKIN_TYPES = { I: { name: 'I · Very fair', base: 67 }, II: { name: 'II · Fair', base: 100 }, III: { name: 'III · Light', base: 200 }, IV: { name: 'IV · Mid', base: 300 }, V: { name: 'V · Dark', base: 400 }, VI: { name: 'VI · Very dark', base: 500 }, }; function sunburnMinutes(uv, skinType = 'II') { if (!uv || uv <= 0) return Infinity; const base = (SKIN_TYPES[skinType] || SKIN_TYPES.II).base; return base / uv; } function burnLabel(mins) { if (!isFinite(mins)) return '—'; if (mins >= 480) return '8h+'; if (mins >= 60) return `${(mins/60).toFixed(1)}h`; return `${Math.round(mins)}m`; } // ═══════════════════════════════════════════════════════════════════ // CLOUD CATEGORY — pick one of 4 icon styles from low/mid/high split. // ─────────────────────────────────────────────────────────────────── // Returns: 'clear' | 'wispy' | 'scattered' | 'overcast' // Uses total cover for headline level, but biases towards 'wispy' // when only high cloud is present (cirrus barely blocks the sun). // ═══════════════════════════════════════════════════════════════════ function cloudCategory(total, low, mid, high) { const t = total ?? 0; const l = low ?? 0; const m = mid ?? 0; const h = high ?? 0; if (t < 10) return 'clear'; // Mostly high cloud with little low/mid → wispy regardless of % total if (h > 40 && l < 25 && m < 25) return 'wispy'; if (t < 40) return 'wispy'; if (t < 75) return 'scattered'; return 'overcast'; } // ═══════════════════════════════════════════════════════════════════ // CONFIDENCE BANDS — smooth high-noon → sunset gradient on day tabs. // ─────────────────────────────────────────────────────────────────── // `i` is the day index (0 = today, 13 = day 14). // // Each day gets its own shade, interpolated between two endpoint // colours. To re-skin the gradient (say, blue-to-purple instead of // sunset), just change the four RGB endpoint arrays below. // // bg = tab background (lighter on day 0, darker on day 13) // edge = active-tab underline + slim border on the banner // tint = soft wash on the confidence banner above the table // label = qualitative zone name shown in the banner ("Golden hour") // // The label switches in 4 stages so users still see a friendly // description ("you're in the trustworthy zone" vs "this is an // outlook"). The tab background itself flows smoothly day to day. // ═══════════════════════════════════════════════════════════════════ function confidenceBand(i) { // Position along the gradient: 0 on day 0, 1 on day 13. const t = Math.min(1, Math.max(0, i / 13)); // ENDPOINTS — change these four RGB arrays to re-skin the gradient. const bgStart = [255, 247, 214]; // #fff7d6 pale yellow (high noon) const bgEnd = [232, 152, 104]; // #e89868 terracotta (sunset) const edgeStart = [245, 231, 161]; // #f5e7a1 soft golden const edgeEnd = [196, 115, 64]; // #c47340 burnt umber // Linear interpolation between the two endpoints. const lerp = (a, b) => Math.round(a + t * (b - a)); const mix = (s, e) => [lerp(s[0], e[0]), lerp(s[1], e[1]), lerp(s[2], e[2])]; const [br, bg, bb] = mix(bgStart, bgEnd); const [er, eg, eb] = mix(edgeStart, edgeEnd); return { bg: `rgb(${br}, ${bg}, ${bb})`, edge: `rgb(${er}, ${eg}, ${eb})`, tint: `rgba(${er}, ${eg}, ${eb}, 0.22)`, // Qualitative confidence label (camera-focus metaphor — // on-brand for SunScope, and instantly readable). label: i < 3 ? 'Pin-sharp' // days 1–3 highest skill : i < 7 ? 'Sharp' // days 4–7 solid : i < 10 ? 'Soft focus' // days 8–10 trends only : 'Blurry', // days 11–14 outlook only }; } // ═══════════════════════════════════════════════════════════════════ // MOON PHASE — works out which moon emoji to show on night hours. // ─────────────────────────────────────────────────────────────────── // Returns a fraction 0..1: // 0.00 = new moon 0.50 = full moon // 0.25 = first quarter 0.75 = last quarter // The maths is a simple synodic-period calculation referenced from // a known new moon (6 Jan 2000). Accurate to within a few hours. // ═══════════════════════════════════════════════════════════════════ // Moon phase function moonPhaseFraction(date) { const JD = date.getTime() / 86400000 + 2440587.5; const syn = 29.530588; const ref = 2451550.1; let p = ((JD - ref) % syn) / syn; if (p < 0) p += 1; return p; } function moonGlyph(p) { return ['🌑','🌒','🌓','🌔','🌕','🌖','🌗','🌘'][Math.floor(p*8 + 0.5) % 8]; } // ═══════════════════════════════════════════════════════════════════ // SKY FILL — colour inside the little circle, based on sun elevation. // ─────────────────────────────────────────────────────────────────── // > 30° high noon (bright blue) // > 10° mid-sky (pale blue) // > 3° morning/afternoon (warm gold) // > -3° golden hour / sunset (deep amber) // > -8° civil twilight (dusky lilac) // > -14° nautical twilight (deep blue-violet) // else night (indigo) // To shift "when sunset starts" visually, tweak the elevation // thresholds. To recolour: replace the hex codes. // ═══════════════════════════════════════════════════════════════════ // Sky-fill colour by solar elevation function skyFillForElev(e) { if (e > 30) return '#9fd3ef'; if (e > 10) return '#c8e3ee'; if (e > 3) return '#ffd596'; if (e > -3) return '#f59b6e'; if (e > -8) return '#9279b0'; if (e > -14) return '#3a2f60'; return '#1a1538'; } // Grass palette — mirrors skyFillForElev but for the ground. // `top` = grass blade tips (catches sky light), `bot` = soil shadow. function grassFillForElev(e) { if (e > 30) return { top: '#86c44a', bot: '#558a2e' }; // bright noon grass if (e > 10) return { top: '#7ab846', bot: '#4d802c' }; // mid-day if (e > 3) return { top: '#b8a83e', bot: '#7a6a26' }; // golden-hour glow if (e > -3) return { top: '#c08048', bot: '#7a4a2a' }; // sunrise/sunset embers if (e > -8) return { top: '#665884', bot: '#3e3556' }; // civil twilight purple if (e > -14) return { top: '#363356', bot: '#1c1a34' }; // nautical night return { top: '#201d3a', bot: '#0d0b20' }; // astronomical night } // ═══════════════════════════════════════════════════════════════════ // SKYSCOPE — the little porthole circle next to each hour. // ─────────────────────────────────────────────────────────────────── // What gets drawn (back to front): // 1. Sky disk — colour from skyFillForElev() above // 2. Horizon line — faint dashed line at the middle // 3. Sun OR moon — sun positioned vertically by elevation; // moon shows real phase (synodic period) // 4. Brass ring — the telescope/scope edge (#c8922a) // 5. Lens highlight — subtle inner glint // // Tweakable bits inside this function: // • size — pass a different size= when calling for bigger/smaller // • innerR — how thick the brass ring looks // • sunR — the sun's drawn radius // • the stroke colour #c8922a is the brass — change for a different metal // ═══════════════════════════════════════════════════════════════════ function SkyScope({ elev, dt, size = 26 }) { const r = size / 2; const innerR = r - 1.2; const skyFill = skyFillForElev(elev); const isDay = elev > -3; const elevClamped = Math.max(-30, Math.min(90, elev)); const sunY = r - Math.sin((elevClamped * Math.PI) / 180) * (innerR - 2.5); const sunR = Math.max(2.2, innerR * 0.32); const phase = moonPhaseFraction(dt); const moonR = innerR * 0.55; const phaseOffset = Math.cos(2 * Math.PI * phase) * moonR; const moonLitFromRight = phase < 0.5; const shadowCx = r + (moonLitFromRight ? -phaseOffset : phaseOffset); const grass = grassFillForElev(elev); const uid = `${size}-${Math.round(elev * 10)}-${Math.round(phase * 1000)}`; const clipId = `scope-clip-${uid}`; const grassId = `scope-grass-${uid}`; return html` ${isDay ? html` ` : html` `} `; } // ═══════════════════════════════════════════════════════════════════ // WINDVANE — clean compass arrow on transparent background. // ─────────────────────────────────────────────────────────────────── // Traditional weather-vane behaviour: the ARROWHEAD points INTO the // wind (toward the source). Wind from the north → head points north. // // props: // bearing — degrees, 0 = wind FROM north // size — pixel diameter (default 30 to match SkyScope) // // Tweakable bits: // • arrowColor / nMarkerColor — line/fill colours // • Tiny N letter sits just above the arrow tail for orientation // ═══════════════════════════════════════════════════════════════════ function WindVane({ bearing, size = 30 }) { if (bearing == null || isNaN(bearing)) { return html``; } const r = size / 2; // The shaft is drawn pointing DOWN by default (head at the bottom). // To place the head at the bearing direction, rotate by bearing + 180. const rot = (bearing + 180) % 360; const arrowColor = '#2a1a08'; const headColor = '#c44a3a'; const nColor = '#9a7d5a'; // Geometry of the single-ended arrow (drawn pointing DOWN by default). // After rotation by (bearing + 180), the head lands on the bearing // direction — i.e. the side the wind is coming FROM. const tipY = r * 0.15; // arrowhead tip const headBase = r * 0.58; // bottom of the triangle head const headW = r * 0.42; const tailEndY = r * 1.78; // shaft's tail end const tailDotR = Math.max(1.0, size * 0.06); return html` N `; } // ═══════════════════════════════════════════════════════════════════ // CLOUDICON — clouds + sun/moon on a fully transparent background. // No rim, no disc. Day/night aware: when elev < 0, the sun is // replaced with a phased moon (same logic as SkyScope). // ─────────────────────────────────────────────────────────────────── // category: 'clear' | 'wispy' | 'scattered' | 'overcast' // elev: solar elevation in degrees (negative = night) // dt: Date used for moon phase // ═══════════════════════════════════════════════════════════════════ function CloudIcon({ category, size = 30, elev = 90, dt = new Date() }) { const r = size / 2; const u = r; // half-extent for layout const isNight = elev < -3; // Phased moon helper — returns an SVG with the moon + shadow. // Lit fraction direction matches SkyScope (waxing = lit from right). const renderMoon = (cx, cy, moonR) => { const phase = moonPhaseFraction(dt); const phaseOffset = Math.cos(2 * Math.PI * phase) * moonR; const moonLitFromRight = phase < 0.5; const shadowCx = cx + (moonLitFromRight ? -phaseOffset : phaseOffset); const clipId = `cmoon-${size}-${Math.round(cx)}-${Math.round(cy)}-${Math.round(phase * 1000)}`; return html` `; }; return html` ${category === 'clear' && (isNight ? html` ${renderMoon(r, r, u*0.50)}` : html` ${[0,45,90,135,180,225,270,315].map(a => { const x1 = r + Math.sin(a*Math.PI/180) * u*0.65; const y1 = r - Math.cos(a*Math.PI/180) * u*0.65; const x2 = r + Math.sin(a*Math.PI/180) * u*0.95; const y2 = r - Math.cos(a*Math.PI/180) * u*0.95; return html``; })} `)} ${category === 'wispy' && html` ${isNight ? renderMoon(r, r*0.95, u*0.42) : html``} `} ${category === 'scattered' && html` ${isNight ? renderMoon(r+u*0.45, r-u*0.40, u*0.32) : html``} `} ${category === 'overcast' && html` `} `; } // ═══════════════════════════════════════════════════════════════════ // SCOPERETICLE — the big circular UTCI dial in the page header. // ─────────────────────────────────────────────────────────────────── // This is the one with tick marks, the swept colour band, and the // needle pointing at the current felt-temperature. // // Tweakable bits: // • R = 86 outer ring radius (changes overall size) // • cx, cy = 100 centre point (leave alone unless you also // change the viewBox="0 0 200 200" below) // • { length: 36 } number of tick marks (1 every 10°) // • stressBands[] the colour ramp around the rim (matches UTCI) // • (value + 10) / 60 maps UTCI -10..50 onto the 270° sweep — // widen the dial range by changing those numbers // ═══════════════════════════════════════════════════════════════════ function ScopeReticle({ value, cat, loading, elev = 0, dt = new Date() }) { // ── Day/night scene behind the readout ───────────────────────────── // The whole back of the lens is a SkyScope-style scene: sky on top, // grass on the bottom, sun positioned by elevation (or moon at night // with its phase shadow). Mirrors the little hourly SkyScopes. const cx = 100, cy = 100, R = 86; const isDay = elev > -3; const skyFill = skyFillForElev(elev); const grass = grassFillForElev(elev); const phase = moonPhaseFraction(dt); const lensR = 95; // full back of the dial const elevClamped = Math.max(-30, Math.min(90, elev)); const sunY = cy - Math.sin((elevClamped * Math.PI) / 180) * (lensR - 18); const sunDrawR = 14; const moonDrawR = 15; const moonY = cy - 45; // float in the upper sky, away from the readout const phaseOffset = Math.cos(2 * Math.PI * phase) * moonDrawR; const moonLitFromRight = phase < 0.5; const moonShadowCx = cx + (moonLitFromRight ? -phaseOffset : phaseOffset); // Readout text colours flip with day/night for legibility against the sky. const readoutColor = isDay ? '#1e1208' : '#f5edd6'; const readoutMutedColor = isDay ? '#9a7d5a' : '#d4c5a8'; const ticks = Array.from({ length: 36 }, (_, i) => { const deg = i * 10 - 90; const rad = (deg * Math.PI) / 180; const major = i % 9 === 0; const medium = i % 3 === 0; const r2 = major ? R - 14 : medium ? R - 8 : R - 4; return { x1: cx + R * Math.cos(rad), y1: cy + R * Math.sin(rad), x2: cx + r2 * Math.cos(rad), y2: cy + r2 * Math.sin(rad), major, medium, }; }); const stressBands = [ { min: -40, max: -27, color: '#23408f' }, { min: -27, max: -13, color: '#3f73c4' }, { min: -13, max: 0, color: '#7eb0e0' }, { min: 0, max: 9, color: '#bcd9ec' }, { min: 9, max: 18, color: '#c8dcc0' }, { min: 18, max: 26, color: '#6ab05a' }, { min: 26, max: 32, color: '#e8c547' }, { min: 32, max: 38, color: '#dc8a3a' }, { min: 38, max: 46, color: '#c44a3a' }, { min: 46, max: 50, color: '#7a1a1a' }, ]; function fracToXY(frac, r) { const deg = 135 + frac * 270; const rad = (deg * Math.PI) / 180; return [cx + r * Math.cos(rad), cy + r * Math.sin(rad)]; } function bandArcPath(band) { const f1 = Math.min(1, Math.max(0, (band.min + 10) / 60)); const f2 = Math.min(1, Math.max(0, (band.max + 10) / 60)); const arcR = R - 18; const [x1, y1] = fracToXY(f1, arcR); const [x2, y2] = fracToXY(f2, arcR); const large = (f2 - f1) * 270 > 180 ? 1 : 0; return `M ${x1} ${y1} A ${arcR} ${arcR} 0 ${large} 1 ${x2} ${y2}`; } let needleX = cx, needleY = cy + 54; if (value != null) { const frac = Math.min(1, Math.max(0, (value + 10) / 60)); const deg = 135 + frac * 270; const rad = (deg * Math.PI) / 180; needleX = cx + 54 * Math.cos(rad); needleY = cy + 54 * Math.sin(rad); } const glowColor = cat ? cat.bg : '#c8922a'; return html` ${isDay ? html`<${Fragment}> ` : html`<${Fragment}> `} ${stressBands.map((b, i) => html` `)} ${ticks.map((t, i) => html` `)} ${[[-1,-1],[1,-1],[-1,1],[1,1]].map(([sx, sy], i) => html` `)} ${value != null && html` <${Fragment}> `} ${loading ? html`· · ·` : value != null ? html`<${Fragment}> ${value.toFixed(1)}° UTCI NOW ${cat.label.toUpperCase()} ` : html` AWAITING `} `; } // ════════════════════════════════════════════════════════════════════════ // MAIN COMPONENT — this is what the page renders. // ════════════════════════════════════════════════════════════════════════ // Everything below is one big function. Reading order: // // 1. STATE (useState calls) — the bits that change as // the user clicks around. // 2. EFFECTS (useEffect calls) — code that runs when // something changes // (search input, location). // 3. COMPUTATION (hourlyRows, days, …) — turns raw API data into // rows ready to display. // 4. JSX RETURN (the big html`...`) — the actual page markup. // ════════════════════════════════════════════════════════════════════════ function UTCIForecast() { // ── 1. STATE ────────────────────────────────────────────────────────── // Each useState() pairs a value with a setter. Calling the setter // re-renders the page with the new value. // The location we're forecasting for. Change the values below to set // a different starting location for new visitors. const [location, setLocation] = useState({ name: 'Pangbourne, Berkshire', lat: 51.4839, lon: -1.0725, country: 'GB', }); const [forecast, setForecast] = useState(null); // raw Open-Meteo response const [loading, setLoading] = useState(false); // true while fetching const [error, setError] = useState(null); // fetch error message const [searchQuery, setSearchQuery] = useState(''); // text in the search box const [searchResults, setSearchResults] = useState([]); // geocoding dropdown const [searching, setSearching] = useState(false); // search-in-flight flag const [selectedDay, setSelectedDay] = useState(0); // which day tab is active const [proPromptDay, setProPromptDay] = useState(null); // locked day clicked → show upsell card // Day-tabs horizontal scrolling — chevrons show only when there's more // content to reveal in that direction. Auto-scrolls active tab into view. const dayTabsRef = useRef(null); const [canScrollLeft, setCanScrollLeft] = useState(false); const [canScrollRight, setCanScrollRight] = useState(false); // Re-runs whenever the number of day tabs changes (e.g. when the // forecast finishes loading and the tabs first appear). Also re-measures // on scroll, on window resize, and via ResizeObserver if the element's // own width changes (e.g. layout shifts when sidebar opens). useEffect(() => { const el = dayTabsRef.current; if (!el) return; const update = () => { setCanScrollLeft(el.scrollLeft > 1); setCanScrollRight(el.scrollLeft + el.clientWidth < el.scrollWidth - 1); }; update(); el.addEventListener('scroll', update, { passive: true }); window.addEventListener('resize', update); let ro = null; if (typeof ResizeObserver !== 'undefined') { ro = new ResizeObserver(update); ro.observe(el); } return () => { el.removeEventListener('scroll', update); window.removeEventListener('resize', update); if (ro) ro.disconnect(); }; }, [forecast]); useEffect(() => { const el = dayTabsRef.current; if (!el) return; const activeTab = el.querySelector('.utci-day-tab.active'); if (!activeTab) return; const elRect = el.getBoundingClientRect(); const tabRect = activeTab.getBoundingClientRect(); if (tabRect.left < elRect.left + 8) { el.scrollBy({ left: tabRect.left - elRect.left - 24, behavior: 'smooth' }); } else if (tabRect.right > elRect.right - 8) { el.scrollBy({ left: tabRect.right - elRect.right + 24, behavior: 'smooth' }); } }, [selectedDay]); const scrollDayTabs = (dir) => { const el = dayTabsRef.current; if (!el) return; el.scrollBy({ left: dir * 200, behavior: 'smooth' }); }; // ─── PRO TIER STUB ──────────────────────────────────────────────────── // FLIP THE `false` BELOW TO `true` TO PREVIEW THE PRO EXPERIENCE. // When this is wired to real billing/auth, replace `useState(false)` // with a check against the logged-in user. const [isPro, setIsPro] = useState(true); // How many days the free tier shows. Days beyond this get a 🔒. // Bump this number if you want to give free users more access. const FREE_DAYS = 3; // Which columns appear in the hourly table by default. // true = visible on first load (and the only ones free users see) // false = hidden by default (Pro users can toggle these on) const [visibleCols, setVisibleCols] = useState({ hour: true, air: true, rh: false, dew: false, wind: true, dir: false, cloud: false, sun: false, direct: false, diffuse: false, tmrt: false, delta: false, utci: false, uvA: false, uvB: false, burn: false, utciP: true, precip: true, soilT: false, soilT6: false, soilM: false, }); const toggleCol = (col) => setVisibleCols(prev => ({ ...prev, [col]: !prev[col] })); // Skin type for the sunburn-time column. Fitzpatrick II is typical UK fair. const [skinType, setSkinType] = useState('II'); const searchTimeout = useRef(null); // Refs for the two-scroller table layout (sticky-to-viewport header + // horizontally-scrolling body). The header is clipped (overflow:hidden) // and its inner "track" gets translateX'd via JS to follow the body's // scrollLeft. See the useLayoutEffect just below where the JS sync // happens, and the .utci-thead-sticky / .utci-tbody-scroll CSS rules. const headStickyRef = useRef(null); const headTrackRef = useRef(null); const headTableRef = useRef(null); const bodyScrollRef = useRef(null); const bodyTableRef = useRef(null); // ─── TABLE SCROLL SYNC ─────────────────────────────────────────────── // The hourly table is rendered as two stacked scroll areas: // • Sticky header strip (locked to viewport top, clipped) // • Body scroller (overflow-x: auto — owns the horizontal scrollbar) // We need to (a) keep the header track shifted horizontally to match // the body's scrollLeft, and (b) keep the header cells the same pixel // width as the body cells even as columns toggle or the window resizes. // ───────────────────────────────────────────────────────────────────── const handleBodyScroll = () => { const track = headTrackRef.current; const body = bodyScrollRef.current; if (!track || !body) return; track.style.transform = `translate3d(${-body.scrollLeft}px, 0, 0)`; }; useLayoutEffect(() => { // Synchronise the head and body table column widths with a // "shrink-to-fit then distribute" strategy: // • Measure each column's true natural (content-fit) width by // temporarily switching both tables to table-layout: auto + // width: max-content. White-space: nowrap on cells stops content // from wrapping, so the measurement is the smallest width that // won't clip the content. // • If the body scroller has spare horizontal space (natural total // < container width), scale every column up proportionally to // fill it — so toggling columns off makes the remaining ones fan // out instead of leaving an awkward gap. // • Otherwise apply the natural widths as-is and let the body // scroller's overflow-x: auto produce a horizontal scrollbar. const sync = () => { const headTable = headTableRef.current; const bodyTable = bodyTableRef.current; const bodyScroll = bodyScrollRef.current; if (!headTable || !bodyTable || !bodyScroll) return; const bodyRow = bodyTable.querySelector('tbody tr'); const headRow = headTable.querySelector('thead tr'); if (!bodyRow || !headRow) return; const headCells = Array.from(headRow.children); const bodyCells = Array.from(bodyRow.children); const n = Math.min(headCells.length, bodyCells.length); if (n === 0) return; // Step 1: clear any previously-forced cell widths and switch the // tables to natural sizing so the measurement reflects the true // content-fit width — independent of how wide the container is. headCells.forEach(c => { c.style.width = ''; c.style.minWidth = ''; c.style.maxWidth = ''; }); bodyCells.forEach(c => { c.style.width = ''; c.style.minWidth = ''; c.style.maxWidth = ''; }); headTable.style.width = 'max-content'; bodyTable.style.width = 'max-content'; headTable.style.tableLayout = 'auto'; bodyTable.style.tableLayout = 'auto'; // Step 2: read each cell's natural width. getBoundingClientRect // forces synchronous layout — that's what we want. const naturalW = new Array(n); let naturalTotal = 0; for (let i = 0; i < n; i++) { const headW = headCells[i].getBoundingClientRect().width; const bodyW = bodyCells[i].getBoundingClientRect().width; const w = Math.max(Math.ceil(headW), Math.ceil(bodyW)); naturalW[i] = w; naturalTotal += w; } // Step 3: decide final widths based on available container width. const containerW = bodyScroll.clientWidth; const finalW = new Array(n); let totalWidth; if (naturalTotal > 0 && naturalTotal < containerW) { // Spare space — distribute proportionally across columns so they // fan out to fill the scroller (no awkward right-hand gap). const scale = containerW / naturalTotal; let running = 0; for (let i = 0; i < n - 1; i++) { finalW[i] = Math.floor(naturalW[i] * scale); running += finalW[i]; } // Absorb sub-pixel rounding into the last column so the total // exactly matches the container width. finalW[n - 1] = containerW - running; totalWidth = containerW; } else { // Naturals don't fit — use them as-is and let the body scroll. for (let i = 0; i < n; i++) finalW[i] = naturalW[i]; totalWidth = naturalTotal; } // Step 4: restore the CSS-defined table-layout: fixed so the // explicit cell widths we apply below are honoured by the browser // (not redistributed by the auto-layout algorithm). headTable.style.tableLayout = ''; bodyTable.style.tableLayout = ''; // Step 5: apply the final width to both head and body cells. for (let i = 0; i < n; i++) { const px = `${finalW[i]}px`; headCells[i].style.width = px; headCells[i].style.minWidth = px; headCells[i].style.maxWidth = px; bodyCells[i].style.width = px; bodyCells[i].style.minWidth = px; bodyCells[i].style.maxWidth = px; } // Make both tables exactly totalWidth wide so they share the same // horizontal extent — column N in the header sits directly above // column N in the body, no drift as you scroll right. headTable.style.width = `${totalWidth}px`; bodyTable.style.width = `${totalWidth}px`; // Re-apply current horizontal offset so column alignment survives. handleBodyScroll(); }; // Run once after layout sync(); // Re-sync when the scroll container's width changes (window resize, // sidebar opens, etc). We observe the scroller — not the body table — // because the body table's width is now driven by sync itself, which // would otherwise create a feedback loop. let ro = null; if (typeof ResizeObserver !== 'undefined' && bodyScrollRef.current) { ro = new ResizeObserver(sync); ro.observe(bodyScrollRef.current); } window.addEventListener('resize', sync); return () => { if (ro) ro.disconnect(); window.removeEventListener('resize', sync); }; }, [forecast, visibleCols, selectedDay, skinType]); // Geocoding search useEffect(() => { if (searchQuery.length < 2) { setSearchResults([]); return; } if (searchTimeout.current) clearTimeout(searchTimeout.current); searchTimeout.current = setTimeout(async () => { setSearching(true); try { const r = await fetch( `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(searchQuery)}&count=6&language=en&format=json` ); const j = await r.json(); setSearchResults(j.results || []); } catch { setSearchResults([]); } finally { setSearching(false); } }, 300); }, [searchQuery]); // ─── FORECAST FETCH ────────────────────────────────────────────────── // Runs every time `location` changes (i.e. when a new city is picked). // Builds the Open-Meteo URL and stores the response in `forecast`. // Change forecast_days=14 below to fetch a different range (max 16). // Add or remove fields in the `&hourly=...` list to fetch more data — // but if you remove one that's used elsewhere, expect errors. useEffect(() => { async function load() { setLoading(true); setError(null); try { const url = `https://api.open-meteo.com/v1/forecast` + `?latitude=${location.lat}&longitude=${location.lon}` + `&hourly=temperature_2m,relative_humidity_2m,dew_point_2m,` + `wind_speed_10m,wind_direction_10m,wind_gusts_10m,` + `direct_radiation,diffuse_radiation,shortwave_radiation,` + `cloud_cover,cloud_cover_low,cloud_cover_mid,cloud_cover_high,` + `uv_index,precipitation,snowfall,` + `soil_temperature_0cm,soil_temperature_6cm,soil_moisture_0_to_1cm` + `&wind_speed_unit=ms&timezone=auto&forecast_days=14`; const r = await fetch(url); if (!r.ok) throw new Error(`Open-Meteo HTTP ${r.status}`); setForecast(await r.json()); } catch (e) { setError(e.message); } finally { setLoading(false); } } load(); }, [location]); // ─── COMPUTATION ───────────────────────────────────────────────────── // Take the raw API arrays and stitch them into one object per hour, // calculating UTCI + soak-factor for each row. This is what gets // displayed in the table. const hourlyRows = forecast ? forecast.hourly.time.map((iso, i) => { const h = forecast.hourly; const Ta = h.temperature_2m[i]; const RH = h.relative_humidity_2m[i]; const dew = h.dew_point_2m ? h.dew_point_2m[i] : null; const va = h.wind_speed_10m[i]; const wd = h.wind_direction_10m ? h.wind_direction_10m[i] : null; const gust = h.wind_gusts_10m ? h.wind_gusts_10m[i] : null; const dir = h.direct_radiation[i] || 0; const dif = h.diffuse_radiation[i] || 0; const glob = h.shortwave_radiation[i] || 0; const cc = h.cloud_cover[i]; const ccLow = h.cloud_cover_low ? h.cloud_cover_low[i] : null; const ccMid = h.cloud_cover_mid ? h.cloud_cover_mid[i] : null; const ccHigh = h.cloud_cover_high ? h.cloud_cover_high[i] : null; const uv = h.uv_index ? (h.uv_index[i] || 0) : 0; const precip = h.precipitation[i] || 0; const snow = h.snowfall[i] || 0; const soilT0 = h.soil_temperature_0cm ? h.soil_temperature_0cm[i] : null; const soilT6 = h.soil_temperature_6cm ? h.soil_temperature_6cm[i] : null; const soilM = h.soil_moisture_0_to_1cm ? h.soil_moisture_0_to_1cm[i] : null; const dt = new Date(iso); const elev = solarElevationDeg(location.lat, location.lon, dt); const eh = vaporPressureHpa(Ta, RH); const Tmrt = calcTmrt(Ta, dir, dif, glob, elev); const utci = utciApprox(Ta, Tmrt, va, eh); const utciAdj = utci + precipPenalty(precip, snow, va); // Derived const compass = windCompass8(wd); const { uvA, uvB } = uvSplit(uv, elev); const cloudCat = cloudCategory(cc, ccLow, ccMid, ccHigh); return { iso, dt, Ta, RH, dew, va, wd, gust, dir, dif, glob, cc, ccLow, ccMid, ccHigh, cloudCat, uv, uvA, uvB, precip, snow, soilT0, soilT6, soilM, elev, Tmrt, utci, utciAdj, eh, compass, }; }) : []; // Group those hourly rows into days for the day tabs. const days = []; hourlyRows.forEach(row => { const key = row.iso.slice(0, 10); let day = days.find(d => d.key === key); if (!day) { day = { key, date: new Date(row.iso), rows: [] }; days.push(day); } day.rows.push(row); }); const visible = days[selectedDay]?.rows || []; const now = new Date(); const currentRow = hourlyRows.length > 0 ? (hourlyRows.find(row => now.toDateString() === row.dt.toDateString() && now.getHours() === row.dt.getHours() ) ?? hourlyRows.reduce((best, row) => Math.abs(row.dt - now) < Math.abs(best.dt - now) ? row : best)) : null; const currentCat = currentRow ? utciCategory(currentRow.utciAdj) : { bg: '#4a4228', fg: '#ede4cc', label: 'No data' }; // ─── 4. JSX RETURN ─────────────────────────────────────────────────── // Everything below is the actual page markup, written as one big HTM // template. Search tips: // • "utci-header" — the top section (title + dial + search) // • "utci-day-tabs" — the 14 day buttons with band colours // • "col-toggles" — the column-customisation row (Pro only) // • "utci-table" — the hourly table itself // • "utci-legend" — the thermal-stress band legend // • "utci-about" — the explainer paragraphs at the bottom // • "utci-footer" — the "reading the table" note return html`

SUNScope beta

See the sun the way your body does.
Universal Thermal Climate Index · Bröde 2012 · Open-Meteo · SunScope soak-factor
↳ ${location.name} ${location.lat.toFixed(3)}°, ${location.lon.toFixed(3)}°
<${ScopeReticle} value=${currentRow?.utciAdj ?? null} cat=${currentCat} loading=${loading} elev=${currentRow?.elev ?? 0} dt=${currentRow?.dt ?? new Date()} />
setSearchQuery(e.currentTarget.value)} /> ${searchResults.length > 0 && html`
${searchResults.map((r) => html`
{ setLocation({ name: `${r.name}${r.admin1 ? ', ' + r.admin1 : ''}`, lat: r.latitude, lon: r.longitude, country: r.country_code, }); setSearchQuery(''); setSearchResults([]); setSelectedDay(0); }} >
${r.name}${r.admin1 ? `, ${r.admin1}` : ''}
${r.country} · ${r.latitude.toFixed(2)}°, ${r.longitude.toFixed(2)}°
`)}
`} ${searching && html`
Searching…
`}
${error && html`
⚠ ${error}
`} ${loading && !error && html`
Acquiring forecast data…
`} ${forecast && days.length > 0 && html` <${Fragment}>
${days.map((d, i) => { const band = confidenceBand(i); const locked = !isPro && i >= FREE_DAYS; const isActive = i === selectedDay; const dayName = i === 0 ? 'Today' : i === 1 ? 'Tomorrow' : d.date.toLocaleDateString('en-GB', { weekday: 'short' }); return html` `; })}
${proPromptDay !== null && days[proPromptDay] && (() => { const promptDate = days[proPromptDay].date; const dayName = promptDate.toLocaleDateString('en-GB', { weekday: 'long' }); const dayLong = promptDate.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'short' }); return html`
🔒 ${dayName}'s forecast is part of SunScope Pro
Pro unlocks the full 14-day forecast, customisable columns, and an ad-free view.
£2 / month · launching soon
Notify me at launch
`; })()} ${(() => { const band = confidenceBand(selectedDay); const isOutlook = selectedDay >= 7; return html`
Day ${selectedDay + 1} of 14 · Forecast clarity: ${band.label} ${isOutlook && html` forecast skill is reduced — treat hourly detail as trend, not precision `}
`; })()} ${isPro ? html`
Columns: ${[ // Hour and UTCI+P are always-on — no toggle button for them. { key: 'air', label: 'Air' }, { key: 'rh', label: 'RH' }, { key: 'dew', label: 'Dew' }, { key: 'soilT', label: 'Soil °C' }, { key: 'soilT6', label: 'Soil 6cm' }, { key: 'soilM', label: 'Soil moist' }, { key: 'wind', label: 'Wind' }, { key: 'dir', label: 'Dir' }, { key: 'cloud', label: 'Cloud' }, { key: 'sun', label: 'Sun' }, { key: 'direct', label: 'Direct' }, { key: 'diffuse', label: 'Diffuse' }, { key: 'tmrt', label: 'Tmrt' }, { key: 'delta', label: 'Δ' }, { key: 'utci', label: 'UTCI' }, { key: 'uvA', label: 'UV-A' }, { key: 'uvB', label: 'UV-B' }, { key: 'burn', label: 'Burn' }, { key: 'precip', label: 'Precip' }, ].map(c => html` `)} ${visibleCols.burn && html` Skin `}
` : html`
Default columns customisable columns & days 4–14 are part of SunScope Pro
`}
${visibleCols.air && html``} ${visibleCols.rh && html``} ${visibleCols.dew && html``} ${visibleCols.soilT && html``} ${visibleCols.soilT6 && html``} ${visibleCols.soilM && html``} ${visibleCols.wind && html``} ${visibleCols.dir && html``} ${visibleCols.cloud && html``} ${visibleCols.sun && html``} ${visibleCols.direct && html``} ${visibleCols.diffuse && html``} ${visibleCols.tmrt && html``} ${visibleCols.delta && html``} ${visibleCols.utci && html``} ${visibleCols.uvA && html``} ${visibleCols.uvB && html``} ${visibleCols.burn && html``} ${visibleCols.precip && html``}
HourAir °CRH %Dew °CSoil °C surfaceSoil 6cm °C rootSoil moist m³/m³Wind m/s (gust)Dir -Cloud %Sun elev°Direct W/m²Diffuse W/m²Tmrt °CΔ UTCI−AirUTCI °C feltUV-A est. idxUV-B est. idxBurn to MEDPcpt mm/hUTCI+P °C adj.
${visible.map((r) => { const cat = utciCategory(r.utci); const isNight = r.elev < 0; const isNow = now.toDateString() === r.dt.toDateString() && now.getHours() === r.dt.getHours(); const delta = r.utci - r.Ta; const adjCat = utciCategory(r.utciAdj); return html` ${visibleCols.air && html``} ${visibleCols.rh && html``} ${visibleCols.dew && html``} ${visibleCols.soilT && html` `} ${visibleCols.soilT6 && html` `} ${visibleCols.soilM && html` `} ${visibleCols.wind && html``} ${visibleCols.dir && html``} ${visibleCols.cloud && html``} ${visibleCols.sun && html``} ${visibleCols.direct && html``} ${visibleCols.diffuse && html``} ${visibleCols.tmrt && html``} ${visibleCols.delta && html` `} ${visibleCols.utci && html` `} ${visibleCols.uvA && html` `} ${visibleCols.uvB && html` `} ${visibleCols.burn && html` `} ${visibleCols.precip && html` `} `; })}
<${SkyScope} elev=${r.elev} dt=${r.dt} size=${30} /> ${r.dt.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' })} ${r.Ta.toFixed(1)}${Math.round(r.RH)}${r.dew != null ? r.dew.toFixed(1) : '—'}${r.soilT0 != null ? r.soilT0.toFixed(1) : '—'}${r.soilT6 != null ? r.soilT6.toFixed(1) : '—'}${r.soilM != null ? r.soilM.toFixed(3) : '—'} ${r.va.toFixed(1)}${r.gust != null && r.gust > r.va + 0.5 ? html`(${r.gust.toFixed(1)})` : ''} <${WindVane} bearing=${r.wd} size=${28} /> ${r.compass.label} <${CloudIcon} category=${r.cloudCat} elev=${r.elev} dt=${r.dt} size=${28} /> ${Math.round(r.cc)} ${r.elev > 0 ? r.elev.toFixed(1) : '—'}${Math.round(r.dir)}${Math.round(r.dif)}${r.Tmrt.toFixed(1)} 3 ? '#c8601a' : delta < -3 ? '#3f73c4' : '#9a7d5a', fontWeight: 600, }}> ${delta > 0 ? '+' : ''}${delta.toFixed(1)} ${r.utci.toFixed(1)} 0 ? '#c8922a' : '#5a4228' }}> ${r.uvA > 0 ? r.uvA.toFixed(1) : '—'} 0 ? '#c44a3a' : '#5a4228', fontWeight: 600 }}> ${r.uvB > 0 ? r.uvB.toFixed(2) : '—'} 0 ? (sunburnMinutes(r.uv, skinType) < 30 ? '#c44a3a' : '#c8601a') : '#5a4228' }}> ${burnLabel(sunburnMinutes(r.uv, skinType))} 0 ? '#6090c8' : r.precip > 0 ? '#5090b0' : '#c0a880' }}> ${r.snow > 0 ? '❅ ' + r.snow.toFixed(1) + 'cm' : r.precip > 0 ? r.precip.toFixed(1) : '—'} ${r.utciAdj.toFixed(1)}
Thermal stress bands
${[ { l: '-27 to -13 Arctic', bg: '#3f73c4', fg: '#fff' }, { l: '-13 to 0 Freezing', bg: '#7eb0e0', fg: '#111' }, { l: '0 to 9 Cold', bg: '#bcd9ec', fg: '#111' }, { l: '9 to 18 Chilled', bg: '#c8dcc0', fg: '#111' }, { l: '18 to 26 Comfortable', bg: '#6ab05a', fg: '#fff' }, { l: '26 to 32 Mod heat', bg: '#e8c547', fg: '#111' }, { l: '32 to 38 Strong heat', bg: '#dc8a3a', fg: '#111' }, { l: '38 to 46 V. strong', bg: '#c44a3a', fg: '#fff' }, { l: '> 46 Extreme heat', bg: '#7a1a1a', fg: '#fff' }, ].map((b, i) => html` ${b.l} `)}
`}

What is SunScope?

SunScope shows how the weather will actually feel on your body — not just the air temperature. It uses the Universal Thermal Climate Index (UTCI), a peer-reviewed biometeorological standard developed by Bröde et al. (2012) that combines air temperature, humidity, wind speed, and solar radiation into a single felt temperature. On a calm, sunny winter day UTCI can read several degrees warmer than the thermometer; on a grey, blustery day it can read far colder. Forecast data is sourced in real time from Open-Meteo, a free and open-source weather API, and solar radiation is used to calculate Mean Radiant Temperature — the heat your skin absorbs from the sun — making SunScope one of the most complete outdoor comfort forecasts available for free.

The UTCI+P column adds the SunScope soak-factor: an original precipitation penalty that accounts for the extra chill of rain and snow on exposed skin and wet clothing. Light drizzle reduces the felt temperature by around 1–2 °C; heavy rain combined with wind can push it down by 7–8 °C. Snow carries an additional penalty on top. The result is an honest, real-world comfort score for any location worldwide — simply search for your town or city and compare the hourly forecast across the next 3 days (and up to 14 days with SunScope Pro).

`; } // ════════════════════════════════════════════════════════════════════════ // MOUNT — find the empty
in index.html and render // the whole UTCIForecast component into it. This is the very last thing // the script does. If nothing appears on the page, check that: // 1. index.html contains
// 2. index.html loads this file as