-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
1575 lines (1409 loc) · 57.8 KB
/
script.js
File metadata and controls
1575 lines (1409 loc) · 57.8 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
const searchBtn = document.getElementById('search-btn');
const locationBtn = document.getElementById('location-btn');
const cityInput = document.getElementById('city-input');
const suggestionsList = document.getElementById('suggestions-list');
const weatherContent = document.getElementById('weather-content');
const skeletonLoader = document.getElementById('skeleton-loader');
const errorMessage = document.getElementById('error-message');
const errorText = document.getElementById('error-text');
const retryBtn = document.getElementById('retry-btn');
const forecastList = document.getElementById('forecast-list');
const hourlyForecastList = document.getElementById('hourly-forecast');
const windList = document.getElementById('wind-list');
const unitSwitch = document.getElementById('unit-switch');
const favBtn = document.getElementById('fav-btn');
const shareBtn = document.getElementById('share-btn');
const countryFlag = document.getElementById('country-flag');
const favoritesList = document.getElementById('favorites-list');
const chartButtons = document.querySelectorAll('.chart-btn');
const bgLayers = [document.getElementById('bg-layer-1'), document.getElementById('bg-layer-2')];
const glassCard = document.querySelector('.glass-card');
const searchBox = document.querySelector('.search-box');
const searchIconPath = document.getElementById('search-path');
// SVG Paths
const PATH_SEARCH = "M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z";
const PATH_CLOSE = "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z";
// State
let currentUnit = 'metric'; // 'metric' or 'imperial'
let currentCity = localStorage.getItem('lastCity') || 'Delhi';
let currentForecastData = null;
let lastFetchedCurrentWeather = null;
let weatherChart = null;
let favorites = JSON.parse(localStorage.getItem('favorites')) || [];
let debounceTimer;
let activeBgIndex = 0;
let weatherIconsCache = {}; // Cache for resized chart icons
// Initialize
init();
function init() {
if (typeof CONFIG === 'undefined') {
console.error("CONFIG is not defined.");
showError("Configuration missing.");
return;
}
loadFavorites();
fetchWeather(currentCity);
startClock(); // Start the live clock
// Event Listeners
searchBtn.addEventListener('click', () => {
if (searchBox.classList.contains('focus-mode') && cityInput.value.length > 0) {
cityInput.value = '';
cityInput.focus();
handleSearchInput({ target: cityInput });
} else {
const city = cityInput.value.trim();
if (city) {
fetchWeather(city);
cityInput.blur();
} else {
cityInput.focus();
}
}
});
locationBtn.addEventListener('click', handleLocationSearch);
cityInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
const city = cityInput.value.trim();
if (city) {
fetchWeather(city);
cityInput.blur();
} else {
showToast("Please enter a city name");
}
suggestionsList.classList.remove('show');
}
});
// Search Focus/Blur & Morphing Logic
cityInput.addEventListener('focus', () => {
searchBox.classList.add('focus-mode');
document.body.classList.add('search-focus');
searchIconPath.setAttribute('d', PATH_CLOSE);
});
cityInput.addEventListener('blur', () => {
setTimeout(() => {
if (document.activeElement !== cityInput) {
searchBox.classList.remove('focus-mode');
document.body.classList.remove('search-focus');
searchIconPath.setAttribute('d', PATH_SEARCH);
suggestionsList.classList.remove('show');
}
}, 200);
});
cityInput.addEventListener('input', handleSearchInput);
document.addEventListener('click', (e) => {
if (!e.target.closest('.search-box')) {
suggestionsList.classList.remove('show');
}
});
unitSwitch.addEventListener('change', () => {
currentUnit = unitSwitch.checked ? 'imperial' : 'metric';
if (currentUnit === 'imperial') {
glassCard.classList.add('is-imperial');
} else {
glassCard.classList.remove('is-imperial');
}
fetchWeather(currentCity);
});
favBtn.addEventListener('click', toggleFavorite);
shareBtn.addEventListener('click', handleShare);
retryBtn.addEventListener('click', () => {
fetchWeather(currentCity);
});
chartButtons.forEach(btn => {
btn.addEventListener('click', (e) => {
chartButtons.forEach(b => b.classList.remove('active'));
e.target.classList.add('active');
const type = e.target.dataset.type;
if (currentForecastData) updateChart(currentForecastData, type);
});
});
// Auto-refresh data every 5 minutes silently
setInterval(() => {
if (navigator.onLine && currentCity) {
fetchWeather(currentCity, true);
}
}, 300000);
// Fetch real commit dates from GitHub and populate timeline
initTimelineDates();
// Offline/Online notifications
window.addEventListener('offline', () => {
showToast("Your internet connection is not working. Please check your internet connection.", "wifi_off");
});
window.addEventListener('online', () => {
showToast("Internet connection restored.", "wifi");
if (currentCity) fetchWeather(currentCity, true);
});
}
// --- Clock Logic ---
function startClock() {
const dateEl = document.getElementById('current-date');
const timeEl = document.getElementById('current-time');
function update() {
const now = new Date();
// Date: Day, DD/MM/YYYY
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const dayName = days[now.getDay()];
const date = now.getDate().toString().padStart(2, '0');
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const year = now.getFullYear();
if (dateEl) dateEl.textContent = `${dayName}, ${date}/${month}/${year}`;
// Time: HH:MM:SS AM/PM
let hours = now.getHours();
const minutes = now.getMinutes().toString().padStart(2, '0');
const seconds = now.getSeconds().toString().padStart(2, '0');
const ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12;
if (timeEl) timeEl.textContent = `${hours}:${minutes}:${seconds} ${ampm}`;
}
update();
setInterval(update, 1000);
}
// --- Share Logic (Off-Screen Flattened DOM Render) ---
async function handleShare() {
// Guard: must have weather data loaded first
if (!lastFetchedCurrentWeather) {
showToast('Search for a city first before sharing!');
return;
}
// Step 1 — Show loading spinner on button
shareBtn.innerHTML = '<span class="material-icons">hourglass_empty</span>';
shareBtn.classList.add('loading');
shareBtn.disabled = true;
try {
const data = lastFetchedCurrentWeather;
const unitSymbol = currentUnit === 'metric' ? '°C' : '°F';
const speedUnit = currentUnit === 'metric' ? 'm/s' : 'mph';
const isNight = document.body.classList.contains('night-mode');
const bgMap = isNight ? CONFIG.nightBackgrounds : CONFIG.backgrounds;
const weatherMain = data.weather[0].main;
const bgUrl = bgMap[weatherMain] || bgMap['Default'];
// Step 2 — Convert Chart.js canvas to static base64 BEFORE capture
// (avoids blank/mid-animation chart in the snapshot)
let chartDataUrl = '';
if (weatherChart) {
try {
chartDataUrl = weatherChart.toBase64Image('image/png', 1);
} catch (e) {
console.warn('Chart export failed, continuing without chart:', e);
}
}
// Step 3 — Populate the hidden export template with current state
const container = document.getElementById('export-canvas-container');
// Background image — set on the #export-bg child so the container
// itself keeps its CSS fallback gradient, which renders cleanly.
const exportBg = document.getElementById('export-bg');
exportBg.style.backgroundImage = `url('${bgUrl}')`;
// Header: date + time
const now = new Date();
const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
const dateStr = `${days[now.getDay()]}, ${now.getDate().toString().padStart(2,'0')}/${(now.getMonth()+1).toString().padStart(2,'0')}/${now.getFullYear()}`;
let h = now.getHours(), m = now.getMinutes().toString().padStart(2,'0');
const ampm = h >= 12 ? 'PM' : 'AM';
h = h % 12 || 12;
document.getElementById('export-datetime').innerHTML = `${dateStr}<br>${h}:${m} ${ampm}`;
// City + flag
document.getElementById('export-city').textContent =
`${data.name}, ${data.sys.country}`;
const exportFlag = document.getElementById('export-flag');
if (data.sys.country) {
exportFlag.src = `https://flagcdn.com/h40/${data.sys.country.toLowerCase()}.png`;
exportFlag.style.display = 'inline-block';
} else {
exportFlag.style.display = 'none';
}
// Temperature, icon, description
document.getElementById('export-temp').textContent =
`${Math.round(data.main.temp)}${unitSymbol}`;
document.getElementById('export-icon').src = getIconUrl(data.weather[0].icon);
document.getElementById('export-desc').textContent =
data.weather[0].description;
// Stats strip
document.getElementById('export-humidity').textContent =
`${data.main.humidity}%`;
document.getElementById('export-wind').textContent =
`${data.wind.speed} ${speedUnit}`;
document.getElementById('export-sunrise').textContent =
formatTime(data.sys.sunrise, data.timezone);
document.getElementById('export-sunset').textContent =
formatTime(data.sys.sunset, data.timezone);
// Chart: inject static base64 image so it's guaranteed fully rendered
const chartImg = document.getElementById('export-chart-img');
if (chartDataUrl) {
chartImg.src = chartDataUrl;
chartImg.style.display = 'block';
} else {
chartImg.style.display = 'none';
}
// Step 4 — Wait for the background image to actually load
// (prevents blank bg when image hasn't been cached yet)
await new Promise((resolve) => {
const testImg = new Image();
testImg.onload = resolve;
testImg.onerror = resolve; // proceed even on CORS/load failure
testImg.src = bgUrl;
});
// Also wait for weather icon to load
const exportIconEl = document.getElementById('export-icon');
await new Promise((resolve) => {
if (exportIconEl.complete) { resolve(); return; }
exportIconEl.onload = resolve;
exportIconEl.onerror = resolve;
});
// Small settledown tick so the browser has painted the hidden DOM
await new Promise(r => setTimeout(r, 80));
// Step 5 — Run html2canvas on the hidden export container
const canvas = await html2canvas(container, {
useCORS: true, // required for OpenWeather icons + flag CDN
allowTaint: false,
scale: 2, // retina-quality output
backgroundColor: null, // preserve container's own background
width: 1200,
height: 630,
logging: false
});
// Step 6 — Trigger download / Web Share API
canvas.toBlob(async (blob) => {
const fileName = `SkyCast-${currentCity}-${Date.now()}.png`;
// Try native Web Share (mobile)
const file = new File([blob], fileName, { type: 'image/png' });
if (
navigator.share &&
navigator.canShare &&
navigator.canShare({ files: [file] })
) {
try {
await navigator.share({
files: [file],
title: `Weather in ${currentCity}`,
text: `Current weather in ${currentCity} — shared from SkyCast`
});
showToast('Shared successfully! 🎉');
} catch (err) {
if (err.name !== 'AbortError') {
downloadBlob(blob, fileName);
showToast('Snapshot downloaded! 📸');
}
}
} else {
// Desktop fallback — direct download
downloadBlob(blob, fileName);
showToast('Snapshot downloaded! 📸');
}
// Restore button
shareBtn.innerHTML = '<span class="material-icons">share</span>';
shareBtn.classList.remove('loading');
shareBtn.disabled = false;
}, 'image/png');
} catch (err) {
console.error('Export snapshot error:', err);
// Graceful failure — non-intrusive toast, no silent console-only errors
showToast('Unable to generate snapshot. Please try again.', 'error');
shareBtn.innerHTML = '<span class="material-icons">share</span>';
shareBtn.classList.remove('loading');
shareBtn.disabled = false;
}
}
function downloadBlob(blob, fileName = `SkyCast-${currentCity}.png`) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// --- Fetching Logic ---
async function fetchWeather(city, isSilent = false) {
if (!navigator.onLine) {
if (!isSilent) {
showError("No Internet Connection");
showToast("Your internet connection is not working. Please check your internet connection.", "wifi_off");
}
return;
}
if (!isSilent) showSkeleton();
try {
const weatherRes = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${CONFIG.apiKey}&units=${currentUnit}`);
if (weatherRes.status === 404) throw new Error('City not found');
if (weatherRes.status === 429) throw new Error('API Limit Reached');
if (!weatherRes.ok) throw new Error('Something went wrong');
const weatherData = await weatherRes.json();
currentCity = weatherData.name;
localStorage.setItem('lastCity', currentCity);
lastFetchedCurrentWeather = weatherData;
await fetchAdditionalData(weatherData, isSilent);
} catch (error) {
console.error(error);
if (!isSilent) showError(error.message);
}
}
async function fetchWeatherByCoords(lat, lon, isSilent = false) {
if (!navigator.onLine) {
if (!isSilent) {
showError("No Internet Connection");
showToast("Your internet connection is not working. Please check your internet connection.", "wifi_off");
}
return;
}
if (!isSilent) showSkeleton();
try {
const weatherRes = await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${CONFIG.apiKey}&units=${currentUnit}`);
if (!weatherRes.ok) throw new Error('Location not found');
const weatherData = await weatherRes.json();
currentCity = weatherData.name;
localStorage.setItem('lastCity', currentCity);
lastFetchedCurrentWeather = weatherData;
await fetchAdditionalData(weatherData, isSilent);
} catch (error) {
console.error(error);
if (!isSilent) showError(error.message);
}
}
async function fetchAdditionalData(weatherData, isSilent = false) {
try {
const { lat, lon } = weatherData.coord;
const forecastRes = await fetch(`https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${CONFIG.apiKey}&units=${currentUnit}`);
const forecastData = await forecastRes.json();
currentForecastData = forecastData;
await preloadChartIcons(forecastData.list.slice(0, 8));
const airRes = await fetch(`https://api.openweathermap.org/data/2.5/air_pollution?lat=${lat}&lon=${lon}&appid=${CONFIG.apiKey}`);
const airData = await airRes.json();
updateUI(weatherData);
updateAirQuality(airData);
// Initialize Hazard Interpretation Layer
if (typeof HazardSystem !== 'undefined') {
updateHazards(weatherData, forecastData, airData);
}
// Initialize Precipitation Probability Layer
if (typeof ProbabilitySystem !== 'undefined') {
updatePrecipitation(forecastData);
}
chartButtons.forEach(b => b.classList.remove('active'));
document.querySelector('[data-type="temp"]').classList.add('active');
updateChart(forecastData, 'temp');
updateForecast(forecastData);
updateHourlyForecast(forecastData);
updateWindForecast(forecastData);
updateBackground(weatherData.weather[0].main, weatherData);
checkFavoriteStatus(weatherData.name);
if (!isSilent) hideSkeleton();
// Initialize Wind Map here (after element is visible)
if (typeof WindMap !== 'undefined') {
const weatherId = weatherData.weather[0].id;
const isNight = document.body.classList.contains('night-mode');
WindMap.init('windMapCanvas', weatherData.wind.speed, weatherData.wind.deg, weatherId, isNight);
}
} catch (error) {
console.error(error);
if (!isSilent) showToast("Failed to load some details");
updateUI(weatherData);
if (!isSilent) hideSkeleton();
// Initialize Wind Map even on partial error if basic data exists
if (typeof WindMap !== 'undefined') {
WindMap.init('windMapCanvas', weatherData.wind.speed, weatherData.wind.deg, weatherData.weather[0].id, false);
}
}
}
// --- Icon Preloading ---
function preloadChartIcons(list) {
const uniqueCodes = [...new Set(list.map(item => item.weather[0].icon))];
const promises = uniqueCodes.map(code => {
if (weatherIconsCache[code]) return Promise.resolve();
return new Promise((resolve) => {
const img = new Image();
img.crossOrigin = "Anonymous"; // Allow CORS for icons used in canvas to prevent tainting
img.src = getIconUrl(code);
img.onload = () => {
const size = 40;
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, size, size);
weatherIconsCache[code] = canvas;
resolve();
};
img.onerror = () => {
console.warn(`Failed to load icon: ${code}`);
resolve();
};
});
});
return Promise.all(promises);
}
// --- UI Updates ---
function updateUI(data) {
const unitSymbol = currentUnit === 'metric' ? '°C' : '°F';
const speedUnit = currentUnit === 'metric' ? 'm/s' : 'mph';
document.getElementById('city-name').textContent = `${data.name}, ${data.sys.country}`;
if (data.sys.country) {
countryFlag.src = `https://flagcdn.com/h40/${data.sys.country.toLowerCase()}.png`;
countryFlag.style.display = 'block';
} else {
countryFlag.style.display = 'none';
}
document.getElementById('temperature').textContent = `${Math.round(data.main.temp)}${unitSymbol}`;
document.getElementById('description').textContent = data.weather[0].description;
const iconCode = data.weather[0].icon;
document.getElementById('weather-icon').src = getIconUrl(iconCode);
document.getElementById('wind-speed').textContent = `${data.wind.speed} ${speedUnit}`;
document.getElementById('wind-dir').textContent = getCardinalDirection(data.wind.deg);
document.getElementById('humidity').textContent = `${data.main.humidity}%`;
document.getElementById('pressure').textContent = `${data.main.pressure} hPa`;
const visibility = currentUnit === 'metric' ?
`${(data.visibility / 1000).toFixed(1)} km` :
`${(data.visibility / 1609).toFixed(1)} mi`;
document.getElementById('visibility').textContent = visibility;
document.getElementById('sunrise').textContent = formatTime(data.sys.sunrise, data.timezone);
document.getElementById('sunset').textContent = formatTime(data.sys.sunset, data.timezone);
updateCountdown(data.sys.sunrise, data.sys.sunset, data.timezone);
}
function updateHazards(current, forecast, air) {
const container = document.getElementById('hazard-container');
if (!container) return;
const alerts = HazardSystem.analyze(current, forecast, air, currentUnit);
container.innerHTML = '';
if (alerts.length === 0) {
container.style.display = 'none';
return;
}
container.style.display = 'flex';
alerts.forEach(alert => {
const div = document.createElement('div');
div.className = `hazard-item hazard-${alert.level}`;
div.innerHTML = `
<span class="material-icons hazard-icon">${alert.icon}</span>
<div class="hazard-content">
<strong>${alert.title}</strong>
<p>${alert.msg}</p>
</div>
`;
container.appendChild(div);
});
}
function updatePrecipitation(forecast) {
const container = document.getElementById('precip-container');
if (!container) return;
if (typeof ProbabilitySystem === 'undefined') {
container.style.display = 'none';
return;
}
const data = ProbabilitySystem.analyze(forecast);
if (!data) {
container.style.display = 'none';
return;
}
container.style.display = 'block';
container.innerHTML = `
<div class="precip-header">
<span class="precip-title">Rain Probability: ${data.pop}%</span>
<span class="precip-trend ${data.trendClass}">${data.trend}</span>
</div>
<div class="precip-phrase">${data.phrase}</div>
<div class="precip-context">${data.context}</div>
<div class="precip-explanation">
<span class="material-icons" style="font-size: 14px; vertical-align: middle;">info</span>
${data.explanation}
</div>
<div class="precip-disclaimer">${data.disclaimer}</div>
`;
}
function updateBackground(weatherMain, data, isNightOverride = null) {
let isNight;
if (isNightOverride !== null) {
isNight = isNightOverride; // Allow manual override for testing
} else if (data && data.sys) {
const now = Math.floor(Date.now() / 1000);
isNight = now > data.sys.sunset || now < data.sys.sunrise;
} else {
isNight = false;
}
// Toggle night-mode class on body for CSS styling
if (isNight) {
document.body.classList.add('night-mode');
} else {
document.body.classList.remove('night-mode');
}
let bgUrl;
if (isNight && CONFIG.nightBackgrounds) {
bgUrl = CONFIG.nightBackgrounds[weatherMain] || CONFIG.nightBackgrounds['Default'];
} else {
bgUrl = CONFIG.backgrounds[weatherMain] || CONFIG.backgrounds['Default'];
}
const nextIndex = (activeBgIndex + 1) % 2;
const nextLayer = bgLayers[nextIndex];
const currentLayer = bgLayers[activeBgIndex];
nextLayer.style.backgroundImage = `url('${bgUrl}')`;
setTimeout(() => {
nextLayer.classList.add('active');
currentLayer.classList.remove('active');
activeBgIndex = nextIndex;
}, 100);
}
function updateCountdown(sunrise, sunset, timezone) {
const el = document.getElementById('daylight-countdown');
if (window.countdownInterval) clearInterval(window.countdownInterval);
function update() {
const now = Math.floor(Date.now() / 1000);
let targetTime, label;
if (now < sunrise) {
targetTime = sunrise;
label = "Sunrise";
} else if (now < sunset) {
targetTime = sunset;
label = "Sunset";
} else {
targetTime = sunrise + 86400;
label = "Sunrise";
}
const diff = targetTime - now;
if (diff <= 0) {
el.textContent = "Now";
return;
}
const hrs = Math.floor(diff / 3600);
const mins = Math.floor((diff % 3600) / 60);
el.textContent = `${label} in ${hrs}h ${mins}m`;
}
update();
window.countdownInterval = setInterval(update, 60000);
}
function updateAirQuality(data) {
if (!data.list || data.list.length === 0) return;
const record = data.list[0];
const aqi = record.main.aqi;
const { pm2_5, so2, no2, o3, co } = record.components;
const aqiLabels = { 1: 'Good', 2: 'Fair', 3: 'Moderate', 4: 'Poor', 5: 'Very Poor' };
document.getElementById('aqi-status').textContent = aqiLabels[aqi] || aqi;
document.getElementById('pm25').textContent = pm2_5;
document.getElementById('so2').textContent = so2;
document.getElementById('no2').textContent = no2;
document.getElementById('o3').textContent = o3;
document.getElementById('co').textContent = co;
}
function updateHourlyForecast(data) {
hourlyForecastList.innerHTML = '';
const unitSymbol = currentUnit === 'metric' ? '°C' : '°F';
const hourlyData = data.list.slice(0, 8);
hourlyData.forEach(item => {
const date = new Date(item.dt * 1000);
// Changed to ensure 12 hour format
const time = date.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit', hour12: true });
const temp = Math.round(item.main.temp);
const iconCode = item.weather[0].icon;
const div = document.createElement('div');
div.className = 'hourly-item';
div.innerHTML = `
<p class="h-time">${time}</p>
<img src="${getIconUrl(iconCode)}" alt="${item.weather[0].main}">
<p class="h-temp">${temp}${unitSymbol}</p>
`;
hourlyForecastList.appendChild(div);
});
}
function updateWindForecast(data) {
if (!windList) return;
windList.innerHTML = '';
const speedUnit = currentUnit === 'metric' ? 'm/s' : 'mph';
data.list.slice(0, 8).forEach(item => {
const windSpeed = item.wind.speed;
const windDeg = item.wind.deg;
const date = new Date(item.dt * 1000);
// Changed to ensure 12 hour format
const time = date.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit', hour12: true });
const li = document.createElement('li');
li.classList.add('wind-item');
li.innerHTML = `
<p class="h-time">${time}</p>
<img
src="images/weather_icons/direction.png"
class="direction-icon"
alt="Wind Direction"
style="transform: rotate(${windDeg - 180}deg)"
>
<p class="h-temp">${Math.round(windSpeed)} ${speedUnit}</p>
`;
windList.appendChild(li);
});
}
function updateForecast(data) {
forecastList.innerHTML = '';
const unitSymbol = currentUnit === 'metric' ? '°C' : '°F';
const dailyMap = new Map();
data.list.forEach(item => {
const dateStr = item.dt_txt.split(' ')[0];
if (!dailyMap.has(dateStr)) {
dailyMap.set(dateStr, []);
}
dailyMap.get(dateStr).push(item);
});
const days = Array.from(dailyMap.keys()).slice(0, 5);
days.forEach(dateStr => {
const items = dailyMap.get(dateStr);
let forecastItem = items.find(i => i.dt_txt.includes("12:00:00"));
if (!forecastItem) {
forecastItem = items[Math.floor(items.length / 2)];
}
const date = new Date(forecastItem.dt * 1000);
const dayName = date.toLocaleDateString('en-US', { weekday: 'short' });
const temp = Math.round(forecastItem.main.temp);
const iconCode = forecastItem.weather[0].icon;
const desc = forecastItem.weather[0].main;
const pop = Math.round(forecastItem.pop * 100);
const div = document.createElement('div');
div.className = 'forecast-item';
div.innerHTML = `
<p class="f-day">${dayName}</p>
<img src="${getIconUrl(iconCode)}" alt="${desc}">
<p class="f-temp">${temp}${unitSymbol}</p>
<p class="f-desc">${desc}</p>
${pop > 0 ? `<span class="pop-badge">${pop}% Rain</span>` : ''}
`;
forecastList.appendChild(div);
});
}
function updateChart(data, type) {
const ctx = document.getElementById('forecastChart').getContext('2d');
const slice = data.list.slice(0, 8);
const labels = slice.map(item => {
const d = new Date(item.dt * 1000);
let hours = d.getHours();
const ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12;
return `${hours}:00 ${ampm}`;
});
const city = data.city;
const startDt = slice[0].dt;
const endDt = slice[slice.length - 1].dt;
const daySeconds = 86400;
const baseSunrise = city.sunrise;
const baseSunset = city.sunset;
const sunEvents = [];
[-1, 0, 1].forEach(dayOffset => {
const sr = baseSunrise + (dayOffset * daySeconds);
const ss = baseSunset + (dayOffset * daySeconds);
if (sr >= startDt && sr <= endDt) sunEvents.push({ type: 'sunrise', time: sr });
if (ss >= startDt && ss <= endDt) sunEvents.push({ type: 'sunset', time: ss });
});
const dayNightPlugin = {
id: 'dayNightPlugin',
beforeDraw: (chart) => {
const { ctx, chartArea, scales } = chart;
const xAxis = scales.x;
const getPixelForTime = (timestamp) => {
for (let i = 0; i < slice.length - 1; i++) {
const t1 = slice[i].dt;
const t2 = slice[i + 1].dt;
if (timestamp >= t1 && timestamp <= t2) {
const pct = (timestamp - t1) / (t2 - t1);
const x1 = xAxis.getPixelForValue(i);
const x2 = xAxis.getPixelForValue(i + 1);
return x1 + (x2 - x1) * pct;
}
}
return null;
};
sunEvents.sort((a, b) => a.time - b.time);
const eventPixels = sunEvents.map(e => ({ ...e, x: getPixelForTime(e.time) })).filter(e => e.x !== null);
const boundaries = [
{ x: chartArea.left, time: startDt },
...eventPixels,
{ x: chartArea.right, time: endDt }
];
ctx.save();
for (let i = 0; i < boundaries.length - 1; i++) {
const start = boundaries[i];
const end = boundaries[i + 1];
let isNight = false;
if (i === 0) {
const daysPassed = Math.round((startDt - baseSunrise) / 86400);
const localSR = baseSunrise + daysPassed * 86400;
const localSS = baseSunset + daysPassed * 86400;
if (startDt >= localSR && startDt < localSS) {
isNight = false;
} else {
isNight = true;
}
} else {
const boundaryType = boundaries[i].type;
if (boundaryType === 'sunset') isNight = true;
else if (boundaryType === 'sunrise') isNight = false;
}
const width = end.x - start.x;
if (width <= 0) continue;
// Enhanced Backgrounds
const grd = ctx.createLinearGradient(0, chartArea.top, 0, chartArea.bottom);
if (isNight) {
// Night: Deep Blue/Purple gradient
grd.addColorStop(0, 'rgba(15, 23, 42, 0.6)');
grd.addColorStop(1, 'rgba(15, 23, 42, 0.2)');
} else {
// Day: Warm/Clear gradient
grd.addColorStop(0, 'rgba(255, 251, 235, 0.4)');
grd.addColorStop(1, 'rgba(255, 255, 255, 0.05)');
}
ctx.fillStyle = grd;
ctx.fillRect(start.x, chartArea.top, width, chartArea.height);
}
ctx.restore();
// Draw Event Lines & Icons
ctx.save();
eventPixels.forEach(e => {
const x = e.x;
const yBottom = chartArea.bottom;
const yTop = chartArea.top;
ctx.beginPath();
ctx.setLineDash([5, 5]);
ctx.strokeStyle = 'rgba(255, 255, 255, 0.5)';
ctx.lineWidth = 1;
ctx.moveTo(x, yTop);
ctx.lineTo(x, yBottom);
ctx.stroke();
const iconSize = 14;
const iconY = yBottom - 10;
ctx.beginPath();
ctx.arc(x, iconY, iconSize / 2, Math.PI, 0);
ctx.fillStyle = '#fbbf24';
ctx.fill();
ctx.beginPath();
ctx.setLineDash([]);
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
ctx.moveTo(x - iconSize, iconY);
ctx.lineTo(x + iconSize, iconY);
ctx.stroke();
});
ctx.restore();
}
};
// Prepare Data & Semantic Coloring
const datasetData = [];
const pointStyles = [];
const pointRadii = [];
const pointHoverRadii = [];
const pointBackgroundColors = [];
const pointBorderColors = [];
// Extract values first to determine Min/Max
slice.forEach(item => {
if (type === 'humidity') datasetData.push(item.main.humidity);
else if (type === 'wind') datasetData.push(item.wind.speed);
else datasetData.push(item.main.temp);
});
const minVal = Math.min(...datasetData);
const maxVal = Math.max(...datasetData);
let label, color, gradient;
gradient = ctx.createLinearGradient(0, 0, 0, 400);
if (type === 'humidity') {
label = 'Humidity (%)';
color = '#38bdf8';
gradient.addColorStop(0, 'rgba(56, 189, 248, 0.5)');
gradient.addColorStop(1, 'rgba(56, 189, 248, 0.0)');
} else if (type === 'wind') {
label = currentUnit === 'metric' ? 'Wind Speed (m/s)' : 'Wind Speed (mph)';
color = '#fbbf24';
gradient.addColorStop(0, 'rgba(251, 191, 36, 0.5)');
gradient.addColorStop(1, 'rgba(251, 191, 36, 0.0)');
} else {
label = currentUnit === 'metric' ? 'Temperature (°C)' : 'Temperature (°F)';
color = '#fb923c';
gradient.addColorStop(0, 'rgba(251, 146, 60, 0.5)');
gradient.addColorStop(1, 'rgba(251, 146, 60, 0.0)');
}
let lastCondition = null;
slice.forEach((item, index) => {
const val = datasetData[index];
const condition = item.weather[0].main;
const iconCode = item.weather[0].icon;
const showIcon = (index % 3 === 0) || (lastCondition && condition !== lastCondition);
const isMax = val === maxVal;
const isMin = val === minVal;
// Semantic Coloring Logic
if (isMax) {
// Peak: Red Dot
pointStyles.push('circle');
pointRadii.push(6);
pointHoverRadii.push(9);
pointBackgroundColors.push('#ef4444');
pointBorderColors.push('#fff');
} else if (isMin) {
// Low: Blue Dot
pointStyles.push('circle');
pointRadii.push(6);
pointHoverRadii.push(9);
pointBackgroundColors.push('#3b82f6');
pointBorderColors.push('#fff');
} else if (showIcon && weatherIconsCache[iconCode]) {
// Icon
pointStyles.push(weatherIconsCache[iconCode]);
pointRadii.push(15);
pointHoverRadii.push(25);
pointBackgroundColors.push('rgba(255, 255, 255, 0.2)'); // Slight backing for icon
pointBorderColors.push(color);
} else {
// Standard Dot - Changed to White to avoid "Black dot" confusion
pointStyles.push('circle');
pointRadii.push(4);
pointHoverRadii.push(7);
pointBackgroundColors.push('#ffffff');
pointBorderColors.push(color);
}
lastCondition = condition;
});
let yScaleConfig = {
display: true,
title: {
display: window.innerWidth > 480, // Hide on mobile — button already labels it
text: label,
color: '#000000',
font: {
family: "'Orbitron', sans-serif",
size: window.innerWidth <= 768 ? 10 : 12,
weight: 'bold'
},
padding: { bottom: 10 }
},
grid: {
color: 'rgba(255, 255, 255, 0.1)',
drawBorder: false,
tickLength: 8
},
border: {
display: false
},
ticks: {
color: '#000000',
font: {
family: "'Nova Round', sans-serif",
size: window.innerWidth <= 480 ? 9 : window.innerWidth <= 768 ? 10 : 11,
weight: '600'
},
padding: window.innerWidth <= 480 ? 4 : 8,
maxTicksLimit: window.innerWidth <= 480 ? 4 : 6
}