Upgrade maps to MapLibre GL JS; compact header; move search to settings
- Replace Leaflet with MapLibre GL JS v4.7.1 across all map instances - CARTO dark/light and Esri satellite raster basemaps (no API key) - All overlays (hurricane, wildfire, SPC, wind arrows) ported to GeoJSON sources/layers - AQI, alert, temp, sun/moon markers via maplibregl.Marker with custom HTML - Radar animation pre-loads all frames on load for smoother playback - Compact loc-header: tighter padding and font sizes, all info preserved - Search bar moved from header to Settings tab under Location section - Service worker bumped to weather-v7 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
1863f6784b
commit
a25864d9ed
6 files changed
+1732
-343
No files matched your search
+818
-268
File diff suppressed because it is too large.
Load diff
+170
-47
@@ -12,10 +12,12 @@
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||
<meta name="apple-mobile-web-app-title" content="NeCloud Weather">
|
||||
<meta name="mobile-web-app-capable" content="yes">
|
||||
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
|
||||
<link rel="stylesheet" href="https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.css">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="offline-banner" class="offline-banner hidden">No internet connection — showing cached data</div>
|
||||
<div id="ptr-indicator" class="ptr-indicator hidden">↓ Refreshing…</div>
|
||||
<div class="app">
|
||||
|
||||
<header class="masthead">
|
||||
@@ -23,25 +25,13 @@
|
||||
<nav class="tabs">
|
||||
<button class="tab active" data-tab="conditions">Conditions</button>
|
||||
<button class="tab" data-tab="unified-map">Map</button>
|
||||
<button class="tab" data-tab="alerts">Alerts</button>
|
||||
<button class="tab" data-tab="alerts">Alerts<span class="alert-badge hidden" id="alert-badge-nav"></span></button>
|
||||
<button class="tab" data-tab="learn">Learn</button>
|
||||
<button class="tab" data-tab="settings">Settings</button>
|
||||
</nav>
|
||||
<span class="tagline">Open-Meteo · RainViewer</span>
|
||||
</header>
|
||||
|
||||
<!-- Search bar (shared, always visible) -->
|
||||
<div class="search-wrap">
|
||||
<div class="search-row">
|
||||
<input id="search-input" type="text" placeholder="City, region, or country…" autocomplete="off" spellcheck="false">
|
||||
<button id="search-btn">Search</button>
|
||||
<button id="locate-btn" title="Use my location">⌖</button>
|
||||
<button id="units-btn" title="Toggle units">US</button>
|
||||
</div>
|
||||
<ul id="suggestions" class="suggestions hidden"></ul>
|
||||
<p id="error-msg" class="error hidden"></p>
|
||||
</div>
|
||||
|
||||
<!-- Loading -->
|
||||
<div id="loading" class="loading hidden">
|
||||
<div class="loading-container">
|
||||
@@ -123,38 +113,44 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── WIND & ATMOSPHERE ── -->
|
||||
<div class="section-head">
|
||||
<span class="section-label">Wind & Atmosphere</span>
|
||||
</div>
|
||||
<div class="card-group">
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Wind</div>
|
||||
<div class="stat-val"><span id="cur-wind">--</span> <span class="stat-unit wind-unit">mph</span></div>
|
||||
<div class="stat-sub" id="cur-wind-dir">--</div>
|
||||
<!-- ── WIND & ATMOSPHERE (collapsed by default on mobile) ── -->
|
||||
<details class="details-drawer wind-drawer" id="wind-drawer">
|
||||
<summary class="drawer-summary">
|
||||
Wind & Atmosphere
|
||||
<span class="wind-drawer-peek" id="wind-drawer-peek"></span>
|
||||
<span class="drawer-chevron">›</span>
|
||||
</summary>
|
||||
<div class="drawer-body">
|
||||
<div class="card-group drawer-card-group">
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Wind</div>
|
||||
<div class="stat-val"><span id="cur-wind">--</span> <span class="stat-unit wind-unit">mph</span></div>
|
||||
<div class="stat-sub" id="cur-wind-dir">--</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Gusts</div>
|
||||
<div class="stat-val"><span id="cur-gust">--</span> <span class="stat-unit gust-unit">mph</span></div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Humidity</div>
|
||||
<div class="stat-val"><span id="cur-hum">--</span><span class="stat-unit">%</span></div>
|
||||
<div class="stat-sub" id="hum-feel"></div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Dewpoint</div>
|
||||
<div class="stat-val"><span id="cur-dew">--</span>°</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Pressure</div>
|
||||
<div class="stat-val"><span id="cur-pres">--</span> <span class="stat-unit">hPa</span></div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Visibility</div>
|
||||
<div class="stat-val"><span id="cur-vis">--</span> <span class="stat-unit vis-unit">mi</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Gusts</div>
|
||||
<div class="stat-val"><span id="cur-gust">--</span> <span class="stat-unit gust-unit">mph</span></div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Humidity</div>
|
||||
<div class="stat-val"><span id="cur-hum">--</span><span class="stat-unit">%</span></div>
|
||||
<div class="stat-sub" id="hum-feel"></div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Dewpoint</div>
|
||||
<div class="stat-val"><span id="cur-dew">--</span>°</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Pressure</div>
|
||||
<div class="stat-val"><span id="cur-pres">--</span> <span class="stat-unit">hPa</span></div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">Visibility</div>
|
||||
<div class="stat-val"><span id="cur-vis">--</span> <span class="stat-unit vis-unit">mi</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<!-- ── MORE DETAILS DRAWER ── -->
|
||||
<details class="details-drawer">
|
||||
@@ -211,11 +207,15 @@
|
||||
<!-- Hourly -->
|
||||
<div class="section-head" style="margin-top:1.5rem">
|
||||
<span class="section-label">Hourly Forecast</span>
|
||||
<span class="section-note">next 24 hours</span>
|
||||
<span class="section-note">
|
||||
<button id="hourly-feels-toggle" class="link-btn">Feels-like</button>
|
||||
<button id="hourly-extend-btn" class="link-btn">48h</button>
|
||||
</span>
|
||||
</div>
|
||||
<div id="hourly-scroll" class="hourly-scroll">
|
||||
<div id="hourly-track" class="hourly-track"></div>
|
||||
</div>
|
||||
<div id="precip-chart-wrap" class="precip-chart-wrap"></div>
|
||||
|
||||
<!-- 7-day -->
|
||||
<div class="section-head">
|
||||
@@ -224,6 +224,18 @@
|
||||
</div>
|
||||
<div id="daily-list" class="daily-list"></div>
|
||||
|
||||
<details class="details-drawer discussion-drawer" id="discussion-drawer">
|
||||
<summary class="drawer-summary">
|
||||
Forecaster's Discussion
|
||||
<span class="discussion-office" id="discussion-office"></span>
|
||||
<span class="drawer-chevron">›</span>
|
||||
</summary>
|
||||
<div class="drawer-body">
|
||||
<p class="discussion-meta" id="discussion-meta"></p>
|
||||
<pre class="discussion-text" id="discussion-text">Loading…</pre>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<div class="footer-note">
|
||||
Weather: <a href="https://open-meteo.com" target="_blank">Open-Meteo</a> ·
|
||||
Radar: <a href="https://www.rainviewer.com" target="_blank">RainViewer</a> ·
|
||||
@@ -307,6 +319,27 @@
|
||||
<span class="toggle-slider"></span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="toggle-control">
|
||||
<span class="toggle-label">🌀 Hurricanes</span>
|
||||
<span class="switch-toggle">
|
||||
<input type="checkbox" id="toggle-hurricane" data-layer="hurricane">
|
||||
<span class="toggle-slider"></span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="toggle-control">
|
||||
<span class="toggle-label">🔥 Wildfires</span>
|
||||
<span class="switch-toggle">
|
||||
<input type="checkbox" id="toggle-wildfire" data-layer="wildfire">
|
||||
<span class="toggle-slider"></span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="toggle-control">
|
||||
<span class="toggle-label">🌪️ SPC Reports</span>
|
||||
<span class="switch-toggle">
|
||||
<input type="checkbox" id="toggle-spc" data-layer="spc">
|
||||
<span class="toggle-slider"></span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -369,6 +402,7 @@
|
||||
|
||||
<!-- ── TAB: ALERTS ── -->
|
||||
<div id="tab-alerts" class="tab-panel hidden">
|
||||
<div id="hurricane-panel" class="hurricane-panel"></div>
|
||||
<div id="alerts-wrap" class="alerts-wrap hidden">
|
||||
<div class="section-head">
|
||||
<span class="section-label">Weather Alerts</span>
|
||||
@@ -386,6 +420,20 @@
|
||||
<!-- ── TAB: SETTINGS ── -->
|
||||
<div id="tab-settings" class="tab-panel hidden">
|
||||
<div class="settings-wrap">
|
||||
|
||||
<!-- Location search — moved here from header -->
|
||||
<div class="settings-section-label">Location</div>
|
||||
<div class="search-wrap settings-search">
|
||||
<div class="search-row">
|
||||
<input id="search-input" type="text" placeholder="City, region, or country…" autocomplete="off" spellcheck="false">
|
||||
<button id="search-btn">Search</button>
|
||||
<button id="locate-btn" title="Use my location">⌖</button>
|
||||
<button id="units-btn" title="Toggle units">US</button>
|
||||
</div>
|
||||
<ul id="suggestions" class="suggestions hidden"></ul>
|
||||
<p id="error-msg" class="error hidden"></p>
|
||||
</div>
|
||||
|
||||
<div class="saved-wrap">
|
||||
<div class="saved-head">
|
||||
<span>Saved locations</span>
|
||||
@@ -411,6 +459,80 @@
|
||||
<span class="settings-label">Units</span>
|
||||
<button id="units-btn-settings" class="settings-btn" type="button">US</button>
|
||||
</div>
|
||||
|
||||
<div class="settings-row">
|
||||
<span class="settings-label">Theme</span>
|
||||
<div class="theme-toggle-group">
|
||||
<button class="theme-btn" data-theme="system">System</button>
|
||||
<button class="theme-btn" data-theme="light">Light</button>
|
||||
<button class="theme-btn" data-theme="dark">Dark</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-section-title">Push Notifications (ntfy)</div>
|
||||
<div class="settings-row settings-row--block">
|
||||
<div class="settings-row-head">
|
||||
<span class="settings-label">ntfy Topic URL</span>
|
||||
<button id="ntfy-test-btn" class="settings-btn" type="button">Test</button>
|
||||
</div>
|
||||
<input id="ntfy-url-input" class="settings-input" type="url"
|
||||
placeholder="https://ntfy.sh/my-weather-alerts"
|
||||
autocomplete="off" spellcheck="false">
|
||||
<p class="settings-help">
|
||||
Receive alerts on any device via the <a href="https://ntfy.sh" target="_blank" rel="noopener">ntfy app</a>.
|
||||
Enter your topic URL — alerts will be pushed here whenever new weather warnings are found.
|
||||
</p>
|
||||
<p id="ntfy-status" class="settings-help hidden"></p>
|
||||
</div>
|
||||
|
||||
<div class="settings-section-title">Web Push (Browser Notifications)</div>
|
||||
<div class="settings-row settings-row--block">
|
||||
<div class="settings-row-head">
|
||||
<span class="settings-label">Push alerts for saved location</span>
|
||||
<button id="push-subscribe-btn" class="settings-btn" type="button">Enable</button>
|
||||
</div>
|
||||
<p id="push-status" class="settings-help hidden"></p>
|
||||
</div>
|
||||
|
||||
<div class="settings-section-title">Alert Thresholds</div>
|
||||
<div class="settings-row settings-row--block">
|
||||
<div class="settings-row-head">
|
||||
<label class="settings-label" for="threshold-wind">Wind gust alert (mph)</label>
|
||||
<input id="threshold-wind" class="settings-input settings-input--short" type="number" min="0" max="200" placeholder="e.g. 40">
|
||||
</div>
|
||||
<div class="settings-row-head" style="margin-top:0.5rem">
|
||||
<label class="settings-label" for="threshold-temp-low">Freeze alert below (°F)</label>
|
||||
<input id="threshold-temp-low" class="settings-input settings-input--short" type="number" min="-60" max="60" placeholder="e.g. 32">
|
||||
</div>
|
||||
<div class="settings-row-head" style="margin-top:0.5rem">
|
||||
<label class="settings-label" for="threshold-aqi">AQI alert above</label>
|
||||
<input id="threshold-aqi" class="settings-input settings-input--short" type="number" min="0" max="500" placeholder="e.g. 100">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-section-title">Daily Digest</div>
|
||||
<div class="settings-row">
|
||||
<label class="settings-label" for="digest-hour">Send forecast at hour (local, 0–23)</label>
|
||||
<input id="digest-hour" class="settings-input settings-input--short" type="number" min="0" max="23" value="7">
|
||||
</div>
|
||||
|
||||
<div class="settings-section-title">Personal Weather Station</div>
|
||||
<div class="settings-row settings-row--block">
|
||||
<div class="settings-row-head">
|
||||
<span class="settings-label">PWS JSON URL</span>
|
||||
<button id="pws-save-btn" class="settings-btn" type="button">Save</button>
|
||||
</div>
|
||||
<input id="pws-url-input" class="settings-input" type="url"
|
||||
placeholder="http://192.168.1.x/weather.json"
|
||||
autocomplete="off" spellcheck="false">
|
||||
<p class="settings-help">Point to a local device that serves a JSON weather payload.</p>
|
||||
<p id="pws-status" class="settings-help hidden"></p>
|
||||
</div>
|
||||
|
||||
<div class="settings-row" id="pwa-install-row" style="display:none">
|
||||
<span class="settings-label">Install App</span>
|
||||
<button id="pwa-install-btn" class="settings-btn" type="button">Add to Home Screen</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1118,6 +1240,7 @@
|
||||
<button class="bottom-tab" data-tab="alerts" type="button">
|
||||
<span class="bottom-icon">⚠️</span>
|
||||
<span class="bottom-label">Alerts</span>
|
||||
<span class="alert-badge hidden" id="alert-badge-bottom"></span>
|
||||
</button>
|
||||
<button class="bottom-tab" data-tab="learn" type="button">
|
||||
<span class="bottom-icon">📘</span>
|
||||
@@ -1129,7 +1252,7 @@
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
|
||||
<script src="https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.js"></script>
|
||||
<script src="app.js"></script>
|
||||
<script>
|
||||
if ('serviceWorker' in navigator) {
|
||||
|
||||
@@ -5,8 +5,9 @@
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"display_override": ["window-controls-overlay", "standalone"],
|
||||
"background_color": "#191510",
|
||||
"theme_color": "#1a1a1a",
|
||||
"theme_color": "#191510",
|
||||
"orientation": "portrait-primary",
|
||||
"categories": ["weather", "utilities"],
|
||||
"icons": [
|
||||
@@ -28,5 +29,33 @@
|
||||
"type": "image/svg+xml",
|
||||
"purpose": "any"
|
||||
}
|
||||
],
|
||||
"share_target": {
|
||||
"action": "/?share",
|
||||
"method": "GET",
|
||||
"params": { "title": "title", "text": "text", "url": "url" }
|
||||
},
|
||||
"shortcuts": [
|
||||
{
|
||||
"name": "Current Conditions",
|
||||
"short_name": "Now",
|
||||
"description": "View current weather and forecast",
|
||||
"url": "/?tab=conditions",
|
||||
"icons": [{ "src": "/icons/icon-192.png", "sizes": "192x192" }]
|
||||
},
|
||||
{
|
||||
"name": "Radar Map",
|
||||
"short_name": "Map",
|
||||
"description": "Live radar and weather map",
|
||||
"url": "/?tab=unified-map",
|
||||
"icons": [{ "src": "/icons/icon-192.png", "sizes": "192x192" }]
|
||||
},
|
||||
{
|
||||
"name": "Active Alerts",
|
||||
"short_name": "Alerts",
|
||||
"description": "Weather warnings and alerts",
|
||||
"url": "/?tab=alerts",
|
||||
"icons": [{ "src": "/icons/icon-192.png", "sizes": "192x192" }]
|
||||
}
|
||||
]
|
||||
}
|
||||
+373
-26
@@ -24,7 +24,7 @@
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
:root:not([data-theme="light"]) {
|
||||
--ink: #ece7dc;
|
||||
--ink-mid: #d2c8b1;
|
||||
--ink-light: #beb399;
|
||||
@@ -37,6 +37,18 @@
|
||||
}
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
--ink: #ece7dc;
|
||||
--ink-mid: #d2c8b1;
|
||||
--ink-light: #beb399;
|
||||
--paper: #191510;
|
||||
--paper-dark: #201c16;
|
||||
--paper-darker: #2b2620;
|
||||
--border: #3a342a;
|
||||
--accent: #e07848;
|
||||
--cool: #5ab0d8;
|
||||
}
|
||||
|
||||
html, body {
|
||||
min-height: 100%;
|
||||
background: var(--paper);
|
||||
@@ -293,7 +305,32 @@ a:hover { text-decoration: underline; }
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.leaflet-tooltip.map-label {
|
||||
.map-location-dot {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
background: #e07848;
|
||||
border: 2px solid #fff;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 1px 4px rgba(0,0,0,0.5);
|
||||
}
|
||||
|
||||
.map-labeled-marker {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.map-dot {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border: 2px solid #fff;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
box-shadow: 0 1px 4px rgba(0,0,0,0.4);
|
||||
}
|
||||
|
||||
.map-dot-label {
|
||||
background: rgba(20, 18, 14, 0.9);
|
||||
border: 1px solid rgba(255, 255, 255, 0.22);
|
||||
color: #fff;
|
||||
@@ -305,10 +342,7 @@ a:hover { text-decoration: underline; }
|
||||
letter-spacing: 0.01em;
|
||||
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.55);
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);
|
||||
}
|
||||
|
||||
.leaflet-tooltip.map-label:before {
|
||||
border-top-color: rgba(20, 18, 14, 0.9);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.data-label {
|
||||
@@ -359,6 +393,7 @@ a:hover { text-decoration: underline; }
|
||||
padding: 0.55rem;
|
||||
box-shadow: var(--surface-shadow);
|
||||
}
|
||||
.settings-search { margin-bottom: 1rem; }
|
||||
|
||||
.search-row { display: flex; }
|
||||
|
||||
@@ -969,19 +1004,19 @@ a:hover { text-decoration: underline; }
|
||||
.loc-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-end;
|
||||
margin-bottom: 1.5rem;
|
||||
align-items: center;
|
||||
margin-bottom: 0.75rem;
|
||||
border: var(--surface-border);
|
||||
border-radius: var(--surface-radius-lg);
|
||||
background: var(--card-bg-soft);
|
||||
padding: 0.9rem 1rem;
|
||||
padding: 0.45rem 0.8rem;
|
||||
}
|
||||
|
||||
.loc-name { font-family: var(--serif); font-size: 1.6rem; font-weight: 400; line-height: 1.1; }
|
||||
.loc-name { font-family: var(--serif); font-size: 1.3rem; font-weight: 400; line-height: 1.1; }
|
||||
.loc-name { color: var(--card-ink); }
|
||||
.loc-sub { font-size: 0.8rem; color: var(--card-sub); letter-spacing: 0.06em; margin-top: 0.2rem; text-transform: uppercase; }
|
||||
.loc-time { font-size: 0.8rem; color: var(--card-sub); text-align: right; letter-spacing: 0.04em; line-height: 1.5; }
|
||||
.loc-actions { display: flex; flex-direction: column; align-items: flex-end; gap: 0.35rem; }
|
||||
.loc-sub { font-size: 0.72rem; color: var(--card-sub); letter-spacing: 0.06em; margin-top: 0.1rem; text-transform: uppercase; }
|
||||
.loc-time { font-size: 0.72rem; color: var(--card-sub); text-align: right; letter-spacing: 0.03em; white-space: nowrap; }
|
||||
.loc-actions { display: flex; flex-direction: column; align-items: flex-end; gap: 0.2rem; }
|
||||
|
||||
/* ── HERO ── */
|
||||
.hero {
|
||||
@@ -1805,14 +1840,31 @@ details[open] .drawer-chevron { transform: rotate(90deg); }
|
||||
/* iOS momentum scrolling */
|
||||
.hourly-scroll { -webkit-overflow-scrolling: touch; }
|
||||
|
||||
/* ── Leaflet overrides ── */
|
||||
.leaflet-container { background: #1a1f2e; }
|
||||
.leaflet-tile { transition: opacity 0.24s linear; }
|
||||
.leaflet-control-zoom a {
|
||||
background: var(--paper-dark) !important;
|
||||
/* ── MapLibre overrides ── */
|
||||
.maplibregl-map { background: #1a1f2e; }
|
||||
.maplibregl-ctrl-zoom-in,
|
||||
.maplibregl-ctrl-zoom-out,
|
||||
.maplibregl-ctrl-compass {
|
||||
background-color: var(--paper-dark) !important;
|
||||
color: var(--ink) !important;
|
||||
border-color: var(--border) !important;
|
||||
}
|
||||
.maplibregl-ctrl-group {
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 1px 4px rgba(0,0,0,0.4);
|
||||
}
|
||||
.maplibregl-ctrl button:not(:disabled) span {
|
||||
filter: invert(0.8);
|
||||
}
|
||||
.maplibregl-popup-content {
|
||||
background: var(--paper-dark);
|
||||
color: var(--ink);
|
||||
border-radius: 8px;
|
||||
font-size: 0.85rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
box-shadow: 0 2px 8px rgba(0,0,0,0.35);
|
||||
}
|
||||
.maplibregl-popup-tip { border-top-color: var(--paper-dark); }
|
||||
|
||||
/* ── Mobile Bottom Navigation ── */
|
||||
.bottom-nav {
|
||||
@@ -1925,15 +1977,13 @@ details[open] .drawer-chevron { transform: rotate(90deg); }
|
||||
#units-btn { min-width: 56px; }
|
||||
|
||||
.loc-header {
|
||||
flex-direction: column;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
gap: 0.45rem;
|
||||
}
|
||||
.loc-name { font-size: 2rem; }
|
||||
.loc-sub { font-size: 0.88rem; }
|
||||
.loc-actions { align-items: center; margin-top: 0; }
|
||||
.loc-time { text-align: center; font-size: 0.88rem; }
|
||||
.loc-name { font-size: 1.5rem; }
|
||||
.loc-sub { font-size: 0.8rem; }
|
||||
.loc-actions { align-items: flex-end; margin-top: 0; }
|
||||
.loc-time { text-align: right; font-size: 0.8rem; }
|
||||
|
||||
.hero { grid-template-columns: 1fr; text-align: center; }
|
||||
.hero-left { align-items: center; }
|
||||
@@ -2066,3 +2116,300 @@ details[open] .drawer-chevron { transform: rotate(90deg); }
|
||||
}
|
||||
}
|
||||
|
||||
/* ── ntfy / Settings additions ────────────────────────────────────────── */
|
||||
.settings-section-title {
|
||||
font-size: 0.65rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.1em;
|
||||
color: var(--ink-mid);
|
||||
padding: 0.25rem 0.25rem 0;
|
||||
}
|
||||
|
||||
.settings-row--block {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 0.55rem;
|
||||
}
|
||||
|
||||
.settings-row-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.settings-input {
|
||||
width: 100%;
|
||||
background: var(--paper-darker);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
color: var(--ink);
|
||||
font-family: var(--mono);
|
||||
font-size: 0.78rem;
|
||||
padding: 0.45rem 0.6rem;
|
||||
outline: none;
|
||||
transition: border-color 0.15s;
|
||||
}
|
||||
|
||||
.settings-input:focus { border-color: var(--accent); }
|
||||
.settings-input::placeholder { color: var(--ink-mid); opacity: 0.7; }
|
||||
|
||||
.settings-help {
|
||||
font-size: 0.68rem;
|
||||
color: var(--ink-mid);
|
||||
line-height: 1.5;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.settings-help a { color: var(--accent); text-decoration: none; }
|
||||
.settings-help a:hover { text-decoration: underline; }
|
||||
.settings-input--short { width: 6rem; }
|
||||
|
||||
/* ── Wind drawer peek (shows summary when collapsed) ────────────────────── */
|
||||
.wind-drawer-peek {
|
||||
font-size: 0.72rem;
|
||||
color: var(--ink-mid);
|
||||
font-weight: 400;
|
||||
margin-left: 0.4rem;
|
||||
}
|
||||
|
||||
/* ── Forecast Discussion drawer ──────────────────────────────────────────── */
|
||||
.discussion-drawer { margin-top: 1.5rem; }
|
||||
|
||||
.discussion-office {
|
||||
font-size: 0.65rem;
|
||||
color: var(--ink-mid);
|
||||
margin-left: 0.5rem;
|
||||
font-weight: 400;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.discussion-meta {
|
||||
font-size: 0.68rem;
|
||||
color: var(--ink-mid);
|
||||
margin: 0 0 0.75rem;
|
||||
}
|
||||
|
||||
.discussion-text {
|
||||
font-family: 'Courier New', 'Consolas', monospace;
|
||||
font-size: 0.72rem;
|
||||
line-height: 1.55;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
color: var(--ink);
|
||||
background: var(--paper-darker);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--surface-radius-sm);
|
||||
padding: 0.75rem 1rem;
|
||||
max-height: 55vh;
|
||||
overflow-y: auto;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* ── Offline banner ─────────────────────────────────────────────────────── */
|
||||
.offline-banner {
|
||||
position: fixed;
|
||||
top: 0; left: 0; right: 0;
|
||||
background: #b91c1c;
|
||||
color: #fff;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
padding: 0.4rem 1rem;
|
||||
z-index: 9999;
|
||||
transition: transform 0.25s ease;
|
||||
}
|
||||
.offline-banner.hidden { display: none; }
|
||||
|
||||
/* ── Pull-to-refresh indicator ──────────────────────────────────────────── */
|
||||
.ptr-indicator {
|
||||
position: fixed;
|
||||
top: 0; left: 50%;
|
||||
transform: translateX(-50%) translateY(-100%);
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
padding: 0.35rem 1rem;
|
||||
border-radius: 0 0 12px 12px;
|
||||
z-index: 9998;
|
||||
transition: transform 0.25s ease;
|
||||
}
|
||||
.ptr-indicator.visible { transform: translateX(-50%) translateY(0); }
|
||||
.ptr-indicator.hidden { display: none; }
|
||||
|
||||
/* ── Alert badge ─────────────────────────────────────────────────────────── */
|
||||
.tab[data-tab="alerts"],
|
||||
.bottom-tab[data-tab="alerts"] { position: relative; }
|
||||
|
||||
.alert-badge {
|
||||
position: absolute;
|
||||
top: 2px; right: 2px;
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
border-radius: 10px;
|
||||
font-size: 0.6rem;
|
||||
font-weight: 700;
|
||||
padding: 1px 5px;
|
||||
min-width: 16px;
|
||||
text-align: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
.alert-badge.hidden { display: none; }
|
||||
|
||||
/* ── Precip chart (hidden — bars now inline in hourly cells) ─────────────── */
|
||||
.precip-chart-wrap { display: none; }
|
||||
|
||||
/* ── Inline hourly precip bar ─────────────────────────────────────────────── */
|
||||
.hour-bar-wrap {
|
||||
width: 100%;
|
||||
height: 28px;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.hour-bar {
|
||||
width: 60%;
|
||||
min-height: 2px;
|
||||
border-radius: 2px 2px 0 0;
|
||||
transition: height 0.2s ease;
|
||||
}
|
||||
|
||||
/* ── Hurricane tracking panel ────────────────────────────────────────────── */
|
||||
.hurricane-panel { margin-bottom: 1rem; }
|
||||
|
||||
.hurricane-panel:empty { display: none; }
|
||||
|
||||
.hurricane-storm-card {
|
||||
background: var(--card-bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--surface-radius-md);
|
||||
padding: 0.75rem 1rem;
|
||||
margin-bottom: 0.6rem;
|
||||
box-shadow: var(--surface-shadow);
|
||||
}
|
||||
|
||||
.hurricane-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
.hurricane-name {
|
||||
font-size: 1rem;
|
||||
font-weight: 700;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.hurricane-cat-badge {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 8px;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
}
|
||||
.cat-td { background: #2196f3; }
|
||||
.cat-ts { background: #9c27b0; }
|
||||
.cat-1 { background: #ff9800; }
|
||||
.cat-2 { background: #f44336; }
|
||||
.cat-3 { background: #b71c1c; }
|
||||
.cat-4 { background: #7b1fa2; }
|
||||
.cat-5 { background: #1a237e; }
|
||||
|
||||
.hurricane-stats {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.4rem 1.2rem;
|
||||
font-size: 0.78rem;
|
||||
color: var(--ink-light);
|
||||
}
|
||||
|
||||
/* ── Animated current condition icon ─────────────────────────────────────── */
|
||||
@keyframes icon-spin { to { transform: rotate(360deg); } }
|
||||
@keyframes icon-drip { 0%,100% { transform: translateY(0); } 50% { transform: translateY(4px); } }
|
||||
@keyframes icon-fall { 0%,100% { transform: translateY(0) rotate(-5deg); } 50% { transform: translateY(5px) rotate(5deg); } }
|
||||
@keyframes icon-flash { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
|
||||
@keyframes icon-sway { 0%,100% { transform: rotate(-8deg); } 50% { transform: rotate(8deg); } }
|
||||
|
||||
#cur-icon[data-wmo-group="clear"] { animation: icon-spin 20s linear infinite; display: inline-block; }
|
||||
#cur-icon[data-wmo-group="cloud"] { animation: icon-sway 4s ease-in-out infinite; display: inline-block; }
|
||||
#cur-icon[data-wmo-group="rain"] { animation: icon-drip 1.2s ease-in-out infinite; display: inline-block; }
|
||||
#cur-icon[data-wmo-group="snow"] { animation: icon-fall 1.5s ease-in-out infinite; display: inline-block; }
|
||||
#cur-icon[data-wmo-group="storm"] { animation: icon-flash 0.8s ease-in-out infinite; display: inline-block; }
|
||||
|
||||
/* ── Theme toggle buttons ─────────────────────────────────────────────────── */
|
||||
.theme-toggle-group {
|
||||
display: flex;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.theme-btn {
|
||||
background: var(--paper-darker);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
color: var(--ink);
|
||||
font-size: 0.75rem;
|
||||
padding: 0.3rem 0.65rem;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s, border-color 0.15s;
|
||||
}
|
||||
.theme-btn:hover { border-color: var(--accent); }
|
||||
.theme-btn.active { background: var(--accent); color: #fff; border-color: var(--accent); }
|
||||
|
||||
/* ── Saved mini weather cards ────────────────────────────────────────────── */
|
||||
.saved-cards {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.saved-mini-card {
|
||||
background: var(--card-bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--surface-radius-md);
|
||||
padding: 0.5rem 0.75rem;
|
||||
cursor: pointer;
|
||||
min-width: 100px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
position: relative;
|
||||
transition: border-color 0.15s;
|
||||
}
|
||||
.saved-mini-card:hover { border-color: var(--accent); }
|
||||
|
||||
.mini-city-name {
|
||||
font-size: 0.72rem;
|
||||
font-weight: 600;
|
||||
color: var(--ink);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 90px;
|
||||
}
|
||||
|
||||
.mini-weather-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.mini-remove {
|
||||
position: absolute;
|
||||
top: 3px; right: 5px;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--ink-light);
|
||||
font-size: 0.75rem;
|
||||
cursor: pointer;
|
||||
line-height: 1;
|
||||
padding: 0 2px;
|
||||
}
|
||||
.mini-remove:hover { color: var(--accent); }
|
||||
|
||||
+32
-1
@@ -4,7 +4,7 @@ self.addEventListener('message', event => {
|
||||
if (event.data === 'skipWaiting') self.skipWaiting();
|
||||
});
|
||||
|
||||
const CACHE = 'weather-v5';
|
||||
const CACHE = 'weather-v7';
|
||||
|
||||
// App shell cached on install for offline resilience.
|
||||
const PRECACHE = [
|
||||
@@ -31,6 +31,37 @@ self.addEventListener('activate', event => {
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('push', event => {
|
||||
if (!event.data) return;
|
||||
let payload;
|
||||
try { payload = event.data.json(); } catch { payload = { title: 'NeCloud Weather', body: event.data.text() }; }
|
||||
event.waitUntil(
|
||||
self.registration.showNotification(payload.title || 'NeCloud Weather', {
|
||||
body: payload.body || '',
|
||||
icon: '/icons/icon-192.png',
|
||||
badge: '/icons/icon-192.png',
|
||||
tag: payload.tag || 'weather-alert',
|
||||
data: { url: payload.url || '/' },
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('notificationclick', event => {
|
||||
event.notification.close();
|
||||
const url = event.notification.data?.url || '/';
|
||||
event.waitUntil(
|
||||
clients.matchAll({ type: 'window', includeUncontrolled: true }).then(wins => {
|
||||
for (const w of wins) {
|
||||
if (w.url.startsWith(self.registration.scope) && 'focus' in w) {
|
||||
w.navigate(url);
|
||||
return w.focus();
|
||||
}
|
||||
}
|
||||
return clients.openWindow(url);
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', event => {
|
||||
const { request } = event;
|
||||
const url = new URL(request.url);
|
||||
|
||||
+309
@@ -1,11 +1,39 @@
|
||||
const express = require('express');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const webpush = require('web-push');
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3000;
|
||||
const weatherCache = new Map();
|
||||
const WEATHER_CACHE_MAX_ENTRIES = 500;
|
||||
|
||||
// ── Persistent data directory ─────────────────────────────────────────────────
|
||||
const DATA_DIR = path.join(__dirname, 'data');
|
||||
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
|
||||
// ── VAPID web push ────────────────────────────────────────────────────────────
|
||||
const VAPID_FILE = path.join(DATA_DIR, 'vapid.json');
|
||||
let vapidKeys;
|
||||
try {
|
||||
vapidKeys = JSON.parse(fs.readFileSync(VAPID_FILE, 'utf8'));
|
||||
} catch {
|
||||
vapidKeys = webpush.generateVAPIDKeys();
|
||||
fs.writeFileSync(VAPID_FILE, JSON.stringify(vapidKeys));
|
||||
console.log('[vapid] Generated new keys. Public key:', vapidKeys.publicKey);
|
||||
}
|
||||
webpush.setVapidDetails('mailto:nate@necloud.us', vapidKeys.publicKey, vapidKeys.privateKey);
|
||||
|
||||
// ── Push subscription store ───────────────────────────────────────────────────
|
||||
const SUBS_FILE = path.join(DATA_DIR, 'subscriptions.json');
|
||||
let pushSubscriptions = [];
|
||||
try {
|
||||
if (fs.existsSync(SUBS_FILE)) pushSubscriptions = JSON.parse(fs.readFileSync(SUBS_FILE, 'utf8'));
|
||||
} catch { pushSubscriptions = []; }
|
||||
function saveSubs() {
|
||||
try { fs.writeFileSync(SUBS_FILE, JSON.stringify(pushSubscriptions, null, 2)); } catch {}
|
||||
}
|
||||
|
||||
function setCache(key, data) {
|
||||
if (weatherCache.size >= WEATHER_CACHE_MAX_ENTRIES) {
|
||||
const oldestKey = weatherCache.keys().next().value;
|
||||
@@ -308,4 +336,285 @@ app.get('/api/radar/times', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.use(express.json({ limit: '10kb' }));
|
||||
|
||||
// ── VAPID public key ──────────────────────────────────────────────────────────
|
||||
app.get('/api/vapid-public-key', (_req, res) => res.json({ publicKey: vapidKeys.publicKey }));
|
||||
|
||||
// ── Push subscription management ──────────────────────────────────────────────
|
||||
app.post('/api/push-subscribe', (req, res) => {
|
||||
const { subscription, lat, lon, ntfyTopic, thresholds, digestHour } = req.body;
|
||||
if (!subscription?.endpoint) return res.status(400).json({ error: 'Missing subscription' });
|
||||
if (!isValidCoord(lat, -90, 90) || !isValidCoord(lon, -180, 180)) return res.status(400).json({ error: 'Invalid coords' });
|
||||
const idx = pushSubscriptions.findIndex(s => s.subscription.endpoint === subscription.endpoint);
|
||||
const entry = {
|
||||
subscription, lat: Number(lat), lon: Number(lon),
|
||||
ntfyTopic: ntfyTopic || '', thresholds: thresholds || {},
|
||||
digestHour: digestHour ?? 7,
|
||||
seenAlertIds: idx >= 0 ? pushSubscriptions[idx].seenAlertIds : [],
|
||||
lastDigestDate: idx >= 0 ? pushSubscriptions[idx].lastDigestDate : '',
|
||||
lastThresholdDate: '', lastThresholdAlerted: {},
|
||||
};
|
||||
if (idx >= 0) pushSubscriptions[idx] = entry; else pushSubscriptions.push(entry);
|
||||
saveSubs();
|
||||
res.status(201).json({ ok: true });
|
||||
});
|
||||
|
||||
app.post('/api/push-unsubscribe', (req, res) => {
|
||||
const { endpoint } = req.body || {};
|
||||
pushSubscriptions = pushSubscriptions.filter(s => s.subscription.endpoint !== endpoint);
|
||||
saveSubs();
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
// ── Hurricane tracking proxy (NHC) ────────────────────────────────────────────
|
||||
const hCache = { data: null, at: 0 };
|
||||
app.get('/api/hurricanes', async (_req, res) => {
|
||||
if (hCache.data && Date.now() - hCache.at < 5 * 60 * 1000) return res.json(hCache.data);
|
||||
try {
|
||||
const r = await fetchWithRetry('https://www.nhc.noaa.gov/CurrentStorms.json', {
|
||||
attempts: 2, timeoutMs: 10000,
|
||||
fetchOptions: { headers: { 'User-Agent': 'weather-app-v2 (nate@necloud.us)', Accept: 'application/json' } },
|
||||
});
|
||||
const data = await r.json();
|
||||
hCache.data = { storms: data.activeStorms || [] };
|
||||
hCache.at = Date.now();
|
||||
res.json(hCache.data);
|
||||
} catch (e) {
|
||||
console.error('Hurricane fetch error:', e.message);
|
||||
res.json(hCache.data || { storms: [] });
|
||||
}
|
||||
});
|
||||
|
||||
// ── Wildfire perimeter proxy (NIFC) ───────────────────────────────────────────
|
||||
const wfCache = { data: null, at: 0 };
|
||||
app.get('/api/wildfires', async (_req, res) => {
|
||||
if (wfCache.data && Date.now() - wfCache.at < 15 * 60 * 1000) return res.json(wfCache.data);
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
where: 'GISAcres>100', outFields: 'IncidentName,GISAcres,PercentContained',
|
||||
f: 'geojson', resultRecordCount: '150', geometryPrecision: '4', outSR: '4326',
|
||||
});
|
||||
const r = await fetchWithRetry(
|
||||
`https://services3.arcgis.com/T4QMspbfLg3qTGWY/arcgis/rest/services/WFIGS_Interagency_Perimeters_Current/FeatureServer/0/query?${params}`,
|
||||
{ attempts: 2, timeoutMs: 15000 }
|
||||
);
|
||||
wfCache.data = await r.json();
|
||||
wfCache.at = Date.now();
|
||||
res.json(wfCache.data);
|
||||
} catch (e) {
|
||||
console.error('Wildfire fetch error:', e.message);
|
||||
res.json(wfCache.data || { type: 'FeatureCollection', features: [] });
|
||||
}
|
||||
});
|
||||
|
||||
// ── SPC storm reports proxy ────────────────────────────────────────────────────
|
||||
const spcCache = { data: null, at: 0 };
|
||||
function parseSPCCsv(csv, type) {
|
||||
return csv.trim().split('\n').slice(1).flatMap(line => {
|
||||
const p = line.split(',');
|
||||
const lat = parseFloat(p[5]), lon = parseFloat(p[6]);
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lon) || Math.abs(lat) > 90) return [];
|
||||
return [{
|
||||
type: 'Feature',
|
||||
geometry: { type: 'Point', coordinates: [lon, lat] },
|
||||
properties: { type, location: p[4] || '', comments: p.slice(7).join(',').slice(0, 120) },
|
||||
}];
|
||||
});
|
||||
}
|
||||
app.get('/api/spc/reports', async (_req, res) => {
|
||||
if (spcCache.data && Date.now() - spcCache.at < 10 * 60 * 1000) return res.json(spcCache.data);
|
||||
try {
|
||||
const results = await Promise.allSettled(['torn', 'wind', 'hail'].map(t =>
|
||||
fetchWithRetry(`https://www.spc.noaa.gov/climo/reports/today_filtered_${t}.csv`, {
|
||||
attempts: 1, timeoutMs: 8000,
|
||||
fetchOptions: { headers: { 'User-Agent': 'weather-app-v2 (nate@necloud.us)' } },
|
||||
}).then(r => r.text()).then(csv => parseSPCCsv(csv, t))
|
||||
));
|
||||
spcCache.data = { type: 'FeatureCollection', features: results.flatMap(r => r.status === 'fulfilled' ? r.value : []) };
|
||||
spcCache.at = Date.now();
|
||||
res.json(spcCache.data);
|
||||
} catch (e) {
|
||||
console.error('SPC fetch error:', e.message);
|
||||
res.json(spcCache.data || { type: 'FeatureCollection', features: [] });
|
||||
}
|
||||
});
|
||||
|
||||
// ── Personal weather station proxy ────────────────────────────────────────────
|
||||
app.get('/api/pws', async (req, res) => {
|
||||
const { url } = req.query;
|
||||
if (!url) return res.status(400).json({ error: 'Missing url' });
|
||||
let parsed;
|
||||
try { parsed = new URL(url); } catch { return res.status(400).json({ error: 'Invalid url' }); }
|
||||
if (!['http:', 'https:'].includes(parsed.protocol)) return res.status(400).json({ error: 'Only http/https allowed' });
|
||||
try {
|
||||
const r = await fetchWithRetry(url, { attempts: 1, timeoutMs: 5000 });
|
||||
res.json(await r.json());
|
||||
} catch (e) {
|
||||
res.status(502).json({ error: 'PWS fetch failed' });
|
||||
}
|
||||
});
|
||||
|
||||
// ── NWS Forecast Discussion ───────────────────────────────────────────────────
|
||||
const nwsDiscCache = new Map();
|
||||
app.get('/api/nws/discussion', async (req, res) => {
|
||||
const { lat, lon } = req.query;
|
||||
if (!isValidCoord(lat, -90, 90) || !isValidCoord(lon, -180, 180)) {
|
||||
return res.status(400).json({ error: 'Invalid coords' });
|
||||
}
|
||||
const cacheKey = `${parseFloat(lat).toFixed(2)},${parseFloat(lon).toFixed(2)}`;
|
||||
const cached = nwsDiscCache.get(cacheKey);
|
||||
if (cached && Date.now() - cached.at < 45 * 60 * 1000) return res.json(cached.data);
|
||||
|
||||
const NWS_HEADERS = { 'User-Agent': 'weather-app-v2 (nate@necloud.us)', Accept: 'application/geo+json' };
|
||||
try {
|
||||
// Step 1: resolve lat/lon to NWS forecast office
|
||||
const ptRes = await fetchWithRetry(
|
||||
`https://api.weather.gov/points/${parseFloat(lat).toFixed(4)},${parseFloat(lon).toFixed(4)}`,
|
||||
{ attempts: 2, timeoutMs: 10000, fetchOptions: { headers: NWS_HEADERS } }
|
||||
);
|
||||
if (!ptRes.ok) return res.status(404).json({ error: 'Location not covered by NWS (US only)' });
|
||||
const ptData = await ptRes.json();
|
||||
const cwa = ptData.properties?.cwa;
|
||||
if (!cwa) return res.status(404).json({ error: 'No NWS office found for this location' });
|
||||
|
||||
// Step 2: get list of Area Forecast Discussions for that office
|
||||
const listRes = await fetchWithRetry(
|
||||
`https://api.weather.gov/products/types/AFD/locations/${cwa}`,
|
||||
{ attempts: 2, timeoutMs: 10000, fetchOptions: { headers: { 'User-Agent': NWS_HEADERS['User-Agent'] } } }
|
||||
);
|
||||
const listData = await listRes.json();
|
||||
const latest = listData['@graph']?.[0];
|
||||
if (!latest) return res.status(404).json({ error: 'No forecast discussion available' });
|
||||
|
||||
// Step 3: fetch the actual product text
|
||||
const prodUrl = latest['@id'];
|
||||
const prodRes = await fetchWithRetry(prodUrl, {
|
||||
attempts: 2, timeoutMs: 10000,
|
||||
fetchOptions: { headers: { 'User-Agent': NWS_HEADERS['User-Agent'] } }
|
||||
});
|
||||
const prodData = await prodRes.json();
|
||||
|
||||
const result = {
|
||||
office: cwa,
|
||||
issuingOffice: prodData.issuingOffice || cwa,
|
||||
issuanceTime: prodData.issuanceTime,
|
||||
text: prodData.productText || '',
|
||||
};
|
||||
nwsDiscCache.set(cacheKey, { data: result, at: Date.now() });
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
console.error('[discussion]', e.message);
|
||||
const stale = nwsDiscCache.get(cacheKey);
|
||||
if (stale) return res.json(stale.data);
|
||||
res.status(502).json({ error: 'Could not fetch forecast discussion' });
|
||||
}
|
||||
});
|
||||
|
||||
// ── Alert watcher + daily digest + threshold cron ─────────────────────────────
|
||||
const WMO_SHORT = { 0:'Clear',1:'Mainly clear',2:'Partly cloudy',3:'Overcast',45:'Fog',51:'Light drizzle',61:'Light rain',63:'Rain',65:'Heavy rain',71:'Light snow',73:'Snow',75:'Heavy snow',80:'Showers',95:'Thunderstorm' };
|
||||
function wmoShort(c) { return WMO_SHORT[c] || 'Variable'; }
|
||||
|
||||
async function doWebPush(sub, payload) {
|
||||
try {
|
||||
await webpush.sendNotification(sub.subscription, JSON.stringify(payload));
|
||||
} catch (err) {
|
||||
if (err.statusCode === 410 || err.statusCode === 404) {
|
||||
pushSubscriptions = pushSubscriptions.filter(s => s.subscription.endpoint !== sub.subscription.endpoint);
|
||||
saveSubs();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function doNtfy(topic, title, body, priority = 'default') {
|
||||
if (!topic) return;
|
||||
try {
|
||||
await fetch(topic, { method: 'POST', body, headers: { Title: title, Priority: priority, Tags: 'weather' } });
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function alertWatcherCron() {
|
||||
if (!pushSubscriptions.length) return;
|
||||
const now = new Date();
|
||||
const todayStr = now.toDateString();
|
||||
const currentHour = now.getHours();
|
||||
const base = `http://localhost:${PORT}`;
|
||||
|
||||
for (const sub of [...pushSubscriptions]) {
|
||||
try {
|
||||
// ── NWS alerts ──────────────────────────────────────────────────────────
|
||||
const alertData = await fetch(`${base}/api/alerts?lat=${sub.lat}&lon=${sub.lon}`)
|
||||
.then(r => r.json()).catch(() => ({ features: [] }));
|
||||
const newAlerts = (alertData.features || []).filter(f => {
|
||||
const id = f.id || f.properties?.id;
|
||||
return id && !sub.seenAlertIds.includes(id);
|
||||
});
|
||||
if (newAlerts.length) {
|
||||
for (const a of newAlerts) {
|
||||
const p = a.properties || {};
|
||||
const title = `Weather alert: ${p.event || 'Severe weather'}`;
|
||||
const body = p.headline || p.description || 'Alert for your saved location.';
|
||||
await doWebPush(sub, { title, body, tag: 'weather-alert', url: '/?tab=alerts' });
|
||||
await doNtfy(sub.ntfyTopic, title, body, 'high');
|
||||
}
|
||||
sub.seenAlertIds = [...new Set([...sub.seenAlertIds, ...newAlerts.map(f => f.id || f.properties?.id)])].slice(-200);
|
||||
saveSubs();
|
||||
}
|
||||
|
||||
// ── Daily digest ─────────────────────────────────────────────────────────
|
||||
if (sub.lastDigestDate !== todayStr && currentHour === (sub.digestHour ?? 7)) {
|
||||
const wx = await fetch(`${base}/api/weather?lat=${sub.lat}&lon=${sub.lon}`).then(r => r.json()).catch(() => null);
|
||||
if (wx) {
|
||||
const d = wx.daily;
|
||||
const body = `High ${Math.round(d.temperature_2m_max[0])}° / Low ${Math.round(d.temperature_2m_min[0])}° · ${wmoShort(d.weather_code[0])} · Rain ${d.precipitation_probability_max[0]}% · UV ${Math.round(d.uv_index_max[0] ?? 0)}`;
|
||||
await doWebPush(sub, { title: '☀️ NeCloud Daily Forecast', body, tag: 'daily-digest', url: '/' });
|
||||
await doNtfy(sub.ntfyTopic, '☀️ NeCloud Daily Forecast', body);
|
||||
sub.lastDigestDate = todayStr;
|
||||
saveSubs();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Custom thresholds ─────────────────────────────────────────────────────
|
||||
if (sub.thresholds && Object.keys(sub.thresholds).length) {
|
||||
if (sub.lastThresholdDate !== todayStr) { sub.lastThresholdAlerted = {}; sub.lastThresholdDate = todayStr; }
|
||||
const wx = await fetch(`${base}/api/weather?lat=${sub.lat}&lon=${sub.lon}`).then(r => r.json()).catch(() => null);
|
||||
if (wx) {
|
||||
const c = wx.current;
|
||||
const alerted = sub.lastThresholdAlerted || {};
|
||||
if (sub.thresholds.wind && c.wind_gusts_10m > sub.thresholds.wind && !alerted.wind) {
|
||||
alerted.wind = true;
|
||||
const body = `Gusts at ${Math.round(c.wind_gusts_10m)} mph — your threshold is ${sub.thresholds.wind} mph`;
|
||||
await doWebPush(sub, { title: '💨 Wind Alert', body, tag: 'wind-threshold', url: '/' });
|
||||
await doNtfy(sub.ntfyTopic, '💨 Wind Alert', body, 'high');
|
||||
}
|
||||
if (sub.thresholds.tempLow && c.temperature_2m < sub.thresholds.tempLow && !alerted.tempLow) {
|
||||
alerted.tempLow = true;
|
||||
const body = `Temperature at ${Math.round(c.temperature_2m)}°F — at or below your freeze threshold`;
|
||||
await doWebPush(sub, { title: '🧊 Freeze Alert', body, tag: 'temp-threshold', url: '/' });
|
||||
await doNtfy(sub.ntfyTopic, '🧊 Freeze Alert', body);
|
||||
}
|
||||
if (sub.thresholds.aqi) {
|
||||
const aqData = await fetch(`${base}/api/air-quality?lat=${sub.lat}&lon=${sub.lon}`).then(r => r.json()).catch(() => null);
|
||||
const aqi = aqData?.current?.us_aqi;
|
||||
if (aqi && aqi > sub.thresholds.aqi && !alerted.aqi) {
|
||||
alerted.aqi = true;
|
||||
const body = `AQI at ${aqi} — above your threshold of ${sub.thresholds.aqi}`;
|
||||
await doWebPush(sub, { title: '😷 Air Quality Alert', body, tag: 'aqi-threshold', url: '/' });
|
||||
await doNtfy(sub.ntfyTopic, '😷 Air Quality Alert', body);
|
||||
}
|
||||
}
|
||||
sub.lastThresholdAlerted = alerted;
|
||||
saveSubs();
|
||||
}
|
||||
}
|
||||
await new Promise(r => setTimeout(r, 200));
|
||||
} catch (err) {
|
||||
console.error('[cron] Subscription error:', err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setTimeout(alertWatcherCron, 15000);
|
||||
setInterval(alertWatcherCron, 10 * 60 * 1000);
|
||||
|
||||
app.listen(PORT, () => console.log(`Weather app running on port ${PORT}`));
|
||||
Reference in new issue
Block a user