-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
2018 lines (1762 loc) · 86.2 KB
/
script.js
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
let proxyurl;
let clocktype;
let hourformat;
window.addEventListener('DOMContentLoaded', async () => {
try {
// Cache DOM elements
const userAPIInput = document.getElementById("userAPI");
const userLocInput = document.getElementById("userLoc");
const userProxyInput = document.getElementById("userproxy");
const saveAPIButton = document.getElementById("saveAPI");
const saveLocButton = document.getElementById("saveLoc");
const resetbtn = document.getElementById("resetsettings");
const saveProxyButton = document.getElementById("saveproxy");
// Load saved data from localStorage
const savedApiKey = localStorage.getItem("weatherApiKey");
const savedLocation = localStorage.getItem("weatherLocation");
const savedProxy = localStorage.getItem("proxy");
// Pre-fill input fields with saved data
if (savedApiKey) userAPIInput.value = savedApiKey;
if (savedLocation) {
userLocInput.value = savedLocation;
//document.getElementById("location").textContent = savedLocation;
}
if (savedProxy) userProxyInput.value = savedProxy;
// Function to simulate button click on Enter key press
function handleEnterPress(event, buttonId) {
if (event.key === 'Enter') {
document.getElementById(buttonId).click();
}
}
// Add event listeners for handling Enter key presses
userAPIInput.addEventListener('keydown', (event) => handleEnterPress(event, 'saveAPI'));
userLocInput.addEventListener('keydown', (event) => handleEnterPress(event, 'saveLoc'));
userProxyInput.addEventListener('keydown', (event) => handleEnterPress(event, 'saveproxy'));
// Save API key to localStorage
saveAPIButton.addEventListener("click", () => {
const apiKey = userAPIInput.value;
localStorage.setItem("weatherApiKey", apiKey);
userAPIInput.value = "";
location.reload();
});
// Save location to localStorage
saveLocButton.addEventListener("click", () => {
const userLocation = userLocInput.value;
localStorage.setItem("weatherLocation", userLocation);
userLocInput.value = "";
location.reload();
});
// Reset settings (clear localStorage)
resetbtn.addEventListener("click", () => {
if (confirm("Are you sure you want to reset your settings? This action cannot be undone.")) {
localStorage.clear();
location.reload();
}
});
saveProxyButton.addEventListener("click", () => {
const proxyurl = userProxyInput.value;
// Check if the input contains 'http://' or 'https://'
if (proxyurl.startsWith("http://") || proxyurl.startsWith("https://")) {
if (!proxyurl.endsWith("/")) {
// Save the proxy to localStorage
localStorage.setItem("proxy", proxyurl);
userProxyInput.value = "";
location.reload();
}
else {
alert("There shouldn't be / at the end of the link");
}
} else {
// Alert the user if it's not a valid link
alert("Only links (starting with http:// or https://) are allowed.");
}
});
// Use the saved or default API key and proxy
const defaultApiKey = 'd36ce712613d4f21a6083436240910'; // Default Weather API key
const defaultProxyURL = 'https://mynt-proxy.rhythmcorehq.com'; //Default proxy url
// Check if the user has entered their own API key
const userApiKey = userAPIInput.value.trim();
const userproxyurl = userProxyInput.value.trim();
// Use the user's API key if available, otherwise use the default API key
const apiKey = userApiKey || defaultApiKey;
proxyurl = userproxyurl || defaultProxyURL;
// Determine the location to use
let currentUserLocation = savedLocation;
// If no saved location, fetch the IP-based location
if (!currentUserLocation) {
try {
const geoLocation = 'https://ipinfo.io/json/';
const locationData = await fetch(geoLocation);
const parsedLocation = await locationData.json();
currentUserLocation = parsedLocation.city; // Update to user's city from IP
localStorage.setItem("weatherLocation", currentUserLocation); // Save and show the fetched location
} catch (error) {
currentUserLocation = "auto:ip"; // Fallback if fetching location fails
}
}
const currentLanguage = getLanguageStatus('selectedLanguage') || 'en';
// Fetch weather data using Weather API
const weatherApi = `https://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${currentUserLocation}&aqi=no&lang=${currentLanguage}`;
const data = await fetch(weatherApi);
const parsedData = await data.json();
// Weather data
const conditionText = parsedData.current.condition.text;
const tempCelsius = Math.round(parsedData.current.temp_c);
const tempFahrenheit = Math.round(parsedData.current.temp_f);
const humidity = parsedData.current.humidity;
const feelsLikeCelsius = parsedData.current.feelslike_c;
const feelsLikeFahrenheit = parsedData.current.feelslike_f;
// Update DOM elements with the weather data
document.getElementById("conditionText").textContent = conditionText;
// Localize and display temperature and humidity
const localizedHumidity = localizeNumbers(humidity.toString(), currentLanguage);
const localizedTempCelsius = localizeNumbers(tempCelsius.toString(), currentLanguage);
const localizedFeelsLikeCelsius = localizeNumbers(feelsLikeCelsius.toString(), currentLanguage);
const localizedTempFahrenheit = localizeNumbers(tempFahrenheit.toString(), currentLanguage);
const localizedFeelsLikeFahrenheit = localizeNumbers(feelsLikeFahrenheit.toString(), currentLanguage);
/// Set humidity level
const humidityLabel = translations[currentLanguage]?.humidityLevel || translations['en'].humidityLevel; // Fallback to English if translation is missing
document.getElementById("humidityLevel").textContent = `${humidityLabel} ${localizedHumidity}%`;
// Event Listener for the Fahrenheit toggle
const fahrenheitCheckbox = document.getElementById("fahrenheitCheckbox");
const updateTemperatureDisplay = () => {
const tempElement = document.getElementById("temp");
if (fahrenheitCheckbox.checked) {
tempElement.innerHTML = `${localizedTempFahrenheit}<span class="tempUnit">°F</span>`;
const feelsLikeFUnit = currentLanguage === 'cs' ? ' °F' : '°F'; // Add space for Czech in Fahrenheit
document.getElementById("feelsLike").textContent = `${translations[currentLanguage]?.feelsLike || translations['en'].feelsLike} ${localizedFeelsLikeFahrenheit}${feelsLikeFUnit}`;
} else {
tempElement.innerHTML = `${localizedTempCelsius}<span class="tempUnit">°C</span>`;
const feelsLikeCUnit = currentLanguage === 'cs' ? ' °C' : '°C'; // Add space for Czech in Celsius
document.getElementById("feelsLike").textContent = `${translations[currentLanguage]?.feelsLike || translations['en'].feelsLike} ${localizedFeelsLikeCelsius}${feelsLikeCUnit}`;
}
};
updateTemperatureDisplay();
// Setting weather Icon
const newWIcon = parsedData.current.condition.icon;
const weatherIcon = newWIcon.replace("//cdn", "https://cdn");
document.getElementById("wIcon").src = weatherIcon;
// Set slider width based on humidity
if (humidity > 40) {
document.getElementById("slider").style.width = `calc(${localizedHumidity}% - 60px)`;
}
// Update location
var city = parsedData.location.name;
// var city = "Thiruvananthapuram";
var maxLength = 10;
var limitedText = city.length > maxLength ? city.substring(0, maxLength) + "..." : city;
document.getElementById("location").textContent = limitedText;
} catch (error) {
console.error("Error fetching weather data:", error);
}
});
// ---------------------------end of weather stuff--------------------
// Retrieve current time and calculate initial angles
var currentTime = new Date();
var initialSeconds = currentTime.getSeconds();
var initialMinutes = currentTime.getMinutes();
var initialHours = currentTime.getHours();
// Initialize cumulative rotations
let cumulativeSecondRotation = initialSeconds * 6; // 6° par seconde
let cumulativeMinuteRotation = initialMinutes * 6 + (initialSeconds / 10); // 6° par minute + ajustement pour les secondes
let cumulativeHourRotation = (30 * initialHours + initialMinutes / 2); // 30° par heure + ajustement pour les minutes
// Apply initial rotations (no need to wait 1s now)
document.getElementById("second").style.transform = `rotate(${cumulativeSecondRotation}deg)`;
document.getElementById("minute").style.transform = `rotate(${cumulativeMinuteRotation}deg)`;
document.getElementById("hour").style.transform = `rotate(${cumulativeHourRotation}deg)`;
let intervalId;
let secondreset = false;
let hourreset = false;
let minreset = false;
function initializeClockType() {
const savedClockType = localStorage.getItem("clocktype");
clocktype = savedClockType ? savedClockType : "analog"; // Default to "analog" if nothing is saved
localStorage.setItem("clocktype", clocktype); // Ensure it's set in local storage
}
// Call this function to initialize the clock type
initializeClockType();
function updateDate() {
if (clocktype === "analog") {
var currentTime = new Date();
var dayOfWeek = currentTime.getDay();
var dayOfMonth = currentTime.getDate();
var month = currentTime.getMonth();
// Define the current language
var currentLanguage = getLanguageStatus('selectedLanguage') || 'en';
// Get the translated name of the day
var dayName;
if (
translations[currentLanguage] &&
translations[currentLanguage].days &&
translations[currentLanguage].days[dayOfWeek]
) {
dayName = translations[currentLanguage].days[dayOfWeek];
} else {
dayName = translations['en'].days[dayOfWeek]; // Fallback to English day name
}
// Get the translated name of the month
var monthName;
if (
translations[currentLanguage] &&
translations[currentLanguage].months &&
translations[currentLanguage].months[month]
) {
monthName = translations[currentLanguage].months[month];
} else {
monthName = translations['en'].months[month]; // Fallback to English month name
}
// Localize the day of the month
var localizedDayOfMonth = localizeNumbers(dayOfMonth.toString(), currentLanguage);
const dateDisplay = {
bn: `${dayName}, ${localizedDayOfMonth} ${monthName}`,
zh: `${monthName}${dayOfMonth}日${dayName}`,
cs: `${dayName}, ${dayOfMonth}. ${monthName}`,
hi: `${dayName}, ${dayOfMonth} ${monthName}`,
it: `${dayName.substring(0, 3)} ${dayOfMonth} ${monthName.substring(0, 3)}`,
pt: `${dayName.substring(0, 3)}, ${dayOfMonth} ${monthName.substring(0, 3)}`,
ru: `${dayName.substring(0, 2)}, ${dayOfMonth} ${monthName.substring(0, 4)}.`,
tr: `${dayName.substring(0, 3)}, ${dayOfMonth} ${monthName}`,
uz: `${dayName.substring(0, 3)}, ${dayOfMonth}-${monthName}`,
vi: `${dayName}, Ngày ${dayOfMonth} ${monthName}`,
default: `${dayName.substring(0, 3)}, ${monthName.substring(0, 3)} ${localizedDayOfMonth}`
};
document.getElementById("date").innerText = dateDisplay[currentLanguage] || dateDisplay.default;
}
}
function updateanalogclock() {
var currentTime = new Date();
var initialSeconds = currentTime.getSeconds();
var initialMinutes = currentTime.getMinutes();
var initialHours = currentTime.getHours();
// Initialize cumulative rotations
let cumulativeSecondRotation = initialSeconds * 6; // 6° par seconde
let cumulativeMinuteRotation = initialMinutes * 6 + (initialSeconds / 10); // 6° par minute + ajustement pour les secondes
let cumulativeHourRotation = (30 * initialHours + initialMinutes / 2);
if (secondreset) {
document.getElementById("second").style.transition = "none";
document.getElementById("second").style.transform = `rotate(0deg)`;
secondreset = false;
return;
}
if (minreset) {
document.getElementById("minute").style.transition = "none";
document.getElementById("minute").style.transform = `rotate(0deg)`;
minreset = false;
return;
}
if (hourreset) {
document.getElementById("hour").style.transition = "none";
document.getElementById("hour").style.transform = `rotate(0deg)`;
hourreset = false;
return;
}
if (cumulativeSecondRotation == 0) {
document.getElementById("second").style.transition = "transform 1s ease";
document.getElementById("second").style.transform = `rotate(361deg)`;
secondreset = true;
} else if (secondreset != true) {
document.getElementById("second").style.transition = "transform 1s ease";
document.getElementById("second").style.transform = `rotate(${cumulativeSecondRotation}deg)`;
}
if (cumulativeMinuteRotation == 0) {
document.getElementById("minute").style.transition = "transform 1s ease";
document.getElementById("minute").style.transform = `rotate(361deg)`;
minreset = true;
} else if (minreset != true) {
document.getElementById("minute").style.transition = "transform 1s ease";
document.getElementById("minute").style.transform = `rotate(${cumulativeMinuteRotation}deg)`;
} if (cumulativeHourRotation == 0) {
document.getElementById("hour").style.transition = "transform 1s ease";
document.getElementById("hour").style.transform = `rotate(361deg)`;
hourreset = true;
} else if (hourreset != true) {
document.getElementById("hour").style.transition = "transform 1s ease"; // Transition fluide
document.getElementById("hour").style.transform = `rotate(${cumulativeHourRotation}deg)`;
}
// Update date immediately
updateDate();
}
function getGreeting() {
const currentHour = new Date().getHours();
let greetingKey;
// Determine the greeting key based on the current hour
if (currentHour < 12) {
greetingKey = 'morning';
} else if (currentHour < 17) {
greetingKey = 'afternoon';
} else {
greetingKey = 'evening';
}
// Get the user's language setting
const userLang = getLanguageStatus('selectedLanguage') || 'en'; // Default to English
// Check if the greeting is available for the selected language
if (
translations[userLang] &&
translations[userLang].greeting &&
translations[userLang].greeting[greetingKey]
) {
return translations[userLang].greeting[greetingKey];
} else {
// Fallback to English greeting if the userLang or greeting key is missing
return translations['en'].greeting[greetingKey];
}
}
function updatedigiClock() {
const hourformatstored = localStorage.getItem("hourformat");
let hourformat = hourformatstored === "true"; // Default to false if null
const greetingCheckbox = document.getElementById("greetingcheckbox");
const isGreetingEnabled = localStorage.getItem("greetingEnabled") === "true";
greetingCheckbox.checked = isGreetingEnabled;
const now = new Date();
const dayOfWeek = now.getDay(); // Get day of the week (0-6)
const dayOfMonth = now.getDate(); // Get current day of the month (1-31)
const currentLanguage = getLanguageStatus('selectedLanguage') || 'en';
// Get translated day name
let dayName;
if (
translations[currentLanguage] &&
translations[currentLanguage].days &&
translations[currentLanguage].days[dayOfWeek]
) {
dayName = translations[currentLanguage].days[dayOfWeek];
} else {
dayName = translations['en'].days[dayOfWeek]; // Fallback to English day name
}
// Localize the day of the month
const localizedDayOfMonth = localizeNumbers(dayOfMonth.toString(), currentLanguage);
// Determine the translated short date string based on language
const dateFormats = {
bn: `${dayName}, ${localizedDayOfMonth}`,
zh: `${dayOfMonth}日${dayName}`,
cs: `${dayName}, ${dayOfMonth}.`,
hi: `${dayName}, ${dayOfMonth}`,
pt: `${dayName}, ${dayOfMonth}`,
ru: `${dayOfMonth} ${dayName.substring(0, 2)}`,
vi: `${dayOfMonth} ${dayName}`,
default: `${localizedDayOfMonth} ${dayName.substring(0, 3)}`, // e.g., "24 Thu"
};
const dateString = dateFormats[currentLanguage] || dateFormats.default;
// Handle time formatting based on the selected language
let timeString;
let period = ''; // For storing AM/PM equivalent
// Array of languages to use 'en-US' format
const specialLanguages = ['tr', 'zh'];
const localizedLanguages = ['bn'];
// Force the 'en-US' format for Bengali, otherwise, it will be localized twice, resulting in NaN
// Set time options and determine locale based on the current language
const timeOptions = { hour: '2-digit', minute: '2-digit', hour12: hourformat };
const locale = specialLanguages.includes(currentLanguage) || localizedLanguages.includes(currentLanguage) ? 'en-US' : currentLanguage;
timeString = now.toLocaleTimeString(locale, timeOptions);
// Split the time and period (AM/PM) if in 12-hour format
if (hourformat) {
[timeString, period] = timeString.split(' '); // Split AM/PM if present
}
// Split the hours and minutes from the localized time string
let [hours, minutes] = timeString.split(':');
// Remove leading zero from hours for specific languages in 12-hour format only
if (hourformat && currentLanguage !== 'en' && currentLanguage !== 'it') {
hours = parseInt(hours, 10).toString(); // Remove leading zero
}
// Localize hours and minutes for the selected language
const localizedHours = localizeNumbers(hours, currentLanguage);
const localizedMinutes = localizeNumbers(minutes, currentLanguage);
// Update the hour, colon, and minute text elements
document.getElementById('digihours').textContent = localizedHours;
document.getElementById('digicolon').textContent = ':'; // Static colon
document.getElementById('digiminutes').textContent = localizedMinutes;
// For Turkish and Chinese, no AM/PM; for others, show AM/PM
if (specialLanguages.includes(currentLanguage)) {
document.getElementById('amPm').textContent = ''; // No AM/PM for Turkish and Chinese
} else {
document.getElementById('amPm').textContent = period; // Show AM/PM for other languages
}
// Update the translated date
document.getElementById('digidate').textContent = dateString;
const clocktype1 = localStorage.getItem("clocktype");
if (clocktype1 === "digital" && isGreetingEnabled) {
document.getElementById("date").innerText = getGreeting();
} else if (clocktype1 === "digital") {
document.getElementById("date").innerText = ""; // Hide the greeting
}
}
// Function to start the clock
function startClock() {
if (!intervalId) { // Only set interval if not already set
intervalId = setInterval(updateanalogclock, 500);
}
}
// Function to stop the clock
function stopClock() {
clearInterval(intervalId);
intervalId = null; // Reset intervalId
}
// Initial clock display
displayClock();
setInterval(updatedigiClock, 1000); // Update digital clock every second
// Start or stop clocks based on clock type and visibility state
if (clocktype === "digital") {
updatedigiClock();
} else if (clocktype === "analog") {
if (document.visibilityState === 'visible') {
startClock();
updateDate(); // Immediately update date when clock is analog
}
}
// Event listener for visibility change
document.addEventListener("visibilitychange", function () {
if (document.visibilityState === 'visible') {
startClock(); // Start the clock if the tab is focused
updateDate(); // Update date when the tab becomes visible
} else {
stopClock(); // Stop the clock if the tab is not focused
}
});
function displayClock() {
const analogClock = document.getElementById('analogClock');
const digitalClock = document.getElementById('digitalClock');
if (clocktype === 'analog') {
analogClock.style.display = 'block'; // Show the analog clock
digitalClock.style.display = 'none'; // Hide the digital clock
} else if (clocktype === 'digital') {
digitalClock.style.display = 'block'; // Show the digital clock
analogClock.style.display = 'none'; // Hide the analog clock
}
}
// Call updateanalogclock when the document is fully loaded
document.addEventListener("DOMContentLoaded", function () {
updateanalogclock();
});
// End of clock display
document.addEventListener("DOMContentLoaded", () => {
const userTextDiv = document.getElementById("userText");
const userTextCheckbox = document.getElementById("userTextCheckbox");
// Load and apply the checkbox state
const isUserTextVisible = localStorage.getItem("userTextVisible") !== "false";
userTextCheckbox.checked = isUserTextVisible;
userTextDiv.style.display = isUserTextVisible ? "block" : "none";
// Toggle userText display based on checkbox state
userTextCheckbox.addEventListener("change", () => {
const isVisible = userTextCheckbox.checked;
userTextDiv.style.display = isVisible ? "block" : "none";
localStorage.setItem("userTextVisible", isVisible);
});
// Set the default language to English if no language is saved
const savedLang = localStorage.getItem('selectedLanguage') || 'en';
applyLanguage(savedLang);
// Load the stored text if it exists
const storedValue = localStorage.getItem("userText");
if (storedValue) {
userTextDiv.textContent = storedValue;
} else {
// Fallback to the placeholder based on the selected language
const placeholder = userTextDiv.dataset.placeholder || translations['en'].userText; // Fallback to English
userTextDiv.textContent = placeholder;
}
// Handle input event
userTextDiv.addEventListener("input", function () {
localStorage.setItem("userText", userTextDiv.textContent);
});
// Remove placeholder text when the user starts editing
userTextDiv.addEventListener("focus", function () {
if (userTextDiv.textContent === userTextDiv.dataset.placeholder) {
userTextDiv.textContent = ""; // Clear the placeholder when focused
}
});
// Restore placeholder if the user leaves the div empty after editing
userTextDiv.addEventListener("blur", function () {
if (userTextDiv.textContent === "") {
userTextDiv.textContent = userTextDiv.dataset.placeholder; // Show the placeholder again if empty
}
});
});
// Showing border or outline in when you click on searchbar
const searchbar = document.getElementById('searchbar');
searchbar.addEventListener('click', function () {
searchbar.classList.toggle('active');
// if (searchInput2.value !== "") {
// showResultBox()
// }
});
document.addEventListener('click', function (event) {
// Check if the clicked element is not the searchbar
if (!searchbar.contains(event.target)) {
searchbar.classList.remove('active');
}
});
//search function
document.addEventListener("DOMContentLoaded", () => {
const enterBTN = document.getElementById("enterBtn");
const searchInput = document.getElementById("searchQ");
const searchEngineRadio = document.getElementsByName("search-engine");
// Make entire search-engine div clickable
document.querySelectorAll(".search-engine").forEach((engineDiv) => {
engineDiv.addEventListener("click", () => {
const radioButton = engineDiv.querySelector('input[type="radio"]');
radioButton.checked = true;
localStorage.setItem("selectedSearchEngine", radioButton.value);
});
});
// Function to perform search
function performSearch() {
var selectedOption = document.querySelector('input[name="search-engine"]:checked').value;
var searchTerm = searchInput.value;
var searchEngines = {
engine1: 'https://www.google.com/search?q=',
engine2: 'https://duckduckgo.com/?q=',
engine3: 'https://bing.com/?q=',
engine4: 'https://search.brave.com/search?q=',
engine5: 'https://www.youtube.com/results?search_query='
};
if (searchTerm !== "") {
var searchUrl = searchEngines[selectedOption] + encodeURIComponent(searchTerm);
window.location.href = searchUrl;
}
}
// Event listeners
enterBTN.addEventListener("click", performSearch);
searchInput.addEventListener("keypress", (event) => {
if (event.key === "Enter") {
performSearch();
}
});
// Set selected search engine from local storage
const storedSearchEngine = localStorage.getItem("selectedSearchEngine");
if (storedSearchEngine) {
const selectedRadioButton = document.querySelector(`input[name = "search-engine"][value = "${storedSearchEngine}"]`);
if (selectedRadioButton) {
selectedRadioButton.checked = true;
}
}
// Event listener for search engine radio buttons
searchEngineRadio.forEach((radio) => {
radio.addEventListener("change", () => {
const selectedOption = document.querySelector('input[name="search-engine"]:checked').value;
localStorage.setItem("selectedSearchEngine", selectedOption);
});
});
// -----The stay changed even if user reload the page---
// 🔴🟠🟡🟢🔵🟣⚫️⚪️🟤
const storedTheme = localStorage.getItem(themeStorageKey);
if (storedTheme) {
applySelectedTheme(storedTheme);
const selectedRadioButton = document.querySelector(`.colorPlate[value = "${storedTheme}"]`);
if (selectedRadioButton) {
selectedRadioButton.checked = true;
}
}
});
// -----------Voice Search------------
// Function to detect Chrome and Edge on desktop
function isSupportedBrowser() {
const userAgent = navigator.userAgent;
const isChrome = /Chrome/.test(userAgent) && /Google Inc/.test(navigator.vendor);
const isEdge = /Edg/.test(userAgent);
const isDesktop = !/Android|iPhone|iPad|iPod/.test(userAgent); // Check if the device is not mobile
return (isChrome || isEdge) && isDesktop;
}
// Hide mic icon if the browser is not supported
const micIcon = document.getElementById("micIcon");
if (!isSupportedBrowser()) {
micIcon.style.display = 'none';
} else {
// Proceed with Web Speech API if browser supports it
const micIcon = document.getElementById("micIcon");
const searchInput = document.getElementById("searchQ");
const resultBox = document.getElementById("resultBox");
const currentLanguage = getLanguageStatus('selectedLanguage') || 'en';
// Check if the browser supports SpeechRecognition API
const isSpeechRecognitionAvailable = 'webkitSpeechRecognition' in window || 'SpeechRecognition' in window;
if (isSpeechRecognitionAvailable) {
// Initialize SpeechRecognition (cross-browser compatibility)
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.continuous = false; // Stop recognition after first result
recognition.interimResults = true; // Enable interim results for live transcription
recognition.lang = currentLanguage; // Set the language dynamically based on selected language
let isRecognizing = false; // Flag to check if recognition is active
// When speech recognition starts
recognition.onstart = () => {
isRecognizing = true; // Set the flag to indicate recognition is active
// micIcon.style.color = 'var(--darkerColor-blue)';
// micIcon.style.transform = 'scale(1.1)';
searchInput.placeholder = `${translations[currentLanguage]?.listenPlaceholder || translations['en'].listenPlaceholder}`;
const micIcon = document.querySelector('.micIcon');
micIcon.classList.add('micActive');
};
// When speech recognition results are available (including interim results)
recognition.onresult = (event) => {
let transcript = '';
// Loop through results to build the transcript text
for (let i = 0; i < event.results.length; i++) {
transcript += event.results[i][0].transcript; // Append each piece of the transcript
}
// Display the interim result in the search input
searchInput.value = transcript;
// If the result is final, hide the result box
if (event.results[event.results.length - 1].isFinal) {
resultBox.style.display = 'none'; // Hide result box after final input
}
};
// When an error occurs during speech recognition
recognition.onerror = (event) => {
console.error('Speech recognition error: ', event.error);
isRecognizing = false; // Reset flag on error
};
// When speech recognition ends (either by user or automatically)
recognition.onend = () => {
isRecognizing = false; // Reset the flag to indicate recognition has stopped
// micIcon.style.color = 'var(--darkColor-blue)'; // Reset mic color
// micIcon.style.transform = 'scale(1)'; // Reset scaling
const micIcon = document.querySelector('.micIcon');
micIcon.classList.remove('micActive');
searchInput.placeholder = `${translations[currentLanguage]?.searchPlaceholder || translations['en'].searchPlaceholder}`;
};
// Start speech recognition when mic icon is clicked
micIcon.addEventListener('click', () => {
if (isRecognizing) {
recognition.stop(); // Stop recognition if it's already listening
} else {
recognition.start(); // Start recognition if it's not already listening
}
});
} else {
console.warn('Speech Recognition API not supported in this browser.');
}
}
// -----------End of Voice Search------------
// Function to apply the selected theme
// 🔴🟠🟡🟢🔵🟣⚫️⚪️🟤
const radioButtons = document.querySelectorAll('.colorPlate');
const themeStorageKey = 'selectedTheme';
const storedTheme = localStorage.getItem(themeStorageKey);
let darkThemeStyleTag; // Variable to store the dynamically added style tag
const resetDarkTheme = () => {
// Remove the dark theme class
document.documentElement.classList.remove('dark-theme');
// Remove the injected dark theme style tag
if (darkThemeStyleTag) {
darkThemeStyleTag.remove();
darkThemeStyleTag = null;
}
// Reset inline styles that were applied specifically for dark mode
const resetElements = [
"searchQ",
"searchIconDark",
"darkFeelsLikeIcon",
"menuButton",
"menuCloseButton",
"closeBtnX"
];
resetElements.forEach((id) => {
const element = document.getElementById(id);
if (element) {
element.removeAttribute('style');
}
});
// Reset fill color for elements with the class "accentColor"
const accentElements = document.querySelectorAll('.accentColor');
accentElements.forEach((element) => {
element.style.fill = ''; // Reset fill color
});
};
const applySelectedTheme = (colorValue) => {
// If the selected theme is not dark, reset dark theme styles
if (colorValue !== "dark") {
resetDarkTheme();
// Apply styles for other themes (not dark)
if (colorValue === "blue") {
// Special handling for blue theme
document.documentElement.style.setProperty('--bg-color-blue', '#BBD6FD');
document.documentElement.style.setProperty('--accentLightTint-blue', '#E2EEFF');
document.documentElement.style.setProperty('--darkerColor-blue', '#3569b2');
document.documentElement.style.setProperty('--darkColor-blue', '#4382EC');
document.documentElement.style.setProperty('--textColorDark-blue', '#1b3041');
} else {
document.documentElement.style.setProperty('--bg-color-blue', `var(--bg-color-${colorValue})`);
document.documentElement.style.setProperty('--accentLightTint-blue', `var(--accentLightTint-${colorValue})`);
document.documentElement.style.setProperty('--darkerColor-blue', `var(--darkerColor-${colorValue})`);
document.documentElement.style.setProperty('--darkColor-blue', `var(--darkColor-${colorValue})`);
document.documentElement.style.setProperty('--textColorDark-blue', `var(--textColorDark-${colorValue})`);
}
}
// If the selected theme is dark
else if (colorValue === "dark") {
// Apply dark theme styles using CSS variables
document.documentElement.style.setProperty('--bg-color-blue', `var(--bg-color-${colorValue})`);
document.documentElement.style.setProperty('--accentLightTint-blue', `var(--accentLightTint-${colorValue})`);
document.documentElement.style.setProperty('--darkerColor-blue', `var(--darkerColor-${colorValue})`);
document.documentElement.style.setProperty('--darkColor-blue', `var(--darkColor-${colorValue})`);
document.documentElement.style.setProperty('--textColorDark-blue', `var(--textColorDark-${colorValue})`);
document.documentElement.style.setProperty('--shortcutColor-blue', `var(--shortcutColor-${colorValue})`);
document.documentElement.style.setProperty('--shortcutIconColor-blue', `var(--shortcutIconColor-${colorValue})`);
// Add dark theme styles for specific elements
darkThemeStyleTag = document.createElement('style');
darkThemeStyleTag.textContent = `
.dark-theme .search-engine input[type="radio"]:checked {
background-color: #333;
border: 2px solid #919191;
}
.dark-theme .search-engine input[type="radio"] {
background-color: #9d9d9d ;
border: 0px solid #000000;
}
.dark-theme .colorsContainer {
background-color: #212121;
}
.dark-theme #themeButton {
background-color: #212121;
}
.dark-theme #themeIconSvg, .dark-theme #languageSelectorIconSvg {
fill: #cdcdcd !important;
}
.dark-theme .languageIcon,
.dark-theme .languageSelector {
background-color: #212121;
}
.dark-theme .bottom a {
color: #a1a1a1;
}
.dark-theme .ttcont input {
background-color: #212121;
}
.dark-theme input:checked + .toggle {
background-color: #aaaaaa;
}
.dark-theme .tilesCont .tiles {
color: #e8e8e8;
}
#searchQ{
color: #fff;
}
.searchbar.active {
outline: 2px solid #696969;
}
#searchIconDark {
fill: #bbb !important;
}
.tilesContainer .tiles {
background-color: #212121;
}
#darkFeelsLikeIcon{
fill: #fff !important;
}
.humidityBar .thinLine{
background-color: #aaaaaa;
}
.search-engine .darkIconForDarkTheme, .aiDarkIcons{
fill: #bbbbbb !important;
}
.divider{
background-color: #cdcdcd;
}
.shorcutDarkColor{
fill: #3c3c3c !important;
}
.shortcutsContainer .shortcuts .shortcutLogoContainer {
background: radial-gradient(circle, #bfbfbf 44%, #000 64%);
}
.digiclock {
fill: #909090;
}
#minute, #minute::after, #second::after {
background-color: #909090;
}
#menuButton::before{
background-color: #bfbfbf;
}
#menuButton::after{
border: 4px solid #858585;
}
#menuCloseButton, #menuCloseButton:hover {
background-color: var(--darkColor-dark);
}
#menuCloseButton .icon{
background-color: #cdcdcd;
}
#closeBtnX{
border: 2px solid #bdbdbd;
border-radius: 100px;
}
body{
background-color: #191919
}
#HangNoAlive{
fill: #c2c2c2 !important;
}
.tempUnit{
color: #dadada;
}
.dark-theme #githab,
.dark-theme #sujhaw {
fill: #b1b1b1;
}
`;
document.head.appendChild(darkThemeStyleTag);
// Apply dark theme class
document.documentElement.classList.add('dark-theme');
// Change fill color for elements with the class "accentColor"
const accentElements = document.querySelectorAll('.accentColor');
accentElements.forEach((element) => {
element.style.fill = '#212121';
});
}
// Change the extension icon based on the selected theme
const iconPaths = {
"blue": "./favicon/blue.png",
"yellow": "./favicon/yellow.png",
"red": "./favicon/red.png",
"green": "./favicon/green.png",
"cyan": "./favicon/cyan.png",
"orange": "./favicon/orange.png",
"purple": "./favicon/purple.png",
"pink": "./favicon/pink.png",
"dark": "./favicon/dark.png",
"amoled": "./favicon/amoled.png"
};
// Function to update the extension icon based on browser
const updateExtensionIcon = (colorValue) => {
if (typeof chrome !== "undefined" && chrome.action) {
// Chromium-based: Chrome, Edge, Brave
chrome.action.setIcon({ path: iconPaths[colorValue] });
} else if (typeof browser !== "undefined" && browser.browserAction) {
// Firefox
browser.browserAction.setIcon({ path: iconPaths[colorValue] });
} else if (typeof safari !== "undefined") {
// Safari
safari.extension.setToolbarIcon({ path: iconPaths[colorValue] });
}
};
updateExtensionIcon(colorValue);
// Change the favicon dynamically
const faviconLink = document.querySelector("link[rel='icon']");
if (faviconLink && iconPaths[colorValue]) {
faviconLink.href = iconPaths[colorValue];
}
};
// Apply the stored theme on page load
if (storedTheme) {
applySelectedTheme(storedTheme);
const selectedRadioButton = document.querySelector(`.colorPlate[value="${storedTheme}"]`);
if (selectedRadioButton) {
selectedRadioButton.checked = true;
}
}
radioButtons.forEach(radioButton => {
radioButton.addEventListener('change', function () {
if (this.checked) {
const colorValue = this.value;
localStorage.setItem(themeStorageKey, colorValue);
applySelectedTheme(colorValue);
}
});
});
// end of Function to apply the selected theme
// when User click on "AI-Tools"
const element = document.getElementById("toolsCont");
const shortcuts = document.getElementById("shortcutsContainer");
document.getElementById("0NIHK").onclick = () => {
const unfoldShortcutsButton = document.getElementById("unfoldShortcutsBtn");
if (shortcutsCheckbox.checked) {
if (element.style.display === "flex") {
shortcuts.style.display = 'flex';
element.style.opacity = "0";
element.style.gap = "0";
element.style.transform = "translateX(-100%)";
unfoldShortcutsButton.style.display = "none";
setTimeout(() => {
element.style.display = "none";
shortcuts.style.display = 'flex';
}, 500);
} else {
shortcuts.style.display = 'none';
unfoldShortcutsButton.style.display = "block";
element.style.display = "flex";
setTimeout(() => {
element.style.opacity = "1";
element.style.transform = "translateX(0)";
}, 1);
setTimeout(() => {
element.style.gap = "12px";
}, 300);
}
} else {
if (element.style.display === "flex") {
shortcuts.style.display = 'none';
unfoldShortcutsButton.style.display = "none";
element.style.opacity = "0";
element.style.gap = "0";
element.style.transform = "translateX(-100%)";
setTimeout(() => {
element.style.display = "none";