-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
745 lines (633 loc) · 33.4 KB
/
Copy pathscript.js
File metadata and controls
745 lines (633 loc) · 33.4 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
// Remove previous meteor interval if it exists
if (window.meteorInterval) {
clearInterval(window.meteorInterval);
window.meteorInterval = null;
}
// Update the digital clock (without seconds)
function updateClock() {
const now = new Date();
// Format time with leading zeros (no seconds)
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
// Update clock display (HH:MM format)
document.getElementById('digital-clock').textContent = `${hours}:${minutes}`;
// Update date
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
const dateStr = now.toLocaleDateString(undefined, options);
document.getElementById('date').textContent = dateStr;
}
// Initialize and update the clock every minute
updateClock();
setInterval(updateClock, 60000);
// Handle bookmark clicks with optimized event delegation
document.querySelector('.bookmarks-container').addEventListener('click', (e) => {
const bookmarkItem = e.target.closest('.bookmark-item');
if (bookmarkItem) {
const url = bookmarkItem.getAttribute('data-url');
if (url) {
window.location.href = url;
}
}
});
// Fetch motivational quotes with better error handling and caching
async function fetchMotivationalQuote() {
try {
// Check if we have a cached quote
const cachedQuote = localStorage.getItem('cachedQuote');
const cachedTime = localStorage.getItem('quoteTimestamp');
const now = new Date().getTime();
if (cachedQuote && cachedTime && (now - parseInt(cachedTime) < 1800000)) {
// Use cached quote if it's less than 30 minutes old
const quoteData = JSON.parse(cachedQuote);
updateQuoteDisplay(quoteData.content, quoteData.author);
return;
}
// Try with local fallback quotes immediately instead of failing network requests
useFallbackQuote();
// Still try the network request in the background for next time
fetch('https://api.quotable.io/random?tags=inspirational,wisdom', {
method: 'GET',
mode: 'cors',
headers: {
'Accept': 'application/json'
}
})
.then(response => {
if (!response.ok) throw new Error('Network response not ok');
return response.json();
})
.then(data => {
if (data && data.content && data.author) {
// Cache for next time
localStorage.setItem('cachedQuote', JSON.stringify({
content: data.content,
author: data.author
}));
localStorage.setItem('quoteTimestamp', new Date().getTime().toString());
}
})
.catch(e => console.log('Background quote fetch failed, using fallback'));
} catch (error) {
console.error('Error in quote function:', error);
useFallbackQuote();
}
}
function updateQuoteDisplay(text, author) {
const quoteElement = document.getElementById('quote');
const authorElement = document.getElementById('author');
// Only update DOM if needed (performance optimization)
if (quoteElement.textContent !== `"${text}"`) {
quoteElement.textContent = `"${text}"`;
authorElement.textContent = `- ${author}`;
}
}
function useFallbackQuote() {
// Fallback quotes in case API fails
const fallbackQuotes = [
{ text: "The only way to do great work is to love what you do.", author: "Steve Jobs" },
{ text: "Believe you can and you're halfway there.", author: "Theodore Roosevelt" },
{ text: "It always seems impossible until it's done.", author: "Nelson Mandela" },
{ text: "Your time is limited, don't waste it living someone else's life.", author: "Steve Jobs" },
{ text: "Strive not to be a success, but rather to be of value.", author: "Albert Einstein" },
{ text: "The future belongs to those who believe in the beauty of their dreams.", author: "Eleanor Roosevelt" }
];
const randomQuote = fallbackQuotes[Math.floor(Math.random() * fallbackQuotes.length)];
updateQuoteDisplay(randomQuote.text, randomQuote.author);
}
// Set up quotes with optimized interval
function setupQuotes() {
// Initial quote
fetchMotivationalQuote();
// Update quote every 2 minutes instead of 30 seconds to reduce API calls
return setInterval(fetchMotivationalQuote, 120000);
}
// Add focus to search input when pressing '/' key
document.addEventListener('keydown', function(e) {
if (e.key === '/' && document.activeElement.tagName !== 'INPUT') {
e.preventDefault();
document.querySelector('.search-box input').focus();
}
});
// Allow pressing Escape to blur the search input
document.querySelector('.search-box input').addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
this.blur();
}
});
// Weather widget functionality - updated to detect location
async function fetchWeather() {
try {
// Get selected city from localStorage (default to Pune)
const selectedCity = localStorage.getItem('selectedCity') || 'Pune';
// Check if we should detect location
const detectLocation = selectedCity === 'auto-detect';
// Check if we have cached weather data
const cacheKey = detectLocation ? 'cachedWeather_detected' : `cachedWeather_${selectedCity}`;
const cachedWeather = localStorage.getItem(cacheKey);
const cachedTime = localStorage.getItem(`weatherTimestamp_${cacheKey}`);
const now = new Date().getTime();
if (cachedWeather && cachedTime && (now - parseInt(cachedTime) < 1800000)) {
// Use cached weather if it's less than 30 minutes old
const weatherData = JSON.parse(cachedWeather);
updateWeatherUI(weatherData, detectLocation ? weatherData.name : selectedCity);
return;
}
// If auto-detect, try to get user's location
if (detectLocation) {
try {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition(
async (position) => {
const { latitude, longitude } = position.coords;
// Simulate API call with mock data for the detected location
// In a real app, you'd call the API with these coordinates
// const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&units=metric&appid=YOUR_API_KEY`);
// For now, use simulated data based on coordinates
const detectedData = {
main: { temp: Math.round(20 + Math.random() * 10) }, // Random temp between 20-30°C
weather: [{ id: 800, main: 'Clear', description: 'clear sky' }],
name: 'Current Location'
};
// Try to reverse geocode to get location name
try {
// Simulate geocoding lookup
detectedData.name = "Detected Location";
// In reality you'd use: https://api.openweathermap.org/geo/1.0/reverse?lat=${latitude}&lon=${longitude}&limit=1&appid=YOUR_API_KEY
} catch (e) {
console.error('Geocoding error:', e);
}
// Cache the detected weather data
localStorage.setItem('cachedWeather_detected', JSON.stringify(detectedData));
localStorage.setItem('weatherTimestamp_cachedWeather_detected', now.toString());
updateWeatherUI(detectedData, detectedData.name);
},
(error) => {
console.error("Geolocation error:", error);
// Fall back to default city
localStorage.setItem('selectedCity', 'Pune');
fetchWeather();
},
{ timeout: 5000 }
);
return; // Early return as geolocation is async
}
} catch (e) {
console.error('Geolocation error:', e);
// Fall back to default
localStorage.setItem('selectedCity', 'Pune');
}
}
// Fallback weather data for predefined cities
const fallbackData = {
'Pune': {
main: { temp: 28 },
weather: [{ id: 800, main: 'Clear', description: 'clear sky' }],
name: 'Pune'
},
'Pimpri-Chinchwad': {
main: { temp: 27.5 },
weather: [{ id: 801, main: 'Clouds', description: 'few clouds' }],
name: 'Pimpri-Chinchwad'
},
'Nashik': {
main: { temp: 26 },
weather: [{ id: 500, main: 'Rain', description: 'light rain' }],
name: 'Nashik'
}
};
// Use fallback data for the selected city
const weatherData = fallbackData[selectedCity];
// Cache the weather data
localStorage.setItem(`cachedWeather_${selectedCity}`, JSON.stringify(weatherData));
localStorage.setItem(`weatherTimestamp_cachedWeather_${selectedCity}`, now.toString());
updateWeatherUI(weatherData, selectedCity);
} catch (error) {
console.error('Error fetching weather:', error);
updateWeatherUI(null);
}
}
function updateWeatherUI(data, selectedCity) {
const tempEl = document.querySelector('.weather-temp');
const locationEl = document.querySelector('.weather-location');
const iconEl = document.querySelector('.weather-icon');
const weatherDescEl = document.querySelector('.weather-desc');
const cityMenuEl = document.querySelector('.city-selector');
const weatherCoverEl = document.querySelector('.weather-cover');
if (!data) {
// Use fallback data
tempEl.textContent = '21°C';
locationEl.textContent = selectedCity || 'Weather Unavailable';
iconEl.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><path fill="#efefef" d="M49.7 50.2H16.8c-5.6 0-10.2-4.6-10.2-10.2c0-4.4 2.9-8.3 7-9.7V30c0-5.1 4.2-9.3 9.3-9.3c1.3 0 2.5 0.3 3.7 0.8c2.5-3.7 6.6-6 11.3-6c7.4 0 13.4 6 13.4 13.4c0 0.8-0.1 1.6-0.2 2.4c4.7 0.9 8.2 5 8.2 10C59.3 45.9 55 50.2 49.7 50.2z"/></svg>';
weatherDescEl.textContent = 'Unavailable';
weatherCoverEl.style.backgroundColor = 'rgba(30, 30, 30, 0.6)';
return;
}
// Update temperature
tempEl.textContent = `${Math.round(data.main.temp)}°C`;
// Update location
locationEl.textContent = selectedCity || data.name;
// Update description
weatherDescEl.textContent = data.weather[0].description;
// Update background color based on conditions
const weatherId = data.weather[0].id;
let bgColor = 'rgba(30, 30, 30, 0.6)';
let iconSvg = '';
// Update icon and background based on weather condition
if (weatherId >= 200 && weatherId < 300) {
// Thunderstorm
bgColor = 'rgba(40, 40, 70, 0.7)';
iconSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><path fill="#efefef" d="M50,26c0,0.5-0.1,1.1-0.1,1.6C49.4,36.2,42.2,43,33.5,43H19c-7.2,0-13-5.8-13-13c0-6.9,5.3-12.5,12.1-13C19.4,10.4,25.4,5,32.5,5c7.4,0,13.5,6,13.5,13.3L46,22C48.3,22.4,50,24,50,26z"/><path fill="#ffce31" d="M31,38h-6l3,6h-5l-4,10h18l-6-11l4-5H31z"/></svg>';
} else if (weatherId >= 300 && weatherId < 500) {
// Drizzle
bgColor = 'rgba(70, 90, 100, 0.7)';
iconSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><path fill="#efefef" d="M49.7 31.2c0-7.4-6-13.4-13.4-13.4-4.7 0-8.8 2.4-11.3 6-1.1-0.5-2.4-0.8-3.7-0.8-5.1 0-9.3 4.2-9.3 9.3v0.3c-4.1 1.4-7 5.2-7 9.7 0 5.6 4.6 10.2 10.2 10.2h32.8c5.3 0 9.6-4.3 9.6-9.6 0-5-3.5-9-8.2-10-0.1-0.7-0.2-1.5-0.2-2.3z"/><path fill="#87dbff" d="M27.5 46c0 1.4-1.1 2.5-2.5 2.5s-2.5-1.1-2.5-2.5 2.5-6.5 2.5-6.5 2.5 5.1 2.5 6.5zM34.5 46c0 1.4-1.1 2.5-2.5 2.5s-2.5-1.1-2.5-2.5 2.5-6.5 2.5-6.5 2.5 5.1 2.5 6.5zM41.5 46c0 1.4-1.1 2.5-2.5 2.5s-2.5-1.1-2.5-2.5 2.5-6.5 2.5-6.5 2.5 5.1 2.5 6.5z"/></svg>';
} else if (weatherId >= 500 && weatherId < 600) {
// Rain
bgColor = 'rgba(60, 90, 100, 0.7)';
iconSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><path fill="#efefef" d="M49.7 24.2c0-7.4-6-13.4-13.4-13.4-4.7 0-8.8 2.4-11.3 6-1.1-0.5-2.4-0.8-3.7-0.8-5.1 0-9.3 4.2-9.3 9.3v0.3c-4.1 1.4-7 5.2-7 9.7 0 5.6 4.6 10.2 10.2 10.2h32.8c5.3 0 9.6-4.3 9.6-9.6 0-5-3.5-9-8.2-10-0.1-0.8-0.2-1.6-0.2-2.4z"/><path fill="#87dbff" d="M25.5 40c0 0.3-0.1 0.5-0.2 0.7l-7 12.1c-0.2 0.3-0.5 0.5-0.8 0.5-0.1 0-0.3 0-0.4-0.1-0.4-0.2-0.6-0.8-0.4-1.2l7-12.1c0.2-0.4 0.8-0.6 1.2-0.4 0.4 0.2 0.6 0.8 0.4 1.2 0.1-0.1 0.2 0.1 0.2 0.3zM32.5 40c0 0.3-0.1 0.5-0.2 0.7l-7 12.1c-0.2 0.3-0.5 0.5-0.8 0.5-0.1 0-0.3 0-0.4-0.1-0.4-0.2-0.6-0.8-0.4-1.2l7-12.1c0.2-0.4 0.8-0.6 1.2-0.4 0.4 0.2 0.6 0.8 0.4 1.2 0.1-0.1 0.2 0.1 0.2 0.3zM39.5 40c0 0.3-0.1 0.5-0.2 0.7l-7 12.1c-0.2 0.3-0.5 0.5-0.8 0.5-0.1 0-0.3 0-0.4-0.1-0.4-0.2-0.6-0.8-0.4-1.2l7-12.1c0.2-0.4 0.8-0.6 1.2-0.4 0.4 0.2 0.6 0.8 0.4 1.2 0.1-0.1 0.2 0.1 0.2 0.3zM46.5 40c0 0.3-0.1 0.5-0.2 0.7l-7 12.1c-0.2 0.3-0.5 0.5-0.8 0.5-0.1 0-0.3 0-0.4-0.1-0.4-0.2-0.6-0.8-0.4-1.2l7-12.1c0.2-0.4 0.8-0.6 1.2-0.4 0.4 0.2 0.6 0.8 0.4 1.2 0.1-0.1 0.2 0.1 0.2 0.3z"/></svg>';
} else if (weatherId >= 600 && weatherId < 700) {
// Snow
bgColor = 'rgba(80, 110, 140, 0.7)';
iconSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><path fill="#efefef" d="M49.7 24.2c0-7.4-6-13.4-13.4-13.4-4.7 0-8.8 2.4-11.3 6-1.1-0.5-2.4-0.8-3.7-0.8-5.1 0-9.3 4.2-9.3 9.3v0.3c-4.1 1.4-7 5.2-7 9.7 0 5.6 4.6 10.2 10.2 10.2h32.8c5.3 0 9.6-4.3 9.6-9.6 0-5-3.5-9-8.2-10-0.1-0.8-0.2-1.6-0.2-2.4z"/><path fill="#d2f0ff" d="M42 36c-0.3 0-0.5-0.1-0.7-0.3-0.4-0.4-0.4-1 0-1.4l2-2-2-2c-0.4-0.4-0.4-1 0-1.4s1-0.4 1.4 0l2.7 2.7c0.4 0.4 0.4 1 0 1.4l-2.7 2.7c-0.2 0.2-0.5 0.3-0.7 0.3zM37 41c-0.3 0-0.5-0.1-0.7-0.3-0.4-0.4-0.4-1 0-1.4l2-2-2-2c-0.4-0.4-0.4-1 0-1.4s1-0.4 1.4 0l2.7 2.7c0.4 0.4 0.4 1 0 1.4l-2.7 2.7c-0.2 0.2-0.5 0.3-0.7 0.3zM32 46c-0.3 0-0.5-0.1-0.7-0.3-0.4-0.4-0.4-1 0-1.4l2-2-2-2c-0.4-0.4-0.4-1 0-1.4s1-0.4 1.4 0l2.7 2.7c0.4 0.4 0.4 1 0 1.4l-2.7 2.7c-0.2 0.2-0.5 0.3-0.7 0.3zM27 41c-0.3 0-0.5-0.1-0.7-0.3-0.4-0.4-0.4-1 0-1.4l2-2-2-2c-0.4-0.4-0.4-1 0-1.4s1-0.4 1.4 0l2.7 2.7c0.4 0.4 0.4 1 0 1.4l-2.7 2.7c-0.2 0.2-0.4 0.3-0.7 0.3zM22 36c-0.3 0-0.5-0.1-0.7-0.3-0.4-0.4-0.4-1 0-1.4l2-2-2-2c-0.4-0.4-0.4-1 0-1.4s1-0.4 1.4 0l2.7 2.7c0.4 0.4 0.4 1 0 1.4l-2.7 2.7c-0.2 0.2-0.5 0.3-0.7 0.3z"/></svg>';
} else if (weatherId >= 700 && weatherId < 800) {
// Atmosphere (fog, mist)
bgColor = 'rgba(90, 90, 90, 0.7)';
iconSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><path fill="#efefef" d="M49.7 34.2c0-7.4-6-13.4-13.4-13.4-4.7 0-8.8 2.4-11.3 6-1.1-0.5-2.4-0.8-3.7-0.8-5.1 0-9.3 4.2-9.3 9.3v0.3c-4.1 1.4-7 5.2-7 9.7 0 5.6 4.6 10.2 10.2 10.2h32.8c5.3 0 9.6-4.3 9.6-9.6 0-5-3.5-9-8.2-10-0.1-0.8-0.2-1.6-0.2-2.4z"/><path fill="#efefef" d="M17 44h30v2H17zM17 48h30v2H17zM17 52h30v2H17z"/></svg>';
} else if (weatherId === 800) {
// Clear
bgColor = 'rgba(40, 80, 130, 0.7)';
iconSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><path fill="#ffce31" d="M32 15c-9.4 0-17 7.6-17 17s7.6 17 17 17 17-7.6 17-17-7.6-17-17-17zm0 30c-7.2 0-13-5.8-13-13s5.8-13 13-13 13 5.8 13 13-5.8 13-13 13z"/><path fill="#ffce31" d="M32 7c1.1 0 2-0.9 2-2V2c0-1.1-0.9-2-2-2s-2 0.9-2 2v3c0 1.1 0.9 2 2 2zM32 57c-1.1 0-2 0.9-2 2v3c0 1.1 0.9 2 2 2s2-0.9 2-2v-3c0-1.1-0.9-2-2-2zM57 30h3c1.1 0 2-0.9 2-2s-0.9-2-2-2h-3c-1.1 0-2 0.9-2 2s0.9 2 2 2zM7 34H4c-1.1 0-2 0.9-2 2s0.9 2 2 2h3c1.1 0 2-0.9 2-2s-0.9-2-2-2zM14.9 49.1c-0.8-0.8-2-0.8-2.8 0l-2.1 2.1c-0.8 0.8-0.8 2 0 2.8 0.4 0.4 0.9 0.6 1.4 0.6s1-0.2 1.4-0.6l2.1-2.1c0.8-0.8 0.8-2 0-2.8zM52 12.9c0.4 0.4 0.9 0.6 1.4 0.6s1-0.2 1.4-0.6l2.1-2.1c0.8-0.8 0.8-2 0-2.8-0.8-0.8-2-0.8-2.8 0l-2.1 2.1c-0.8 0.8-0.8 2 0 2.8zM14.9 14.9c0.4 0.4 0.9 0.6 1.4 0.6s1-0.2 1.4-0.6c0.8-0.8 0.8-2 0-2.8l-2.1-2.1c-0.8-0.8-2-0.8-2.8 0-0.8 0.8-0.8 2 0 2.8l2.1 2.1zM52 51.1c-0.8-0.8-2-0.8-2.8 0-0.8 0.8-0.8 2 0 2.8l2.1 2.1c0.4 0.4 0.9 0.6 1.4 0.6s1-0.2 1.4-0.6c0.8-0.8 0.8-2 0-2.8l-2.1-2.1z"/></svg>';
} else {
// Clouds
bgColor = 'rgba(50, 70, 90, 0.7)';
iconSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><path fill="#efefef" d="M49.7 24.2c0-7.4-6-13.4-13.4-13.4-4.7 0-8.8 2.4-11.3 6-1.1-0.5-2.4-0.8-3.7-0.8-5.1 0-9.3 4.2-9.3 9.3v0.3c-4.1 1.4-7 5.2-7 9.7 0 5.6 4.6 10.2 10.2 10.2h32.8c5.3 0 9.6-4.3 9.6-9.6 0-5-3.5-9-8.2-10-0.1-0.8-0.2-1.6-0.2-2.4z"/></svg>';
}
// Update the weather icon with SVG
iconEl.innerHTML = iconSvg;
// Update background color
weatherCoverEl.style.backgroundColor = bgColor;
// Update the city dropdown to match the current city
if (cityMenuEl) {
cityMenuEl.value = selectedCity;
}
}
// Function to handle city selection change
function handleCityChange(city) {
localStorage.setItem('selectedCity', city);
fetchWeather();
}
// Enhanced media controller to receive messages from content scripts
function setupMediaController() {
const playBtn = document.getElementById('play-btn');
const prevBtn = document.getElementById('prev-btn');
const nextBtn = document.getElementById('next-btn');
const trackName = document.querySelector('.track-name');
const trackArtist = document.querySelector('.track-artist');
const mediaPreview = document.querySelector('.media-preview');
const progressBar = document.querySelector('.progress-bar');
const progress = document.querySelector('.progress');
const playerInner = document.querySelector('.player-inner');
// Sample playlist with cover art for fallback
const fallbackPlaylist = [
{
title: 'Lo-Fi Study Music',
artist: 'ChillBeats',
coverUrl: 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNDAgMjQwIj48cmVjdCB3aWR0aD0iMjQwIiBoZWlnaHQ9IjI0MCIgZmlsbD0iIzNkNDg2MyIvPjxjaXJjbGUgY3g9IjEyMCIgY3k9IjEyMCIgcj0iNTAiIGZpbGw9IiMxZDI3M2EiLz48cG9seWdvbiBwb2ludHM9IjExMCw5MCAxMTAsMTUwIDE2MCwxMjAiIGZpbGw9IiMzZDQ4NjMiLz48Y2lyY2xlIGN4PSI4MCIgY3k9IjE4MCIgcj0iMjAiIGZpbGw9IiMxZDI3M2EiLz48Y2lyY2xlIGN4PSIxNDAiIGN5PSIxODAiIHI9IjIwIiBmaWxsPSIjMWQyNzNhIi8+PHJlY3QgeD0iODAiIHk9IjE4MCIgd2lkdGg9IjYwIiBoZWlnaHQ9IjIwIiBmaWxsPSIjMWQyNzNhIi8+PC9zdmc+',
duration: 180
},
{
title: 'Ambient Relaxation',
artist: 'MindfulTunes',
coverUrl: 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNDAgMjQwIj48cmVjdCB3aWR0aD0iMjQwIiBoZWlnaHQ9IjI0MCIgZmlsbD0iIzJjODZhOCIvPjxjaXJjbGUgY3g9IjEyMCIgY3k9IjEyMCIgcj0iODAiIGZpbGw9IiMxZjViNzMiLz48cGF0aCBkPSJNODAsODAgUzEwMCw0MCAxNDAsNDAgUzIwMCw4MCAyMDAsODAgUzE2MCwxNjAgMTIwLDE2MCBTODAsODAgODAsODAiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzJjODZhOCIgc3Ryb2tlLXdpZHRoPSI1Ii8+PC9zdmc+',
duration: 210
},
{
title: 'Focus & Concentration',
artist: 'BrainwaveBeats',
coverUrl: 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNDAgMjQwIj48cmVjdCB3aWR0aD0iMjQwIiBoZWlnaHQ9IjI0MCIgZmlsbD0iIzJkMzY0MCIvPjxjaXJjbGUgY3g9IjEyMCIgY3k9IjEyMCIgcj0iNjAiIGZpbGw9IiMxYTIxMjciIHN0cm9rZT0iI2ZmZiIgc3Ryb2tlLXdpZHRoPSIyIi8+PGNpcmNsZSBjeD0iMTIwIiBjeT0iMTIwIiByPSI0MCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1kYXNoYXJyYXk9IjUsMTAiLz48Y2lyY2xlIGN4PSIxMjAiIGN5PSIxMjAiIHI9IjIwIiBmaWxsPSIjMWEyMTI3Ii8+PC9zdmc+',
duration: 195
}
];
let currentTrack = 0;
let isPlaying = false;
let progressInterval;
let animationFrameId;
// Update track display
function updateTrackInfo(track) {
if (track) {
trackName.textContent = track.title || 'Unknown Track';
if (trackArtist) {
trackArtist.textContent = track.artist || '';
}
// Update cover art
if (track.coverUrl) {
mediaPreview.style.backgroundImage = `url(${track.coverUrl})`;
mediaPreview.style.display = 'block';
// Set background color based on cover art
playerInner.style.backgroundColor = 'rgba(30, 30, 30, 0.8)';
}
} else {
trackName.textContent = 'No media playing';
if (trackArtist) {
trackArtist.textContent = '';
}
mediaPreview.style.display = 'none';
}
}
// Function to update music player UI based on browser media
function updatePlayerFromMediaSession() {
if ('mediaSession' in navigator && navigator.mediaSession.metadata) {
const metadata = navigator.mediaSession.metadata;
const track = {
title: metadata.title || 'Unknown Track',
artist: metadata.artist || '',
coverUrl: metadata.artwork && metadata.artwork.length > 0 ?
metadata.artwork[0].src : null
};
updateTrackInfo(track);
// Update play/pause button state
if (navigator.mediaSession.playbackState === 'playing') {
playBtn.innerHTML = '<i class="fas fa-pause"></i>';
isPlaying = true;
} else {
playBtn.innerHTML = '<i class="fas fa-play"></i>';
isPlaying = false;
}
} else {
// Use fallback if no media is playing
const track = fallbackPlaylist[currentTrack];
updateTrackInfo(track);
}
}
// Initialize with fallback playlist
updateTrackInfo(fallbackPlaylist[currentTrack]);
// Add new function to create a pulse animation on the player
function pulsePlayer() {
playerInner.classList.add('pulse');
setTimeout(() => {
playerInner.classList.remove('pulse');
}, 300);
}
// Toggle play/pause
playBtn.addEventListener('click', () => {
pulsePlayer();
// Try to control browser media first
const mediaElements = document.querySelectorAll('audio, video');
let activeMedia = false;
for (let media of mediaElements) {
if (!media.paused) {
media.pause();
activeMedia = true;
isPlaying = false;
break;
}
}
if (!activeMedia && mediaElements.length > 0) {
mediaElements[0].play();
activeMedia = true;
isPlaying = true;
}
// If no browser media, use fallback
if (!activeMedia) {
isPlaying = !isPlaying;
if (isPlaying) {
playBtn.innerHTML = '<i class="fas fa-pause"></i>';
// Simulate progress bar
let progressValue = 0;
const duration = fallbackPlaylist[currentTrack].duration;
progressInterval = setInterval(() => {
progressValue += 100 / (duration * 5);
if (progressValue >= 100) {
nextTrack();
} else {
progress.style.width = `${progressValue}%`;
}
}, 200);
// Add animated equalizer effect to the cover
mediaPreview.classList.add('playing');
} else {
playBtn.innerHTML = '<i class="fas fa-play"></i>';
clearInterval(progressInterval);
// Remove equalizer effect
mediaPreview.classList.remove('playing');
}
}
});
// Previous track
prevBtn.addEventListener('click', () => {
pulsePlayer();
// Try browser media API first
if ('mediaSession' in navigator) {
const prevTrackHandler = navigator.mediaSession.actions.get('previoustrack');
if (prevTrackHandler) {
prevTrackHandler();
return;
}
}
// Fallback to our playlist
currentTrack = (currentTrack - 1 + fallbackPlaylist.length) % fallbackPlaylist.length;
updateTrackInfo(fallbackPlaylist[currentTrack]);
if (isPlaying) {
clearInterval(progressInterval);
// Simulate progress bar
let progressValue = 0;
const duration = fallbackPlaylist[currentTrack].duration;
progressInterval = setInterval(() => {
progressValue += 100 / (duration * 5);
if (progressValue >= 100) {
nextTrack();
} else {
progress.style.width = `${progressValue}%`;
}
}, 200);
}
});
// Next track
function nextTrack() {
pulsePlayer();
// Try browser media API first
if ('mediaSession' in navigator) {
const nextTrackHandler = navigator.mediaSession.actions.get('nexttrack');
if (nextTrackHandler) {
nextTrackHandler();
return;
}
}
// Fallback to our playlist
currentTrack = (currentTrack + 1) % fallbackPlaylist.length;
updateTrackInfo(fallbackPlaylist[currentTrack]);
if (isPlaying) {
clearInterval(progressInterval);
// Simulate progress bar
let progressValue = 0;
const duration = fallbackPlaylist[currentTrack].duration;
progressInterval = setInterval(() => {
progressValue += 100 / (duration * 5);
if (progressValue >= 100) {
nextTrack();
} else {
progress.style.width = `${progressValue}%`;
}
}, 200);
}
}
nextBtn.addEventListener('click', nextTrack);
// Handle clicks on progress bar
if (progressBar) {
progressBar.addEventListener('click', (e) => {
const rect = progressBar.getBoundingClientRect();
const clickPosition = e.clientX - rect.left;
const clickPercentage = (clickPosition / rect.width) * 100;
// Find active media element and seek
const mediaElements = document.querySelectorAll('audio, video');
for (let media of mediaElements) {
if (!media.paused) {
media.currentTime = (clickPercentage / 100) * media.duration;
break;
}
}
// Update fallback progress if using it
if (isPlaying && progressInterval) {
clearInterval(progressInterval);
progress.style.width = `${clickPercentage}%`;
let progressValue = clickPercentage;
const duration = fallbackPlaylist[currentTrack].duration;
progressInterval = setInterval(() => {
progressValue += 100 / (duration * 5);
if (progressValue >= 100) {
nextTrack();
} else {
progress.style.width = `${progressValue}%`;
}
}, 200);
}
});
}
// Add a pulsing effect when track changes
function addPulseEffect() {
mediaPreview.classList.add('pulse');
setTimeout(() => {
mediaPreview.classList.remove('pulse');
}, 300);
}
// Listen for media playback events
document.addEventListener('play', (e) => {
if (e.target.tagName === 'AUDIO' || e.target.tagName === 'VIDEO') {
isPlaying = true;
playBtn.innerHTML = '<i class="fas fa-pause"></i>';
// Get media info when possible
updateMediaInfo(e.target);
addPulseEffect();
// Clear any existing animation frame
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
// Update progress continuously
function updateMediaProgress() {
if (e.target.duration) {
const percent = (e.target.currentTime / e.target.duration) * 100;
progress.style.width = `${percent}%`;
}
if (!e.target.paused) {
animationFrameId = requestAnimationFrame(updateMediaProgress);
}
}
updateMediaProgress();
}
}, true);
document.addEventListener('pause', (e) => {
if (e.target.tagName === 'AUDIO' || e.target.tagName === 'VIDEO') {
isPlaying = false;
playBtn.innerHTML = '<i class="fas fa-play"></i>';
mediaPreview.classList.remove('playing');
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
}
}, true);
function updateMediaInfo(mediaElement) {
// Try to get metadata from the media element
let track = {
title: mediaElement.title || document.title || 'Unknown Track',
artist: '',
coverUrl: null
};
// Try to capture video preview if it's a video
if (mediaElement.tagName === 'VIDEO') {
try {
const canvas = document.createElement('canvas');
canvas.width = 160;
canvas.height = 90;
const ctx = canvas.getContext('2d');
ctx.drawImage(mediaElement, 0, 0, canvas.width, canvas.height);
track.coverUrl = canvas.toDataURL();
// Add animated equalizer effect
mediaPreview.classList.add('playing');
} catch (e) {
console.error('Could not create video preview', e);
}
}
// Update the player with this track
updateTrackInfo(track);
}
// Add visualizer effect for currently playing media
function addVisualizer() {
const visualizer = document.createElement('div');
visualizer.classList.add('visualizer');
for (let i = 0; i < 5; i++) {
const bar = document.createElement('div');
bar.classList.add('visualizer-bar');
visualizer.appendChild(bar);
}
mediaPreview.appendChild(visualizer);
}
// Add visualizer
addVisualizer();
// Listen for messages from content scripts
if (chrome && chrome.runtime) {
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'MEDIA_INFO') {
console.log('Received media info:', message.data);
// Update media player with received data
const track = {
title: message.data.title || 'Unknown Track',
artist: message.data.artist || '',
coverUrl: message.data.thumbnail || null,
duration: 300 // Placeholder duration
};
updateTrackInfo(track);
// Update play state
if (message.data.isPlaying) {
isPlaying = true;
playBtn.innerHTML = '<i class="fas fa-pause"></i>';
mediaPreview.classList.add('playing');
} else {
isPlaying = false;
playBtn.innerHTML = '<i class="fas fa-play"></i>';
mediaPreview.classList.remove('playing');
}
// Pulse to indicate update
addPulseEffect();
// Respond to confirm receipt
sendResponse({ success: true });
}
});
}
}
// Initialize with performance optimizations
document.addEventListener('DOMContentLoaded', () => {
// Use requestAnimationFrame for smoother rendering
requestAnimationFrame(() => {
setupQuotes();
});
// Initialize weather widget
fetchWeather();
// Re-fetch weather periodically (every 30 minutes)
setInterval(fetchWeather, 1800000);
// Initialize media controller instead of the sample music player
setupMediaController();
// Request notification permission for media notifications
if ('Notification' in window && Notification.permission !== 'granted') {
Notification.requestPermission();
}
});