-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrossingforecast.html
797 lines (688 loc) · 35.3 KB
/
crossingforecast.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta name="description" content="Check the Golden Gate Bridge weather forecast tailored for cyclists and runners. View live bridge images, get real-time updates, and customize forecasts for your planned crossings, helping you dress appropriately for current and future conditions." />
<title>Golden Gate Bridge Weather Forecast for Cyclists and Runners</title>
<!-- External CSS and JS libraries -->
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<style>
/* Animation for blinking effect */
@keyframes blink {
0%, 100% { opacity: 0; }
50% { opacity: 0.5; }
}
.animate-blink {
animation: blink 0.5s ease-in-out 3;
}
/* Night mode styles */
body.night-mode {
background-color: #1a1a1a;
color: #f0f0f0;
}
/* Adjust background color for white elements in night mode */
body.night-mode .bg-white {
background-color: #2a2a2a;
}
/* Style form inputs and selects for night mode */
body.night-mode input,
body.night-mode select {
background-color: #3a3a3a;
color: #f0f0f0;
border-color: #4a4a4a;
}
/* Adjust shadow for better visibility in night mode */
body.night-mode .shadow-md {
box-shadow: 0 4px 6px -1px rgba(255, 255, 255, 0.1), 0 2px 4px -1px rgba(255, 255, 255, 0.06);
}
/* Container for the image, controls aspect ratio and cropping */
.image-container {
position: relative;
width: 100%;
padding-top: 63.75%; /* 75% * 0.85 to crop 15% of height */
overflow: hidden;
}
/* Styles for the image itself */
#ggb-image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 117.65%; /* 100 / 0.85 to compensate for cropping */
object-fit: cover; /* Ensures image fills container without distortion */
object-position: center top; /* Aligns image to top, cropping from bottom */
transition: opacity 0.3s ease-in-out;
}
#ggb-image.loading {
opacity: 0.5;
}
</style>
</head>
<body class="bg-gray-100 min-h-screen">
<div class="container mx-auto px-4 py-4 sm:py-8">
<h1 class="text-3xl font-bold mb-6 text-center hidden sm:block">Golden Gate Bridge Live</h1>
<!-- Live image feed of Golden Gate Bridge -->
<div class="mb-2">
<!-- Container for the image with rounded corners and hidden overflow -->
<div class="image-container rounded-lg overflow-hidden">
<img id="ggb-image" class="w-full h-full object-cover" src="https://raw.githubusercontent.com/danielraffel/ggb/main/ggb.screenshot.png" alt="Golden Gate Bridge">
</div>
<div id="sunset-info" class="text-sm mt-2 text-center"></div>
</div>
<!-- First crossing information -->
<div id="first-crossing" class="bg-white shadow-md rounded-lg p-6 mb-4 sm:mb-6">
<h2 class="text-1xl font-semibold mb-2 sm:mb-4">1st GGB Crossing</h2>
<div class="flex items-center space-x-2 sm:space-x-4 mb-2 sm:mb-4">
<span>in</span>
<!-- Desktop view for time difference input -->
<input type="text" id="first-crossing-time-diff" class="border rounded px-2 py-1 w-20 hidden sm:inline">
<!-- Mobile view for time difference input -->
<div class="flex space-x-1 sm:hidden">
<select id="first-crossing-hours" class="border rounded px-1 py-1 w-16">
<!-- Options will be populated by JavaScript -->
</select>
<select id="first-crossing-minutes" class="border rounded px-1 py-1 w-[4.5rem]">
<!-- Options will be populated by JavaScript -->
</select>
</div>
<span>at</span>
<div class="relative">
<input type="time" id="first-crossing-time" class="border rounded px-2 py-1">
<div id="first-crossing-time-blink" class="absolute inset-0 bg-yellow-200 opacity-0 pointer-events-none"></div>
</div>
</div>
<div id="first-crossing-weather" class="text-lg"></div>
</div>
<!-- Second crossing information -->
<div id="second-crossing" class="bg-white shadow-md rounded-lg p-6">
<h2 class="text-1xl font-semibold mb-2 sm:mb-4">2nd GGB Crossing</h2>
<div class="flex items-center space-x-2 sm:space-x-4 mb-2 sm:mb-4">
<!-- Desktop view for time difference input -->
<input type="text" id="second-crossing-time-diff" class="border rounded px-2 py-1 w-20 hidden sm:inline">
<!-- Mobile view for time difference input -->
<div class="flex space-x-1 sm:hidden">
<select id="second-crossing-hours" class="border rounded px-1 py-1 w-16">
<!-- Options will be populated by JavaScript -->
</select>
<select id="second-crossing-minutes" class="border rounded px-1 py-1 w-[4.5rem]">
<!-- Options will be populated by JavaScript -->
</select>
</div>
<span>later at</span>
<input type="time" id="second-crossing-time" class="border rounded px-2 py-1">
</div>
<div id="second-crossing-weather" class="text-lg"></div>
</div>
</div>
<div>
<div class="text-sm sm:mt-0 mt-2 sm:mb-6 mb-0 text-center">
<a href="https://github.com/danielraffel/ggb" target="_blank" style="text-decoration: underline;">About this Site</a>
</div>
</div>
<script>
// Helper functions
// Get and set functions for localStorage
function getFirstCrossingTimeDiff() {
return localStorage.getItem('firstCrossingTimeDiff') || '0h0m';
}
function setFirstCrossingTimeDiff(value) {
localStorage.setItem('firstCrossingTimeDiff', value);
}
function getSecondCrossingTimeDiff() {
return localStorage.getItem('secondCrossingTimeDiff') || '2h0m';
}
function setSecondCrossingTimeDiff(value) {
localStorage.setItem('secondCrossingTimeDiff', value);
}
// Normalize time difference to standard format
function normalizeTimeDiff(value) {
if (/^(0|0[hm]|0h0m)$/.test(value)) {
return '0h0m';
}
const match = value.match(/^(\d+)(?:h|m)?(\d+)?m?$/);
if (match) {
const hours = parseInt(match[1]);
const minutes = match[2] ? parseInt(match[2]) : 0;
if (match[0].includes('h') || (!match[0].includes('h') && !match[0].includes('m') && hours >= 60)) {
return `${hours}h${minutes}m`;
} else {
return `${hours}m`;
}
}
return value;
}
// Parse time difference string to minutes
function parseTimeDiff(timeDiff) {
if (timeDiff === '0' || timeDiff === '0h' || timeDiff === '0m' || timeDiff === '0h0m') {
return 0;
}
const match = timeDiff.match(/^(\d+)(?:h|m)?(\d+)?m?$/);
if (match) {
const firstNumber = parseInt(match[1]);
const secondNumber = match[2] ? parseInt(match[2]) : 0;
if (match[0].includes('h') || (!match[0].includes('h') && !match[0].includes('m') && firstNumber >= 60)) {
return firstNumber * 60 + secondNumber;
} else {
return firstNumber;
}
}
return 0;
}
// Format minutes to time difference string
function formatTimeDiff(minutes) {
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
if (hours === 0 && mins === 0) return '0h0m';
if (hours === 0) return `${mins}m`;
if (mins === 0) return `${hours}h`;
return `${hours}h${mins}m`;
}
// Add minutes to a date
function addMinutesToDate(date, minutes) {
return new Date(date.getTime() + minutes * 60000);
}
// Get minutes between two dates
function getMinutesBetweenDates(date1, date2) {
return Math.round((date2 - date1) / 60000);
}
// Format time to HH:MM
function formatTime(date) {
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${hours}:${minutes}`;
}
// Format sunset time
function formatSunsetTime(date) {
const hours = date.getHours();
const minutes = String(date.getMinutes()).padStart(2, '0');
const period = hours >= 12 ? 'pm' : 'am';
const formattedHours = hours % 12 || 12;
return `${formattedHours}:${minutes}${period}`;
}
// Format date and time
function formatDateTime(date) {
return date.toLocaleString('en-US', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: true
});
}
// DOM elements
const firstCrossingTimeDiff = document.getElementById('first-crossing-time-diff');
const firstCrossingTime = document.getElementById('first-crossing-time');
const secondCrossingTimeDiff = document.getElementById('second-crossing-time-diff');
const secondCrossingTime = document.getElementById('second-crossing-time');
const firstCrossingWeather = document.getElementById('first-crossing-weather');
const secondCrossingWeather = document.getElementById('second-crossing-weather');
const sunsetInfo = document.getElementById('sunset-info');
const firstHoursSelect = document.getElementById('first-crossing-hours');
const firstMinutesSelect = document.getElementById('first-crossing-minutes');
const secondHoursSelect = document.getElementById('second-crossing-hours');
const secondMinutesSelect = document.getElementById('second-crossing-minutes');
// Main logic functions
// Update first crossing information
function updateFirstCrossing() {
const now = new Date();
let fcitMinutes = parseTimeDiff(firstCrossingTimeDiff.value);
let fcat = new Date(now.getTime() + fcitMinutes * 60000);
// Ensure fcat is not before now and not after 11:59 PM today
const endOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59);
if (fcat < now || fcat > endOfToday) {
provideFeedback(firstCrossingTime);
fcat = new Date(Math.max(now.getTime(), Math.min(fcat.getTime(), endOfToday.getTime())));
}
fcitMinutes = getMinutesBetweenDates(now, fcat);
firstCrossingTime.value = formatTime(fcat);
firstCrossingTimeDiff.value = normalizeTimeDiff(formatTimeDiff(fcitMinutes));
updateAllInputs();
updateSecondCrossing(fcat);
updateWeather('first', fcat);
}
// Update second crossing information
function updateSecondCrossing(fcat) {
if (!fcat) {
const [hours, minutes] = firstCrossingTime.value.split(':');
const now = new Date();
fcat = new Date(now.getFullYear(), now.getMonth(), now.getDate(), parseInt(hours), parseInt(minutes));
}
let scitMinutes = parseTimeDiff(secondCrossingTimeDiff.value);
let scat = new Date(fcat.getTime() + scitMinutes * 60000);
// Ensure scat is not before fcat and not after 11:59 PM today
const endOfToday = new Date(fcat.getFullYear(), fcat.getMonth(), fcat.getDate(), 23, 59);
if (scat < fcat || scat > endOfToday) {
provideFeedback(secondCrossingTime);
scat = new Date(Math.max(fcat.getTime(), Math.min(scat.getTime(), endOfToday.getTime())));
}
scitMinutes = getMinutesBetweenDates(fcat, scat);
secondCrossingTime.value = formatTime(scat);
secondCrossingTimeDiff.value = normalizeTimeDiff(formatTimeDiff(scitMinutes));
setSecondCrossingTimeDiff(secondCrossingTimeDiff.value);
updateAllInputs();
updateWeather('second', scat);
}
// Handle first crossing time change
function handleFirstCrossingTimeChange() {
const now = new Date();
const [hours, minutes] = firstCrossingTime.value.split(':');
let fcat = new Date(now.getFullYear(), now.getMonth(), now.getDate(), parseInt(hours), parseInt(minutes));
// Ensure fcat is not before now and not after 11:59 PM today
const endOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59);
if (fcat < now || fcat > endOfToday) {
provideFeedback(firstCrossingTime);
fcat = new Date(Math.max(now.getTime(), Math.min(fcat.getTime(), endOfToday.getTime())));
firstCrossingTime.value = formatTime(fcat);
}
let fcitMinutes = getMinutesBetweenDates(now, fcat);
firstCrossingTimeDiff.value = formatTimeDiff(fcitMinutes);
setFirstCrossingTimeDiff(firstCrossingTimeDiff.value);
updateFirstCrossing();
}
// Handle second crossing time change
function handleSecondCrossingTimeChange() {
const [firstHours, firstMinutes] = firstCrossingTime.value.split(':');
const [secondHours, secondMinutes] = secondCrossingTime.value.split(':');
const now = new Date();
let fcat = new Date(now.getFullYear(), now.getMonth(), now.getDate(), parseInt(firstHours), parseInt(firstMinutes));
let scat = new Date(now.getFullYear(), now.getMonth(), now.getDate(), parseInt(secondHours), parseInt(secondMinutes));
// Ensure scat is not before fcat and not after 11:59 PM today
const endOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59);
if (scat < fcat || scat > endOfToday) {
provideFeedback(secondCrossingTime);
scat = new Date(Math.max(fcat.getTime(), Math.min(scat.getTime(), endOfToday.getTime())));
secondCrossingTime.value = formatTime(scat);
}
let scitMinutes = getMinutesBetweenDates(fcat, scat);
secondCrossingTimeDiff.value = formatTimeDiff(scitMinutes);
setSecondCrossingTimeDiff(secondCrossingTimeDiff.value);
updateSecondCrossing(fcat);
}
// Update single input (for mobile view)
function updateSingleInput(timeDiffInput, hoursSelect, minutesSelect, crossing) {
const hours = parseInt(hoursSelect.value);
const minutes = parseInt(minutesSelect.value);
const value = formatTimeDiff(hours * 60 + minutes);
timeDiffInput.value = value;
if (crossing === 'first') {
setFirstCrossingTimeDiff(value);
updateFirstCrossing();
} else {
setSecondCrossingTimeDiff(value);
updateSecondCrossing();
}
}
// Populate hour and minute dropdowns
function populateDropdowns(hoursSelect, minutesSelect) {
hoursSelect.innerHTML = '';
minutesSelect.innerHTML = '';
for (let i = 0; i <= 23; i++) {
hoursSelect.innerHTML += `<option value="${i}">${i}h</option>`;
}
for (let i = 0; i <= 59; i++) {
minutesSelect.innerHTML += `<option value="${i}">${i}m</option>`;
}
}
// Update dropdowns when single input changes
function updateDropdowns(timeDiffInput, hoursSelect, minutesSelect) {
const [hours, minutes] = parseTimeDiff(timeDiffInput.value);
hoursSelect.value = hours;
minutesSelect.value = minutes;
}
// Fetch sunset data
async function fetchSunsetData() {
const now = new Date();
// Log current system time when fetching sunset data
// console.log('Current system time:', now);
const today = now.toISOString().split('T')[0];
const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000).toISOString().split('T')[0];
try {
const url = `https://api.open-meteo.com/v1/forecast?latitude=37.8199&longitude=-122.4783&daily=sunset&timezone=America/Los_Angeles&start_date=${today}&end_date=${tomorrow}`;
const response = await axios.get(url);
const data = response.data;
if (data.daily && data.daily.sunset && data.daily.sunset.length >= 2) {
const todaySunset = new Date(data.daily.sunset[0]);
const tomorrowSunset = new Date(data.daily.sunset[1]);
let sunsetToShow;
let dateToShow;
// Compare dates without time
const nowDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const todaySunsetDate = new Date(todaySunset.getFullYear(), todaySunset.getMonth(), todaySunset.getDate());
if (nowDate.getTime() === todaySunsetDate.getTime()) {
// If the dates match, it's today
sunsetToShow = todaySunset;
dateToShow = now;
// Log when showing today's sunset
// console.log('Showing today\'s sunset');
} else {
// If the dates don't match, it's tomorrow
sunsetToShow = tomorrowSunset;
dateToShow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
// Log when showing tomorrow's sunset
// console.log('Showing tomorrow\'s sunset');
}
const formattedDate = dateToShow.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' });
sunsetInfo.innerHTML = `<p>Next sunset at ${formatSunsetTime(sunsetToShow)} on ${formattedDate}</p>`;
} else {
sunsetInfo.innerHTML = '<p>Sunset information not available.</p>';
}
} catch (error) {
console.error('Error fetching sunset data:', error);
sunsetInfo.innerHTML = '<p>Sunset information not available.</p>';
}
}
// Update weather information for a given crossing (first or second) at a specific time
async function updateWeather(crossing, specificTime = null) {
const timeInput = crossing === 'first' ? firstCrossingTime : secondCrossingTime;
const weatherInfo = crossing === 'first' ? firstCrossingWeather : secondCrossingWeather;
try {
const now = new Date();
let targetTime = specificTime ? new Date(specificTime) : new Date(now.getFullYear(), now.getMonth(), now.getDate(), ...timeInput.value.split(':').map(Number));
// If the target time is in the past, move it to now
if (targetTime < now) {
targetTime = new Date(now);
}
// Format the date for the API request
const formattedDate = targetTime.toISOString().split('T')[0];
// Fetch weather data from the API
const response = await axios.get(`https://api.open-meteo.com/v1/forecast?latitude=37.8199&longitude=-122.4783&hourly=temperature_2m,windspeed_10m,precipitation_probability&timezone=America/Los_Angeles&start_date=${formattedDate}&end_date=${formattedDate}&temperature_unit=fahrenheit&windspeed_unit=mph`);
const data = response.data;
if (!data.hourly || !data.hourly.time) {
throw new Error('Unexpected API response format');
}
// Find the closest time in the hourly data
const targetHour = targetTime.getHours();
const index = data.hourly.time.findIndex(t => new Date(t).getHours() === targetHour);
if (index !== -1) {
const temperature = data.hourly.temperature_2m[index];
const windSpeed = data.hourly.windspeed_10m[index];
const precipitationProbability = data.hourly.precipitation_probability[index];
weatherInfo.innerHTML = `
<p>Temperature: ${temperature.toFixed(1)}°F</p>
<p>Wind Speed: ${windSpeed.toFixed(1)} mph</p>
<p>Precipitation Probability: ${precipitationProbability}%</p>
`;
} else {
weatherInfo.innerHTML = '<p>Weather data not available for the selected time.</p>';
}
} catch (error) {
console.error(`Error fetching weather data for ${crossing} crossing:`, error);
weatherInfo.innerHTML = '<p>Unable to fetch weather data. Please try again later.</p>';
}
}
// Initialize page
function initializePage() {
const now = new Date();
// Log when initializing the page
// console.log(`Initializing page at: ${formatDateTime(now)}`);
// Set first crossing time
const firstTimeDiff = normalizeTimeDiff(getFirstCrossingTimeDiff());
firstCrossingTimeDiff.value = firstTimeDiff;
// Set second crossing time
const secondTimeDiff = normalizeTimeDiff(getSecondCrossingTimeDiff());
secondCrossingTimeDiff.value = secondTimeDiff;
updateFirstCrossing();
// Populate dropdowns
populateDropdowns(firstHoursSelect, firstMinutesSelect);
populateDropdowns(secondHoursSelect, secondMinutesSelect);
// Update dropdowns with initial values
updateMobileInputs();
}
// Event listeners
firstCrossingTimeDiff.addEventListener('change', () => {
setFirstCrossingTimeDiff(firstCrossingTimeDiff.value);
updateFirstCrossing();
});
secondCrossingTimeDiff.addEventListener('change', () => {
setSecondCrossingTimeDiff(secondCrossingTimeDiff.value);
updateSecondCrossing();
});
firstCrossingTime.addEventListener('change', handleFirstCrossingTimeChange);
secondCrossingTime.addEventListener('change', handleSecondCrossingTimeChange);
// Function to update weather periodically
function startWeatherUpdate() {
setInterval(() => {
updateWeather('first');
updateWeather('second');
}, 60000); // Update every minute
}
// Helper function to log the current state
function logCurrentState() {
// Log current state header
// console.log('Current State:');
// Log first crossing time difference
// console.log(`First crossing time diff: ${firstCrossingTimeDiff.value}`);
// Log first crossing time
// console.log(`First crossing time: ${firstCrossingTime.value}`);
// Log second crossing time difference
// console.log(`Second crossing time diff: ${secondCrossingTimeDiff.value}`);
// Log second crossing time
// console.log(`Second crossing time: ${secondCrossingTime.value}`);
}
// Call fetchSunsetData on page load
fetchSunsetData();
// Start periodic weather updates
startWeatherUpdate();
// Initialize the page
initializePage();
// Functions to handle mobile input changes
function handleMobileFirstCrossingChange() {
const hours = parseInt(firstHoursSelect.value);
const minutes = parseInt(firstMinutesSelect.value);
const value = formatTimeDiff(hours * 60 + minutes);
firstCrossingTimeDiff.value = value;
setFirstCrossingTimeDiff(value);
updateFirstCrossing();
}
function handleMobileSecondCrossingChange() {
const hours = parseInt(secondHoursSelect.value);
const minutes = parseInt(secondMinutesSelect.value);
const value = formatTimeDiff(hours * 60 + minutes);
secondCrossingTimeDiff.value = value;
setSecondCrossingTimeDiff(value);
updateSecondCrossing();
}
// Event listeners for mobile inputs
firstHoursSelect.addEventListener('change', handleMobileFirstCrossingChange);
firstMinutesSelect.addEventListener('change', handleMobileFirstCrossingChange);
secondHoursSelect.addEventListener('change', handleMobileSecondCrossingChange);
secondMinutesSelect.addEventListener('change', handleMobileSecondCrossingChange);
// Function to update mobile inputs from desktop values
function updateMobileInputs() {
const firstMinutes = parseTimeDiff(firstCrossingTimeDiff.value);
firstHoursSelect.value = Math.floor(firstMinutes / 60);
firstMinutesSelect.value = firstMinutes % 60;
const secondMinutes = parseTimeDiff(secondCrossingTimeDiff.value);
secondHoursSelect.value = Math.floor(secondMinutes / 60);
secondMinutesSelect.value = secondMinutes % 60;
}
// Function to update both mobile and desktop inputs
function updateAllInputs() {
updateMobileInputs();
firstCrossingTime.value = formatTime(addMinutesToDate(new Date(), parseTimeDiff(firstCrossingTimeDiff.value)));
secondCrossingTime.value = formatTime(addMinutesToDate(new Date(), parseTimeDiff(firstCrossingTimeDiff.value) + parseTimeDiff(secondCrossingTimeDiff.value)));
}
// Window resize event listener
window.addEventListener('resize', updateAllInputs);
// Function to determine if it's night time (between 8 PM and 6 AM)
function isNightTime() {
const hour = new Date().getHours();
return hour < 6 || hour >= 20; // Consider night time between 8 PM and 6 AM
}
// Function to apply the appropriate theme based on time of day
function applyTheme() {
const body = document.body;
const isNight = isNightTime();
if (isNight) {
body.classList.add('night-mode');
} else {
body.classList.remove('night-mode');
}
}
// Apply theme on page load
applyTheme();
// Check and update theme every minute
setInterval(applyTheme, 60000);
// Function to update the image
async function updateGGBImage() {
const img = document.getElementById('ggb-image');
img.classList.add('loading');
try {
// Cache-busting technique 1: Use GitHub API to get the latest file content
// This bypasses GitHub's raw content caching
const apiUrl = 'https://api.github.com/repos/danielraffel/ggb/contents/ggb.screenshot.png';
const apiResponse = await fetch(apiUrl, {
headers: {
'Accept': 'application/vnd.github.v3+json',
// Cache-busting technique 2: Add no-cache header to API request
'Cache-Control': 'no-cache'
}
});
const fileData = await apiResponse.json();
if (!fileData.content) {
throw new Error('No content found in the API response');
}
// Cache-busting technique 3: Decode and use the Base64 content directly
// This ensures we're using the exact data returned by the API, not a cached version
const byteCharacters = atob(fileData.content);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], {type: 'image/png'});
// Cache-busting technique 4: Use a Blob URL
// This creates a unique URL for each new image version
const objectURL = URL.createObjectURL(blob);
// Create a new Image object to preload the image
const tempImg = new Image();
tempImg.onload = function() {
console.log('New image loaded, updating src');
// Cache-busting technique 5: Update image src with the new Blob URL
// This ensures the browser displays the new image, not a cached version
img.src = objectURL;
URL.revokeObjectURL(img.src);
img.classList.remove('loading');
};
tempImg.onerror = function() {
console.error('Error loading new image');
img.classList.remove('loading');
};
tempImg.src = objectURL;
} catch (error) {
console.error('Error fetching image:', error);
img.classList.remove('loading');
}
}
// Cache-busting technique 6: Frequent updates
// Update the image every 30 seconds to ensure latest version
setInterval(updateGGBImage, 30 * 1000);
// Call updateGGBImage immediately after defining the image element
document.getElementById('ggb-image').onload = function() {
updateGGBImage();
};
// Add this function to provide subtle UX feedback
function provideFeedback(element) {
element.classList.remove('animate-blink');
void element.offsetWidth; // Trigger reflow
element.classList.add('animate-blink');
setTimeout(() => {
element.classList.remove('animate-blink');
}, 1500);
}
function updateWeatherChart(data) {
const ctx = document.getElementById('weatherChart').getContext('2d');
// Convert wind speed from km/h to mph and round to 1 decimal place
const windSpeedMph = data.windSpeed.map(speed => Number((speed * 0.621371).toFixed(1)));
if (weatherChart) {
weatherChart.destroy();
}
weatherChart = new Chart(ctx, {
type: 'line',
data: {
labels: data.time,
datasets: [
{
label: 'Temperature (°F)',
data: data.temperature,
borderColor: chartColors.temperature,
backgroundColor: chartColors.temperature + '33',
pointBackgroundColor: chartColors.temperature,
yAxisID: 'y-temp',
},
{
label: 'Cloud Cover (%)',
data: data.cloudCover,
borderColor: chartColors.cloudCover,
backgroundColor: chartColors.cloudCover + '33',
pointBackgroundColor: chartColors.cloudCover,
yAxisID: 'y-cloud',
},
{
label: 'Wind Speed (mph)',
data: windSpeedMph,
borderColor: chartColors.windSpeed,
backgroundColor: chartColors.windSpeed + '33',
pointBackgroundColor: chartColors.windSpeed,
yAxisID: 'y-wind',
},
{
label: 'Precipitation Probability (%)',
data: data.precipitationProbability,
borderColor: chartColors.precipitationProbability,
backgroundColor: chartColors.precipitationProbability + '33',
pointBackgroundColor: chartColors.precipitationProbability,
yAxisID: 'y-precip',
}
]
},
options: {
// ... (keep existing options)
scales: {
// ... (keep existing scales)
'y-wind': {
type: 'linear',
position: 'right',
title: {
display: true,
text: 'Wind Speed (mph)'
},
ticks: {
callback: function(value) {
return value.toFixed(1);
}
},
// ... (keep other scale options)
},
// ... (keep other scales)
},
plugins: {
tooltip: {
callbacks: {
label: function(context) {
let label = context.dataset.label || '';
if (label) {
label += ': ';
}
if (context.parsed.y !== null) {
if (context.dataset.yAxisID === 'y-wind') {
label += context.parsed.y.toFixed(1) + ' mph';
} else {
label += context.parsed.y.toFixed(1);
}
}
return label;
}
}
}
}
}
});
}
</script>
</body>
</html>