// ════════════════════════════════════════════════════════════════════════
// app.js — Main UTCIForecast component.
//
// This is the top-level Preact component that owns all state, fetches
// the forecast, runs the per-hour computations, and renders the page.
//
// Reading order inside UTCIForecast():
// 1. STATE (useState calls) — bits that change on interaction
// 2. EFFECTS (useEffect calls) — runs on search / location change
// 3. COMPUTATION (hourlyRows, days, …) — API data → display rows
// 4. JSX RETURN (the big html`...`) — actual page markup
//
// QUICK MAP
// ──────────────────────────────────────────────────────────────────────
// 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
// Starting location ............ useState({...}) on `location` near top
// Default columns shown ........ useState({...}) on visibleCols
// Page tagline / about copy .... search "utci-tagline" or "utci-about-text"
// ════════════════════════════════════════════════════════════════════════
import { h, render, Fragment } from '../vendor/preact.js';
import { useState, useRef, useEffect } from '../vendor/preact-hooks.js';
import htm from '../vendor/htm.js';
import {
utciCategory, UTCI_BANDS, bandGradient,
SKIN_TYPES, sunburnMinutes, burnLabel,
VEHICLE_TYPES, BUILDING_TYPES,
confidenceBand, moonGlyph,
} from './utils.js';
import { SkyScope, WindVane, CloudIcon, ScopeReticle, PrecipIcon, CustomSelect, VentPill } from './components.js';
import { getCellTagEvents, getUpcomingEvents } from './events.js';
import { POLLEN_TYPES, COL_DESCRIPTIONS, UTCI_ENVIRONMENTS } from './config.js';
import { useAppState } from './hooks/useAppState.js';
import { DayTabs } from './components/DayTabs.js';
import { computeWhyFeelsLike, computeGlanceSummary } from './compute.js';
import { solarElevationDeg } from './physics.js';
import { exportDayXls } from './export.js';
const html = htm.bind(h);
// ── Scope time-lapse playback ───────────────────────────────────────────
// Drives the big scope through the next 24h so you can watch the sky/ground
// gradients and weather evolve. Speed: 15 simulated minutes every 5 real
// seconds (≈ a full day in 8 minutes). UI advances smoothly every 200ms.
const PLAYBACK_SIM_MS_PER_REAL_MS = 180; // 15 min / 5 s = 180×
const PLAYBACK_STEP_MS = 200; // UI update cadence
const PLAYBACK_WINDOW_MS = 24 * 60 * 60 * 1000;
// Interpolates the hourly rows to an arbitrary instant (ms). Returns a row
// with smoothly blended elevation / cloud / precip so the scope animates
// continuously rather than snapping hour to hour.
function interpolateRowAt(rows, t) {
if (!rows || rows.length === 0) return null;
if (t <= +rows[0].dt) return rows[0];
if (t >= +rows[rows.length - 1].dt) return rows[rows.length - 1];
let lo = rows[0], hi = rows[1];
for (let i = 1; i < rows.length; i++) {
if (+rows[i].dt >= t) { lo = rows[i - 1]; hi = rows[i]; break; }
}
const f = (t - +lo.dt) / (+hi.dt - +lo.dt);
const L = (a, b) => (a == null || b == null) ? (a ?? b) : a + (b - a) * f;
return {
...lo,
dt: new Date(t),
elev: L(lo.elev, hi.elev),
glob: L(lo.glob, hi.glob),
utciAdj: L(lo.utciAdj, hi.utciAdj),
cc: L(lo.cc, hi.cc),
ccLow: L(lo.ccLow, hi.ccLow),
ccMid: L(lo.ccMid, hi.ccMid),
ccHigh: L(lo.ccHigh, hi.ccHigh),
precip: L(lo.precip, hi.precip),
snow: L(lo.snow, hi.snow),
visKm: L(lo.visKm, hi.visKm),
};
}
export function UTCIForecast() {
// ── STATE + EFFECTS ───────────────────────────────────────────────────
// All useState, useEffect, useCallback and useRef logic lives in
// useAppState. See hooks/useAppState.js for the full reading order.
const {
location, setLocationAndSave,
forecast, airQuality, loading, error, now, fetchedAt,
searchQuery, setSearchQuery, searchResults, setSearchResults, searching,
selectedDay, setSelectedDay,
proPromptDay, setProPromptDay,
proPromptSource, setProPromptSource,
dayTabsRef, canScrollLeft, canScrollRight, scrollDayTabs,
isPro, setIsPro,
activeProfile, setActiveProfile, activateProfile, activeCols,
visibleCols, setVisibleCols, toggleCol,
showDecimals, toggleShowDecimals,
showUnits, toggleShowUnits,
tableInterval, setTableInterval,
activityOptions, placeOptions, workOptions,
activityValue, activityLabel, placeValue, placeLabel, workValue, workLabel,
skinType, setSkinType,
vehicleType, setVehicleType,
vehicleVent, setVehicleVent,
outdoorsVariant, setOutdoorsVariantAndSave,
buildingType, setBuildingType,
indoorManaged, setIndoorManaged,
indoorMode, setIndoorMode,
pollenType, setPollenTypeAndSave,
utciEnv, setUtciEnv,
headStickyRef, headTrackRef, headTableRef,
bodyScrollRef, bodyTableRef, tableWrapRef,
colPopup, colPopupRef,
handleThClick, handleThEnter, handleThLeave,
handlePopupEnter, handlePopupLeave,
eventTagPopup, eventTagPopupRef,
evSlideIndex, evTransition, evSlideTo,
handleEventTagClick, handleEventTagEnter, handleEventTagLeave,
handleEventTagPopupEnter, handleEventTagPopupLeave,
closePopup, closeEventTagPopup,
tableCanScrollLeft, tableCanScrollRight, handleBodyScroll,
hourlyRows, days, utcOffsetMs,
visible, tableRows, nowLocalISO, currentRow, currentCat,
liveElev,
activeEvents, lensEvent, selectedDayEvents,
bannerIndex, bannerTransition, bannerPrevIndex,
bannerVisible, bannerStageRef,
bannerSlideTo, dismissBanner,
} = useAppState();
// Search is hidden by default and revealed via the magnifier next to the
// location. The input then overlays the location line to save space.
const [searchOpen, setSearchOpen] = useState(false);
const searchWrapRef = useRef(null);
const searchInputRef = useRef(null);
// Focus the input the moment the search opens.
useEffect(() => {
if (searchOpen) searchInputRef.current?.focus();
}, [searchOpen]);
// Close the search on outside-click or Escape, clearing any stray query.
useEffect(() => {
if (!searchOpen) return;
const onDown = (e) => {
if (searchWrapRef.current && !searchWrapRef.current.contains(e.target)) {
setSearchOpen(false);
setSearchQuery('');
}
};
const onKey = (e) => {
if (e.key === 'Escape') { setSearchOpen(false); setSearchQuery(''); }
};
document.addEventListener('mousedown', onDown);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('mousedown', onDown);
document.removeEventListener('keydown', onKey);
};
}, [searchOpen, setSearchQuery]);
// ─── SCOPE TIME-LAPSE ──────────────────────────────────────────────────
// `playing` toggles the time-lapse; `simMs` is the simulated instant shown.
const [playing, setPlaying] = useState(false);
const [simMs, setSimMs] = useState(null);
useEffect(() => {
if (!playing) return;
const start = now.getTime();
const end = start + PLAYBACK_WINDOW_MS;
setSimMs(prev => (prev == null || prev < start || prev > end) ? start : prev);
const id = setInterval(() => {
setSimMs(prev => {
let next = (prev == null ? start : prev) + PLAYBACK_STEP_MS * PLAYBACK_SIM_MS_PER_REAL_MS;
if (next > end) next = start; // loop back to "now"
return next;
});
}, PLAYBACK_STEP_MS);
return () => clearInterval(id);
}, [playing]);
// Columns that mark the start of a logical group - used to draw a faint
// vertical border separating groups in the forecast table.
const GROUP_ORDER = {
felt: ['utciP', 'vehicleT', 'indoorT', 'managedT', 'burn', 'utci', 'delta', 'tmrt'],
surface: ['concreteT', 'soilT', 'soilT6', 'soilM'],
ambient: ['air', 'rh', 'dew'],
precip: ['precip', 'precipProb'],
sky: ['cloud', 'vis'],
wind: ['wind', 'dir'],
airqual: ['aqi', 'pollen'],
solar: ['uvA', 'uvB', 'sun', 'direct', 'diffuse'],
};
const GROUP_OF = Object.fromEntries(
Object.entries(GROUP_ORDER).flatMap(([g, keys]) => keys.map(k => [k, g]))
);
// Returns col-group-start when this column is the leftmost VISIBLE member
// of its group. If the canonical first member is hidden the border migrates
// to the next visible column in the same group.
const isColVisible = (k) => {
if (k === 'indoorT') return indoorMode === 'on' && !indoorManaged;
if (k === 'managedT') return indoorMode === 'on' && indoorManaged;
return !!visibleCols[k];
};
const groupStart = (key) => {
const group = GROUP_OF[key];
if (!group) return '';
const first = GROUP_ORDER[group].find(isColVisible);
return first === key ? 'col-group-start' : '';
};
// Returns a CSS class encoding the group name - used to tint header cells
// and group label spans.
const groupColor = (key) => {
const g = GROUP_OF[key];
return g ? `grp-${g}` : '';
};
// Builds the group label row above the column headers.
// Each visible group gets one spanning cell; groups with no visible
// columns are skipped entirely. Hour always gets a blank lead cell.
const groupLabelRow = () => {
const groups = Object.keys(GROUP_ORDER);
const cells = [html`
${glanceDate} `];
for (const g of groups) {
const span = GROUP_ORDER[g].filter(isColVisible).length;
if (span === 0) continue;
const labels = { felt: 'Felt', surface: 'Surface', ambient: 'Ambient', precip: 'Precip', sky: 'Sky', wind: 'Wind', airqual: 'Air quality', solar: 'Solar' };
cells.push(html`${labels[g]} `);
}
return html`${cells} `;
};
// Continuous temperature colour scale - hoisted so both the table columns
// and the thermal stress legend can share the same function.
const TEMP_STOPS = [
[-10, [ 90, 155, 220]],
[ 0, [140, 195, 235]],
[ 10, [155, 215, 195]],
[ 16, [140, 210, 140]],
[ 20, [195, 225, 110]],
[ 24, [240, 225, 80]],
[ 28, [250, 175, 65]],
[ 32, [240, 120, 55]],
[ 36, [220, 70, 50]],
[ 40, [185, 30, 30]],
[ 50, [130, 0, 20]],
];
const airTempRgb = (t) => {
if (t == null) return null;
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
let i = TEMP_STOPS.findIndex(s => t < s[0]);
if (i === -1) i = TEMP_STOPS.length;
const raw = i === 0 ? TEMP_STOPS[0][1]
: i >= TEMP_STOPS.length ? TEMP_STOPS[TEMP_STOPS.length-1][1]
: (() => {
const [t0, c0] = TEMP_STOPS[i-1];
const [t1, c1] = TEMP_STOPS[i];
const x = clamp((t - t0) / (t1 - t0), 0, 1);
const lerp = (a, b) => Math.round(a + (b - a) * x);
return [lerp(c0[0],c1[0]), lerp(c0[1],c1[1]), lerp(c0[2],c1[2])];
})();
return raw.map(c => Math.min(255, Math.round(c + (255 - c) * 0.66)));
};
// ─── 3b. PANEL COMPUTATIONS ──────────────────────────────────────────
// Derived from currentRow and the active day - no side effects.
const whyFeelsLike = computeWhyFeelsLike(currentRow ?? null, UTCI_ENVIRONMENTS[utciEnv]);
// Interpolated row at the precise current instant — used for the scope
// display even outside playback so there's no jump when play is pressed.
const nowRow = interpolateRowAt(hourlyRows, now.getTime());
// During time-lapse, advance from simMs; otherwise fall back to nowRow/currentRow.
const simRow = (playing && simMs != null) ? interpolateRowAt(hourlyRows, simMs) : null;
const scopeRow = simRow || nowRow || currentRow;
// Elevation computed continuously from the simulated instant so the sun
// starts exactly where liveElev left off (same solarElevationDeg call).
const scopeElev = (playing && simMs != null && location?.lat != null)
? solarElevationDeg(location.lat, location.lon, new Date(simMs))
: (liveElev ?? currentRow?.elev ?? 0);
const scopeDt = simRow ? simRow.dt : now;
const scopeCat = scopeRow ? utciCategory(scopeRow.utciAdj) : currentCat;
// Synthesize a storm overlay (lightning) when the simulated hour is wet;
// outside playback keep the real active event.
const scopeEvent = simRow ? ((simRow.precip ?? 0) >= 4 ? { id: 'storm' } : null) : lensEvent;
// Local clock label for the playback button, e.g. "14:30".
const simClock = (playing && scopeDt)
? new Date(scopeDt.getTime() + utcOffsetMs).toISOString().slice(11, 16)
: null;
const staleThreshMs = isPro ? 15 * 60 * 1000 : 30 * 60 * 1000;
const isStale = fetchedAt ? (now - fetchedAt) > staleThreshMs : false;
const glanceSummary = computeGlanceSummary(
days[selectedDay]?.rows ?? [],
activeProfile,
outdoorsVariant,
skinType,
);
// Human-readable date for the "Day at a glance" heading, e.g. "Mon 2nd June 2026".
const glanceDate = (() => {
const key = days[selectedDay]?.key;
if (!key) return '';
const d = new Date(key + 'T00:00Z');
const wd = d.toLocaleDateString('en-GB', { weekday: 'short', timeZone: 'UTC' });
const day = d.getUTCDate();
const mon = d.toLocaleDateString('en-GB', { month: 'long', timeZone: 'UTC' });
const yr = d.getUTCFullYear();
const ord = (n => { const s = ['th', 'st', 'nd', 'rd'], v = n % 100; return s[(v - 20) % 10] || s[v] || s[0]; })(day);
return `${wd} ${day}${ord} ${mon} ${yr}`;
})();
// Pro: export the selected day's full hourly data as a styled spreadsheet.
const handleExportDay = () => {
exportDayXls(visible, {
locationName: location?.name ?? 'Unknown',
dateLabel: glanceDate,
skinType,
});
};
// Day's events surfaced in the "Day at a glance" box. Reuses the same
// row shape as glanceSummary items: { icon, label, value, alert }.
const hhmm = (iso) => (iso ? iso.slice(11, 16) : '');
const eventGlanceItems = (selectedDayEvents ?? [])
.filter(ev => ev.type !== 'promo')
.map(ev => ({
icon: ev.emoji,
label: ev.title,
value: ev.isoRange
? (ev.isoRange[0] === ev.isoRange[1]
? hhmm(ev.isoRange[0])
: `${hhmm(ev.isoRange[0])} – ${hhmm(ev.isoRange[1])}`)
: (ev.nightOnly ? 'Overnight' : 'All day'),
alert: false,
}));
// ─── 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`
{ const n = document.getElementById('site-nav'); n.classList.remove('nav-open'); document.getElementById('nav-drawer').classList.remove('is-open'); }}>
Sun Scope
See the world the way your skin does.
{
const nav = document.getElementById('site-nav');
const drawer = document.getElementById('nav-drawer');
const btn = document.getElementById('burger-btn');
const open = nav.classList.toggle('nav-open');
drawer.classList.toggle('is-open', open);
btn.setAttribute('aria-expanded', open ? 'true' : 'false');
}}>
${activeEvents.length > 0 && (() => {
const renderSlide = (idx, isOutgoing) => {
const ev = activeEvents[idx] || activeEvents[0];
const fmtDate = (iso) => iso
? new Date(iso + 'T00:00Z').toLocaleDateString('en-GB', { day: 'numeric', month: 'short', timeZone: 'UTC' })
: null;
const startFmt = fmtDate(ev.start);
const peakFmt = fmtDate(ev.peak);
const endFmt = fmtDate(ev.end);
const showDates = startFmt && endFmt;
const dateLine = showDates
? (startFmt === endFmt
? peakFmt ? `Peak: ${peakFmt}` : `Date: ${startFmt}`
: peakFmt && peakFmt !== startFmt && peakFmt !== endFmt
? `Active ${startFmt} – ${endFmt} · Peak: ${peakFmt}`
: `Active ${startFmt} – ${endFmt}`)
: null;
return html`
${ev.emoji}
${ev.title}
${ev.message}
${dateLine && html`
${dateLine}
`}
${activeEvents.length > 1 && html`
${activeEvents.map((_, i) => html`
bannerSlideTo(i)}
style=${{ background: ev.textColor }}
/>
`)}
`}
${!isOutgoing && html`
dismissBanner(ev.id)}
aria-label="Dismiss"
title="Dismiss this event"
>✕ `}
`;
};
return html`
${bannerTransition === 'crossfading' && bannerPrevIndex !== null
? renderSlide(bannerPrevIndex, true)
: null}
${renderSlide(bannerIndex, false)}
`;
})()}
${error && html`
⚠ ${error}
`}
${loading && !error && html`
`}
${forecast && days.length > 0 && html`<${DayTabs}
days=${days}
selectedDay=${selectedDay} setSelectedDay=${setSelectedDay}
isPro=${isPro}
proPromptDay=${proPromptDay} setProPromptDay=${setProPromptDay}
proPromptSource=${proPromptSource} setProPromptSource=${setProPromptSource}
activeProfile=${activeProfile} activateProfile=${activateProfile} activeCols=${activeCols}
visibleCols=${visibleCols}
activityOptions=${activityOptions} placeOptions=${placeOptions} workOptions=${workOptions}
activityValue=${activityValue} activityLabel=${activityLabel}
placeValue=${placeValue} placeLabel=${placeLabel}
workValue=${workValue} workLabel=${workLabel}
outdoorsVariant=${outdoorsVariant} setOutdoorsVariantAndSave=${setOutdoorsVariantAndSave}
setActiveProfile=${setActiveProfile} setVisibleCols=${setVisibleCols}
setIndoorMode=${setIndoorMode} setIndoorManaged=${setIndoorManaged}
setBuildingType=${setBuildingType}
dayTabsRef=${dayTabsRef} canScrollLeft=${canScrollLeft} canScrollRight=${canScrollRight}
scrollDayTabs=${scrollDayTabs}
/>`}
Columns:
${(isPro ? (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['utciP']) : activeCols['utciP']) && html`
<${CustomSelect}
value=${utciEnv}
isOn=${visibleCols.utciP}
grpClass="grp-felt"
hideLabel="SunSoak"
hidingLabel="Hide SunSoak"
groupedLeft=${true}
isLastChild=${true}
options=${Object.entries(UTCI_ENVIRONMENTS).map(([k, v]) => ({
value: k,
label: v.label,
}))}
onChange=${(v) => {
if (v === 'off') {
setVisibleCols(prev => ({ ...prev, utciP: false }));
} else {
setUtciEnv(v);
setVisibleCols(prev => ({ ...prev, utciP: true }));
}
}}
/>
`}
${(isPro ? (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['vehicleT']) : activeCols['vehicleT']) && html`
<${CustomSelect}
value=${vehicleType}
isOn=${visibleCols.vehicleT}
grpClass="grp-felt"
hideLabel="Vehicle"
hidingLabel="Hide Vehicle"
groupedLeft=${true}
isLastChild=${!visibleCols.vehicleT}
options=${Object.entries(VEHICLE_TYPES).map(([k, v]) => ({
value: k,
label: v.name,
}))}
onChange=${(v) => {
if (v === 'off') {
setVisibleCols(prev => ({ ...prev, vehicleT: false }));
setVehicleVent(false);
} else {
setVehicleType(v);
setVisibleCols(prev => ({ ...prev, vehicleT: true }));
}
}}
/>
${visibleCols.vehicleT && html`
<${VentPill}
checked=${vehicleVent}
onChange=${() => setVehicleVent(v => !v)}
grpClass="grp-felt"
label="Ventilation"
title="Ventilation — open windows significantly reduce cabin heat build-up"
/>`}
`}
${(isPro ? (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['indoorT'] || activeCols['managedT']) : (activeCols['indoorT'] || activeCols['managedT'])) && html`
<${CustomSelect}
value=${buildingType}
isOn=${indoorMode === 'on'}
grpClass="grp-felt"
hideLabel="Indoors"
hidingLabel="Hide Indoors"
groupedLeft=${true}
isLastChild=${indoorMode !== 'on'}
options=${Object.entries(BUILDING_TYPES).map(([k, v]) => ({
value: k,
label: v.name,
}))}
onChange=${(v) => {
if (v === 'off') {
setIndoorMode('off');
setIndoorManaged(false);
} else {
setBuildingType(v);
setIndoorMode('on');
}
}}
/>
${indoorMode === 'on' && html`
<${VentPill}
checked=${indoorManaged}
onChange=${() => setIndoorManaged(v => !v)}
grpClass="grp-felt"
label="Managed"
title="Managed: curtains closed by day, windows open when cooler outside"
/>`}
`}
${(isPro ? (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['burn']) : activeCols['burn']) && html`
<${CustomSelect}
value=${skinType}
isOn=${visibleCols.burn}
grpClass="grp-felt"
hideLabel="Burn"
hidingLabel="Hide Burn"
options=${Object.entries(SKIN_TYPES).map(([k, v]) => ({
value: k,
label: v.name.split(' · ')[1] + ' skin',
}))}
onChange=${(v) => {
if (v === 'off') {
setVisibleCols(prev => ({ ...prev, burn: false }));
} else {
setSkinType(v);
setVisibleCols(prev => ({ ...prev, burn: true }));
}
}}
/>`}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['utci']) && html` toggleCol('utci')}>UTCI `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['delta']) && html` toggleCol('delta')}>Δ `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['tmrt']) && html` toggleCol('tmrt')}>Tmrt `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['concreteT']) && html` toggleCol('concreteT')}>Concrete `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['soilT']) && html` toggleCol('soilT')}>Soil °C `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['soilT6']) && html` toggleCol('soilT6')}>Soil 6cm `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['soilM']) && html` toggleCol('soilM')}>Soil moist `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['air']) && html` toggleCol('air')}>Air `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['rh']) && html` toggleCol('rh')}>RH `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['dew']) && html` toggleCol('dew')}>Dew `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['precip']) && html` toggleCol('precip')}>Precip `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['precipProb']) && html` toggleCol('precipProb')}>Rain% `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['cloud']) && html` toggleCol('cloud')}>Cloud `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['vis']) && html` toggleCol('vis')}>Visibility `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['wind']) && html` toggleCol('wind')}>Wind `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['dir']) && html` toggleCol('dir')}>Dir `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['aqi']) && html` toggleCol('aqi')}>Air Quality `}
${(isPro ? (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['pollen']) : activeCols['pollen']) && html`<${CustomSelect}
value=${pollenType}
isOn=${visibleCols.pollen}
grpClass="grp-airqual"
hideLabel="Pollen"
hidingLabel="Hide Pollen"
options=${Object.entries(POLLEN_TYPES).flatMap(([k, v], i) => [
{ value: k, label: v.name },
...(i === 0 ? [{ value: '_div', divider: true }] : []),
])}
onChange=${(v) => {
if (v === 'off') {
setVisibleCols(prev => ({ ...prev, pollen: false }));
} else {
setPollenTypeAndSave(v);
setVisibleCols(prev => ({ ...prev, pollen: true }));
}
}}
/>`}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['uvA']) && html` toggleCol('uvA')}>UV-A `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['uvB']) && html` toggleCol('uvB')}>UV-B `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['sun']) && html` toggleCol('sun')}>Sun `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['direct']) && html` toggleCol('direct')}>Direct `}
${isPro && (activeProfile === 'custom' || activeProfile === 'showall' || activeCols['diffuse']) && html` toggleCol('diffuse')}>Diffuse `}
Decimals
Units
${forecast && ((glanceSummary && glanceSummary.length > 0) || eventGlanceItems.length > 0 || visible.length > 0) && html`
${((glanceSummary && glanceSummary.length > 0) || eventGlanceItems.length > 0) && html`
At a glance${glanceDate ? ` · ${glanceDate}` : ''}
${glanceSummary.map(({ icon, label, value, alert }) => html`
${icon}
${label}
${value}
`)}
${eventGlanceItems.map(({ icon, label, value, alert }) => html`
${icon}
${label}
${value}
`)}
`}
${visible.length > 0 && html`
${isPro
? html`
⬇
Export day data
Excel / LibreOffice · 41 columns · hourly
`
: html`
{ setProPromptSource('export'); setProPromptDay(0); }}
title="Export day data is part of SunScope Extra">
🔒
Export day data
SunScope Extra feature
`}
`}
`}
${colPopup && COL_DESCRIPTIONS[colPopup.key] && html`
`}
${eventTagPopup && (() => {
const evs = eventTagPopup.events;
const ev = evs[evSlideIndex] || evs[0];
return html`
`;
})()}
Thermal stress bands
${[
{ t: -9, label: 'Freezing' },
{ t: 1, label: 'Cold' },
{ t: 11, label: 'Cool' },
{ t: 21, label: 'Comfortable', bold: true },
{ t: 31, label: 'Hot' },
{ t: 41, label: 'Very hot' },
{ t: 51, label: 'Danger' },
].map((b, i) => {
const rgb = airTempRgb(b.t) || [200, 200, 200];
const mid = `rgb(${rgb[0]},${rgb[1]},${rgb[2]})`;
const light = `rgb(${rgb.map(c => Math.min(255, Math.round(c + (255-c)*0.30))).join(',')})`;
const dark = `rgb(${rgb.map(c => Math.round(c * 0.96)).join(',')})`;
const bg = `linear-gradient(135deg, ${light} 0%, ${mid} 60%, ${dark} 100%)`;
const lum = (rgb[0]*299 + rgb[1]*587 + rgb[2]*114) / 1000;
const fg = lum > 165 ? '#1a1a1a' : '#ffffff';
return html`${b.label} `;
})}
${(() => {
const upcoming = getUpcomingEvents(location, 90);
const formatPeak = (iso) => {
const d = new Date(iso + 'T00:00Z');
return d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' });
};
const countdownLabel = (days) => {
if (days === 0) return 'Tonight!';
if (days === 1) return 'Tomorrow';
if (days < 7) return `In ${days} days`;
if (days < 14) return 'Next week';
if (days < 60) return `In ${Math.round(days / 7)} weeks`;
return `In ${Math.round(days / 30)} months`;
};
return html`
${upcoming.length === 0
? html`
No major cosmic events in the next 90 days — clear skies ahead.
`
: upcoming.map(ev => html`
${ev.emoji}
${ev.title}
${formatPeak(ev.peak)}
${countdownLabel(ev.daysUntil)}
${ev.desc}
${ev.visibilityNote && html`
📍 ${ev.visibilityNote}
`}
`)
}
`;
})()}
What is SunScope?
SunScope is a free hourly weather forecast built around felt temperature ,
not just air temperature. It uses the Universal Thermal Climate Index (UTCI)
— the biometeorological standard used in heat-health warning systems worldwide — as its
foundation, combining air temperature, humidity, wind, and solar radiation into a single
honest number. Then it goes further. Our SunSoak index layers three extra
dimensions on top: a rain and snow penalty so wet, windy days read as cold as they feel;
an environment modifier that adjusts the solar load for where you actually
are — forest canopy, alpine altitude, lakeside glare, shaded riverbank, desert ground heat;
and the full radiant heat absorbed from surrounding surfaces. One number that honestly
answers: what will my body actually feel out there?
Beyond SunSoak, SunScope calculates vehicle cabin heat (choose your
vehicle type; toggle windows open), indoor temperature (seven building
types including office blocks; managed heatwave mode), urban concrete surface
temperature , UV index and sunburn time by skin type, and
soil temperature and moisture for farming and motorhome use. Switch
profiles — Places, Activities, Work — to see the data that matters for your situation,
or go Custom and build your own view.
Learn more →
`;
}