-
Notifications
You must be signed in to change notification settings - Fork 0
/
evergreen.js
1908 lines (1744 loc) · 72.8 KB
/
evergreen.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
// initialize config to sensible defaults before it properly loads
let config = {
blur: 0,
timeformat: "12",
dateformat: "md",
// searchtags: "wallpapers",
refreshtime: 0,
tempunit: "f",
iconset: "climacons",
autolocate: true,
weather_address: {
"latitude": undefined, "longitude": undefined
},
weather_enabled: true,
weather_provider: "openweathermap"
}
let promotional = false; // use the same BG for promotional purposes
let version = chrome.runtime.getManifest().version;
let devmode = undefined;
let download_url = undefined;
let weather_info = {
"openweathermap": {
"fetched": 0,
"data": null
},
"nws": {
"fetched": 0,
"data": null
},
};
let weather_location_string;
const qs = document.querySelector.bind(document);
console.debug("Evergreen New Tab for chrome");
function isNumeric(num) {
return !isNaN(num)
}
function set_html_if_needed(object, html) {
// sets the innerHTML of an object if possible and different
if (object && "innerHTML" in object && object.innerHTML !== html) {
object.innerHTML = html;
}
}
function preload_image(url, callback) {
let img = new Image();
img.setAttribute("crossorigin", "anonymous")
img.src = url;
img.onload = function () {
callback()
};
}
function follow_redirects(url, callback) {
// finds where URL redirects to
fetch(url, {method: 'HEAD'}).then(r => callback(r.url))
}
function update_newtab_datetime() {
// updates the date and time at the top and top right of the newtab respectively
let date = new Date();
// time
let h = date.getHours(); // 0 - 23
let m = String(date.getMinutes()).padStart(2, '0'); // 0 - 59
let s = String(date.getSeconds()).padStart(2, '0'); // 0 - 59
let time;
// i think i stole this code lol
if (config["timeformat"] === "12") {
let session = "AM";
if (h === 0) {
h = 12;
} else if (h === 12) {
session = "PM";
} else if (h > 12) {
h = h - 12;
session = "PM";
}
time = `${h}:${m}:${s} ${session}`;
} else {
time = `${String(h).padStart(2, '0')}:${m}:${s}`;
}
set_html_if_needed(qs("#clock"), time);
// date
let d = date.getDate();
let mo = date.getMonth() + 1; // 0 indexed
let y = date.getFullYear();
let da;
if (config["dateformat"] === "md") {
da = `${mo}/${d}/${y}`;
} else if (config["dateformat"] === "dm") {
da = `${d}/${mo}/${y}`;
} else if (config["dateformat"] === "ymd") {
da = `${y}-${mo.toString().padStart(2, "0")}-${d.toString().padStart(2, "0")}`;
}
set_html_if_needed(qs("#date"), da);
}
function epoch_to_date(epoch) {
// convert UNIX epoch to js date object
// * 1000 necessary because JS uses ms while most places use seconds
return new Date(epoch * 1000);
}
function epoch_to_locale_hour_string(epoch) {
// represents an epoch number as an "hour string"
// for 12h time examples are 1 AM, 2 PM, etc.
// for 24h time examples are 01:00, 13:00, etc.
let d = epoch_to_date(epoch);
let h = d.getHours(); // 0 - 23
let time;
if (config["timeformat"] === "12") {
let session = "AM";
if (h === 0) {
h = 12;
} else if (h === 12) {
session = "PM";
} else if (h > 12) {
h = h - 12;
session = "PM";
}
time = `${h} ${session}`;
} else {
time = `${String(h).padStart(2, '0')}:00`;
}
return time;
}
function epoch_to_relative(epoch) {
let d = epoch_to_date(epoch);
let now = new Date();
let diff = Math.ceil((d - now) / (60 * 60 * 1000));
let rtf = new Intl.RelativeTimeFormat();
return rtf.format(diff, 'hour')
}
function dayofepoch(epoch) {
// gets weekday of epoch
const weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
let d = epoch_to_date(epoch);
return weekdays[d.getDay()]
}
function roundton(num, n) {
return Number(num.toFixed(n));
}
function tunit(temp, round = false) {
// converts temperature unit if needed
if (config["tempunit"] === "f") {
temp = c_to_f(temp);
}
return round ? Math.round(temp) : temp;
}
function invtunit(temp) {
if (config["tempunit"] === "f") {
return f_to_c(temp)
} else {
return temp
}
}
function vunit(speed) {
// converts velocity unit if needed
if (config["tempunit"] === "f") {
// meters per second
speed /= 0.44704;
}
return speed;
}
function sunit(size) {
// converts size units if needed
if (config["tempunit"] === "f") {
// inch to mm
size /= 25.4
}
return size;
}
function rainintensity(rainfall, over_whole_day = false) {
if (over_whole_day) {
rainfall /= 24
}
// https://en.wikipedia.org/wiki/Rain#Intensity
// https://glossary.ametsoc.org/wiki/Rain
if (rainfall <= 0) {
return "none"
} else if (0 < rainfall && rainfall < sunit(0.254)) {
return "trace"
} else if (sunit(0.254) <= rainfall && rainfall < sunit(2.54)) {
return "light"
} else if (sunit(2.54) <= rainfall && rainfall <= sunit(7.62)) {
return "moderate"
} else if (sunit(7.62) < rainfall && rainfall < sunit(50.8)) {
return "heavy"
} else if (rainfall >= sunit(50.8)) {
return "violent"
} else {
return "invalid"
}
}
function stripzeropoint(val) {
val = `${val}`
if (val.startsWith("0.")) val = val.substring(1)
return val
}
function climacon(icon) {
// converts icon prop to HTML icon based on user settings
if (config["iconset"] === "climacons") {
if (icon && icon["climacon"]) {
return `<span aria-hidden="true" class="climacon ${icon["climacon"]}"></span>`;
} else {
// sensible default
console.warn("no weather icon available, choosing default.")
return `<span aria-hidden="true" class="climacon cloud"></span>`
}
} else {
if (icon && icon["fontawesome"]) {
return `<i class="fas fa-${icon["fontawesome"]}"></i>`
} else {
// sensible default
console.warn("no weather icon available, choosing default.")
return `<i class="fas fa-cloud"></i>`
}
}
}
function every_100ms() {
// ran every 100ms
update_newtab_datetime();
// qs("#clockpopover").setAttribute("data-bs-content", `<div id="tpop">${clock_datetime()}</div>`);
let tpop = qs("#tpop");
if (tpop) {
set_html_if_needed(tpop, clock_datetime());
}
}
const weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
function clock_datetime() {
const now = new Date();
return `
<div id="tpop">
<h4 style="margin:0;">
${weekdays[now.getDay()]} ${months[now.getMonth()]} ${("0" + now.getDate()).slice(-2)} ${now.getFullYear()}
${now.toLocaleTimeString()}
</h4>
</div>
`;
}
// called by settings menu
function settings_set_tempunit() {
if (this.id === "farradio") {
config["tempunit"] = "f";
} else {
config["tempunit"] = "c";
}
console.debug("reloading weather div with cached info");
construct_weather_popover()
save_settings();
}
function settings_set_iconset() {
if (this.id === "cradio") {
config["iconset"] = "climacons";
} else {
config["iconset"] = "fontawesome";
}
console.debug("reloading weather div with cached info");
construct_weather_popover();
save_settings();
}
function settings_set_timeformat() {
if (this.id === "12radio") {
config["timeformat"] = "12";
} else {
config["timeformat"] = "24";
}
console.debug("reloading weather div with cached info");
construct_weather_popover();
// i have to do this since the weather popup uses the time format
save_settings();
}
function settings_set_dateformat() {
if (this.id === "mdradio") {
config["dateformat"] = "md";
} else if (this.id === "dmradio") {
config["dateformat"] = "dm";
} else if (this.id === "ymdradio") {
config["dateformat"] = "ymd";
}
save_settings();
}
// function settings_set_searchtags() {
// config["searchtags"] = this.value;
// save_settings();
// }
function settings_set_blur() {
set_blur(this.value);
save_settings();
}
function set_blur(val) {
// sets blur
if (val === 0) {
qs("#bg").style["transform"] = "initial";
qs("#bg").style["filter"] = "initial";
} else {
qs("#bg").style["transform"] = `scale(${1 + 0.1 * (val / 15)})`;
qs("#bg").style["filter"] = `blur(${val}px)`;
}
qs("#blurval").innerHTML = `<i class="fas fa-droplet"></i> Background blur: ${val}px`;
config["blur"] = val;
}
function settings_set_refreshtime() {
config["refreshtime"] = this.value;
save_settings();
}
function settings_set_provider() {
switch (this.id) {
case "wp-openweathermap-radio":
config["weather_provider"] = "openweathermap";
break;
case "wp-nws-radio":
config["weather_provider"] = "nws";
break
}
save_settings();
fetch_weather_using_cache();
}
function handle_disabling_weather_options(autolocation, weatherenable) {
// all .disable-on-autolocate have .disable-if-weather-disabled
// also my brain hurts after this
if (weatherenable) {
// if weather is enabled, enable everything
document.querySelectorAll(".disable-if-weather-disabled").forEach(elem => {
elem.removeAttribute("disabled")
})
// after enabling everything, then if autolocate is on, disable relevant options
if (autolocation) {
document.querySelectorAll(".disable-on-autolocate").forEach(elem => {
elem.setAttribute("disabled", "disabled")
})
}
} else {
// if weather is disabled, it doesnt matter what state autolocate is in, we disable it
document.querySelectorAll(".disable-if-weather-disabled").forEach(elem => {
elem.setAttribute("disabled", "disabled")
})
}
}
function set_autolocation(enabled) {
handle_disabling_weather_options(enabled, config["weather_enabled"])
}
function weather_enable(enabled) {
handle_disabling_weather_options(config["autolocate"], enabled)
qs("#weatherpopover").style.display = enabled ? "inline" : "none"
}
function settings_set_autolocation() {
config["autolocate"] = this.checked
set_autolocation(this.checked)
save_settings()
}
function settings_set_weather() {
config["weather_enabled"] = this.checked
weather_enable(this.checked)
save_settings()
// weather was just enabled but we don't have any info
if (this.checked) {
qs("#weather").innerHTML = `<i class="fa-solid fa-sun fa-spin"></i>`
fetch_weather_using_cache()
}
}
function save_settings() {
chrome.storage.local.set({
blurval: config["blur"],
tempunit: config["tempunit"],
timeformat: config["timeformat"],
dateformat: config["dateformat"],
// searchtags: config["searchtags"],
refreshtime: config["refreshtime"],
iconset: config["iconset"],
autolocate: config["autolocate"],
weather_address: config["weather_address"],
weather_enabled: config["weather_enabled"],
weather_provider: config["weather_provider"]
}).then(_ => {
qs("#savetext").innerHTML = "Saved.";
});
}
function change_background() {
if (!promotional) {
console.debug("changing BG...");
fetch(`https://api.unsplash.com/photos/random?topics=bo8jQKTaE0Y`, {
headers: {
"Authorization": "Client-ID RlxQwIigHZSLdNPZgSC6r1BihERopYeizq4T0A-wEtw"
}
}).then(r => {
return r.json()
}).then(r => {
console.debug(r)
let url = `${r["urls"]["raw"]}&fit=crop&w=${window.screen.width}&h=${window.screen.height}&dpr=${window.devicePixelRatio}`;
preload_image(url, function () {
qs("#bg").style["background-image"] = `url(${url})`;
// setup download url
download_url = r["links"]["download_location"];
qs("#bg-download").removeAttribute("disabled")
// attribution
qs("#attribution").innerHTML = `<p><i class="fa-solid fa-message-image"></i> <a href="${r["links"]["html"]}?utm_source=evergreen_new_tab_for_chrome&utm_medium=referral">Photo</a> by <a href="${r["user"]["links"]["html"]}?utm_source=evergreen_new_tab_for_chrome&utm_medium=referral">${r["user"]["name"]}</a> on <a href="https://unsplash.com/?utm_source=evergreen_new_tab_for_chrome&utm_medium=referral">Unsplash</a></p>`;
// api requires hotlinking
document.querySelector("#bga").setAttribute("href", r["links"]["html"] + "?utm_source=evergreen_new_tab_for_chrome&utm_medium=referral")
});
chrome.storage.local.set({
bgimage: url, lastbgrefresh: new Date().getTime() / 1000
});
console.debug("BG changed");
})
// follow_redirects(`https://source.unsplash.com/${window.screen.width}x${window.screen.height}/?${config["searchtags"]}`, function (response) {
// preload_image(response, function () {
// qs("#bg").style["background-image"] = `url(${response})`;
// });
// chrome.storage.local.set({
// bgimage: response, lastbgrefresh: new Date().getTime() / 1000
// });
// console.debug("BG changed");
// });
}
}
function settings_download_background() {
// unsplash requires me to hit this endpoint on download
fetch(download_url, {
headers: {
"Authorization": "Client-ID RlxQwIigHZSLdNPZgSC6r1BihERopYeizq4T0A-wEtw"
}
}).then(r => {
return r.json()
}).then(r => {
console.debug(r)
window.location = r["url"];
})
}
function settings_set_location() {
config["weather_address"] = {}
config["weather_address"]["latitude"] = qs("#weather-latitude").value
config["weather_address"]["longitude"] = qs("#weather-longitude").value
if (isNumeric(config["weather_address"]["latitude"]) && isNumeric(config["weather_address"]["longitude"])) {
allow_weather_refresh()
} else { // disable if no coords
qs("#refresh-weather").setAttribute("disabled", "disabled")
}
save_settings()
}
function init_background_blur() {// background blur
chrome.storage.local.get(['blurval'], result => {
// sensible default
if (result["blurval"] === undefined) {
result["blurval"] = "0";
}
config["blur"] = result["blurval"];
// set blur on load
set_blur(result["blurval"], false);
qs("#blurslider").setAttribute("value", result["blurval"]);
// add listener to settings
qs('#blurslider').addEventListener('input', settings_set_blur);
});
}
function weather_error(...args) {
console.error(...args)
qs("#weather").innerHTML = `<i class="fa-solid fa-cloud-exclamation fa-shake" style="--fa-animation-iteration-count: 1;"></i>`
qs("#weatherimage").innerHTML = ""
const weatherpopover = qs("#weatherpopover")
let existing_popover = bootstrap.Popover.getInstance(weatherpopover);
if (existing_popover) {
existing_popover.dispose()
}
const html = `<h5><i class="fa-solid fa-cloud-exclamation"></i> Failed to fetch weather</h5><p class="mb-0">Check debug console for details.</p>`
bootstrap.Popover.getOrCreateInstance(qs("#weatherpopover"), {
html: true,
sanitize: false,
placement: "top",
trigger: "click",
content: html,
customClass: "dontdismisspopover"
})
return Promise.reject(args)
}
function handle_weather_from_latlong(latitude, longitude) {
weather_info[config["weather_provider"]]["data"] = null;
reverse_geocode(latitude, longitude).then(geocode_response => {
console.debug(geocode_response)
weather_location_string = geocode_response;
// reconstruct if needed
if (weather_info[config["weather_provider"]]["data"]) {
construct_weather_popover()
}
chrome.storage.local.set({
geocode: geocode_response
});
}).catch(r => {
// do not error if this fails, who fucking cares lmao
console.error(r);
weather_location_string = null;
// reconstruct if needed
if (weather_info[config["weather_provider"]]["data"]) {
construct_weather_popover()
}
chrome.storage.local.set({
geocode: null
});
})
return get_weather_from_latlong(latitude, longitude, config["weather_provider"]).then(weather_response => {
console.debug(weather_response)
weather_info[config["weather_provider"]] = {
"fetched": new Date().getTime(),
"data": weather_response
}
chrome.storage.local.set({
weather: weather_info
});
construct_weather_popover()
return weather_info
}).catch(weather_error)
}
function fetch_weather_using_cache() {
// refreshes weather given current provider & data
// no weather info, we have to fetch
let data = null;
try {
data = weather_info[config["weather_provider"]]["data"];
} catch (e) {
}
if (!data) {
console.debug("no weather info found, fetching new info.")
return fetch_weather().catch(weather_error)
}
let lastfetched = 0;
try {
lastfetched = weather_info[config["weather_provider"]]["fetched"];
} catch (e) {
}
let sincelastdownload = new Date().getTime() - lastfetched;
let timetowait = 60 * 10 * 1000;
if (navigator.onLine && sincelastdownload > timetowait) {
console.debug("weather info is stale, fetching new info.")
return fetch_weather().catch(weather_error)
} else {
console.debug("using cached weather info");
console.debug(weather_info)
construct_weather_popover();
}
}
function fetch_weather() {
if (config["autolocate"]) {
return geolocate().then(position => {
return handle_weather_from_latlong(position.coords.latitude, position.coords.longitude)
}).catch(weather_error)
} else {
let lat = config["weather_address"]["latitude"];
let long = config["weather_address"]["longitude"]
if (isNumeric(lat) && isNumeric(long)) {
lat = Number(lat)
long = Number(long)
if (-90 <= lat && lat <= 90 && -180 <= long && long <= 180) {
return handle_weather_from_latlong(config["weather_address"]["latitude"], config["weather_address"]["longitude"])
} else {
return weather_error("Can't fetch weather due to out-of-bounds coordinates.", config["weather_address"])
}
} else {
return weather_error("Can't fetch weather due to non-numeric coordinates.", config["weather_address"])
}
}
}
function init_weather() {
// temperature unit handler AND iconset AND location settings AND weather
chrome.storage.local.get([
'tempunit', 'iconset', 'weather', "geocode", "autolocate",
"weather_address", "weather_enabled", "weather_provider",
], function (result) {
// init temp unit settings options
config["tempunit"] = result["tempunit"];
if (config["tempunit"] === undefined) {
config["tempunit"] = "f";
}
if (config["tempunit"] === "f") {
qs("#farradio").setAttribute("checked", "checked");
} else {
qs("#celradio").setAttribute("checked", "checked");
}
qs('#farradio').addEventListener('input', settings_set_tempunit);
qs('#celradio').addEventListener('input', settings_set_tempunit);
// init icon set settings options
config["iconset"] = result['iconset'];
if (config["iconset"] === undefined) {
config["iconset"] = "climacons";
}
if (config["iconset"] === "climacons") {
qs("#cradio").setAttribute("checked", "checked");
} else {
qs("#faradio").setAttribute("checked", "checked");
}
qs('#cradio').addEventListener('input', settings_set_iconset);
qs('#faradio').addEventListener('input', settings_set_iconset);
bootstrap.Tooltip.getOrCreateInstance(qs("#cradio").parentElement, {
html: true, placement: "top", trigger: "hover", title: `<span aria-hidden="true" class="popover-climacon climacon sun"></span>
<span aria-hidden="true" class="popover-climacon climacon cloud sun"></span>
<span aria-hidden="true" class="popover-climacon climacon cloud"></span>`
})
bootstrap.Tooltip.getOrCreateInstance(qs("#faradio").parentElement, {
html: true,
placement: "top",
trigger: "hover",
title: `<i class='fas fa-sun'></i> <i class='fas fa-cloud-sun'></i> <i class='fas fa-cloud'></i>`
})
// init weather provider
config["weather_provider"] = result['weather_provider'];
if (config["weather_provider"] === undefined || config["weather_provider"] === "darksky") {
config["weather_provider"] = "openweathermap";
}
switch (config["weather_provider"]) {
case "openweathermap":
qs("#wp-openweathermap-radio").setAttribute("checked", "checked");
break;
case "nws":
qs("#wp-nws-radio").setAttribute("checked", "checked");
break;
}
qs('#wp-openweathermap-radio').addEventListener('input', settings_set_provider);
qs('#wp-nws-radio').addEventListener('input', settings_set_provider);
bootstrap.Tooltip.getOrCreateInstance(qs("#wp-nws-radio").parentElement, {
placement: "top",
trigger: "hover",
html: true,
title: `NWS weather data has not yet been implemented. Check back on a later date.<br>The National Weather Service only provides weather for The United States.`
})
// init saved weather address
if (result["weather_address"] === undefined) {
config["weather_address"] = {
"longitude": null,
"latitude": null
}
} else {
config["weather_address"]["latitude"] = result["weather_address"]["latitude"]
config["weather_address"]["longitude"] = result["weather_address"]["longitude"]
qs("#weather-latitude").value = config["weather_address"]["latitude"]
qs("#weather-longitude").value = config["weather_address"]["longitude"]
}
document.querySelectorAll(".weather-coords").forEach(elem => {
elem.addEventListener("input", settings_set_location)
})
// init autolocate switch
qs("#autolocate").addEventListener("input", settings_set_autolocation)
qs("#autolocate").addEventListener("input", allow_weather_refresh)
config["autolocate"] = result["autolocate"]
if (result["autolocate"] === undefined || result["autolocate"]) {
config["autolocate"] = true;
set_autolocation(true)
qs("#autolocate").setAttribute("checked", "checked")
} else {
set_autolocation(false)
}
// init weather switch
qs("#enableweather").addEventListener("input", settings_set_weather)
config["weather_enabled"] = result["weather_enabled"]
if (result["weather_enabled"] === undefined || result["weather_enabled"]) {
config["weather_enabled"] = true;
weather_enable(true)
qs("#enableweather").setAttribute("checked", "checked")
} else {
weather_enable(false)
}
// init weather refresh button
let lastfetched = 0;
try {
lastfetched = result["weather"][config["weather_provider"]]["fetched"];
} catch (e) {
}
let sincelastdownload = new Date().getTime() - lastfetched;
let timetowait = 60 * 10 * 1000;
if (timetowait > sincelastdownload) {
// disable button if used in last 10 mins
qs("#refresh-weather").setAttribute("disabled", "disabled")
weather_refresh_timeout = setTimeout(_ => {
allow_weather_refresh()
}, (timetowait - sincelastdownload) * 1000)
}
// when weather refresh requested
qs("#refresh-weather").addEventListener("click", _ => {
// ignore if clicked while disabled
if (qs("#refresh-weather").getAttribute("disabled")) {
return
}
qs("#refresh-weather").setAttribute("disabled", "disabled")
// loading animation
qs("#refresh-progress").innerHTML = `<i class="fa-solid fa-arrows-rotate fa-spin"></i>`
// fetch weather and change button
fetch_weather().then(_ => {
qs("#refresh-progress").innerHTML = `<i class="fa-solid fa-check"></i>`
if (weather_refresh_timeout) {
clearTimeout(weather_refresh_timeout)
}
weather_refresh_timeout = setTimeout(_ => {
allow_weather_refresh()
}, timetowait * 1000)
}).catch(allow_weather_refresh)
})
// init reverse geocode
qs("#submit-address").addEventListener("click", _ => {
if (qs("#submit-address").getAttribute("disabled")) {
return
}
qs("#submit-address").setAttribute("disabled", "disabled")
qs("#weather-address").setAttribute("disabled", "disabled")
qs("#submit-address").innerHTML = `<i class="fa-solid fa-arrows-rotate fa-spin"></i>`
geocode(qs("#weather-address").value).then((addr) => {
if (addr) {
const {latitude, longitude} = addr;
qs("#weather-latitude").value = latitude
qs("#weather-longitude").value = longitude
settings_set_location()
qs("#submit-address").innerHTML = `<i class="fa-solid fa-magnifying-glass-location"></i>`
} else {
qs("#submit-address").innerHTML = `<i class="fa-solid fa-circle-exclamation fa-shake"></i>`
setTimeout(_ => {
qs("#submit-address").innerHTML = `<i class="fa-solid fa-magnifying-glass-location"></i>`
}, 1000);
}
qs("#submit-address").removeAttribute("disabled")
qs("#weather-address").removeAttribute("disabled")
})
})
// load weather
if (result["weather"]) {
if (result["openweathermap"] && result["nws"]) {
weather_info = result["weather"];
}
// don't set weather info if the previous info is invalid such as from previous version
}
weather_location_string = result["geocode"]
if (config["weather_enabled"]) {
fetch_weather_using_cache();
} else {
// hide loading icon
qs("#weather").innerHTML = ""
}
});
}
function init_timeformat() {
// initialize time format options
chrome.storage.local.get(['timeformat'], function (result) {
config["timeformat"] = result["timeformat"];
if (config["timeformat"] === undefined) {
config["timeformat"] = "12";
}
if (config["timeformat"] === "12") {
document.getElementById("12radio").setAttribute("checked", "checked");
} else {
document.getElementById("24radio").setAttribute("checked", "checked");
}
document.getElementById('12radio').addEventListener('input', settings_set_timeformat);
document.getElementById('24radio').addEventListener('input', settings_set_timeformat);
});
}
function init_background(lastbgrefresh) {
// set the actual background
if (promotional) {
qs("#bg").style["background-image"] = `url(https://images.unsplash.com/photo-1440558929809-1412944a6225?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1920&q=80)`;
} else {
// set background to cached image (well the browser should have cached it lol)
chrome.storage.local.get(['bgimage'], function (result) {
let bgimage = result["bgimage"];
if (bgimage) {
qs("#bg").style["background-image"] = `url(${bgimage})`;
}
});
// handle BG based on refreshtime
if (config["refreshtime"] !== 0) {
// config to not refresh everytime is set
// check if it's been long enough to get a new bg
let sincelastdownload = (new Date().getTime() / 1000) - lastbgrefresh;
let timetowait = config["refreshtime"] * 60;
if (sincelastdownload > timetowait) {
change_background();
} else {
// no action needed since cached bg was set
console.debug(`been less than ${config["refreshtime"]} mins, using same BG`);
}
} else {
change_background();
}
}
}
let weather_refresh_timeout;
function allow_weather_refresh() {
if (weather_refresh_timeout) {
clearTimeout(weather_refresh_timeout)
}
weather_refresh_timeout = undefined
qs("#refresh-weather").removeAttribute("disabled")
qs("#refresh-progress").innerHTML = `<i class="fa-solid fa-arrows-rotate"></i>`
}
function init_background_settings() {
// initialize background settings
chrome.storage.local.get([/*'searchtags',*/ "lastbgrefresh", "refreshtime"], function (result) {
// search tags options
// config["searchtags"] = result["searchtags"];
// if (config["searchtags"] === undefined) {
// config["searchtags"] = "wallpapers";
// }
qs("#bgrefresh").setAttribute("value", config["refreshtime"]);
qs('#bgrefresh').addEventListener('change', settings_set_refreshtime);
// refreshtime options
config["refreshtime"] = result["refreshtime"];
if (config["refreshtime"] === undefined) {
config["refreshtime"] = 0;
}
// qs("#bgtags").setAttribute("value", config["searchtags"]);
// qs('#bgtags').addEventListener('change', settings_set_searchtags);
init_background(result["lastbgrefresh"])
});
}
function init_dateformat() {
// initialize date format options
chrome.storage.local.get(['dateformat'], function (result) {
config["dateformat"] = result["dateformat"];
if (config["dateformat"] === undefined) {
config["dateformat"] = "md";
}
if (config["dateformat"] === "md") {
qs("#mdradio").setAttribute("checked", "checked");
} else if (config["dateformat"] === "dm") {
qs("#dmradio").setAttribute("checked", "checked");
} else if (config["dateformat"] === "ymd") {
qs("#ymdradio").setAttribute("checked", "checked");
}
qs('#mdradio').addEventListener('input', settings_set_dateformat);
qs('#dmradio').addEventListener('input', settings_set_dateformat);
qs('#ymdradio').addEventListener('input', settings_set_dateformat);
});
}
function initialize_settings_menu() {
// initializes settings menu from saved config options and runs routines that require them (weather, background)
// all functions are async calls to chrome.storage.get
// only separate functions for organization
init_background_blur()
init_timeformat()
init_background_settings()
init_dateformat()
init_weather()
// remove "saved" text when closing settings
qs('#settings_modal').addEventListener('hidden.bs.modal', () => {
qs("#savetext").innerHTML = "";
});
}
document.addEventListener("DOMContentLoaded", on_doc_load);
function show_changelog_if_needed() {
chrome.storage.local.get(['version'], result => {
result = result["version"];
if (result === undefined) {
result = version;
}
if (result !== version) {
new bootstrap.Modal(qs("#changelog")).show()
}
chrome.storage.local.set({
version: version
});
});
}
function show_welcome_if_needed() {
// FIRST INSTALL
chrome.storage.local.get(['firstinstall'], result => {
result = result["firstinstall"];
if (result === undefined || result === true) {
new bootstrap.Modal(qs("#welcome")).show()
}
chrome.storage.local.set({
firstinstall: false
});
});
}
function dates_same_day(d1, d2) {
return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth() && d1.getDate() === d2.getDate();
}
function string_if_condition(cond, string) {
if (cond) {
return string
} else {
return ""
}
}
function calendar_html() {
const now = new Date();
let calday1 = new Date();
// debug
// now.setDate(-4253)
// calday1.setDate(-4253)
// day 1 of month should be in first row
calday1.setDate(1);
// move back to first day of that week
// yes setDate can take negatives and it rolls over to the previous month
calday1.setDate(1 - calday1.getDay())
let tbody = "";
// for 6 weeks in cal
for (let week = 0; week < 6; week++) {
// break if entire week is greyed out (next month)
let weeksun = new Date(calday1.valueOf())
weeksun.setDate(calday1.getDate() + (week * 7));
if (weeksun.getTime() > now.getTime() && now.getMonth() !== weeksun.getMonth()) {