-
Notifications
You must be signed in to change notification settings - Fork 6
/
simple_calender.js
1485 lines (1276 loc) · 50.6 KB
/
simple_calender.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
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: gray; icon-glyph: calendar;
// creator: https://github.com/JoeGit42
//////////////////////////////////////////////////////////////////////////////////////////////
// Description of this widget
// ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
// Simple calendar widget to be used in smart stacks
//
// Layout is clean and simple. There are several switches to configure the widget.
// (most of them in code, 2 important ones as widget parameter) E.g.
// • US-style (other calculation of weeks, and weeks starts on Sundays)
// • calender weeks are shown, but this can be disabled.
// • State (german:Bundesland) to show Public holidays (german: Feiertage) and Holidays (german: Ferien)
//
// Installation/Configuration
// ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
// Most important configuration is to define the month to show and the state (if you want to see marked holidays)
// Parameters have to be divided by ',' Example shows the configuration for the upcoming month, and the state Hessen
//
// 1st (and maybe the only parameter) is the numeric offset for the month.
// • -1 means the previous month is shown.
// • 2 means the month after the next month is shown.
// • This mechanism allows multiple widget in one stack. So you can swipe through the month.
//
// 2nd parameter is state (german: Bundesland)
// • 2-character abbreviation
// BW = Baden-Württemberg
// BY = Bayern
// BE = Berlin
// BB = Brandenburg
// HB = Bremen
// HH = Hamburg
// HE = Hessen
// MV = Mecklenburg-Vorpommern
// NI = Niedersachsen
// NW = Nordrhein-Westfalen
// RP = Rheinland-Pfalz
// SL = Saarland
// SN = Sachsen
// ST = Sachsen-Anhalt
// SH = Schleswig-Holstein
// TH = Thüringen
//
// US = USA (att: special handling, calender get's US style)
// FA = Persian/Farsi calendar
//
//
// ToDo / Ideas
// ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
// (1) Support of US holidays
//
// Misc
// ⎺⎺⎺⎺
// • Holiday icons are downloaded from https://www.streamlineicons.com
//
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
// DEBUG-CONFIG - DON'T TOUCH THIS
//////////////////////////////////////////////////////////////////////////////////////////////
//
const DEBUG = false
let debugRow
let debugText
const appArgs = "" // used in app environment, to have widget configuration
//
//////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
// Configuration
/////////////////////////////////////////////////////////////
let showCW = true // true: shows number of week
let styleUS = false // Shows calendar in US style (1st of the week is Sunday / 1st week in the year is always 1st Jan)
let styleFA = false // Shows persian calendar EXPERIMENTAL !!!
let markPublicHoliday = true // does only work for german public holiday (Feiertage)
let markHoliday = true // does only work for german holiday (Ferien)
let showHolidayIcons = false // shows icons for well known public holidays
let showHolidayEmojis = true // shows emojis for well known public holidays
// config for right sheet (in medium widget)
let showCWR = showCW
let styleUSR = styleUS
let styleFAR = styleFA
let markPublicHolidayR = markPublicHoliday
let markHolidayR = markHoliday
let showHolidayIconsR = showHolidayIcons
let showHolidayEmojisR = showHolidayEmojis
// Background-Image support
// For transparent backgrounds use the following script to create the correct image:
// https://gist.github.com/mzeryck/3a97ccd1e059b3afa3c6666d27a496c9
// After creating the image and saving it to photo library, you have to start this script with scriptable
// Set forceImageSelection = true -> You will get a dialog to select an image from library.
// The selected image will be saved with the filename <imgFileName>
// You have to set the same filename as one of the wdiget parameters
let imgFileName = "image.jpg" // this filename has to be used as widget-parameter
let useImageAsBackground = false
let forceImageSelection = false
let backgroundImage
// Sizes for small/medium widget
const S_FONT_SIZE_HEADER = 15
const S_FONT_SIZE_CAL = 11
const S_SPACER_AFTER_HEADER = 4
const S_HEADER_WIDTH = 150
const S_CELL_SIZE_HEIGHT = 17
const S_CELL_SIZE_WIDTH = 18
const S_CELL_SIZE_CW_WIDTH = 25
// Sizes for large widget (doubling the values works pretty well)
const L_FONT_SIZE_HEADER = 2.2 * S_FONT_SIZE_HEADER
const L_FONT_SIZE_CAL = 2.2 * S_FONT_SIZE_CAL
const L_SPACER_AFTER_HEADER = 2.2 * S_SPACER_AFTER_HEADER
const L_HEADER_WIDTH = 2.2 * S_HEADER_WIDTH
const L_CELL_SIZE_HEIGHT = 2.2 * S_CELL_SIZE_HEIGHT
const L_CELL_SIZE_WIDTH = 2.2 * S_CELL_SIZE_WIDTH
const L_CELL_SIZE_CW_WIDTH = 2.2 * S_CELL_SIZE_CW_WIDTH
// Fonts and Colors
let fontHeader = Font.mediumSystemFont(S_FONT_SIZE_HEADER)
let fontCal = Font.mediumSystemFont(S_FONT_SIZE_CAL)
let fontToday = Font.heavySystemFont(S_FONT_SIZE_CAL)
let fontCalOtherMonth = Font.thinSystemFont(S_FONT_SIZE_CAL)
let fontWeekday = Font.mediumSystemFont(S_FONT_SIZE_CAL)
let spacerAfterHeader = S_SPACER_AFTER_HEADER
let headerWidth = S_HEADER_WIDTH
const fontColorWeekdays = Color.gray()
const fontColorCW = Color.gray()
const fontColorSat = null // null will result in default color
const fontColorSun = Color.red()
const fontColorOtherMonth = Color.gray()
const fontColorToday = Color.green()
const fontColorMonth = null // null will result in default color
const cellColorHoliday = new Color('bbbbbb', 0.42)
const fontColorPrivate = Color.green()
// Size of fields
let cellSizeHeight = S_CELL_SIZE_HEIGHT
let cellSizeWidth = S_CELL_SIZE_WIDTH
let cellSizeWidthR = S_CELL_SIZE_WIDTH
let cellCWSizeWidth = S_CELL_SIZE_CW_WIDTH
let cellCWSizeWidthR = S_CELL_SIZE_CW_WIDTH
// Date format
const dfHeaderFormat = "MMMM"
const dfHeaderCurrentMonthFormat = "d. MMMM" // will be used, if the shown month is the current one
const dfHeaderOtherYearFormat = "MMMM yyyy" // will be used, if the shown month is the current one
const dfDayFormat = "d"
const dfWeekdayFormat = "EEEEE"
const faLocalizationString = "fa-IR"
const faHeaderFormat = {month: 'long'}
const faHeaderCurrentMonthFormat = {day: 'numeric', month: 'long'}
const faHeaderOtherYearFormat = {month: 'long', year: 'numeric'}
const faDayFormat = {day: 'numeric'}
const faWeekdayFormat = {weekday: 'narrow'}
// Refresh
const REFRESH_TIME = "00:00" // widget will be refreshed this time next day. (or not earlier than that)
const REFRESH_OFFSET_MIN = 10 // seconds
const REFRESH_OFFSET_MAX = 400// seconds
// Misc
const forceDownload = false
let monthShift = 0
let areaString = "HE"
let monthShiftR = 1
let areaStringR = "HE"
// Feiertage (bereitgestellt von https://feiertage-api.de)
//
// Auf der Webseite gibt es einen Spenden-Button, um diesen
// tollen Serivce zu unterstützen, der kostenlos bereitgestellt wird
//
// Für jedes Bundesland kann hier eine Liste der Daten für ein bestimmtes Jahr abgefragt werden.
// Kürzel der Bundesländer:
// BW, BY, BE, BB, HB, HH, HE, MV, NI, NW, RP, SL, SN, ST, SH, TH
//
// Beispiel (Daten für Hessen): https://feiertage-api.de/api/?jahr=2020&nur_land=HE
// Beispiel (Daten für Deutschland): https://feiertage-api.de/api/?jahr=2020&nur_daten
//
const feiertageApiURLworld = "https://date.nager.at/api/v2/PublicHolidays/#yyyy#/#area#"
const feiertageApiURLde = "https://feiertage-api.de/api/?jahr=#yyyy#&nur_land=#area#"
var ft1, ft2
// Ferien (bereitgestellt von https://ferien-api.de)
//
// Auf der Webseite gibt es einen Spenden-Button, um diesen
// tollen Serivce zu unterstützen, der kostenlos bereitgestellt wird
//
// Für jedes Bundesland kann hier eine Liste der Daten (ggf. für ein bestimmtes Jahr) abgefragt werden.
// Kürzel der Bundesländer:
// BW, BY, BE, BB, HB, HH, HE, MV, NI, NW, RP, SL, SN, ST, SH, TH
//
// Beispiel (Daten für Hessen): https://ferien-api.de/api/v1/holidays/HE
//
const ferienApiURL = "https://ferien-api.de/api/v1/holidays/"
var ferien
var ferienFromAPI
// Icons
//
const iconBaseURL = "https://github.com/JoeGit42/simple-calendar/blob/main/icons/"
// Days which can be displayed as Emoji
// variable days will be added in initEmojiDays()
// It's possible to replace day with emoji or icon.
// The 1st string is used for the emojis. 2nd string is used for the icon.
// If you enter an emoji also in the 2nd string it will be displayed anyhow.
let commonDays = [
[ 1, 1, "🥂", "champagne-cheers"],
[ 6, 1, "👑", "history-man-king"],
[14, 2, "💝", "love-gift-chocolate-box"], // Valentine's day
[ 1, 5, "🙅🏼♂️", "walking-forbidden"], // Tag der Arbeit, German Labour day
[17, 7, "😀", "smiley-smile"], // World Emoji Day
[ 3, 10, "🇩🇪", "🇩🇪"], // Tag der deutschen Einheit
[31, 10, "🎃", "halloween-pumpkin"],
[ 1, 11, "👼🏼", "christmas-angel"],
[ 6, 12, "🎅🏼", "christmas-santa"],
[24, 12, "🎄", "tree-christmas"],
[25, 12, "🤶🏼", "christmas-tree-ornament"],
[26, 12, "🎁", "christmas-tree-ornaments-1"],
[31, 12, "🍾", "champagne-cooler"]
];
const commonDaysLength = commonDays.length
// List for own private holidays
const privateHoliday = [
// ["2020-12-24", "2021-01-03"],
// ["2020-12-09", "2020-12-09"],
["2020-12-24", "2021-01-03"] // last entry without comma
];
const bl = [
["BW", "Baden_Wuerttemberg"],
["BY", "Bayern"],
["BE", "Berlin"],
["BB", "Brandenburg"],
["HB", "Bremen"],
["HH", "Hamburg"],
["HE", "Hessen"],
["MV", "Mecklenburg_Vorpommern"],
["NI", "Niedersachsen"],
["NW", "Nordrhein_Westfalen"],
["RP", "Rheinland_Pfalz"],
["SL", "Saarland"],
["SN", "Sachsen"],
["ST", "Sachsen_Anhalt"],
["SH", "Schleswig_Holstein"],
["TH", "Thueringen"]
];
// Returns the week of date, calculated according ISO standard
Date.prototype.getWeekISO = function() {
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), 0, 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}
// Returns the week of date calculated in US style (01.01.yyyy is week #01)
Date.prototype.getWeekUS = function() {
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
const firstDayOfYear = new Date(date.getFullYear(), 0, 1);
const pastDaysOfYear = (date.valueOf() - firstDayOfYear.valueOf()) / 86400000;
return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7);
}
// Returns the week of the date.
Date.prototype.getWeek = function(styleUS) {
if (styleUS == true) {
return this.getWeekUS()
} else {
return this.getWeekISO()
}
}
Date.prototype.getFaInLatin = function() {
var date = new Date(this.getTime());
return date.toLocaleDateString('fa-IR').replace(/([۰-۹])/g, token => String.fromCharCode(token.charCodeAt(0) - 1728));
}
Date.prototype.getDateFa = function() {
var date = new Date(this.getTime());
return parseInt( date.toLocaleDateString('fa-IR', {day: 'numeric'}).replace(/([۰-۹])/g, token => String.fromCharCode(token.charCodeAt(0) - 1728)) );
}
// get Farsi month (zero-based !)
Date.prototype.getMonthFa = function() {
var date = new Date(this.getTime());
return parseInt( date.toLocaleDateString('fa-IR', {month: 'numeric'}).replace(/([۰-۹])/g, token => String.fromCharCode(token.charCodeAt(0) - 1728)) -1);
}
Date.prototype.getFullYearFa = function() {
var date = new Date(this.getTime());
return parseInt( date.toLocaleDateString('fa-IR', {year: 'numeric'}).replace(/([۰-۹])/g, token => String.fromCharCode(token.charCodeAt(0) - 1728)) );
}
//returns the day which is the first day in persian calender
Date.prototype.get1stDayInMonthFa = function() {
var date = new Date(this.getTime());
// ATT gregorian_to_jalali() and jalali_to_gregorian() are workin with "correct" month nmot zero-based as usual
faDate = gregorian_to_jalali(date.getFullYear(), date.getMonth()+1, date.getDate())
grDate = jalali_to_gregorian(faDate["y"], faDate["m"], 1)
let returnDate = new Date(grDate["y"], grDate["m"]-1, grDate["d"]);
return returnDate
}
// from https://github.com/hat3ck/Persian-Calendar-Qt
// month from 1..12
function gregorian_to_jalali(gy, gm, gd) {
var g_d_m = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
var jy = (gy <= 1600) ? 0 : 979;
gy -= (gy <= 1600) ? 621 : 1600;
var gy2 = (gm > 2) ? (gy + 1) : gy;
var days = (365 * gy) + (parseInt((gy2 + 3) / 4)) - (parseInt((gy2 + 99) / 100)) +
(parseInt((gy2 + 399) / 400)) - 80 + gd + g_d_m[gm - 1];
jy += 33 * (parseInt(days / 12053));
days %= 12053;
jy += 4 * (parseInt(days / 1461));
days %= 1461;
jy += parseInt((days - 1) / 365);
if (days > 365)
days = (days - 1) % 365;
var jm = (days < 186) ? 1 + parseInt(days / 31) : 7 + parseInt((days - 186) / 30);
var jd = 1 + ((days < 186) ? (days % 31) : ((days - 186) % 30));
return {"y":jy, "m":jm, "d":jd};
}
// from https://github.com/hat3ck/Persian-Calendar-Qt
// month from 1..12
function jalali_to_gregorian(jy, jm, jd) {
var gy = (jy <= 979) ? 621 : 1600;
jy -= (jy <= 979) ? 0 : 979;
var days = (365 * jy) + ((parseInt(jy / 33)) * 8) + (parseInt(((jy % 33) + 3) / 4)) +
78 + jd + ((jm < 7) ? (jm - 1) * 31 : ((jm - 7) * 30) + 186);
gy += 400 * (parseInt(days / 146097));
days %= 146097;
if (days > 36524) {
gy += 100 * (parseInt(--days / 36524));
days %= 36524;
if (days >= 365)
days++;
}
gy += 4 * (parseInt((days) / 1461));
days %= 1461;
gy += parseInt((days - 1) / 365);
if (days > 365)
days = (days - 1) % 365;
var gd = days + 1;
var sal_a = [0, 31, ((gy % 4 == 0 && gy % 100 != 0) || (gy % 400 == 0)) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var gm
for (gm = 0; gm < 13; gm++) {
var v = sal_a[gm];
if (gd <= v) break;
gd -= v;
}
return {"y":gy, "m":gm, "d":gd};
//return [gy, gm, gd];
}
// from https://github.com/hat3ck/Persian-Calendar-Qt
// month from 1..12
function dayInMonthFa(year, month) {
month = month - 1
if (month < 0) return -1;
if (month < 6) return 31;
if (month < 11) return 30;
var ary = [1, 5, 9, 13, 17, 22, 26, 30];
var b = year % 33;
for (var i = 0; i < ary.length; i++)
if (b === ary[i])
return 30;
return 29;
}
// month from 1..12
// return from 0..6
function weekdayFa(jy, jm, jd) {
var d = jalali_to_gregorian(jy, jm, jd)
var g = new Date(d["y"], d["m"] - 1, d["d"])
return g.getDay()
}
// small widget instance
let widget = await createWidget()
if (!config.runsInWidget) await widget.presentMedium()
Script.setWidget(widget)
Script.complete()
function globalInit() {
// init for app environment is done at declaration
if (config.runsInWidget) {
switch (config.widgetFamily) {
case 'small':
case 'medium':
fontHeader = Font.mediumSystemFont(S_FONT_SIZE_HEADER)
fontCal = Font.mediumSystemFont(S_FONT_SIZE_CAL)
fontToday = Font.heavySystemFont(S_FONT_SIZE_CAL)
fontCalOtherMonth = Font.thinSystemFont(S_FONT_SIZE_CAL)
fontWeekday = Font.mediumSystemFont(S_FONT_SIZE_CAL)
spacerAfterHeader = S_SPACER_AFTER_HEADER
cellSizeHeight = S_CELL_SIZE_HEIGHT
cellSizeWidth = (!showCW) ? 1.2 * S_CELL_SIZE_WIDTH : S_CELL_SIZE_WIDTH
cellCWSizeWidth = (!showCW) ? 0.1 * S_CELL_SIZE_CW_WIDTH : S_CELL_SIZE_CW_WIDTH
cellSizeWidthR = (!showCWR) ? 1.2 * S_CELL_SIZE_WIDTH : S_CELL_SIZE_WIDTH
cellCWSizeWidthR = (!showCWR) ? 0.1 * S_CELL_SIZE_CW_WIDTH : S_CELL_SIZE_CW_WIDTH
headerWidth = S_HEADER_WIDTH
break;
case 'large':
default:
fontHeader = Font.mediumSystemFont(L_FONT_SIZE_HEADER)
fontCal = Font.mediumSystemFont(L_FONT_SIZE_CAL)
fontToday = Font.heavySystemFont(L_FONT_SIZE_CAL)
fontCalOtherMonth = Font.thinSystemFont(L_FONT_SIZE_CAL)
fontWeekday = Font.mediumSystemFont(L_FONT_SIZE_CAL)
spacerAfterHeader = L_SPACER_AFTER_HEADER
cellSizeHeight = L_CELL_SIZE_HEIGHT
cellSizeWidth = (!showCW) ? 1.2 * L_CELL_SIZE_WIDTH : L_CELL_SIZE_WIDTH
cellCWSizeWidth = (!showCW) ? 0.1 * L_CELL_SIZE_CW_WIDTH : L_CELL_SIZE_CW_WIDTH
cellSizeWidthR = (!showCWR) ? 1.2 * L_CELL_SIZE_WIDTH : L_CELL_SIZE_WIDTH
cellCWSizeWidthR = (!showCWR) ? 0.1 * L_CELL_SIZE_CW_WIDTH : L_CELL_SIZE_CW_WIDTH
headerWidth = L_HEADER_WIDTH
}
}
}
// main function
async function createWidget(items) {
let w = new ListWidget()
w.setPadding(5,3,5,2)
let showSheetR = false
let thisMonth
let thisYear
let weeksInMonth
// DEBUG init
if (DEBUG) {
debugRow = w.addStack()
debugText = debugRow.addText("DEBUG")
debugText.font = Font.mediumSystemFont(6)
}
// DEBUG_END
// check parameter (month to display can be adjusted)
// state (german: Bundesland) can be given as second parameter
// e.g.
// -1, NW -> last month, holiday of NRW
// 0, BY -> current month, holiday of Bayern
// <empty> -> no paremeter means current month, holiday of Hessen (default)
// 2, HE -> shows the month ofter the next month, holiday of Hessen
let parCount = parseInput(args.widgetParameter)
globalInit()
if ( useImageAsBackground || (forceImageSelection && config.runsInApp) ) {
let foundPicture
try {
foundPicture = await getBackgroundImage();
if (foundPicture) w.backgroundImage = backgroundImage
} catch (err) {
useImageAsBackground = false
}
if (!foundPicture) {
let stack = w.addStack()
stack.addText ("[" + imgFileName + "] not found")
}
}
setWidgetURL(w, areaString)
// Check the number of rows to display (should be equal in both sheets in medium widget)
let dayToCalculateWith = new Date()
if (monthShift != 0) addMonth(dayToCalculateWith, monthShift, styleFA)
if (!styleFA) {
thisMonth = dayToCalculateWith.getMonth()
thisYear = dayToCalculateWith.getFullYear()
weeksInMonth = weekCount(thisYear, thisMonth, styleUS ? 0 : 1)
} else { // styleFA
thisMonth = dayToCalculateWith.getMonthFa()
thisYear = dayToCalculateWith.getFullYearFa()
weeksInMonth = weekCountFa(thisYear, thisMonth+1)
}
if (config.runsInWidget) {
if (config.widgetFamily == "medium") { showSheetR = true }
} else { showSheetR = true } // in app
// the other sheet might have to display more weeks
if (showSheetR) {
dayToCalculateWith = new Date()
if (monthShiftR != 0) addMonth(dayToCalculateWith, monthShiftR, styleFAR)
if (!styleFAR) {
thisMonth = dayToCalculateWith.getMonth()
thisYear = dayToCalculateWith.getFullYear()
weeksInMonth = Math.max(weeksInMonth, weekCount(thisYear, thisMonth, styleUSR ? 0 : 1))
} else { // styleFA
thisMonth = dayToCalculateWith.getMonthFa()
thisYear = dayToCalculateWith.getFullYearFa()
weeksInMonth = Math.max(weeksInMonth, weekCountFa(thisYear, thisMonth+1))
}
}
// a bit more space between the rows, if 5 or 4 weeks are shown
if (weeksInMonth < 6) {
cellSizeHeight = (cellSizeHeight*6)/(weeksInMonth*1.1)
}
doubleSheet = w.addStack()
doubleSheet.layoutHorizontally()
let sheetLeft = doubleSheet.addStack()
sheetLeft.layoutVertically()
await drawSheet(sheetLeft, monthShift, weeksInMonth, areaString, showCW, styleUS, styleFA, markPublicHoliday, markHoliday, showHolidayEmojis, showHolidayIcons, areaString != areaStringR);
// show 2nd in medium widget
if (showSheetR) {
cellCWSizeWidth = cellCWSizeWidthR
cellSizeWidth = cellSizeWidthR
doubleSheet.addSpacer(15)
let sheetRight = doubleSheet.addStack()
sheetRight.layoutVertically()
await drawSheet(sheetRight, monthShiftR, weeksInMonth, areaStringR, showCWR, styleUSR, styleFAR, markPublicHolidayR, markHolidayR, showHolidayEmojisR, showHolidayIconsR, areaString != areaStringR);
}
// set refresh date
w.refreshAfterDate = getRefreshDate(REFRESH_TIME, REFRESH_OFFSET_MIN, REFRESH_OFFSET_MAX)
return w
}
function getRefreshDate (rTimeStr, minOffsetSec, maxOffsetSec) {
// set tomorrow
const d = new Date()
let rDate = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1)
// in the early morning
let rtime = rTimeStr.split(":")
rDate.setHours(rtime[0])
rDate.setMinutes(rtime[1])
rDate.setSeconds(getRandomArbitrary(minOffsetSec, maxOffsetSec))
return rDate
}
// get image to be used as background
async function getBackgroundImage () {
let fm = FileManager.local()
let dir = fm.documentsDirectory()
let path = fm.joinPath(dir, imgFileName)
try {
if (config.runsInApp && forceImageSelection) {
let alert = new Alert()
alert.message = "You can select an image from your library to be used as background."
alert.addAction("OK")
await alert.presentAlert()
backgroundImage = await Photos.fromLibrary()
await fm.writeImage(path, backgroundImage);
return true
}
if ( fm.fileExists(path) ) {
backgroundImage = await fm.readImage(path);
} else {
return false
}
} catch (err) {
useImageAsBackground = false
return false
}
return true
}
// draws one calender sheet (will be called twice in medium widget)
async function drawSheet(drawstack, m_shift, num_rows, area, cw, us, fa, p_holiday, holiday, emojis, icons, showArea) {
// Date string init
const dfHeaderOtherYear = dfCreateAndInit(dfHeaderOtherYearFormat)
const dfHeaderCurrentMonth = dfCreateAndInit(dfHeaderCurrentMonthFormat)
const dfHeader = dfCreateAndInit(dfHeaderFormat)
const dfDay = dfCreateAndInit(dfDayFormat)
const dfWeekday = dfCreateAndInit(dfWeekdayFormat)
// collect all the necessary data
const today = new Date()
let dayToCalcWith = new Date()
if (m_shift != 0) { addMonth(dayToCalcWith, m_shift, fa) }
const thisWeek = today.getWeek(us)
const thisMonth = dayToCalcWith.getMonth()
const thisYear = dayToCalcWith.getFullYear()
const thisMonthFa = dayToCalcWith.getMonthFa()
const thisYearFa = dayToCalcWith.getFullYearFa()
const otherYear = (thisMonth == 0) ? thisYear-1 : thisYear+1 // to get public Holidays for previos year or next year
const thisMonthFirst = new Date(thisYear, thisMonth, 1)
const thisMonthFirstFa = dayToCalcWith.get1stDayInMonthFa()
const thisMonthFirstWeekday = thisMonthFirst.getDay() // Sunday = 0, Monday = 1, ...
//const thisMonthFirstWeek = thisMonthFirst.getWeek(us)
//const thisMonthLast = new Date(thisYear, thisMonth + 1, 0)
//const thisMonthLastWeek = thisMonthLast.getWeek(us)
const weeksInMonth = num_rows // weekCount(thisYear, thisMonth, us ? 0 : 1)
// get holiday info
// if it not succeeds, feature will be disabled
if (p_holiday) {
p_holiday = await fetchPublicHolidayInfo(thisYear, otherYear, area)
}
// get holiday info
// if it not succeeds, feature will be disabled
if (holiday) {
holiday = await fetchHolidayInfo(area)
}
// Prepare the days, which are replaced with Emojis
if (emojis || icons) initEmojiDays(dayToCalcWith)
// Prepare an array with the weekday.
weekdayHeader = prepareWeekdayHeader (us, fa)
// first row will be the month
// e.g. November
if (!fa) {
if ( sameDay(dayToCalcWith, today) ) {
headerStr = dfHeaderCurrentMonth.string(dayToCalcWith) // show day, if it's the current month
} else if (dayToCalcWith.getFullYear() != today.getFullYear()) {
headerStr = dfHeaderOtherYear.string(dayToCalcWith) // show year, if it's not this year
} else {
headerStr = dfHeader.string(dayToCalcWith) // show the month
}
} else { // styleFA
if ( sameDay(dayToCalcWith, today) ) {
headerStr = dayToCalcWith.toLocaleDateString(faLocalizationString, faHeaderCurrentMonthFormat)
} else if (dayToCalcWith.getFullYearFa() != today.getFullYearFa()) {
headerStr = dayToCalcWith.toLocaleDateString(faLocalizationString, faHeaderOtherYearFormat)
} else {
headerStr = dayToCalcWith.toLocaleDateString(faLocalizationString, faHeaderFormat)
}
}
let monthHeaderRow = drawstack.addStack()
monthHeaderRow.size = new Size(headerWidth, 0)
if (DEBUG){ monthHeaderRow.borderWidth = 1; monthHeaderRow.borderColor = Color.yellow(); }
monthHeaderRow.addSpacer(0)
let monthHeaderRowTxt = monthHeaderRow.addText(headerStr.toUpperCase())
monthHeaderRow.addSpacer(0)
monthHeaderRow.centerAlignContent()
monthHeaderRowTxt.font = fontHeader
monthHeaderRowTxt.textColor = fontColorMonth
monthHeaderRowTxt.centerAlignText()
drawstack.addSpacer(spacerAfterHeader)
let fullCal = drawstack.addStack()
let dayToPrint = new Date()
if (DEBUG) { fullCal.borderWidth = 1; }
if (cw) {
// first column
// e.g.
// KW
// #44
// #45
// ...
let cwCol = fullCal.addStack()
if (DEBUG){ cwCol.borderWidth = 1; cwCol.borderColor = Color.gray(); }
cwCol.layoutVertically()
cwCol.centerAlignContent()
let cwCell = cwCol.addStack()
cwCell.size = new Size(cellCWSizeWidth, cellSizeHeight)
cwCell.centerAlignContent()
let cwTxt = cwCell.addText(" ") // empty cell
if (showArea) {
cwTxt.text = area.toLowerCase()
if (cwTxt.text == "nw") {cwTxt.text = "nrw"}
//if (cwTxt.text == "us") {cwTxt.text = "🇺🇸"}
}
cwTxt.font = fontCal
cwTxt.textColor = fontColorCW
cwTxt.centerAlignText()
setDay(dayToPrint, thisMonthFirst)
let weekToShow = dayToPrint.getWeek(us)
for (var i = 0; i < weeksInMonth; i++) {
let cwCell = cwCol.addStack()
if (DEBUG){ cwCell.borderWidth = 1; cwCell.borderColor = Color.green(); }
cwCell.size = new Size(cellCWSizeWidth, cellSizeHeight)
cwCell.centerAlignContent()
weekToShow = dayToPrint.getWeek(us)
let weekToShowStr = (weekToShow < 10) ? "#0" + weekToShow : "#" + weekToShow
let cwTxt = cwCell.addText( weekToShowStr )
cwTxt.font = fontCal
cwTxt.leftAlignText()
if (thisWeek == weekToShow && today.getFullYear() == dayToCalcWith.getFullYear()) { cwTxt.textColor = fontColorToday } else { cwTxt.textColor = fontColorCW }
dayToPrint = addDay(dayToPrint, 7) // prepare for the next week/row
}
} else { // some space instead of calender weeks
fullCal.addSpacer(cellCWSizeWidth)
}
// now we come to the numbers
// - 7 columns - one for each weekday
// - 4 to 6 rows for the week
let diff = us ? thisMonthFirstWeekday : getDay1(thisMonthFirstWeekday) - 1 // number of days which have to be filled with old month in the first row
if (fa) {
var firstOfMonthDay = weekdayFa(thisMonthFirstFa.getFullYearFa(), thisMonthFirstFa.getMonthFa()+1, 1)
diff = (firstOfMonthDay - 6 + 7) % 7;
}
for (var wd = 1; wd <= 7; wd++) { // one column for each weekday
if (!fa) {
setDay(dayToPrint, thisMonthFirst)
dayToPrint = addDay(dayToPrint, (diff * (-1)) + (wd-1)) // set the day to the first day in the week (might be the previous month in the 1st week of the month)
} else { // styleFA
setDay(dayToPrint, thisMonthFirstFa)
dayToPrint = addDay(dayToPrint, (7 - (diff+1)) - (wd-1) ) // set the day to the first day in the week (might be the previous month in the 1st week of the month)
}
let wdCol = fullCal.addStack()
if (DEBUG){ wdCol.borderWidth = 1; wdCol.borderColor = Color.red(); }
wdCol.layoutVertically()
wdCol.centerAlignContent()
let dayCell = wdCol.addStack()
dayCell.size = new Size(cellSizeWidth, cellSizeHeight)
dayCell.centerAlignContent()
let cellTxt = dayCell.addText(weekdayHeader[wd])
cellTxt.font = fontWeekday
cellTxt.textColor = fontColorWeekdays
cellTxt.centerAlignText()
if (!fa && dayToPrint.getDay() == 6 && fontColorSat) cellTxt.textColor = fontColorSat
if (!fa && dayToPrint.getDay() == 0 && fontColorSun) cellTxt.textColor = fontColorSun
if (fa && dayToPrint.getDay() == 5 && fontColorSun) cellTxt.textColor = fontColorSun // persian calendar get the Friday in red
for (var r = 0; r < weeksInMonth; r++) {
let dayCell = wdCol.addStack()
if (DEBUG){ dayCell.borderWidth = 1; dayCell.borderColor = Color.green(); }
dayCell.size = new Size(cellSizeWidth, cellSizeHeight)
dayCell.centerAlignContent()
let cellTxt = dayCell.addText( dfDay.string(dayToPrint) )
if (fa) cellTxt.text = dayToPrint.toLocaleDateString(faLocalizationString, faDayFormat)
await setCellStyle(dayToPrint, (fa) ? thisMonthFirstFa : thisMonthFirst, dayCell, cellTxt, p_holiday, holiday, emojis, icons, fa)
dayToPrint = addDay(dayToPrint, 7) // prepare for the next week/row
}
}
}
// days are equal?
function sameDay(d1, d2) {
return d1.getFullYear() === d2.getFullYear() &&
d1.getMonth() === d2.getMonth() &&
d1.getDate() === d2.getDate()
}
// same month in the same year
function sameMonth(d1, d2, fa) {
if (!fa) {
return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth()
} else { // styleFA
return d1.getFullYearFa() === d2.getFullYearFa() && d1.getMonthFa() === d2.getMonthFa()
}
}
// Change a weekday to have sunday = 7 (instead of 0): Monday = 1, Sunday = 7
function getDay1(d) { return (d==0) ? 7 : d}
// days will be added (can be negative)
function addDay(d, diff) {
d2 = new Date(d.getFullYear(), d.getMonth(), d.getDate() + diff)
//d.setTime( d2.getTime() )
return d2
}
// set d1 to the same time as d2
function setDay(d1, d2) { d1.setTime(d2.getTime()) }
// shifts the month. rollover will be handled automatically
function addMonth(d, shift, fa) {
if (!fa) {
d.setDate(1)
d.setMonth(d.getMonth() + shift)
} else { // shifts the month in persian calendar
let faDay1 = d.get1stDayInMonthFa()
let currentFaMonth = faDay1.getMonthFa() // zero based
let currentFaYear = faDay1.getFullYearFa()
let newFaMonth = (currentFaMonth + shift) % 12 // zero based
let yDiff = Math.floor( (currentFaMonth + shift) / 12 )
let newFaYear = currentFaYear + yDiff
let grDay = jalali_to_gregorian(newFaYear, newFaMonth+1, 1)
let grDate = new Date(grDay["y"], grDay["m"]-1, grDay["d"]);
d.setTime( grDate.getTime() )
}
}
// how many weeks does given month have
function weekCountFa(year, month) {
// month is in the range 1..12
// first day of the week is Saturday (ATT: it's the column on the _right_ edge!)
var firstDayOfWeek = 6;
var numberOfDaysInMonth = dayInMonthFa(year, month)
var firstOfMonthDay = weekdayFa(year, month, 1)
var firstWeekDay = (firstOfMonthDay - firstDayOfWeek + 7) % 7;
var used = firstWeekDay + numberOfDaysInMonth;
return Math.ceil( used / 7);
}
// how many weeks does given month have
function weekCount(year, month_number, startDayOfWeek) {
// month_number is in the range 0..11
// Get the first day of week week day (0: Sunday, 1: Monday, ...)
var firstDayOfWeek = startDayOfWeek || 0;
var firstOfMonth = new Date(year, month_number, 1);
var lastOfMonth = new Date(year, month_number+1, 0);
var numberOfDaysInMonth = lastOfMonth.getDate();
var firstWeekDay = (firstOfMonth.getDay() - firstDayOfWeek + 7) % 7;
var used = firstWeekDay + numberOfDaysInMonth;
return Math.ceil( used / 7);
}
function countCodePoints(str) {
var point;
var index;
var width = 0;
var len = 0;
for (index = 0; index < str.length;) {
point = str.codePointAt(index);
width = 0;
while (point) {
width += 1;
point = point >> 8;
}
index += Math.round(width/2);
len += 1;
}
return len;
}
// set style for the calender
async function setCellStyle(day, reference, cellStack, cellText, p_holiday, holiday, showEmojis, showIcons, fa) {
const today = new Date()
let isPrivate = false;
let iconStr = ""
let iconImg
let stackImage
//check if date can be replaced by emoji
if (showEmojis && sameMonth(day, reference, fa)) {
cellText.text = getEmoji(day, cellText.text)
}
//check if date can be replaced by icon
if (showIcons && sameMonth(day, reference, fa)) {
iconStr = getIconName(day, cellText.text)
console.log(iconStr)
if (iconStr.length > 4) { // length of 1 or 2 indicating numbers 1..31 / to handle emojis also strings with 4 char are not seen as icon name (does not work with all emojis, but the relevant)
iconImg = await getIcon(iconStr);
cellText.text = ""
if (!sameDay(day, today)) { // on same day the icon will be added in green circle below
stackImage = cellStack.addImage(iconImg)
let iconSize = Math.min(cellSizeHeight, cellSizeWidth) - 4
stackImage.imageSize = new Size(iconSize, iconSize)
}
} else {
cellText.text = iconStr
}
}
if (isPrivateHoliday(day)) {
cellText.textColor = fontColorPrivate
isPrivate = true
}
// different style for days of previous and next month
if ( !sameMonth(day, reference, fa) ) {
if (!isPrivate) {cellText.textColor = fontColorOtherMonth} else {cellText.textColor = fontColorPrivate}
if (!fa && day.getDay() == 6 && fontColorSat) cellText.textColor = fontColorSat
if (!fa && day.getDay() == 0 && fontColorSun) cellText.textColor = fontColorSun
if (fa && day.getDay() == 5 && fontColorSun) cellText.textColor = fontColorSun // persian calendar get the Friday in red
cellText.font = fontCalOtherMonth
} else {
if (!fa && day.getDay() == 6 && fontColorSat) cellText.textColor = fontColorSat
if (!fa && day.getDay() == 0 && fontColorSun) cellText.textColor = fontColorSun
if (fa && day.getDay() == 5 && fontColorSun) cellText.textColor = fontColorSun // persian calendar get the Friday in red
cellText.font = fontCal
}
if (p_holiday && ft1 && ft2) {
if (isPublicHoliday (day) && fontColorSun) cellText.textColor = fontColorSun
}
if (holiday && ferien) {
if (isHoliday (day) ) cellStack.backgroundColor = cellColorHoliday
}
// today get a nice circle
if ( sameDay(day, today) ) {
cellText.font = fontToday
const highlightedDate = getHighlightedDate(cellText.text, cellText.textColor, iconImg)
cellText.text = "" // delete text, as circle includes the text
cellStack.addImage(highlightedDate)
}
if (stackImage) {
if (cellText.textColor) {
stackImage.tintColor = cellText.textColor
} else {
stackImage.tintColor = Color.dynamic(Color.black(), Color.white())
}
}
cellText.centerAlignText()
}
// creates circle for a highlighted day
function getHighlightedDate(date, color, icon) {
const drawing = new DrawContext()
let textColor
if (color) {
if (color.hex != fontColorToday.hex) {textColor = color} else {textColor = null}
}
drawing.respectScreenScale = true
const size = 50
drawing.size = new Size(size, size)
drawing.opaque = false
drawing.setFillColor(fontColorToday)
drawing.fillEllipse(new Rect(1, 1, size - 2, size - 2))
drawing.setFont(Font.boldSystemFont(30))
if (textColor) drawing.setTextColor(textColor)
drawing.setTextAlignedCenter()
if (icon) {
drawing.drawImageInRect(icon, new Rect(6, 6, size-12, size-12))
} else {
drawing.drawTextInRect(date, new Rect(0, 6, size, size))
}
const currentDayImg = drawing.getImage()
return currentDayImg
}
function initEmojiDays(date) {
// delete last entries
if (commonDaysLength < commonDays.length) {
for (i = (commonDays.length - commonDaysLength); i; i--) {
commonDays.pop()
}
}
// Special hanbdling for days to calculate
// 1. Advent