-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshared.js
1603 lines (1347 loc) · 50.8 KB
/
shared.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
/* Code by Glen Little - 2014 - 2024 */
// these use VAR to be globally available
var splitSeparator = /[,،]+/;
var prepared = false;
var _currentPageId = null;
var _rawMessages = {};
var _rawMessageTranslationPct = 0;
var _numMessagesEn = 0;
var _cachedMessages = {};
var _cachedMessageUseCount = 0;
var _pendingInstallFunctionsQueue = [];
var _nextFilledWithEach_UsesExactMatchOnly = false;
var _focusTime = null;
var _alarmNamePrefix = "alarm_";
var _refreshPrefix = "refreshAlarm ";
var _holyDaysEngine = null;
var _knownDateInfos = {};
var _di = {};
var _initialDiStamp;
var _firstLoad = true;
var bMonthNameAr;
var bMonthMeaning;
var bWeekdayNameAr;
var bWeekdayMeaning;
var bYearInVahidNameAr;
var bYearInVahidMeaningnull;
var bMonthNamePri;
var bMonthNameSec;
var bWeekdayNamePri;
var bWeekdayNameSec;
var bYearInVahidNamePri;
var bYearInVahidNameSec;
var gWeekdayLong;
var gWeekdayShort;
var gMonthLong;
var gMonthShort;
var ordinall;
var ordinalNames;
var elements;
var tracker; // google
var use24HourClock;
var _iconPrepared = false;
var _remindersEngine = {};
var _inTab = false;
// in alphabetical order
var localStorageKey = {
firstPopup: "firstPopup",
focusPage: "focusPage",
focusTimeAsOf: "focusTimeAsOf",
focusTime: "focusTime",
focusTimeIsEve: "focusTimeIsEve",
gCalLabel: "gCalLabel",
gCalTitle: "gCalTitle",
googleUid: "googleUid",
iconTextColor: "iconTextColor",
locationLat: "locationLat",
locationKnown: "locationKnown",
locationName: "locationName",
locationNameKnown: "locationNameKnown",
locationLong: "locationLong",
reminderDefinitions: "reminderDefinitions",
updateVersion: "updateVersion",
};
var syncStorageKey = {
customFormats: "customFormats",
eventStart: "eventStart",
// exporter_{names}: "exporter_{names}",
exporter_alertMinutes: "exporter_alertMinutes",
exporter_exporterDateRange: "exporter_exporterDateRange",
exporter_exporterName: "exporter_exporterName",
formatToolTip1: "formatToolTip1",
formatToolTip2: "formatToolTip2",
formatTopDay: "formatTopDay",
iftttKey: "iftttKey",
includeFeasts: "includeFeasts",
includeHolyDays: "includeHolyDays",
jumpTo: "jumpTo",
language: "language",
optOutGa: "optOutGa",
planWhat: "planWhat",
// planner_{ids}: "planner_{ids}",
showPointer: "showPointer",
useArNames: "useArNames",
zapierWebhook: "zapierWebhook",
};
var browserType = {
Chrome: "Chrome",
Firefox: "Firefox",
Edge: "Edge",
};
var browserHostType = browserType.Chrome; // hard coded in the Chrome version of the extension
var common = {};
/**
* Set up everything that is needed by the service worker and the popup
*/
async function prepareForBackgroundAndPopupAsync() {
// console.log("%cprepare in shared - started", "color: lightblue");
dayjs.extend(dayjs_plugin_utc);
dayjs.extend(dayjs_plugin_timezone);
common.languageCode = await getFromStorageSyncAsync(syncStorageKey.language, "");
if (!common.languageCode) {
common.languageCode = chrome.i18n.getUILanguage();
putInStorageSyncAsync(syncStorageKey.language, common.languageCode);
}
await loadRawMessages(common.languageCode);
common.useArNames = await getFromStorageSyncAsync(syncStorageKey.useArNames, true);
common.iconTextColor = await getFromStorageLocalAsync(localStorageKey.iconTextColor, "#000000");
common.languageDir = getMessage("textDirection", null, "ltr");
common.locationLat = await getFromStorageLocalAsync(localStorageKey.locationLat);
common.locationLong = await getFromStorageLocalAsync(localStorageKey.locationLong);
common.locationKnown = await getFromStorageLocalAsync(localStorageKey.locationKnown);
common.locationName = await getFromStorageLocalAsync(localStorageKey.locationName);
common.locationNameKnown = await getFromStorageLocalAsync(localStorageKey.locationNameKnown);
common.customFormats = await getFromStorageSyncAsync(syncStorageKey.customFormats, []);
common.googleUid = await getFromStorageLocalAsync(localStorageKey.googleUid, null);
common.eventStart = await getFromStorageSyncAsync(syncStorageKey.eventStart, "1930");
common.jumpTo = await getFromStorageSyncAsync(syncStorageKey.jumpTo, "90");
common.ifttt = await getFromStorageSyncAsync(syncStorageKey.iftttKey, "");
common.zapierWebhook = await getFromStorageSyncAsync(syncStorageKey.zapierWebhook, "");
common.firstPopup = await getFromStorageLocalAsync(localStorageKey.firstPopup, false);
common.includeFeasts = await getFromStorageSyncAsync(syncStorageKey.includeFeasts, true);
common.includeHolyDays = await getFromStorageSyncAsync(syncStorageKey.includeHolyDays, true);
common.showPointer = await getFromStorageSyncAsync(syncStorageKey.showPointer, true);
common.focusTimeAsOf = await getFromStorageLocalAsync(localStorageKey.focusTimeAsOf, "0");
common.focusPage = await getFromStorageLocalAsync(localStorageKey.focusPage);
common.focusTime = await getFromStorageLocalAsync(localStorageKey.focusTime, "B0");
common.formatTopDay = await getFromStorageSyncAsync(syncStorageKey.formatTopDay, getMessage("bTopDayDisplay"));
common.formatToolTip1 = await getFromStorageSyncAsync(syncStorageKey.formatToolTip1, getMessage("formatIconToolTip"));
common.formatToolTip2 = await getFromStorageSyncAsync(syncStorageKey.formatToolTip2, "{nearestSunset}");
bMonthNameAr = getMessage("bMonthNameAr").split(splitSeparator);
bMonthMeaning = getMessage("bMonthMeaning").split(splitSeparator);
bWeekdayNameAr = getMessage("bWeekdayNameAr").split(splitSeparator); // from Saturday
bWeekdayMeaning = getMessage("bWeekdayMeaning").split(splitSeparator);
bYearInVahidNameAr = getMessage("bYearInVahidNameAr").split(splitSeparator);
bYearInVahidMeaning = getMessage("bYearInVahidMeaning").split(splitSeparator);
gWeekdayLong = getMessage("gWeekdayLong").split(splitSeparator);
gWeekdayShort = getMessage("gWeekdayShort").split(splitSeparator);
gMonthLong = getMessage("gMonthLong").split(splitSeparator);
gMonthShort = getMessage("gMonthShort").split(splitSeparator);
ordinal = getMessage("ordinal").split(splitSeparator);
ordinalNames = getMessage("ordinalNames").split(splitSeparator);
elements = getMessage("elements").split(splitSeparator);
use24HourClock = getMessage("use24HourClock") === "true";
setupLanguageChoice();
_holyDaysEngine = new HolyDays();
refreshDateInfo();
// console.log(`Nearest sunset:`, _di.nearestSunset);
prepareAnalyticsTracker();
prepared = true;
// console.log("Finished preparing for background and popup");
await FlushPendingInstallFunctionsAsync();
// console.log("%cprepare in shared - done", "color: lightblue");
}
async function prepareSharedForPopup() {
common.exporter_exporterName = await getFromStorageSyncAsync(syncStorageKey.exporter_exporterName, getMessage("title"));
common.exporter_exporterDateRange = await getFromStorageSyncAsync(syncStorageKey.exporter_exporterDateRange);
common.exporter_alertMinutes = await getFromStorageSyncAsync(syncStorageKey.exporter_alertMinutes, "B0");
common.optedOutOfGoogleAnalytics = await getFromStorageSyncAsync(syncStorageKey.optOutGa, -1);
common.rememberFocusTimeMinutes = 5; // show on settings page?
// integrateIntoGoogleCalendar: await getFromStorageLocalAsync(localStorageKey.enableGCal, true),
// must be set immediately for tab managers to see this name
$("#windowTitle").text(getMessage("title"));
// see messages.json for translations and local names
$("#loadingMsg").html(getMessage("browserActionTitle"));
startGettingLocation();
const langCode = common.languageCode.slice(0, 2);
$("body")
.addClass(common.languageCode)
.addClass(common.languageDir)
.addClass(langCode)
.addClass(browserHostType)
.attr("lang", common.languageCode)
.attr("dir", common.languageDir);
_initialDiStamp = getDateInfo(new Date(), true);
await recallFocusAndSettingsAsync();
updateLoadProgress("refresh date info");
UpdateLanguageBtn();
updateLoadProgress("defaults");
prepareDefaultsInPopup();
if (_iconPrepared) {
refreshDateInfo();
} else {
await refreshDateInfoAndShowAsync();
}
const isEve = await getFromStorageLocalAsync(localStorageKey.focusTimeIsEve, "x");
if (isEve !== "x" && isEve !== _di.bNow.eve) {
toggleEveOrDay(isEve);
}
updateLoadProgress("localize");
localizeHtml();
updateLoadProgress("page custom");
_pageCustom = PageCustom();
updateLoadProgress("showInfo");
showInfo();
updateLoadProgress("showPage");
await showPage();
updateLoadProgress("shortcut keys");
showShortcutKeys();
updateLoadProgress("handlers");
attachHandlersInPopup();
updateLoadProgress("btn open");
showBtnOpen();
updateLoadProgress("tab names");
updateTabNames();
updateLoadProgress("prepare2 soon");
setTimeout(prepare2, 0);
// if viewing first page, show now
if (_currentPageId === "pageDay") {
adjustHeight();
$("#initialCover").hide();
}
}
async function loadJsonfileAsync(filePath) {
try {
const url = browser.runtime.getURL(filePath);
const response = await fetch(url);
if (!response.ok) {
console.log(`File not found: ${filePath}`);
return null;
}
const jsonData = await response.json();
return jsonData;
} catch (error) {
// console.error(`Error fetching file ${filePath}:`, error);
return null;
}
}
async function loadRawMessages(langCode, cb) {
// load base English, then overwrite with base for language, then with full lang code
// console.log("loading", langCode);
const rawLangCodes = { en: true };
if (langCode.length > 2) {
rawLangCodes[langCode.slice(0, 2)] = true;
}
rawLangCodes[langCode] = true;
const langsToLoad = Object.keys(rawLangCodes);
_numMessagesEn = 0;
let numMessagesOther = -1;
_rawMessages = {};
for (let langNum = 0; langNum < langsToLoad.length; langNum++) {
const langToLoad = langsToLoad[langNum];
const url = `/_locales/${langToLoad}/messages.json`;
// console.log("loading lang resource", langNum, langToLoad, url);
const messages = await loadJsonfileAsync(url);
if (!messages) {
console.log("no source found for", langToLoad);
continue;
}
const keys = Object.keys(messages);
// console.log("loading", keys.length, "keys from", langToLoad);
if (langToLoad === "en") {
_numMessagesEn = keys.length;
} else {
// this will be incorrect if the _locales folder does have folders for xx and xx-yy. None do currently.
numMessagesOther = keys.length;
}
// add all to _rawMessages
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
_rawMessages[k.toLowerCase()] = messages[k].message;
}
}
_cachedMessages = {};
_cachedMessageUseCount = 0;
_rawMessageTranslationPct = Math.round(numMessagesOther === -1 || _numMessagesEn === 0 ? 100 : (100 * numMessagesOther) / _numMessagesEn);
console.log(
"loaded",
_numMessagesEn,
numMessagesOther === -1 ? "n/a" : numMessagesOther,
langsToLoad,
Object.keys(_rawMessages).length,
"keys - ",
_rawMessageTranslationPct,
"% translated"
);
if (cb) {
cb();
}
}
function setupLanguageChoice() {
// debugger;
bMonthNamePri = common.useArNames ? bMonthNameAr : bMonthMeaning;
bMonthNameSec = !common.useArNames ? bMonthNameAr : bMonthMeaning;
bWeekdayNamePri = common.useArNames ? bWeekdayNameAr : bWeekdayMeaning;
bWeekdayNameSec = !common.useArNames ? bWeekdayNameAr : bWeekdayMeaning;
bYearInVahidNamePri = common.useArNames ? bYearInVahidNameAr : bYearInVahidMeaning;
bYearInVahidNameSec = !common.useArNames ? bYearInVahidNameAr : bYearInVahidMeaning;
}
function refreshDateInfo() {
// console.log("Refresh date info for", common.locationLat, common.locationLong);
_di = getDateInfo(getFocusTime());
}
function getDateInfo(targetTime, onlyStamp) {
let targetTimeLocal = targetTime;
// hard code limits
const minDate = new Date(1844, 2, 21, 0, 0, 0, 0);
if (targetTimeLocal < minDate) {
targetTimeLocal = minDate;
} else {
const maxDate = new Date(2844, 2, 20, 0, 0, 0, 0);
if (targetTimeLocal > maxDate) {
targetTimeLocal = maxDate;
}
}
const known = _knownDateInfos[targetTimeLocal];
if (known) {
// console.log("%cKnown date info for", "color:lightgreen", targetTimeLocal);
return known;
}
// debugger;
const bNow = _holyDaysEngine.getBDate(targetTimeLocal);
if (onlyStamp) {
return {
stamp: JSON.stringify(bNow),
stampDay: "{y}.{m}.{d}".filledWith(bNow),
};
}
// split the Baha'i day to be "Eve" - sunset to midnight;
// and "Morn" - from midnight through to sunset
const frag1Noon = new Date(targetTimeLocal.getTime());
frag1Noon.setHours(12, 0, 0, 0);
if (!bNow.eve) {
// if not already frag1, make it so
frag1Noon.setDate(frag1Noon.getDate() - 1);
}
const frag2Noon = new Date(frag1Noon.getTime());
frag2Noon.setDate(frag2Noon.getDate() + 1);
const frag1SunTimes = sunCalculator.getTimes(frag1Noon, common.locationLat, common.locationLong);
const frag2SunTimes = sunCalculator.getTimes(frag2Noon, common.locationLat, common.locationLong);
const di = {
// date info
frag1: frag1Noon,
frag1Year: frag1Noon.getFullYear(),
frag1Month: frag1Noon.getMonth(),
frag1Day: frag1Noon.getDate(),
frag1Weekday: frag1Noon.getDay(),
frag2: frag2Noon,
frag2Year: frag2Noon.getFullYear(),
frag2Month: frag2Noon.getMonth(), // 0 based
frag2Day: frag2Noon.getDate(),
frag2Weekday: frag2Noon.getDay(),
currentYear: targetTimeLocal.getFullYear(),
currentMonth: targetTimeLocal.getMonth(), // 0 based
currentMonth1: 1 + targetTimeLocal.getMonth(),
currentDay: targetTimeLocal.getDate(),
currentDay00: digitPad2(targetTimeLocal.getDate()),
currentWeekday: targetTimeLocal.getDay(),
currentTime: targetTimeLocal,
startingSunsetDesc12: getTimeDisplay(frag1SunTimes.sunset),
startingSunsetDesc24: getTimeDisplay(frag1SunTimes.sunset, 24),
endingSunsetDesc12: getTimeDisplay(frag2SunTimes.sunset),
endingSunsetDesc24: getTimeDisplay(frag2SunTimes.sunset, 24),
frag1SunTimes: frag1SunTimes,
frag2SunTimes: frag2SunTimes,
sunriseDesc12: getTimeDisplay(frag2SunTimes.sunrise),
sunriseDesc24: getTimeDisplay(frag2SunTimes.sunrise, 24),
bNow: bNow,
bDay: bNow.d,
bWeekday: 1 + ((frag2Noon.getDay() + 1) % 7),
bMonth: bNow.m,
bYear: bNow.y,
bVahid: Math.floor(1 + (bNow.y - 1) / 19),
bDateCode: `${bNow.m}.${bNow.d}`,
bDayNameAr: bMonthNameAr[bNow.d],
bDayMeaning: bMonthMeaning[bNow.d],
bMonthNameAr: bMonthNameAr[bNow.m],
bMonthMeaning: bMonthMeaning[bNow.m],
bEraLong: getMessage("eraLong"),
bEraAbbrev: getMessage("eraAbbrev"),
bEraShort: getMessage("eraShort"),
stamp: JSON.stringify(bNow), // used to compare to other dates and for developer reference
};
// debugger;
di.bDayNamePri = common.useArNames ? di.bDayNameAr : di.bDayMeaning;
di.bDayNameSec = !common.useArNames ? di.bDayNameAr : di.bDayMeaning;
di.bMonthNamePri = common.useArNames ? di.bMonthNameAr : di.bMonthMeaning;
di.bMonthNameSec = !common.useArNames ? di.bMonthNameAr : di.bMonthMeaning;
di.VahidLabelPri = common.useArNames ? getMessage("vahid") : getMessage("vahidLocal");
di.VahidLabelSec = !common.useArNames ? getMessage("vahid") : getMessage("vahidLocal");
di.KullishayLabelPri = common.useArNames ? getMessage("kullishay") : getMessage("kullishayLocal");
di.KullishayLabelSec = !common.useArNames ? getMessage("kullishay") : getMessage("kullishayLocal");
di.bKullishay = Math.floor(1 + (di.bVahid - 1) / 19);
di.bVahid = di.bVahid - (di.bKullishay - 1) * 19;
di.bYearInVahid = di.bYear - (di.bVahid - 1) * 19 - (di.bKullishay - 1) * 19 * 19;
di.bYearInVahidNameAr = bYearInVahidNameAr[di.bYearInVahid];
di.bYearInVahidMeaning = bYearInVahidMeaning[di.bYearInVahid];
di.bYearInVahidNamePri = common.useArNames ? di.bYearInVahidNameAr : di.bYearInVahidMeaning;
di.bYearInVahidNameSec = !common.useArNames ? di.bYearInVahidNameAr : di.bYearInVahidMeaning;
di.bWeekdayNameAr = bWeekdayNameAr[di.bWeekday];
di.bWeekdayMeaning = bWeekdayMeaning[di.bWeekday];
di.bWeekdayNamePri = common.useArNames ? di.bWeekdayNameAr : di.bWeekdayMeaning;
di.bWeekdayNameSec = !common.useArNames ? di.bWeekdayNameAr : di.bWeekdayMeaning;
di.elementNum = getElementNum(bNow.m);
di.element = elements[di.elementNum - 1];
di.bDayOrdinal = di.bDay + getOrdinal(di.bDay);
di.bVahidOrdinal = di.bVahid + getOrdinal(di.bVahid);
di.bKullishayOrdinal = di.bKullishay + getOrdinal(di.bKullishay);
di.bDayOrdinalName = getOrdinalName(di.bDay);
di.bVahidOrdinalName = getOrdinalName(di.bVahid);
di.bKullishayOrdinalName = getOrdinalName(di.bKullishay);
di.bDay00 = digitPad2(di.bDay);
di.frag1Day00 = digitPad2(di.frag1Day);
di.currentMonth01 = digitPad2(di.currentMonth1);
di.frag2Day00 = digitPad2(di.frag2Day);
di.frag1Month00 = digitPad2(1 + di.frag1Month); // change from 0 based
di.frag2Month00 = digitPad2(1 + di.frag2Month); // change from 0 based
di.bMonth00 = digitPad2(di.bMonth);
di.bYearInVahid00 = digitPad2(di.bYearInVahid);
di.bVahid00 = digitPad2(di.bVahid);
di.startingSunsetDesc = use24HourClock ? di.startingSunsetDesc24 : di.startingSunsetDesc12;
di.endingSunsetDesc = use24HourClock ? di.endingSunsetDesc24 : di.endingSunsetDesc12;
di.sunriseDesc = use24HourClock ? di.sunriseDesc24 : di.sunriseDesc12;
di.frag1MonthLong = gMonthLong[di.frag1Month];
di.frag1MonthShort = gMonthShort[di.frag1Month];
di.frag1WeekdayLong = gWeekdayLong[di.frag1Weekday];
di.frag1WeekdayShort = gWeekdayShort[di.frag1Weekday];
di.frag2MonthLong = gMonthLong[di.frag2Month];
di.frag2MonthShort = gMonthShort[di.frag2Month];
di.frag2WeekdayLong = gWeekdayLong[di.frag2Weekday];
di.frag2WeekdayShort = gWeekdayShort[di.frag2Weekday];
di.currentMonthLong = gMonthLong[di.currentMonth];
di.currentMonthShort = gMonthShort[di.currentMonth];
di.currentWeekdayLong = gWeekdayLong[di.currentWeekday];
di.currentWeekdayShort = gWeekdayShort[di.currentWeekday];
di.currentDateString = dayjs(di.currentTime).format("YYYY-MM-DD");
di.currentRelationToSunset = getMessage(bNow.eve ? "afterSunset" : "beforeSunset");
const thisMoment = new Date().getTime();
di.dayStarted = getMessage(thisMoment > di.frag1SunTimes.sunset.getTime() ? "dayStartedPast" : "dayStartedFuture");
di.dayEnded = getMessage(thisMoment > di.frag2SunTimes.sunset.getTime() ? "dayEndedPast" : "dayEndedFuture");
di.dayStartedLower = di.dayStarted.toLocaleLowerCase();
di.dayEndedLower = di.dayEnded.toLocaleLowerCase();
// di.bMonthDayYear = getMessage('gMonthDayYear', di);
if (di.frag1Year !== di.frag2Year) {
// Dec 31/Jan 1
// Dec 31, 2015/Jan 1, 2015
di.gCombined = getMessage("gCombined_3", di);
di.gCombinedY = getMessage("gCombinedY_3", di);
} else if (di.frag1Month !== di.frag2Month) {
// Mar 31/Apr 1
// Mar 31/Apr 1, 2015
di.gCombined = getMessage("gCombined_2", di);
di.gCombinedY = getMessage("gCombinedY_2", di);
} else {
// Jul 12/13
// Jul 12/13, 2015
di.gCombined = getMessage("gCombined_1", di);
di.gCombinedY = getMessage("gCombinedY_1", di);
}
di.nearestSunset = getMessage(bNow.eve ? "nearestSunsetEve" : "nearestSunsetDay", di);
di.stampDay = "{y}.{m}.{d}".filledWith(di.bNow); // ignore eve/day
//if (!skipUpcoming) {
// getUpcoming(di);
//}
_knownDateInfos[targetTimeLocal] = di;
return di;
}
function getElementNum(num) {
// the Bab's designations, found in 'https://books.google.ca/books?id=XTfoaK15t64C&pg=PA394&lpg=PA394&dq=get+of+the+heart+nader+bab&source=bl&ots=vyF-pWLAr8&sig=ruiuoE48sGWWgaB_AFKcSfkHvqw&hl=en&sa=X&ei=hbp0VfGwIon6oQSTk4Mg&ved=0CDAQ6AEwAw#v=snippet&q=%22air%20of%20eternity%22&f=false'
// 1, 2, 3
// 4, 5, 6, 7
// 8, 9,10,11,12,13
// 14,15,16,17,18,19
let element = 1;
if (num >= 4 && num <= 7) {
element = 2;
} else if (num >= 8 && num <= 13) {
element = 3;
} else if (num >= 14 && num <= 19) {
element = 4;
} else if (num === 0) {
element = 0;
}
return element;
}
function getToolTipMessageTemplate(lineNum) {
// can be overwritten in the custom page
switch (lineNum) {
case 1:
return common.formatToolTip1; // await getFromStorageSyncAsync(localStorageKey.formatToolTip1, getMessage("formatIconToolTip"));
case 2:
return common.formatToolTip2; // await getFromStorageSyncAsync(localStorageKey.formatToolTip2, "{nearestSunset}");
}
return "";
}
function showIcon() {
const dateInfo = getDateInfo(new Date());
const tipLines = [];
tipLines.push(common.formatToolTip1.filledWith(dateInfo));
tipLines.push(common.formatToolTip2.filledWith(dateInfo));
tipLines.push("");
if (dateInfo.special1) {
tipLines.push(dateInfo.special1);
if (dateInfo.special2) {
tipLines.push(dateInfo.special2);
}
tipLines.push("");
}
if (dateInfo.bMonth === 19) {
tipLines.push(`${getMessage("sunriseFastHeading")} - ${getTimeDisplay(dateInfo.frag2SunTimes.sunrise)}`);
tipLines.push("");
}
tipLines.push(getMessage("formatIconClick"));
browser.action.setTitle({ title: tipLines.join("\n") });
try {
browser.action.setIcon({
imageData: drawIconImage(dateInfo.bMonthNamePri, dateInfo.bDay, "center"),
});
_iconPrepared = true;
} catch (e) {
// fails in Firefox unless in the popup
console.log("icon failed");
console.log(e);
_iconPrepared = false;
}
}
function drawIconImage(line1, line2, line2Alignment) {
const size = 19;
const canvas = new OffscreenCanvas(size, size);
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
const fontName = "Tahoma";
context.fillStyle = common.iconTextColor;
// const line1div = "<div>{^0}</div>".filledWith(line1);
// const line2div = "<div>{^0}</div>".filledWith(line2);
context.font = `${size / 2 - 1}px ${fontName}`;
context.fillText(line1, 0, 7);
context.font = `${size / 2 + 1}px ${fontName}`;
context.textAlign = line2Alignment;
let x = 0;
switch (line2Alignment) {
case "center":
x = size / 2;
break;
// case 'end':
// x = size;
// break;
}
context.fillText(line2, x, size);
return context.getImageData(0, 0, size, size);
}
function getUpcoming(di) {
if (di.upcomingHtml) {
return; // already done
}
const dayInfos = _holyDaysEngine.getUpcoming(di, 3);
const today = dayjs(di.frag2);
today.hour(0);
di.special1 = null;
di.special2 = null;
dayInfos.forEach((dayInfo) => {
const targetDi = getDateInfo(dayInfo.GDate);
if (dayInfo.Type === "M") {
dayInfo.A = getMessage("FeastOf").filledWith(targetDi.bMonthNameSec);
} else if (dayInfo.Type.slice(0, 1) === "H") {
dayInfo.A = getMessage(dayInfo.NameEn);
}
if (dayInfo.Special && dayInfo.Special.slice(0, 5) === "AYYAM") {
dayInfo.A = getMessage(dayInfo.NameEn);
}
dayInfo.date = getMessage("upcomingDateFormat", targetDi);
const sameDay = di.stampDay === targetDi.stampDay;
const targetMoment = dayjs(dayInfo.GDate);
dayInfo.away = determineDaysAway(di, today, targetMoment, sameDay);
if (sameDay) {
if (!di.special1) {
di.special1 = dayInfo.A;
} else {
di.special2 = dayInfo.A;
}
}
});
di.upcomingHtml = "<tr class={Type}><td>{away}</td><td>{^A}</td><td>{^date}</td></tr>".filledWithEach(dayInfos);
}
function determineDaysAway(di, moment1, moment2, sameDay) {
const days = moment2.diff(moment1, "days");
if (days === 1 && !di.bNow.eve) {
return getMessage("Tonight");
}
if (days === -1) {
return getMessage("Ended");
}
if (days === 0) {
return getMessage("Now");
}
return getMessage(days === 1 ? "1day" : "otherDays").filledWith(days);
}
function getTimeDisplay(d, use24) {
const hoursType = use24HourClock || use24 === 24 ? 24 : 0;
const show24Hour = hoursType === 24;
const hours24 = d.getHours();
const pm = hours24 >= 12;
const hours = show24Hour ? hours24 : hours24 > 12 ? hours24 - 12 : hours24 === 0 ? 12 : hours24;
const minutes = d.getMinutes();
let time = `${hours}:${`0${minutes}`.slice(-2)}`;
if (!show24Hour) {
if (hours24 === 12 && minutes === 0) {
time = getMessage("noon");
} else if (hours24 === 0 && minutes === 0) {
time = getMessage("midnight");
} else {
time = getMessage("timeFormat12").filledWith({
time: time,
ampm: pm ? getMessage("pm") : getMessage("am"),
});
}
}
return time;
}
async function startGetLocationNameAsync() {
// debugger;
try {
const unknownLocation = getMessage("noLocationName");
const lat = common.locationLat;
const long = common.locationLong;
if (!lat || !long) {
common.locationName = unknownLocation;
// console.log("No location, so not getting location name");
return;
}
// console.log("Getting location name for", lat, long);
// Send a message to the background script to get the city name
browser.runtime
.sendMessage({
action: "getCityName",
lat: lat,
long: long,
unknownLocation: unknownLocation,
})
.then((response) => {
const location = response.city || unknownLocation;
// console.log("Location:", location);
putInStorageLocalAsync(localStorageKey.locationName, location);
common.locationName = location;
const known = location !== unknownLocation;
putInStorageLocalAsync(localStorageKey.locationNameKnown, known);
common.locationNameKnown = known;
stopLoaderButton();
if (typeof _inPopupPage !== "undefined") {
showLocation();
}
});
} catch (error) {
console.log(error);
}
}
function stopLoaderButton() {
$(".btnRetry").removeClass("active");
}
function startGettingLocation() {
const positionOptions = {
enableHighAccuracy: false,
maximumAge: Number.POSITIVE_INFINITY,
timeout: 6000,
};
navigator.geolocation.getCurrentPosition(setLocationAsync, noLocationAsync, positionOptions); // this triggers immediately
}
async function setLocationAsync(position) {
if (+common.locationLat === position.coords.latitude && +common.locationLong === position.coords.longitude && common.locationNameKnown) {
// no changes
// console.log("Location:", common.locationName, common.locationNameKnown);
return;
}
putInStorageLocalAsync(localStorageKey.locationLat, common.locationLat);
common.locationLat = position.coords.latitude;
putInStorageLocalAsync(localStorageKey.locationLong, common.locationLong);
common.locationLong = position.coords.longitude;
_knownDateInfos = {};
common.locationKnown = true;
putInStorageLocalAsync(localStorageKey.locationKnown, true);
common.locationNameKnown = false;
putInStorageLocalAsync(localStorageKey.locationNameKnown, false);
putInStorageLocalAsync(localStorageKey.locationName, getMessage("browserActionTitle")); // temp until we get it
if (typeof _inPopupPage !== "undefined") {
$("#inputLat").val(common.locationLat);
$("#inputLng").val(common.locationLong);
await updateLocationAsync(true);
} else {
await refreshDateInfoAndShowAsync();
}
}
async function noLocationAsync(err) {
if (common.locationNameKnown) {
return;
}
common.locationLat = 0;
common.locationLong = 0;
putInStorageLocalAsync(localStorageKey.locationLat, common.locationLong);
putInStorageLocalAsync(localStorageKey.locationLong, common.locationLong);
_knownDateInfos = {};
console.warn(err);
putInStorageLocalAsync(localStorageKey.locationKnown, false);
common.locationKnown = false;
const noLocAvail = getMessage("noLocationAvailable");
putInStorageLocalAsync(localStorageKey.locationName, noLocAvail);
common.locationName = noLocAvail;
stopLoaderButton();
await refreshDateInfoAndShowAsync();
}
async function recallFocusAndSettingsAsync() {
const storedAsOf = +common.focusTimeAsOf;
if (!storedAsOf) {
common.focusTimeIsEve = null;
putInStorageLocalAsync(localStorageKey.focusTimeIsEve, null);
return;
}
const focusTimeAsOf = new Date(storedAsOf);
let timeSet = false;
const now = new Date();
if (now - focusTimeAsOf < common.rememberFocusTimeMinutes * 60000) {
const focusPage = common.focusPage;
if (focusPage && typeof _currentPageId !== "undefined") {
_currentPageId = focusPage;
}
const stored = +common.focusTime;
if (stored) {
const time = new Date(stored);
if (!Number.isNaN(time)) {
const changing = now.toDateString() !== time.toDateString();
// console.log('reuse focus time: ' + time);
setFocusTime(time);
timeSet = true;
if (changing) {
highlightGDay();
}
}
}
} else {
putInStorageLocalAsync(localStorageKey.focusPage, null);
}
if (!timeSet) {
setFocusTime(new Date());
}
}
function highlightGDay() {
// console.log('highlight');
// if (typeof $().effect !== 'undefined') {
// setTimeout(function () {
// $('#day, #gDay').effect("highlight", 6000);
// },
// 150);
// }
}
async function refreshDateInfoAndShowAsync(resetToNow) {
// also called from alarm, to update to the next day
if (resetToNow) {
setFocusTime(new Date());
} else {
// will reset to now after a few minutes
await recallFocusAndSettingsAsync();
}
// console.log("refreshDateInfoAndShow at", new Date());
refreshDateInfo();
_firstLoad = false;
showIcon();
if (typeof showInfo !== "undefined") {
// are we inside the open popup?
showInfo();
showWhenResetToNow();
}
setAlarmForNextRefresh(_di.currentTime, _di.frag2SunTimes.sunset, _di.bNow.eve);
}
const refreshAlarms = {};
function setAlarmForNextRefresh(currentTime, sunset, inEvening) {
let whenTime;
let alarmName;
if (inEvening) {
// in eve, after sunset, so update after midnight
const midnight = new Date(currentTime.getFullYear(), currentTime.getMonth(), currentTime.getDate() + 1).getTime();
whenTime = midnight + 1000; // to be safe, set at least 1 second after midnight
alarmName = _refreshPrefix + "midnight";
} else {
// in the day, so update right at the sunset
whenTime = sunset.getTime();
alarmName = _refreshPrefix + "sunset";
}
// odd bug... sometimes gets called many times over - is alarm being set in the past?
//if (refreshAlarms[whenTime]) {
// // already set before
// return;
//}
if (whenTime < new Date().getTime()) {
console.warn("ignored attempt to set {0} alarm in the past".filledWith(alarmName));
return;
}
refreshAlarms[whenTime] = true;
browser.alarms.create(alarmName, { when: whenTime });
// debug - show alarm that are set
// browser.alarms.getAll().then((alarms) => {
// console.log("Active Alarms", alarms.length);
// for (let i = 0; i < alarms.length; i++) {
// const alarm = alarms[i];
// console.log("Alarm:", alarm.name, new Date(alarm.scheduledTime));
// }
// });
}
String.prototype.filledWith = function (...args) {
/// <summary>Similar to C# String.Format... in two modes:
/// 1) Replaces {0},{1},{2}... in the string with values from the list of arguments.
/// 2) If the first and only parameter is an object, replaces {xyz}... (only names allowed) in the string with the properties of that object.
/// Notes: the { } symbols cannot be escaped and should only be used for replacement target tokens; only a single pass is done.
/// </summary>
const values = typeof args[0] === "object" && args.length === 1 ? args[0] : args;
// const testForFunc = /^#/; // simple test for "#"
const testForElementAttribute = /^\*/; // simple test for "#"
const testDoNotEscapeHtml = /^\^/; // simple test for "^"
const testDoNotEscpaeHtmlButToken = /^-/; // simple test for "-"
const testDoNotEscpaeHtmlButSinglQuote = /^\>/; // simple test for ">"
const extractTokens = /{([^{]+?)}/g;
let debugCount = 0;
const replaceTokens = (input, debugCount) =>
input.replace(extractTokens, (...inner) => {
const token = inner[1];