-
Notifications
You must be signed in to change notification settings - Fork 45
/
datepickerwidget.js
1219 lines (1142 loc) · 42.6 KB
/
datepickerwidget.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
/*******************************************************************************
* Copyright 2023 Adobe
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
if (typeof window.DatePickerWidget === 'undefined') {
window.DatePickerWidget = class {
#widget = null;
#model = null // passed by reference
#options = null
#lang = "en";
#dp = null;
#curInstance = null;
#calendarIcon = null;
static #visible = false;
static #clickedWindow;
/** default configuration options
*
* yearsPerView: number of years to show in the yearset view
*
* width: with of the widget
*
* viewHeight: Height of the month,year and yearset view. This doesn't include
* the height of the header
*
* locale: locale information for the locale in which to show the datepicker which comprises of
* days: day names to display in the monthview
* months: month names to display in the yearview
* zero: string representation of zero in the locale. Numbers will be
* displayed in that locale only
* clearText: Text to display for the reset button
* name: name of the locale
*
* format: input format for the datepicker (not implemented)
*
* pickerType: type of the datetimepicker (date, datetime and time)
*
* positioning: element around which datepicker will be displayed. if null then it
* will be displayed around the input element
*
* showCalendarIcon: to show the Calendar on the right of the text field or not
*/
#defaultOptions = {
yearsPerView: 16,
width: 340,
viewHeight: 248,
locale: {
days: ["S","M","T","W","T","F","S"],
months: ["January","February","March","April","May","June","July","August","September","October","November","December"],
zero: "0",
clearText: "Clear",
name: "en_US"
},
format: "YYYY-MM-DD",
pickerType: "date",
positioning: null,
showCalendarIcon: true
}
#dates = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
/*
* Actions to perform when clicked on the datepicker buttons
* for different views
* caption: view to show when clicked on caption
* (Year/YearSet/Month/null) null means don't change the view
* li: view to show when clicked on date, month or year element
* upDown: add(up key) or subtract(down key) current date (for monthview),
* month(Year View) or year(YearSetView) with the number provided
* key: identifies the key that needs to be changed for that view
*/
#viewAction = {
Month: {
caption: 'Year',
li: null,
key: "day",
upDown: 7
},
Year: {
caption: "Yearset",
li: "Month",
key: "month",
upDown: 3
},
Yearset: {
caption: null,
li: "Year",
key: "year",
upDown: 4
}
}
selectedDay = 0;
selectedMonth = 0;
selectedYear = 0;
currentDay = 0;
currentMonth = 0;
currentYear = 0;
//view="Month";
#touchSupported = !!("ontouchstart" in window || window.DocumentTouch
&& document instanceof DocumentTouch);
#defaultView = "Month";
#keysEnabled = false;
#focusedOnLi = false;
#keyboardAccessibility = true;
#scriptFocus;
/* template for the clear Button */
#clearButtonTemplate = '<div class="dp-clear">' +
'<a></a>' +
'</div>';
/* template for the calendar
* header contains the navigation icons (left and right arrows)
* and the current caption (which can be date, year or month)
*
* monthview displays the grid for showing the dates for a particular
* month
*
* yearview displays all the months of that year
*
* yearsetview displays a grid of 16 years. This can be configured
* through the option: yearsPerView
*
*/
#calendarTemplate = '<div class="dp-header">' +
'<div class="dp-leftnav"></div>' +
'<div class="dp-caption"></div>' +
'<div class="dp-rightnav"></div>' +
'</div>' +
'<div class="view dp-monthview"></div>' +
'<div class="view dp-yearview"></div>' +
'<div class="view dp-yearsetview"></div>';
constructor(view, widget, model) {
this.#model = model;
this.#lang = view.getModel().lang;
let editValFn = () => {
return model.editValue;
};
let displayValueFn = () => {
return model.displayValue;
};
this.#localizeDateElements(this.#defaultOptions, this.#lang);
this.#options = Object.assign(
{editValue: editValFn, displayValue: displayValueFn},
this.#defaultOptions, this.#model._jsonModel);
this.#initialiseCalenderElement();
//update widget markup to have input type=text element.
let newDatePickerElement = widget.cloneNode(true);
newDatePickerElement.setAttribute("type", "text");
newDatePickerElement.id = model.id + '-widget';
widget.parentNode.replaceChild(newDatePickerElement, widget);
this.#widget = view.getWidget();
this.#attachField(view.getWidget(), this.#options);
}
#initialiseCalenderElement() {
let self = this,
html = "";
if (this.#options.pickerType.match(/date/)) {
html += this.#calendarTemplate;
}
html += this.#clearButtonTemplate;
this.#dp = document.getElementsByClassName("datetimepicker")[0];
if (!this.#dp) {
this.#dp = document.createElement("div");
this.#dp.classList.add("datetimepicker", "datePickerTarget");
this.#dp.innerHTML = html;
//Always inserting it in body
document.body.appendChild(this.#dp);
}
// attach click event on entire datePicker popup
this.#dp.addEventListener("click",
function (evnt) {
//focus only if the device doesn't support touch
// input otherwise on screen keyboard will popup
if (!self.#touchSupported) {
if (self.#curInstance) {
self.#curInstance.$field.focus();
}
}
}, false);
"touchstart mousedown".split(" ").forEach(function (e) {
self.#dp.addEventListener(e, function (evt) {
self.#checkWindowClicked(evt)
}, false);
});
this.$month = this.#dp.getElementsByClassName("dp-monthview")[0];
this.$year = this.#dp.getElementsByClassName("dp-yearview")[0];
this.$yearset = this.#dp.getElementsByClassName("dp-yearsetview")[0];
this.clear = this.#dp.getElementsByClassName(
"dp-clear")[0].getElementsByTagName("a")[0];
this.clear.addEventListener("click", function (evnt) {
if (self.view && self.#curInstance) {
self.#clearDate(self.view);
}
});
this.prevNavWidthBtn = this.#dp.getElementsByClassName("dp-leftnav")[0];
this.prevNavWidthBtn.addEventListener("click",
function (evnt) {
if (self.view && self.#curInstance) {
self.#adjustDate(-1, self.view, false)
}
});
this.nextNavWidthBtn = this.#dp.getElementsByClassName("dp-rightnav")[0];
this.nextNavWidthBtn.addEventListener("click",
function (evnt) {
if (self.view && self.#curInstance) {
self.#adjustDate(1, self.view, false)
}
});
this.caption = this.#dp.getElementsByClassName("dp-caption")[0];
this.caption.addEventListener("click",
function (evnt) {
if (self.view && self.#curInstance) {
if (!self.caption.classList.contains("disabled")) {
self.#layout(self.#viewAction[self.view].caption);
}
}
});
if (this.#keyboardAccessibility) {
[this.prevNavWidthBtn, this.caption, this.nextNavWidthBtn,
this.clear].forEach(function (elem, i) {
elem.setAttribute("tabIndex", i + 1);
});
}
}
/*
* attaches the date picker to the field. This is a one time operation
* First creates a configuration object and stores it in the field data attributes
* then attaches event handlers on click, focus (to show the picker) and blur (to hide) events
*/
#attachField(widget, options) {
let inst = this.#newInst(widget, options),
self = this,
activateField = function (evnt) {
if (!self.#curInstance) {
self.#activateField(evnt);
}
if (self.#options.showCalendarIcon) {
if (evnt.type === self.#getEvent()) {
if (self._iconClicked) {
self._iconClicked = false;
if (DatePickerWidget.#visible) {
self.#hide(); // hide the calendar popup if visible when calendar icon is clicked
self.#curInstance.$field.focus(); // bring back focus in field
} else {
self.#show(); //// show the calendar popup if not visible when calendar icon is clicked
}
}
}
} else {
/*show the popup only if
1. click/touch event
2. focus event in case of non-touch devices and focus is not done using script
*/
if (evnt.type === self.#getEvent() || (evnt.type === "focus"
&& !self.#touchSupported && !self.#scriptFocus)) {
self.#show(evnt);
}
}
DatePickerWidget.#clickedWindow = true;
self.#scriptFocus = false;
},
deactivateField = function (evnt) {
//deactivate only if clicked outside window
// on touch devices only keyboard or calendar should be active at once, touching keyboard should deactivate calendar
if ((DatePickerWidget.#clickedWindow && !self.#focusedOnLi)
&& (self.#options.showCalendarIcon || !self.#touchSupported)) {
self.#hide();
self.#deactivateField();
DatePickerWidget.#clickedWindow = true;
}
};
window.afCache.put(widget, "datetimepicker", inst);
widget.addEventListener(this.#getEvent(), activateField);
widget.onfocus = activateField;
widget.onblur = deactivateField;
if (options.showCalendarIcon) {
let calendarIcon = document.createElement("div");
calendarIcon.classList.add("cmp-adaptiveform-datepicker__calendar-icon");
widget.parentNode.insertBefore(calendarIcon, widget.nextSibling);
if (this.#keyboardAccessibility) {
calendarIcon.setAttribute("tabindex", 0);
}
calendarIcon.addEventListener(this.#getEvent(), function (evnt) {
self._iconClicked = true;
widget.click();
});
calendarIcon.addEventListener("keydown", function (event) {
if (event.keyCode === 32 || event.keyCode === 13) {
widget.click();
}
});
this.#calendarIcon = calendarIcon;
if (options.readOnly) {
this.markAsReadOnly(true)
}
}
}
markAsReadOnly(readonly) {
if (readonly) {
this.#calendarIcon.style.display = "none";
} else {
this.#calendarIcon.style.display = "";
}
}
#newInst(widget, options) {
return {
$field: widget,
locale: options.locale,
positioning: options.positioning || widget,
access: options.access,
selectedDate: options.value,
editValue: options.editValue,
displayValue: options.displayValue,
minValidDate: options.minimum,
maxValidDate: options.maximum,
exclMinDate: options.exclusiveMinimum,
exclMaxDate: options.exclusiveMaximum
}
}
/*
* To check where the click happened, if happened outside the datepicker
* then hide the picker. This is checked whether any ancestor of clicked target
* has a class datePickerTarget. This class is added to the attached element as well
*/
#checkWindowClicked(evnt) {
let self = this;
if (self.#curInstance) {
// datepickerTarget class depicts that the component is a part of the Date Field
// and on click of that class, we should not hide the datepicker or fire exit events.
if (!evnt.target.closest(".datePickerTarget")) {
//non-touch devices do not deactivate on blur. Hence needs to be done here
if (self.#touchSupported) {
self.#hide();
//clicking outside a field doesn't blur the field in IPad. Doing it by script
self.#curInstance.$field.blur();
self.#deactivateField();
} else {
DatePickerWidget.#clickedWindow = true;
}
} else {
DatePickerWidget.#clickedWindow = false;
}
}
}
/*
* handling of key strokes. All the key strokes prevent the default browser action
* unless specified otherwise
* tab: set focus on calendar icon when dateinput field is active, navigates through date picker buttons when datepicker is open,
* otherwise perform default browser action
* escape: hides the datepicker
* down arrow key: navigate the picker downwards by the number specified in actionView.upDown of the current View
* up arrow key: navigate the picker upwards by the number specified in actionView.upDown of the current View
* left arrow key: navigate the picker one unit of that view backward
* right arrow key: navigate the picker one unit of that view forward
* shift + up: perform the action that happens on clicking the caption (as specified in actionView.caption)
* shift + left: perform the action that happens on clicking the left navigation button
* shift + right: perform the action that happens on clicking the right navigation button
* space/enter: triggers the click event for the current focused element from datepicker/ opens datepicker when calendar icon is focused.
*/
#hotKeys(evnt) {
var handled = false, date;
switch (evnt.keyCode) {
case 9: //tab
// CQ-4239352 : Setting clickedWindow property to true on tabbing so that deactivateField logic gets executed
// When clicking on "x" on input field in in IE and when selecting the content and releasing the mouse select outside the field
// the click event is not trigerred on the field and hence activateField is not executed, so clickedWindow remains as false
DatePickerWidget.#clickedWindow = true;
handled = false;
break;
case 27://escape
if (DatePickerWidget.#visible) {
this.#hide();
this.#curInstance.$field.focus();
this.#deactivateField();
handled = true;
}
break;
case 32: //space
case 13: // enter
if (evnt.target.classList.contains("cmp-adaptiveform-datepicker__calendar-icon")) {
if (!DatePickerWidget.#visible) {
this.#show();
return;
}
this.$focusedDate.classList.add("dp-focus");
}
break;
case 40: //down arrow key
if (!DatePickerWidget.#visible) {
this.#show();
return;
}
this.$focusedDate.classList.add("dp-focus");
break;
}
if (DatePickerWidget.#visible && this.#keysEnabled) {
var v = this.#viewAction[this.view].key,
updown = this.#viewAction[this.view].upDown;
switch (evnt.keyCode) {
case 9: // tab
if (evnt.shiftKey) {
if (evnt.target.classList.contains("dp-leftnav")
|| evnt.target.classList.contains("dp-focus")) {
this.#hide();
this.#curInstance.$field.focus();
handled = true;
} else {
handled = false;
}
} else {
const buttonTabindex = evnt.target.getAttribute("tabindex");
if (buttonTabindex === '0') {
if (evnt.target.tagName.toLocaleLowerCase() === "input") {
this.#hide();
handled = false;
} else {
this.prevNavWidthBtn.focus();
handled = true;
}
} else if (buttonTabindex === '4') {
this.#hide();
this.#curInstance.$field.focus();
handled = true;
} else {
handled = false;
}
}
break;
case 32: //select on space
case 13: // select on enter
this.hotKeyPressed = true;
this.#focusedOnLi = false;
if (!this.#focusedOnLi) {
evnt.target.click();
} else {
if (this.$focusedDate) {
this.$focusedDate.click() //todo
}
}
this.hotKeyPressed = false;
handled = true;
break;
case 37: //left arrow key
if (evnt.shiftKey) {
this.prevNavWidthBtn.click();
} else {
this.#adjustDate(-1, v, true);
}
handled = true;
break;
case 38: //up arrow key
if (evnt.shiftKey) {
this.caption.click();
} else {
this.#adjustDate(-updown, v, true);
}
handled = true;
break;
case 39: //right arrow key
if (evnt.shiftKey) {
this.nextNavWidthBtn.click();
} else {
this.#adjustDate(+1, v, true);
}
handled = true;
break;
case 40: //down arrow key
this.#adjustDate(updown, v, true);
handled = true;
break;
default:
}
}
if (handled) {
evnt.preventDefault();
}
}
/*
* show the datepicker. //TODO: migrate this to vanilla js
*/
#show() {
this.#options.locale = this.#curInstance.locale;
if (!DatePickerWidget.#visible) {
let date = new Date(),
validDate,
parsedDate;
if (this.#curInstance.selectedDate) {
validDate = this.#curInstance.selectedDate;
} else if (this.#model.valid) {
validDate = this.#model.value;
}
if (validDate) {
parsedDate = validDate ? new Date(validDate) : null;
date = (parsedDate == null || parsedDate == 'Invalid Date') ? date : parsedDate;
}
const timezoneOffset = date.getTimezoneOffset();
date.setMinutes(date.getMinutes() + timezoneOffset);
this.selectedDay = this.currentDay = date.getDate();
this.selectedMonth = this.currentMonth = date.getMonth();
this.selectedYear = this.currentYear = date.getFullYear();
this.maxValidDate = this.#options.maximum ? new Date(
this.#curInstance.maxValidDate) : null;
this.minValidDate = this.#options.minimum ? new Date(
this.#curInstance.minValidDate) : null;
this.exclMaxDate = this.#curInstance.exclMaxDate;
this.exclMinDate = this.#curInstance.exclMinDate;
this.#dp.getElementsByClassName("dp-clear")[0].getElementsByTagName(
"a")[0].innerText = this.#options.locale.clearText;
this.#layout(this.#defaultView);
this.#position();
this.#dp.style.display = "flex";
this.#focusedOnLi = false;
DatePickerWidget.#visible = true;
if (this.#options.showCalendarIcon) {
this.#curInstance.$field.setAttribute('readonly', true); // when the datepicker is active, deactivate the field
}
}
// Disabling the focus on ipad due to a bug where value of
// date picker is not being set
// Removing this code will only hamper one use case
// where on ipad if you click on the calander then
// the field becomes read only so
// there is no indication where the current focus is
// And if you remove this foucs code all together
// then what happens is that on desktop MF in iframe the exit event
// is not getting called hence calander getting remained open even
// when you click somewhere on window or focus into some other field
if (this.#options.showCalendarIcon && !this.#touchSupported) {
this.#curInstance.$field.focus(); // field loses focus after being marked readonly, causing blur event not to be fired later
}
}
/*
* position the datepicker around the positioning element //TODO: migrate this to vanilla js
* provided in the options
*/
#position() {
let $elem = this.#curInstance.positioning,
windowScrollX = window.scrollX,
windowScrollY = window.scrollY,
windowInnerHeight = window.innerHeight,
windowInnerWidth = window.innerWidth,
height = $elem.offsetHeight,
top = this.#getOffset($elem).top + height,
left = this.#getOffset($elem).left,
styles = {"top": (top + "px"), "left": (left + "px")},
diffBottom = top + 333 - windowInnerHeight - windowScrollY, //todo: hard-coded dp height to 333
newLeft,
newTop;
if (diffBottom > 0) {
//can't appear at the bottom
//check top
newTop = top - height - 333 - 20;
if (newTop < windowScrollY) {
//can't appear at the top as well ... the datePicker pop up overlaps the date field
newTop = top - diffBottom;
}
styles.top = newTop + "px";
}
if (left + 433 > windowScrollX + windowInnerWidth) { //todo: hard-coding width to 433
//align with the right edge
newLeft = windowScrollX + windowInnerWidth - 433 - 20;
styles.left = newLeft + "px";
}
this.#dp.style.top = styles.top;
this.#dp.style.left = styles.left;
const localeObj = new Intl.Locale(this.#lang);
if(localeObj?.textInfo?.direction == "rtl") {
this.#dp.style.right = styles.left;
this.#dp.style.left = "unset"
}
return this;
}
#getOffset(elem) {
let box = elem.getBoundingClientRect();
return {
top: box.top + window.scrollY,
left: box.left + window.scrollX
};
}
/*
* layout the nextView. if nextView is null return
*
*/
#layout(nextView) {
if (nextView == null) {
this.#hide();
} else {
if (this.view) {
this['$' + this.view.toLowerCase()].style.display = "none";
}
this.view = nextView;
this.caption.classList.toggle("disabled",
!this.#viewAction[this.view].caption);
this['$' + this.view.toLowerCase()].style.display = "block";
this["show" + this.view]();
}
return this;
}
/*
* show the month view
*/
showMonth() {
var self = this,
curDate = new Date(this.currentYear, this.currentMonth),
maxDay = this.#maxDate(this.currentMonth),
prevMaxDay = this.#maxDate((this.currentMonth + 11) % 12),
day1 = new Date(this.currentYear, this.currentMonth, 1).getDay(),
data, display;
var localizedYear = this.#getLocalizedYear(curDate);
this.#tabulateView(
{
caption: this.#options.locale.months[this.currentMonth] + ", "
+ this.#convertNumberToLocale(localizedYear),
header: this.#options.locale.days,
numRows: 7,
numColumns: 7,
elementAt: function (row, col) {
var day = (row - 1) * 7 + col - day1 + 1;
var monthVal = self.currentMonth + 1;
let gridId = "day-" + day;
display = self.#convertNumberToLocale(day);
data = day;
if (day < 1) {
display = self.#convertNumberToLocale(prevMaxDay + day);
data = -1;
monthVal = self.currentMonth;
} else if (day > maxDay) {
display = self.#convertNumberToLocale(day - maxDay);
data = -1;
monthVal = self.currentMonth + 2;
} else {
curDate.setDate(day);
// check if the currentdate is valid based on max and min valid date
if (self.#compareVal(curDate, self.maxValidDate,
self.exclMaxDate) || self.#compareVal(self.minValidDate,
curDate, self.exclMinDate)) {
data = -1;
}
}
return {
data: data,
gridId: gridId,
display: display,
ariaLabel: self.#options.editValue(
self.currentYear + "-" + self.#pad2(monthVal)
+ "-" + self.#pad2(display))
};
}
});
}
/**
* returns boolean based on val1, val2, checkEqual
* For comparing date, use date object
*/
#compareVal(val1, val2, checkEqual) {
if (!val1 || !val2) {
return false;
}
if (checkEqual) {
return val1 >= val2;
} else {
return val1 > val2;
}
}
/*
* show the year view
*/
showYear() {
var self = this,
minDate = this.minValidDate ? new Date(
this.minValidDate.getFullYear(), this.minValidDate.getMonth())
: null,
maxDate = this.maxValidDate ? new Date(
this.maxValidDate.getFullYear(), this.maxValidDate.getMonth())
: null,
curDate = new Date(this.currentYear, 0), //can't omit month, if only one param present it is treated as millisecond
data,
month;
var localizedYear = this.#getLocalizedYear(curDate);
this.#tabulateView(
{
caption: this.#convertNumberToLocale(localizedYear),
numRows: 4,
numColumns: 3,
elementAt: function (row, col) {
data = month = row * 3 + col;
let gridId = "month-" + data;
curDate.setMonth(month);
if ((minDate && curDate < minDate) || (maxDate && curDate
> maxDate)) {
data = -1;
}
return {
data: data,
gridId: gridId,
display: self.#options.locale.months[month],
ariaLabel: self.#options.locale.months[month] + " "
+ self.currentYear
};
}
});
}
#getLocalizedYear(date) {
/*
// Only Thai language return year according to Buddhist calendar, rest all languages follows gregorian calendar in practice.
// The Buddhist Year in 2024 = 543 + 2024 = B.E. 2567 (reference https://wesak.org.my/calculating-b-e/)
// Intl.DateTimeFormat#formatToParts returns number (2024) for all languages except for Thai (2567) & for Persian ('۱۴۰۳')
// For Persian ('۱۴۰۳'), returned year is not in numbers that is breaking next flow.
*/
if(this.#lang === 'th') {
const dateFormat = new Intl.DateTimeFormat(this.#lang, {
year: 'numeric'
});
const dateParts = dateFormat.formatToParts(date);
const yearObject = dateParts.find(yearObject => yearObject.type === "year");
const localizedYear = yearObject.value;
return Number(localizedYear);
}
else {
return Number(date.getFullYear());
}
}
/*
* show the year set view
*/
showYearset() {
var year,
minDate = this.minValidDate ? new Date(
this.minValidDate.getFullYear(), 0) : null,
maxDate = this.maxValidDate ? new Date(
this.maxValidDate.getFullYear() + 1, 0) : null,
curDate = new Date(),
data,
self = this;
var localizedYear = this.#getLocalizedYear(new Date(this.currentYear, 0)),
localizedYearSet = this.#getLocalizedYear(new Date(self.currentYear, 0));
this.#tabulateView(
{
caption: this.#convertNumberToLocale(
localizedYear - this.#options.yearsPerView / 2) + "-"
+ this.#convertNumberToLocale(
localizedYear - this.#options.yearsPerView / 2
+ this.#options.yearsPerView - 1),
numRows: 4,
numColumns: 4,
elementAt: function (row, col) {
data = year = localizedYearSet - 8 + (row * 4 + col);
let gridId = "year-" + data;
curDate.setFullYear(year);
if ((minDate && curDate < minDate) || (maxDate && curDate
> maxDate)) {
data = -1;
}
return {
"data": data,
"gridId": gridId,
"display": self.#convertNumberToLocale(year),
ariaLabel: year
};
}
});
}
insertRow(rowNum, rowArray, isHeader, elementAt) {
let $view = this["$" + this.view.toLowerCase()],
$row = $view.getElementsByTagName("ul")[rowNum],
items, $li, element, $tmp,
self = this;
if (!$row) {
let rowEl = document.createElement("ul");
rowEl.removeAttribute("aria-label");
rowEl.classList.toggle("header", isHeader);
$row = $view.appendChild(rowEl);
}
items = $row.getElementsByTagName("li").length;
while (items++ < rowArray.length) {
let listItemEl = document.createElement("li");
listItemEl.id = "li-" + elementAt(rowNum, items).gridId;
$tmp = $row.appendChild(listItemEl);
if (!isHeader) {
let cb = function (evnt) {
self.#selectDate(evnt);
};
$tmp.addEventListener("click", cb);
}
}
rowArray.forEach(function (el, index) {
$li = $row.getElementsByTagName("li")[index];
if (isHeader) {
$li.innerText = rowArray[index];
} else {
element = rowArray[index];
window.afCache.put($li, "value", element.data);
if (self.#checkDateIsFocussed(element.data)) {
if (self.$focusedDate) {
self.$focusedDate.classList.remove("dp-focus");
self.$focusedDate.setAttribute("tabindex", "-1");
}
self.$focusedDate = $li;
if (self.#keysEnabled) {
self.$focusedDate.classList.add("dp-focus")
}
}
$li.setAttribute("title", element.ariaLabel);
$li.setAttribute("aria-label", element.ariaLabel);
$li.setAttribute("tabindex", -1);
$li.classList.toggle("dp-selected",
self.#checkDateIsSelected(element.data));
$li.classList.toggle("disabled", element.data === -1);
$li.innerText = element.display;
}
});
return $row;
}
/*
* creates a tabular view based on the options provided. The options that can be passed are
* numRows: number of rows that needs rendering
* numCols: number of columns that needs rendering
* caption: text for the datepickers caption element
* header: an array of elements that identifies the header row
* elementAt: a function(row, column) that returns an object (data: <data>, display: <display>) where
* <data> is the value to set for that view when the element at (row,column) is clicked and
* <display> is the value that will be visible to the user
*/
#tabulateView(options) {
var r = 0, rows = 0,
row = [],
c;
this.caption.innerHTML = options.caption;
if (options.header) {
this.insertRow(r++, options.header, true, options.elementAt);
}
while (r < options.numRows) {
c = 0;
while (c < options.numColumns) {
row[c] = options.elementAt(r, c);
c++;
}
this.insertRow(r++, row, false, options.elementAt);
}
}
#hotKeysCallBack = this.#hotKeys.bind(this);
#activateField(evnt) {
let self = this;
this.#curInstance = window.afCache.get(evnt.target, "datetimepicker");
// Issue LC-7049:
// datepickerTarget should be added when activate the field and should be removed
// after the fields gets deactivated.
if (this.#options.showCalendarIcon) {
this.#curInstance.$field.parentNode.classList.add("datePickerTarget");
}
//enable hot keys only for non touch devices
if (!this.#touchSupported && !this.#keysEnabled) {
document.addEventListener("keydown", self.#hotKeysCallBack);
this.#keysEnabled = true;
}
}
#deactivateField() {
let self = this;
if (self.#curInstance) {
if (this.#keysEnabled) {
document.removeEventListener("keydown", self.#hotKeysCallBack);
this.#keysEnabled = false;
}
// Issue LC-7049:
// datepickerTarget should be added when activate the field and should be removed
// after the fields gets deactivated. Otherwise clicking on any other datefield
// will not hide the existing datepicker
if (this.#options.showCalendarIcon) {
self.#curInstance.$field.parentNode.classList.remove(
"datePickerTarget");
}
self.#curInstance = null;
this.#hideAllViews();
}
}
#hide() {
if (DatePickerWidget.#visible) {
this.#dp.style.display = "none";
this.#hideAllViews();
DatePickerWidget.#visible = false;
if (this.#options.showCalendarIcon) {
this.#curInstance.$field.removeAttribute('readonly'); // when the datepicker is deactivated, activate the field
}
}
}
#hideAllViews() {
this['$month'].replaceChildren();
this['$year'].replaceChildren();
this['$yearset'].replaceChildren();
this['$month'].style.display = "none";
this['$year'].style.display = "none";
this['$yearset'].style.display = "none";
}
#adjustDate(step, view, focus) {
let maxDate, prevMaxDate;
let _focus = focus || false;
switch (view.toLowerCase()) {
case "day":
this.currentDay += step;
maxDate = this.#maxDate(this.currentMonth)
if (this.currentDay < 1) {
prevMaxDate = this.#maxDate((this.currentMonth - 1 + 12) % 12);
this.currentDay = prevMaxDate + this.currentDay;
return this.#adjustDate(-1, "month", _focus);
}
if (this.currentDay > maxDate) {
this.currentDay -= maxDate;
return this.#adjustDate(+1, "month", _focus);
}
break;
case "month":
this.currentMonth += step;
if (this.currentMonth > 11) {
this.currentYear++;
this.currentMonth = 0;
}
if (this.currentMonth < 0) {
this.currentYear--;
this.currentMonth = 11;
}
break;
case "year":
this.currentYear += step;
break;
case "yearset":
this.currentYear += step * this.#options.yearsPerView;
break;
}
this.#layout(this.view);
if (_focus) {
this.#focusedOnLi = true;
this.$focusedDate.setAttribute("tabindex", 0);
this.$focusedDate.focus();
}
}
#checkDateIsSelected(data) {
switch (this.view.toLowerCase()) {
case "month":