-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSevere-Weather-Dashboard.html
More file actions
1526 lines (1411 loc) · 61.3 KB
/
Severe-Weather-Dashboard.html
File metadata and controls
1526 lines (1411 loc) · 61.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!--
==============================================================================
Severe Weather Dashboard for Mebane, NC
==============================================================================
This dashboard displays real-time severe weather threat assessments for the
Mebane, NC area (Alamance County). It aggregates data from multiple sources:
- Storm Prediction Center (SPC) outlooks for convective risk levels
- National Weather Service (NWS) active alerts for Alamance County (NCZ023)
- NWS Forecast Discussion (AFD) summaries from the Raleigh office (RAH)
Features:
- Threat level assessment with visual indicators (SAFE, MONITOR, CAUTION, WARNING)
- Clickable panels linking to official NWS/SPC sources
- Automatic updates every 15 minutes with 3-minute alert polling
- Responsive design for mobile and desktop
- Intelligent forecast discussion summarization highlighting severe weather hazards
Location: Mebane, NC (36.096°N, -79.267°W)
To customize for a different location, modify the LOCATION_CONFIG object
in the Configuration Constants section (see LOCATION_CONFIG for details).
==============================================================================
-->
<div id="weather-dashboard-wrapper" style="
position: relative;
margin: 20px auto;
max-width: 1000px;
width: 95%;
box-sizing: border-box;
">
<div id="weather-dashboard-container" style="
width: 100%;
background: #1a1a1a;
color: #e0e0e0;
font-family: 'Helvetica Neue', Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
border-radius: 12px;
padding: 20px;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
position: relative;
z-index: 1;
box-sizing: border-box;
">
<div id="dashboard-title" style="
width: 100%;
background: linear-gradient(135deg, #8a6df2 0%, #6a11cb 55%, #5a0fbf 100%);
color: #ffffff;
text-align: center;
font-weight: 700;
font-size: 1.1em;
letter-spacing: 0.3px;
padding: 12px 12px 10px 12px;
border-radius: 10px;
margin: 0 0 14px 0;
box-sizing: border-box;
box-shadow: inset 0 1px 0 rgba(255,255,255,0.12);
">
<div style="font-size: 1.05em; font-weight: 700;">Storm Risk Dashboard</div>
<div style="font-size: 0.78em; font-weight: 500; opacity: 0.9; margin-top: 2px;">Updates every 15 minutes (alerts may trigger faster updates)</div>
</div>
<!--
Dashboard Panels Container
Two-column grid layout displaying threat assessment and alerts/forecast.
Responsive: switches to single column on mobile devices.
-->
<div id="dashboard-panels" style="
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
margin: 0;
padding: 0;
box-sizing: border-box;
">
<!--
Threat Level Panel - CLICKABLE
Displays current severe weather threat assessment based on SPC outlooks
and active warnings. Clicking opens SPC outlook page in new tab.
Status values: SAFE, MONITOR, CAUTION, WARNING
-->
<div id="threat-panel" style="
background: #2d2d2d;
padding: 25px;
border-radius: 8px;
transition: all 0.3s ease;
box-sizing: border-box;
cursor: pointer;
border: 2px solid transparent;
" onclick="window.open('https://www.spc.noaa.gov/products/outlook/', '_blank')"
onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 16px rgba(0,0,0,0.4)'; this.style.borderColor='#4fc3f7';"
onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='none'; this.style.borderColor='transparent';">
<h3 style="margin: 0 0 15px 0; color: #4fc3f7; font-size: 1.4em; font-weight: 600;">
Current Threat Level
<span style="font-size: 0.7em; opacity: 0.8; margin-left: 8px;">↗ Click for SPC Details</span>
</h3>
<div id="threat-content" style="display: flex; align-items: center; gap: 20px; box-sizing: border-box;">
<div id="threat-icon" role="img" aria-label="Safe status" style="
font-size: 3.5em !important;
font-family: 'Apple Color Emoji','Segoe UI Emoji','Noto Color Emoji','Segoe UI Symbol','Helvetica Neue',Arial,sans-serif !important;
display: inline !important;
width: 80px !important;
text-align: center !important;
line-height: 1 !important;
vertical-align: middle !important;
color: inherit !important;
filter: none !important;
background: none !important;
border: none !important;
padding: 0 !important;
">✅</div>
<div style="flex: 1; box-sizing: border-box;">
<div id="threat-status" style="font-size: 2em; font-weight: 700; margin-bottom: 5px; color: #4CAF50;">SAFE</div>
<div id="threat-description" style="opacity: 0.9; font-size: 1em; margin-bottom: 8px;">No severe weather expected</div>
<div id="spc-data" style="font-size: 0.8em; opacity: 0.8; background: #373737; padding: 6px; border-radius: 4px;">SPC: Loading threat assessment...</div>
<div id="threat-updated" style="font-size: 0.75em; opacity: 0.7; margin-top: 6px;">Updated just now</div>
</div>
</div>
</div>
<!--
Alerts & Forecast Panel - MULTIPLE CLICKABLE SECTIONS
Contains two subsections:
1. Alamance County Alerts - Active NWS warnings/watches/advisories
2. NWS Forecast Discussion - Intelligent summary of AFD highlighting severe weather
Each subsection is clickable and opens relevant NWS pages in new tabs.
-->
<div id="alerts-panel" style="
background: #2d2d2d;
padding: 25px;
border-radius: 8px;
box-sizing: border-box;
">
<h3 style="margin: 0 0 15px 0; color: #ff7043; font-size: 1.4em; font-weight: 600;">Active Alerts & Forecast</h3>
<!-- Alamance County Alerts Section - CLICKABLE -->
<div style="margin-bottom: 12px; box-sizing: border-box;">
<div style="font-size: 0.9em; font-weight: 600; color: #4fc3f7; margin-bottom: 6px;">
Alamance County Alerts:
<span style="font-size: 0.7em; opacity: 0.8;">↗ Click for Current Alerts</span>
</div>
<div id="alamance-alerts" style="
background: #373737;
padding: 8px;
border-radius: 4px;
font-size: 0.85em;
box-sizing: border-box;
cursor: pointer;
transition: all 0.3s ease;
border: 1px solid transparent;
"
onmouseover="this.style.backgroundColor='#4a4a4a'; this.style.borderColor='#4fc3f7';"
onmouseout="this.style.backgroundColor='#373737'; this.style.borderColor='transparent';">
<span style="color: #4fc3f7;">●</span> No active severe weather alerts
</div>
<div id="alerts-updated" style="font-size: 0.75em; opacity: 0.7; margin-top: 6px;">Checked just now</div>
</div>
<!-- NWS Forecast Discussion Section - CLICKABLE -->
<div style="box-sizing: border-box;">
<div style="font-size: 0.9em; font-weight: 600; color: #ff7043; margin-bottom: 6px;">
NWS Forecast Discussion:
<span style="font-size: 0.7em; opacity: 0.8;">↗ Click for Full AFD</span>
</div>
<div id="afd-content" style="
background: #373737;
padding: 8px;
border-radius: 4px;
font-size: 0.8em;
max-height: 80px;
overflow-y: auto;
line-height: 1.3;
box-sizing: border-box;
cursor: pointer;
transition: all 0.3s ease;
border: 1px solid transparent;
"
onmouseover="this.style.backgroundColor='#4a4a4a'; this.style.borderColor='#ff7043';"
onmouseout="this.style.backgroundColor='#373737'; this.style.borderColor='transparent';">
Loading forecast discussion...
</div>
</div>
</div>
</div>
</div>
</div>
<!--
============================================================================
CSS Styles
============================================================================
Provides responsive design rules and ensures emoji/icon visibility across
different browsers and devices. Includes mobile breakpoints for optimal
viewing on small screens.
============================================================================
-->
<style type="text/css">
#weather-dashboard-wrapper {
box-sizing: border-box !important;
}
#weather-dashboard-wrapper *,
#weather-dashboard-wrapper *:before,
#weather-dashboard-wrapper *:after {
box-sizing: border-box !important;
}
/* Responsive rules */
@media (max-width: 768px) {
#weather-dashboard-wrapper {
width: 98% !important;
margin: 15px auto !important;
}
#weather-dashboard-container {
padding: 15px !important;
}
#dashboard-title {
font-size: 1em !important;
padding: 10px 10px 8px 10px !important;
border-radius: 8px !important;
margin-bottom: 12px !important;
}
#dashboard-panels {
grid-template-columns: 1fr !important;
gap: 15px !important;
}
#threat-panel, #alerts-panel {
padding: 20px !important;
}
#threat-content {
flex-direction: column !important;
text-align: center !important;
gap: 15px !important;
}
#threat-icon {
width: auto !important;
font-size: 2.5em !important;
}
#threat-status {
font-size: 1.5em !important;
}
}
@media (max-width: 480px) {
#weather-dashboard-wrapper {
width: 98% !important;
margin: 10px auto !important;
}
#weather-dashboard-container {
padding: 12px !important;
border-radius: 8px !important;
}
#threat-panel h3, #alerts-panel h3 {
font-size: 1.2em !important;
}
}
#weather-dashboard-wrapper #threat-icon,
#weather-dashboard-wrapper [id^="threat-icon"] {
font-family: 'Apple Color Emoji', 'Segoe UI Emoji', 'Noto Color Emoji', 'Segoe UI Symbol', 'Helvetica Neue', Arial, sans-serif !important;
font-size: 3.5em !important;
display: inline !important;
width: 80px !important;
text-align: center !important;
line-height: 1 !important;
vertical-align: middle !important;
color: inherit !important;
filter: none !important;
background: none !important;
border: none !important;
padding: 0 !important;
}
#weather-dashboard-wrapper [id^="threat-icon"] span,
#weather-dashboard-wrapper [id^="threat-icon"] img,
#weather-dashboard-wrapper [id^="threat-icon"] svg {
display: inline !important;
font-family: inherit !important;
font-size: inherit !important;
line-height: 1 !important;
color: inherit !important;
background: none !important;
border: 0 !important;
padding: 0 !important;
margin: 0 !important;
filter: none !important;
}
#weather-dashboard-wrapper #threat-icon:empty::before {
content: '⚠️';
}
</style>
<!-- ============================================================================
JavaScript: Dashboard Functionality
============================================================================
Self-contained module that fetches weather data and updates the dashboard UI.
Uses IIFE pattern to avoid global namespace pollution.
============================================================================ -->
<script type="text/javascript">
(function() {
'use strict';
// Prevent multiple initializations if script is loaded multiple times
if (window.correctedWeatherDashboard) {
return;
}
window.correctedWeatherDashboard = true;
// ==========================================================================
// Configuration Constants
// ==========================================================================
// ==========================================================================
// LOCATION CONFIGURATION - Modify these values to change dashboard location
// ==========================================================================
/**
* Location Configuration Object
*
* To customize for a different location, update all of the following:
*
* @property {Object} coords - Geographic coordinates (latitude, longitude)
* @property {string} nwsZone - NWS zone code for alerts (format: STATEZONENUMBER)
* Find your zone: https://forecast.weather.gov/MapClick.php
* @property {string} stateCode - Two-letter state code for fallback alerts (e.g., 'NC', 'TX', 'CA')
* @property {string} nwsOffice - NWS office identifier for forecast discussions (e.g., 'RAH', 'OUN', 'SFO')
* Find your office: https://www.weather.gov/organization.php
* @property {string} locationName - Display name for the location
*/
const LOCATION_CONFIG = {
coords: { lat: 36.096, lng: -79.267 }, // Mebane, NC coordinates
nwsZone: 'NCZ023', // Alamance County, NC zone code
stateCode: 'NC', // North Carolina state code
nwsOffice: 'RAH', // Raleigh, NC NWS office
locationName: 'Mebane, NC' // Location display name
};
// Extract individual values for backward compatibility and easy access
const coords = LOCATION_CONFIG.coords;
const NWS_ZONE = LOCATION_CONFIG.nwsZone;
const STATE_CODE = LOCATION_CONFIG.stateCode;
const NWS_OFFICE = LOCATION_CONFIG.nwsOffice;
/**
* Dashboard update interval in milliseconds (15 minutes)
* Full dashboard refresh rate
*/
const updateInterval = 900000;
/**
* Timestamp of last full dashboard update
* Used to throttle updates and prevent excessive API calls
*/
let lastUpdate = 0;
/**
* Current alert status state tracking
* Values: 'no-alerts', 'active-alerts', 'error'
*/
let currentAlertStatus = 'no-alerts';
let currentAlertDisplay = 'No active severe weather alerts';
let lastAlertsChecked = 0;
/**
* Winter weather detection state tracking
* Values: 'none', 'advisory', 'warning'
*/
let winterWeatherStatus = 'none';
/**
* SPC (Storm Prediction Center) risk category mappings
* Maps SPC risk codes to human-readable descriptions
* @constant {Object<string, string>}
*/
const spcCategories = {
'TSTM': 'General Thunderstorms, No Severe Weather Expected',
'MRGL': 'Marginal Risk - Isolated severe storms possible',
'SLGT': 'Slight Risk - Scattered severe storms likely',
'ENH': 'Enhanced Risk - Numerous severe storms expected',
'MDT': 'Moderate Risk - Widespread severe storms likely',
'HIGH': 'High Risk - Major severe weather outbreak expected'
};
// ==========================================================================
// SPC (Storm Prediction Center) Risk Assessment Functions
// ==========================================================================
/**
* Checks the current SPC convective outlook risk level for the configured location.
* Wrapper function with error handling that calls the API implementation.
*
* @returns {Promise<string|null>} SPC risk code (TSTM, MRGL, SLGT, ENH, MDT, HIGH)
* or null if unable to determine or API error
*/
async function checkSPCRisk() {
try {
return await checkSPCRiskFromAPI();
} catch (error) {
console.log('SPC API failed:', error);
return null;
}
}
/**
* Fetches SPC convective outlook risk level from NOAA ArcGIS REST API.
* Performs a spatial point-in-polygon query to find which outlook polygon
* contains the configured coordinates. Uses timeout protection and validates response.
*
* @returns {Promise<string|null>} SPC risk code from codeMap or null if no match/error
* @private
*/
async function checkSPCRiskFromAPI() {
try {
const baseUrl = 'https://mapservices.weather.noaa.gov/vector/rest/services/outlooks/SPC_wx_outlks/MapServer/1/query';
const params = new URLSearchParams({
'f': 'json',
'geometry': `${coords.lng},${coords.lat}`,
'geometryType': 'esriGeometryPoint',
'spatialRel': 'esriSpatialRelIntersects',
'outFields': 'dn,valid,expire',
'returnGeometry': 'false'
});
// Use fetchJSON for timeout protection and error handling
const data = await fetchJSON(`${baseUrl}?${params}`, 10000);
// Validate response structure
if (!data || typeof data !== 'object') {
console.warn('SPC API: Invalid response structure');
return null;
}
if (data.features && Array.isArray(data.features) && data.features.length > 0) {
const feature = data.features[0];
if (feature && feature.attributes && typeof feature.attributes.dn !== 'undefined') {
const dnValue = feature.attributes.dn;
// Map SPC outlook DN (day number) values to risk category codes
// DN values correspond to outlook risk levels from SPC's classification system
const codeMap = { 2: 'TSTM', 3: 'MRGL', 4: 'SLGT', 5: 'ENH', 6: 'MDT', 8: 'HIGH' };
return codeMap[dnValue] || null;
}
}
return null;
} catch (error) {
console.error('SPC API fetch error:', error.message);
throw error; // Re-throw to be caught by wrapper
}
}
/**
* Updates the SPC information display in the threat panel.
* Fetches current risk level and displays formatted description.
*
* @returns {Promise<string|null>} SPC risk code or null on error
*/
async function updateSPCInfo() {
try {
const spcRiskLevel = await checkSPCRisk();
let spcInfo = "No thunderstorms expected";
if (spcRiskLevel && spcCategories[spcRiskLevel]) {
spcInfo = spcCategories[spcRiskLevel];
}
updateElement('spc-data', `SPC: ${spcInfo}`, 'innerHTML');
return spcRiskLevel;
} catch (error) {
console.error('SPC info update error:', error);
updateElement('spc-data', 'SPC: Data temporarily unavailable', 'innerHTML');
return null;
}
}
// ==========================================================================
// Utility Functions with Robust Error Handling
// ==========================================================================
/**
* Error Handling Strategy:
*
* 1. Timeout Protection: All external API calls use AbortController with configurable timeouts
* 2. Response Validation: Validate JSON structure before accessing properties
* 3. Fallback Mechanisms: Multiple fallback strategies for critical data sources
* - Alerts: Zone → Statewide
* - AFD: API → HTML scrape
* 4. Graceful Degradation: Dashboard remains functional even if some data sources fail
* 5. Error Logging: Detailed console logging for debugging while maintaining user experience
* 6. Network Error Detection: Specific handling for network failures vs API errors
* 7. JSON Parse Protection: Separate JSON parsing with error handling
*/
/**
* Fetches JSON data from a URL with configurable timeout and robust error handling.
* Uses AbortController to cancel request if timeout is exceeded.
*
* @param {string} url - The URL to fetch
* @param {number} timeoutMs - Timeout in milliseconds (default: 8000)
* @returns {Promise<Object>} Parsed JSON response
* @throws {Error} If HTTP error, timeout, network error, or JSON parse error occurs
*/
async function fetchJSON(url, timeoutMs = 8000) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeoutMs);
try {
const resp = await fetch(url, { signal: controller.signal });
if (!resp.ok) {
throw new Error(`HTTP ${resp.status}: ${resp.statusText || 'Request failed'}`);
}
const contentType = resp.headers.get('content-type');
// Accept both application/json and application/geo+json (GeoJSON is valid JSON)
if (contentType && !contentType.includes('application/json') && !contentType.includes('application/geo+json')) {
console.warn(`Unexpected content-type: ${contentType} for URL: ${url}`);
}
const text = await resp.text();
if (!text || text.trim().length === 0) {
throw new Error('Empty response received');
}
try {
return JSON.parse(text);
} catch (parseError) {
throw new Error(`JSON parse error: ${parseError.message}`);
}
} catch (error) {
if (error.name === 'AbortError') {
throw new Error(`Request timeout after ${timeoutMs}ms`);
}
if (error.name === 'TypeError' && error.message.includes('fetch')) {
throw new Error('Network error: Unable to reach server');
}
throw error;
} finally {
clearTimeout(id);
}
}
/**
* Fetches text data from a URL with configurable timeout and error handling.
*
* @param {string} url - The URL to fetch
* @param {number} timeoutMs - Timeout in milliseconds (default: 8000)
* @returns {Promise<string>} Response text
* @throws {Error} If HTTP error, timeout, or network error occurs
*/
async function fetchText(url, timeoutMs = 8000) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeoutMs);
try {
const resp = await fetch(url, { signal: controller.signal });
if (!resp.ok) {
throw new Error(`HTTP ${resp.status}: ${resp.statusText || 'Request failed'}`);
}
return await resp.text();
} catch (error) {
if (error.name === 'AbortError') {
throw new Error(`Request timeout after ${timeoutMs}ms`);
}
if (error.name === 'TypeError' && error.message.includes('fetch')) {
throw new Error('Network error: Unable to reach server');
}
throw error;
} finally {
clearTimeout(id);
}
}
// ==========================================================================
// Winter Weather Detection
// ==========================================================================
/**
* Winter weather synonym dictionary for comprehensive detection.
* Includes NWS official alert types and common weather terminology.
*
* @constant {Object<string, Array<string>>}
*/
const WINTER_WEATHER_SYNONYMS = {
// Official NWS alert types - comprehensive list
alerts: [
// Advisories
'winter weather advisory',
'freezing rain advisory',
'snow advisory',
'wind chill advisory',
'frost advisory',
'lake effect snow advisory',
'winter weather statement',
// Warnings
'winter storm warning',
'winter weather warning',
'ice storm warning',
'blizzard warning',
'wind chill warning',
'freeze warning',
'freezing rain warning',
'snow squall warning',
'lake effect snow warning',
'extreme cold warning',
'hard freeze warning',
// Watches
'winter storm watch',
'ice storm watch',
'blizzard watch',
'wind chill watch',
'extreme cold watch',
'freeze watch',
'freezing rain watch',
'lake effect snow watch'
],
// Weather phenomena keywords - comprehensive coverage
phenomena: [
// Snow terms
'snow', 'snowfall', 'snowing', 'snowstorm', 'snowfall',
'snow squall', 'snow shower', 'snow flurries', 'flurries',
'blowing snow', 'drifting snow', 'snowdrift',
'lake effect snow', 'upslope snow',
'accumulating snow', 'snow accumulation', 'snow totals',
'snowfall rates', 'heavy snow', 'significant snow',
// Ice terms
'ice', 'icing', 'black ice', 'glaze ice',
'freezing rain', 'freezing drizzle', 'freezing fog',
'ice accumulation', 'ice buildup', 'ice storm',
'ice formation', 'ice coating',
// Mixed precipitation
'sleet', 'sleeting', 'sleet pellets',
'wintry', 'wintry mix', 'winter precipitation',
'freezing precipitation', 'mixed precipitation',
// Cold conditions
'freezing temperatures', 'below freezing',
'wind chill', 'windchill', 'wind chill factor',
'extreme cold', 'bitter cold', 'dangerous cold',
'hard freeze', 'freeze', 'frost',
// Visibility/conditions
'blizzard', 'whiteout', 'near-zero visibility',
'winter conditions', 'winter weather',
'hazardous winter weather', 'winter storm'
],
// Timing/severity indicators
severity: [
'imminent', 'occurring', 'expected',
'developing', 'arriving', 'approaching',
'significant', 'hazardous', 'dangerous'
]
};
/**
* Checks if an alert event name indicates winter weather.
* Uses comprehensive synonym matching to detect various winter weather alerts.
*
* @param {string} eventName - Alert event name (case-insensitive)
* @returns {boolean} True if event is winter weather related
*/
function isWinterWeatherAlert(eventName) {
if (!eventName || typeof eventName !== 'string') {
return false;
}
const eventLower = eventName.toLowerCase();
return WINTER_WEATHER_SYNONYMS.alerts.some(alert => eventLower.includes(alert));
}
/**
* Detects winter weather from alert data.
* Checks for winter weather advisories and warnings in active alerts.
*
* @param {Array} alerts - Array of alert objects from NWS API
* @returns {Object} Object with status ('none'|'advisory'|'warning') and details
*/
function detectWinterWeatherFromAlerts(alerts) {
if (!alerts || !Array.isArray(alerts) || alerts.length === 0) {
return { status: 'none', hasAdvisory: false, hasWarning: false };
}
let hasWarning = false;
let hasAdvisory = false;
for (const alert of alerts) {
if (!alert || typeof alert !== 'object' || !alert.properties) {
continue;
}
const event = (alert.properties.event && typeof alert.properties.event === 'string')
? alert.properties.event
: '';
if (!isWinterWeatherAlert(event)) {
continue;
}
const eventLower = event.toLowerCase();
const severity = (alert.properties.severity && typeof alert.properties.severity === 'string')
? alert.properties.severity.toLowerCase()
: '';
// Check for warnings (highest priority) - comprehensive detection
// Look for "warning" keyword but exclude "watch" and "advisory" variations
if (eventLower.includes('warning') &&
!eventLower.includes('watch') &&
!eventLower.includes('advisory') &&
!eventLower.includes('statement')) {
hasWarning = true;
console.log(`[Winter Weather] WARNING detected: "${event}"`);
}
// Check for advisories (lower priority)
// Includes advisory, watch (unless severe), and statements
else if (eventLower.includes('advisory') ||
eventLower.includes('statement') ||
(eventLower.includes('watch') && severity !== 'severe')) {
hasAdvisory = true;
console.log(`[Winter Weather] ADVISORY/WATCH detected: "${event}"`);
}
}
if (hasWarning) {
console.log(`[Winter Weather] Status determined: WARNING (has ${hasWarning ? 'warning' : ''}, ${hasAdvisory ? 'advisory' : ''})`);
return { status: 'warning', hasAdvisory: true, hasWarning: true };
} else if (hasAdvisory) {
console.log(`[Winter Weather] Status determined: ADVISORY`);
return { status: 'advisory', hasAdvisory: true, hasWarning: false };
}
return { status: 'none', hasAdvisory: false, hasWarning: false };
}
/**
* Checks forecast discussion text for winter weather keywords.
* Uses comprehensive synonym matching to detect winter weather mentions.
*
* @param {string} text - Forecast discussion text (case-insensitive)
* @returns {Object} Object with detected status and confidence
*/
function detectWinterWeatherInText(text) {
if (!text || typeof text !== 'string') {
return { status: 'none', confidence: 0 };
}
const textLower = text.toLowerCase();
let score = 0;
let hasWarningTerms = false;
let hasAdvisoryTerms = false;
// Check for winter weather phenomena
for (const term of WINTER_WEATHER_SYNONYMS.phenomena) {
if (textLower.includes(term)) {
score += 2;
}
}
// Check for severity/timing indicators
for (const term of WINTER_WEATHER_SYNONYMS.severity) {
if (textLower.includes(term)) {
score += 1;
if (term === 'imminent' || term === 'occurring') {
hasWarningTerms = true;
}
}
}
// Check for official alert terminology in text (higher weight for official terms)
for (const alert of WINTER_WEATHER_SYNONYMS.alerts) {
if (textLower.includes(alert)) {
score += 3;
// Check for warning terms (higher priority)
if (alert.includes('warning') && !alert.includes('watch') && !alert.includes('advisory')) {
hasWarningTerms = true;
}
// Check for advisory/watch/statement terms
else if (alert.includes('advisory') || alert.includes('watch') || alert.includes('statement')) {
hasAdvisoryTerms = true;
}
}
}
// Determine status based on score and indicators
if (score >= 5) {
// Check for winter weather warning terms (comprehensive detection)
const warningPatterns = [
'winter storm warning', 'winter weather warning', 'ice storm warning',
'blizzard warning', 'freezing rain warning', 'snow squall warning',
'wind chill warning', 'extreme cold warning'
];
const hasWarningPattern = warningPatterns.some(pattern => textLower.includes(pattern));
if (hasWarningTerms || hasWarningPattern) {
console.log('[Winter Weather] Text detection: WARNING status');
return { status: 'warning', confidence: Math.min(score, 10) };
}
// Check for advisory/watch/statement terms
else if (hasAdvisoryTerms ||
textLower.includes('winter weather advisory') ||
textLower.includes('winter storm watch') ||
textLower.includes('winter weather statement')) {
console.log('[Winter Weather] Text detection: ADVISORY status');
return { status: 'advisory', confidence: Math.min(score, 8) };
} else {
console.log('[Winter Weather] Text detection: ADVISORY status (generic winter weather)');
return { status: 'advisory', confidence: Math.min(score, 6) };
}
}
return { status: 'none', confidence: 0 };
}
// ==========================================================================
// NWS Alert Functions
// ==========================================================================
/**
* Fetches and displays active weather alerts for Alamance County (NCZ023).
* Uses a two-tier fallback strategy: first tries zone-specific alerts,
* then falls back to statewide NC alerts if zone query fails.
*
* Filters alerts to show only warnings, watches, and advisories with
* severe/moderate/minor severity levels.
*
* Also detects and tracks winter weather status from alerts.
*
* @returns {Promise<boolean>} True if active warnings (not watches/advisories) exist,
* false otherwise or on error
*/
async function updateLocalAlertsAndGetStatus() {
try {
// Primary: zone-specific alerts; Fallback: statewide alerts
let data = null;
let lastError = null;
// Try zone-specific alerts first
try {
data = await fetchJSON(`https://api.weather.gov/alerts/active?zone=${NWS_ZONE}`, 8000);
// Validate response structure
if (data && typeof data === 'object' && Array.isArray(data.features)) {
// Success - use zone-specific data
} else {
throw new Error('Invalid zone alert response structure');
}
} catch (e) {
lastError = e;
console.log(`Zone-specific alerts unavailable, trying statewide fallback: ${e.message}`);
// Fallback to statewide alerts
try {
data = await fetchJSON(`https://api.weather.gov/alerts/active?area=${STATE_CODE}`, 8000);
// Validate response structure
if (!data || typeof data !== 'object' || !Array.isArray(data.features)) {
throw new Error('Invalid statewide alert response structure');
}
} catch (fallbackError) {
lastError = fallbackError;
console.error('Both zone and statewide alert queries failed:', fallbackError.message);
throw new Error(`Alert API unavailable: ${fallbackError.message}`);
}
}
if (data && data.features && Array.isArray(data.features) && data.features.length > 0) {
// Detect winter weather from alerts
const winterWeather = detectWinterWeatherFromAlerts(data.features);
const previousWinterStatus = winterWeatherStatus;
winterWeatherStatus = winterWeather.status;
// Debug: Log winter weather detection
if (winterWeatherStatus !== 'none') {
console.log(`Winter weather detected: ${winterWeatherStatus} (was: ${previousWinterStatus})`);
}
// Filter alerts to show only warnings/watches/advisories with valid severity
// Excludes informational statements and other non-actionable alerts
// Validates alert structure before processing
const displayAlerts = data.features.filter(alert => {
// Validate alert structure
if (!alert || typeof alert !== 'object' || !alert.properties) {
return false;
}
const properties = alert.properties;
const event = (properties.event && typeof properties.event === 'string')
? properties.event.toLowerCase()
: '';
const severity = (properties.severity && typeof properties.severity === 'string')
? properties.severity.toLowerCase()
: '';
return (event.includes('warning') || event.includes('watch') ||
event.includes('advisory')) &&
(severity === 'severe' || severity === 'moderate' || severity === 'minor');
});
// Separate warnings (highest priority) from watches/advisories
// Used to determine if threat level should be WARNING vs CAUTION/MONITOR
const warningAlerts = data.features.filter(alert => {
// Validate alert structure
if (!alert || typeof alert !== 'object' || !alert.properties) {
return false;
}
const event = (alert.properties.event && typeof alert.properties.event === 'string')
? alert.properties.event.toLowerCase()
: '';
return event.includes('warning') &&
!event.includes('watch') && !event.includes('advisory');
});
if (displayAlerts.length > 0) {
const alertsHtml = displayAlerts.slice(0, 3).map(alert => {
// Validate alert structure before accessing properties
if (!alert || !alert.properties) {
return '<span style="color: #4fc3f7;">●</span> Weather Alert';
}
const event = (alert.properties.event && typeof alert.properties.event === 'string')
? alert.properties.event
: 'Weather Alert';
let color = '#4fc3f7';
const eventLower = event.toLowerCase();
if (eventLower.includes('warning')) {
color = '#f44336';
} else if (eventLower.includes('watch')) {
color = '#ff9800';
} else if (eventLower.includes('advisory')) {
color = '#ffeb3b';
}
// Escape HTML in event names for safety
const safeEvent = event.replace(/</g, '<').replace(/>/g, '>');
return `<span style="color: ${color};">●</span> ${safeEvent}`;
}).join('<br>');
updateElement('alamance-alerts', alertsHtml, 'innerHTML');
currentAlertStatus = 'active-alerts';
currentAlertDisplay = alertsHtml;
const updatedEl = document.getElementById('alerts-updated');
if (updatedEl) {
const d = new Date();
const ts = d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
updatedEl.textContent = `Checked ${ts}`;
}
lastAlertsChecked = Date.now();
return warningAlerts.length > 0;
}
}
// Reset winter weather status if no alerts found
if (!data || !data.features || data.features.length === 0) {
winterWeatherStatus = 'none';
}
const noAlertsHtml = '<span style="color: #4fc3f7;">●</span> No active severe weather alerts';
updateElement('alamance-alerts', noAlertsHtml, 'innerHTML');
currentAlertStatus = 'no-alerts';
currentAlertDisplay = noAlertsHtml;
const updatedEl = document.getElementById('alerts-updated');
if (updatedEl) {
const d = new Date();
const ts = d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
updatedEl.textContent = `Checked ${ts}`;
}
lastAlertsChecked = Date.now();
return false;
} catch (error) {
console.error('Local alerts update failed:', error);
const errorHtml = '<span style="color: #ff7043;">●</span> Alert system temporarily unavailable';
updateElement('alamance-alerts', errorHtml, 'innerHTML');
currentAlertStatus = 'error';
currentAlertDisplay = errorHtml;
const updatedEl = document.getElementById('alerts-updated');
if (updatedEl) {
const d = new Date();
const ts = d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
updatedEl.textContent = `Checked ${ts}`;
}
lastAlertsChecked = Date.now();
return false;
}
}
// ==========================================================================
// Main Dashboard Update Function
// ==========================================================================
/**
* Main dashboard update function that orchestrates all data fetching and UI updates.
*
* Updates threat level based on:
* 1. Active warnings (highest priority) -> WARNING status
* - Winter weather warnings -> "Winter Precipitation Imminent and/or Occurring"
* 2. Winter weather advisories -> MONITOR status with "Monitor for Winter Conditions"
* 3. SPC enhanced/moderate/high risk -> CAUTION status
* 4. SPC marginal/slight risk -> MONITOR status
* 5. No threats -> SAFE status
*
* Checks both NWS alerts and forecast discussion for winter weather indicators.
* Respects updateInterval throttling to prevent excessive API calls.
* Also triggers forecast discussion update.
*
* @returns {Promise<void>}
*/
async function updateDashboard() {
try {
const now = Date.now();
// Throttle updates: skip if less than updateInterval has passed
if (now - lastUpdate < updateInterval) {
return;
}
// Fetch data with independent error handling - one failure doesn't block others
let hasActiveWarnings = false;
let spcRiskLevel = null;
try {
hasActiveWarnings = await updateLocalAlertsAndGetStatus();
} catch (error) {
console.error('Alert update failed, continuing with other data:', error.message);
// Continue - alerts error already displayed in alert panel
}
try {