-
Notifications
You must be signed in to change notification settings - Fork 54
/
datetimebox.js
1786 lines (1529 loc) · 47.6 KB
/
datetimebox.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
// This is a UA widget. It runs in per-origin UA widget scope,
// to be loaded by UAWidgetsChild.jsm.
/*
* This is the class of entry. It will construct the actual implementation
* according to the value of the "type" property.
*/
this.DateTimeBoxWidget = class {
constructor(shadowRoot) {
this.shadowRoot = shadowRoot;
this.element = shadowRoot.host;
this.document = this.element.ownerDocument;
this.window = this.document.defaultView;
}
/*
* Callback called by UAWidgets right after constructor.
*/
onsetup() {
this.switchImpl();
}
/*
* Callback called by UAWidgets when the "type" property changes.
*/
onchange() {
this.switchImpl();
}
/*
* Actually switch the implementation.
* - With type equal to "date", DateInputImplWidget should load.
* - With type equal to "time", TimeInputImplWidget should load.
* - Otherwise, nothing should load and loaded impl should be unloaded.
*/
switchImpl() {
let newImpl;
if (this.element.type == "date") {
newImpl = DateInputImplWidget;
} else if (this.element.type == "time") {
newImpl = TimeInputImplWidget;
}
// Skip if we are asked to load the same implementation.
// This can happen if the property is set again w/o value change.
if (this.impl && this.impl.constructor == newImpl) {
return;
}
if (this.impl) {
this.impl.destructor();
this.shadowRoot.firstChild.remove();
}
if (newImpl) {
this.impl = new newImpl(this.shadowRoot);
this.impl.onsetup();
} else {
this.impl = undefined;
}
}
destructor() {
if (!this.impl) {
return;
}
this.impl.destructor();
this.shadowRoot.firstChild.remove();
delete this.impl;
}
};
this.DateTimeInputBaseImplWidget = class {
constructor(shadowRoot) {
this.shadowRoot = shadowRoot;
this.element = shadowRoot.host;
this.document = this.element.ownerDocument;
this.window = this.document.defaultView;
}
onsetup() {
this.generateContent();
this.DEBUG = false;
this.mDateTimeBoxElement = this.shadowRoot.firstChild;
this.mInputElement = this.element;
this.mLocales = this.window.getWebExposedLocales();
this.mIsRTL = false;
let intlUtils = this.window.intlUtils;
if (intlUtils) {
this.mIsRTL = intlUtils.getLocaleInfo(this.mLocales).direction === "rtl";
}
if (this.mIsRTL) {
let inputBoxWrapper = this.shadowRoot.getElementById("input-box-wrapper");
inputBoxWrapper.dir = "rtl";
}
this.mMin = this.mInputElement.min;
this.mMax = this.mInputElement.max;
this.mStep = this.mInputElement.step;
this.mIsPickerOpen = false;
this.mResetButton = this.shadowRoot.getElementById("reset-button");
this.mResetButton.style.visibility = "hidden";
this.mResetButton.addEventListener("mousedown", this, {
mozSystemGroup: true,
});
this.mInputElement.addEventListener(
"keypress",
this,
{
capture: true,
mozSystemGroup: true,
},
false
);
// This is to open the picker when input element is clicked (this
// includes padding area).
this.mInputElement.addEventListener(
"click",
this,
{ mozSystemGroup: true },
false
);
// Those events are dispatched to <div class="datetimebox"> with bubble set
// to false. They are trapped inside UA Widget Shadow DOM and are not
// dispatched to the document.
this.CONTROL_EVENTS.forEach(eventName => {
this.mDateTimeBoxElement.addEventListener(eventName, this, {}, false);
});
}
generateContent() {
/*
* Pass the markup through XML parser purely for the reason of loading the localization DTD.
* Remove it when migrate to Fluent (bug 1504363).
*/
const parser = new this.window.DOMParser();
parser.forceEnableDTD();
let parserDoc = parser.parseFromString(
`<!DOCTYPE bindings [
<!ENTITY % datetimeboxDTD SYSTEM "chrome://global/locale/datetimebox.dtd">
%datetimeboxDTD;
]>
<div class="datetimebox" xmlns="http://www.w3.org/1999/xhtml" role="none">
<link rel="stylesheet" type="text/css" href="chrome://global/content/bindings/datetimebox.css" />
<div class="datetime-input-box-wrapper" id="input-box-wrapper" role="presentation">
<span class="datetime-input-edit-wrapper"
id="edit-wrapper">
<!-- Each of the date/time input types will append their input child
- elements here -->
</span>
<button class="datetime-reset-button" id="reset-button" tabindex="-1" aria-label="&datetime.reset.label;">
<svg xmlns="http://www.w3.org/2000/svg" class="datetime-reset-button-svg" width="12" height="12">
<path d="M 3.9,3 3,3.9 5.1,6 3,8.1 3.9,9 6,6.9 8.1,9 9,8.1 6.9,6 9,3.9 8.1,3 6,5.1 Z M 12,6 A 6,6 0 0 1 6,12 6,6 0 0 1 0,6 6,6 0 0 1 6,0 6,6 0 0 1 12,6 Z"/>
</svg>
</button>
</div>
<div id="strings"
data-m-year-place-holder="&date.year.placeholder;"
data-m-year-label="&date.year.label;"
data-m-month-place-holder="&date.month.placeholder;"
data-m-month-label="&date.month.label;"
data-m-day-place-holder="&date.day.placeholder;"
data-m-day-label="&date.day.label;"
data-m-hour-place-holder="&time.hour.placeholder;"
data-m-hour-label="&time.hour.label;"
data-m-minute-place-holder="&time.minute.placeholder;"
data-m-minute-label="&time.minute.label;"
data-m-second-place-holder="&time.second.placeholder;"
data-m-second-label="&time.second.label;"
data-m-millisecond-place-holder="&time.millisecond.placeholder;"
data-m-millisecond-label="&time.millisecond.label;"
data-m-day-period-place-holder="&time.dayperiod.placeholder;"
data-m-day-period-label="&time.dayperiod.label;"
></div>
</div>`,
"application/xml"
);
/*
* The <div id="strings"> is also parsed in the document so that there is no
* need to create another XML document just to get the strings.
*/
let stringsElement = parserDoc.getElementById("strings");
stringsElement.remove();
for (let key in stringsElement.dataset) {
// key will be camelCase version of the attribute key above,
// like mYearPlaceHolder.
this[key] = stringsElement.dataset[key];
}
this.shadowRoot.importNodeAndAppendChildAt(
this.shadowRoot,
parserDoc.documentElement,
true
);
}
destructor() {
this.mResetButton.addEventListener("mousedown", this, {
mozSystemGroup: true,
});
this.mInputElement.removeEventListener("keypress", this, {
capture: true,
mozSystemGroup: true,
});
this.mInputElement.removeEventListener("click", this, {
mozSystemGroup: true,
});
this.CONTROL_EVENTS.forEach(eventName => {
this.mDateTimeBoxElement.removeEventListener(eventName, this);
});
this.mInputElement = null;
}
get FIELD_EVENTS() {
return ["focus", "blur", "copy", "cut", "paste"];
}
get CONTROL_EVENTS() {
return [
"MozDateTimeValueChanged",
"MozNotifyMinMaxStepAttrChanged",
"MozFocusInnerTextBox",
"MozBlurInnerTextBox",
"MozDateTimeAttributeChanged",
"MozPickerValueChanged",
"MozSetDateTimePickerState",
];
}
addEventListenersToField(aElement) {
// These events don't bubble out of the Shadow DOM, so we'll have to add
// event listeners specifically on each of the fields, not just
// on the <input>
this.FIELD_EVENTS.forEach(eventName => {
aElement.addEventListener(
eventName,
this,
{ mozSystemGroup: true },
false
);
});
}
removeEventListenersToField(aElement) {
if (!aElement) {
return;
}
this.FIELD_EVENTS.forEach(eventName => {
aElement.removeEventListener(eventName, this, { mozSystemGroup: true });
});
}
log(aMsg) {
if (this.DEBUG) {
this.window.dump("[DateTimeBox] " + aMsg + "\n");
}
}
createEditFieldAndAppend(
aPlaceHolder,
aLabel,
aIsNumeric,
aMinDigits,
aMaxLength,
aMinValue,
aMaxValue,
aPageUpDownInterval
) {
let root = this.shadowRoot.getElementById("edit-wrapper");
let field = this.shadowRoot.createElementAndAppendChildAt(root, "span");
field.classList.add("datetime-edit-field");
field.textContent = aPlaceHolder;
field.placeholder = aPlaceHolder;
field.tabIndex = this.mInputElement.tabIndex;
field.setAttribute("readonly", this.mInputElement.readOnly);
field.setAttribute("disabled", this.mInputElement.disabled);
// Set property as well for convenience.
field.disabled = this.mInputElement.disabled;
field.readOnly = this.mInputElement.readOnly;
field.setAttribute("aria-label", aLabel);
// Used to store the non-formatted value, cleared when value is
// cleared.
// DateTimeInputTypeBase::HasBadInput() will read this to decide
// if the input has value.
field.setAttribute("value", "");
if (aIsNumeric) {
field.classList.add("numeric");
// Maximum value allowed.
field.setAttribute("min", aMinValue);
// Minumim value allowed.
field.setAttribute("max", aMaxValue);
// Interval when pressing pageUp/pageDown key.
field.setAttribute("pginterval", aPageUpDownInterval);
// Used to store what the user has already typed in the field,
// cleared when value is cleared and when field is blurred.
field.setAttribute("typeBuffer", "");
// Minimum digits to display, padded with leading 0s.
field.setAttribute("mindigits", aMinDigits);
// Maximum length for the field, will be advance to the next field
// automatically if exceeded.
field.setAttribute("maxlength", aMaxLength);
// Set spinbutton ARIA role
field.setAttribute("role", "spinbutton");
if (this.mIsRTL) {
// Force the direction to be "ltr", so that the field stays in the
// same order even when it's empty (with placeholder). By using
// "embed", the text inside the element is still displayed based
// on its directionality.
field.style.unicodeBidi = "embed";
field.style.direction = "ltr";
}
} else {
// Set generic textbox ARIA role
field.setAttribute("role", "textbox");
}
return field;
}
updateResetButtonVisibility() {
if (this.isAnyFieldAvailable(false) && !this.isRequired()) {
this.mResetButton.style.visibility = "";
} else {
this.mResetButton.style.visibility = "hidden";
}
}
focusInnerTextBox() {
this.log("Focus inner editable field.");
let editRoot = this.shadowRoot.getElementById("edit-wrapper");
for (let child of editRoot.querySelectorAll(
":scope > span.datetime-edit-field"
)) {
this.mLastFocusedField = child;
child.focus();
this.log("focused");
break;
}
}
blurInnerTextBox() {
this.log("Blur inner editable field.");
if (this.mLastFocusedField) {
this.mLastFocusedField.blur();
} else {
// If .mLastFocusedField hasn't been set, blur all editable fields,
// so that the bound element will actually be blurred. Note that
// blurring on a element that has no focus won't have any effect.
let editRoot = this.shadowRoot.getElementById("edit-wrapper");
for (let child of editRoot.querySelectorAll(
":scope > span.datetime-edit-field"
)) {
child.blur();
}
}
}
notifyInputElementValueChanged() {
this.log("inputElementValueChanged");
this.setFieldsFromInputValue();
}
notifyMinMaxStepAttrChanged() {
// No operation by default
}
setValueFromPicker(aValue) {
this.setFieldsFromPicker(aValue);
}
advanceToNextField(aReverse) {
this.log("advanceToNextField");
let focusedInput = this.mLastFocusedField;
let next = aReverse
? focusedInput.previousElementSibling
: focusedInput.nextElementSibling;
if (!next && !aReverse) {
this.setInputValueFromFields();
return;
}
while (next) {
if (next.matches("span.datetime-edit-field")) {
next.focus();
break;
}
next = aReverse ? next.previousElementSibling : next.nextElementSibling;
}
}
setPickerState(aIsOpen) {
this.log("picker is now " + (aIsOpen ? "opened" : "closed"));
this.mIsPickerOpen = aIsOpen;
}
updateEditAttributes() {
this.log("updateEditAttributes");
let editRoot = this.shadowRoot.getElementById("edit-wrapper");
for (let child of editRoot.querySelectorAll(
":scope > span.datetime-edit-field"
)) {
// "disabled" and "readonly" must be set as attributes because they
// are not defined properties of HTMLSpanElement, and the stylesheet
// checks the literal string attribute values.
child.setAttribute("disabled", this.mInputElement.disabled);
child.setAttribute("readonly", this.mInputElement.readOnly);
// Set property as well for convenience.
child.disabled = this.mInputElement.disabled;
child.readOnly = this.mInputElement.readOnly;
// tabIndex works on all elements
child.tabIndex = this.mInputElement.tabIndex;
}
this.mResetButton.disabled =
this.mInputElement.disabled || this.mInputElement.readOnly;
this.updateResetButtonVisibility();
}
isEmpty(aValue) {
return aValue == undefined || 0 === aValue.length;
}
getFieldValue(aField) {
if (!aField || !aField.classList.contains("numeric")) {
return undefined;
}
let value = aField.getAttribute("value");
// Avoid returning 0 when field is empty.
return this.isEmpty(value) ? undefined : Number(value);
}
clearFieldValue(aField) {
aField.textContent = aField.placeholder;
aField.setAttribute("value", "");
if (aField.classList.contains("numeric")) {
aField.setAttribute("typeBuffer", "");
}
this.updateResetButtonVisibility();
}
setFieldValue() {
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
}
clearInputFields() {
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
}
setFieldsFromInputValue() {
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
}
setInputValueFromFields() {
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
}
setFieldsFromPicker() {
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
}
handleKeypress() {
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
}
handleKeyboardNav() {
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
}
getCurrentValue() {
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
}
isAnyFieldAvailable() {
throw Cr.NS_ERROR_NOT_IMPLEMENTED;
}
notifyPicker() {
if (this.mIsPickerOpen && this.isAnyFieldAvailable(true)) {
this.mInputElement.updateDateTimePicker(this.getCurrentValue());
}
}
isDisabled() {
return this.mInputElement.hasAttribute("disabled");
}
isReadonly() {
return this.mInputElement.hasAttribute("readonly");
}
isEditable() {
return !this.isDisabled() && !this.isReadonly();
}
isRequired() {
return this.mInputElement.hasAttribute("required");
}
containingTree() {
return this.mInputElement.containingShadowRoot || this.document;
}
handleEvent(aEvent) {
this.log("handleEvent: " + aEvent.type);
if (!aEvent.isTrusted) {
return;
}
switch (aEvent.type) {
case "MozDateTimeValueChanged": {
this.notifyInputElementValueChanged();
break;
}
case "MozNotifyMinMaxStepAttrChanged": {
this.notifyMinMaxStepAttrChanged();
break;
}
case "MozFocusInnerTextBox": {
this.focusInnerTextBox();
break;
}
case "MozBlurInnerTextBox": {
this.blurInnerTextBox();
break;
}
case "MozDateTimeAttributeChanged": {
this.updateEditAttributes();
break;
}
case "MozPickerValueChanged": {
this.setValueFromPicker(aEvent.detail);
break;
}
case "MozSetDateTimePickerState": {
this.setPickerState(aEvent.detail);
break;
}
case "keypress": {
this.onKeyPress(aEvent);
break;
}
case "click": {
this.onClick(aEvent);
break;
}
case "focus": {
this.onFocus(aEvent);
break;
}
case "blur": {
this.onBlur(aEvent);
break;
}
case "mousedown":
case "copy":
case "cut":
case "paste": {
aEvent.preventDefault();
break;
}
default:
break;
}
}
onFocus(aEvent) {
this.log("onFocus originalTarget: " + aEvent.originalTarget);
if (this.containingTree().activeElement != this.mInputElement) {
return;
}
let target = aEvent.originalTarget;
if (target.matches("span.datetime-edit-field")) {
if (target.disabled) {
return;
}
this.mLastFocusedField = target;
this.mInputElement.setFocusState(true);
}
}
onBlur(aEvent) {
this.log(
"onBlur originalTarget: " +
aEvent.originalTarget +
" target: " +
aEvent.target
);
let target = aEvent.originalTarget;
target.setAttribute("typeBuffer", "");
this.setInputValueFromFields();
this.mInputElement.setFocusState(false);
}
onKeyPress(aEvent) {
this.log("onKeyPress key: " + aEvent.key);
switch (aEvent.key) {
// Close picker on Enter, Escape or Space key.
case "Enter":
case "Escape":
case " ": {
if (this.mIsPickerOpen) {
this.mInputElement.closeDateTimePicker();
aEvent.preventDefault();
}
break;
}
case "Backspace": {
// TODO(emilio, bug 1571533): These functions should look at
// defaultPrevented.
if (this.isEditable()) {
let targetField = aEvent.originalTarget;
this.clearFieldValue(targetField);
this.setInputValueFromFields();
aEvent.preventDefault();
}
break;
}
case "ArrowRight":
case "ArrowLeft": {
this.advanceToNextField(!(aEvent.key == "ArrowRight"));
aEvent.preventDefault();
break;
}
case "ArrowUp":
case "ArrowDown":
case "PageUp":
case "PageDown":
case "Home":
case "End": {
this.handleKeyboardNav(aEvent);
aEvent.preventDefault();
break;
}
default: {
// printable characters
if (
aEvent.keyCode == 0 &&
!(aEvent.ctrlKey || aEvent.altKey || aEvent.metaKey)
) {
this.handleKeypress(aEvent);
aEvent.preventDefault();
}
break;
}
}
}
onClick(aEvent) {
this.log(
"onClick originalTarget: " +
aEvent.originalTarget +
" target: " +
aEvent.target
);
if (aEvent.defaultPrevented || !this.isEditable()) {
return;
}
if (aEvent.originalTarget == this.mResetButton) {
this.clearInputFields(false);
} else if (!this.mIsPickerOpen) {
this.mInputElement.openDateTimePicker(this.getCurrentValue());
}
}
};
this.DateInputImplWidget = class extends DateTimeInputBaseImplWidget {
constructor(shadowRoot) {
super(shadowRoot);
}
onsetup() {
super.onsetup();
this.mMinMonth = 1;
this.mMaxMonth = 12;
this.mMinDay = 1;
this.mMaxDay = 31;
this.mMinYear = 1;
// Maximum year limited by ECMAScript date object range, year <= 275760.
this.mMaxYear = 275760;
this.mMonthDayLength = 2;
this.mYearLength = 4;
this.mMonthPageUpDownInterval = 3;
this.mDayPageUpDownInterval = 7;
this.mYearPageUpDownInterval = 10;
this.buildEditFields();
this.updateEditAttributes();
if (this.mInputElement.value) {
this.setFieldsFromInputValue();
}
}
destructor() {
this.removeEventListenersToField(this.mYearField);
this.removeEventListenersToField(this.mMonthField);
this.removeEventListenersToField(this.mDayField);
super.destructor();
}
buildEditFields() {
let root = this.shadowRoot.getElementById("edit-wrapper");
let yearMaxLength = this.mMaxYear.toString().length;
let formatter = Intl.DateTimeFormat(this.mLocales, {
year: "numeric",
month: "numeric",
day: "numeric",
});
formatter.formatToParts(Date.now()).map(part => {
switch (part.type) {
case "year":
this.mYearField = this.createEditFieldAndAppend(
this.mYearPlaceHolder,
this.mYearLabel,
true,
this.mYearLength,
yearMaxLength,
this.mMinYear,
this.mMaxYear,
this.mYearPageUpDownInterval
);
this.addEventListenersToField(this.mYearField);
break;
case "month":
this.mMonthField = this.createEditFieldAndAppend(
this.mMonthPlaceHolder,
this.mMonthLabel,
true,
this.mMonthDayLength,
this.mMonthDayLength,
this.mMinMonth,
this.mMaxMonth,
this.mMonthPageUpDownInterval
);
this.addEventListenersToField(this.mMonthField);
break;
case "day":
this.mDayField = this.createEditFieldAndAppend(
this.mDayPlaceHolder,
this.mDayLabel,
true,
this.mMonthDayLength,
this.mMonthDayLength,
this.mMinDay,
this.mMaxDay,
this.mDayPageUpDownInterval
);
this.addEventListenersToField(this.mDayField);
break;
default:
let span = this.shadowRoot.createElementAndAppendChildAt(
root,
"span"
);
span.textContent = part.value;
break;
}
});
}
clearInputFields(aFromInputElement) {
this.log("clearInputFields");
if (!this.isEditable()) {
return;
}
if (
this.mMonthField &&
!this.mMonthField.disabled &&
!this.mMonthField.readOnly
) {
this.clearFieldValue(this.mMonthField);
}
if (
this.mDayField &&
!this.mDayField.disabled &&
!this.mDayField.readOnly
) {
this.clearFieldValue(this.mDayField);
}
if (
this.mYearField &&
!this.mYearField.disabled &&
!this.mYearField.readOnly
) {
this.clearFieldValue(this.mYearField);
}
if (!aFromInputElement) {
if (this.mInputElement.value) {
this.mInputElement.setUserInput("");
} else {
this.mInputElement.updateValidityState();
}
}
}
setFieldsFromInputValue() {
let value = this.mInputElement.value;
if (!value) {
this.clearInputFields(true);
return;
}
this.log("setFieldsFromInputValue: " + value);
let [year, month, day] = value.split("-");
this.setFieldValue(this.mYearField, year);
this.setFieldValue(this.mMonthField, month);
this.setFieldValue(this.mDayField, day);
this.notifyPicker();
}
setInputValueFromFields() {
if (this.isAnyFieldEmpty()) {
// Clear input element's value if any of the field has been cleared,
// otherwise update the validity state, since it may become "not"
// invalid if fields are not complete.
if (this.mInputElement.value) {
this.mInputElement.setUserInput("");
} else {
this.mInputElement.updateValidityState();
}
// We still need to notify picker in case any of the field has
// changed.
this.notifyPicker();
return;
}
let { year, month, day } = this.getCurrentValue();
// Convert to a valid date string according to:
// https://html.spec.whatwg.org/multipage/infrastructure.html#valid-date-string
year = year.toString().padStart(this.mYearLength, "0");
month = month < 10 ? "0" + month : month;
day = day < 10 ? "0" + day : day;
let date = [year, month, day].join("-");
if (date == this.mInputElement.value) {
return;
}
this.log("setInputValueFromFields: " + date);
this.notifyPicker();
this.mInputElement.setUserInput(date);
}
setFieldsFromPicker(aValue) {
let year = aValue.year;
let month = aValue.month;
let day = aValue.day;
if (!this.isEmpty(year)) {
this.setFieldValue(this.mYearField, year);
}
if (!this.isEmpty(month)) {
this.setFieldValue(this.mMonthField, month);
}
if (!this.isEmpty(day)) {
this.setFieldValue(this.mDayField, day);
}
// Update input element's .value if needed.
this.setInputValueFromFields();
}
handleKeypress(aEvent) {
if (!this.isEditable()) {
return;
}
let targetField = aEvent.originalTarget;
let key = aEvent.key;
if (targetField.classList.contains("numeric") && key.match(/[0-9]/)) {
let buffer = targetField.getAttribute("typeBuffer") || "";
buffer = buffer.concat(key);
this.setFieldValue(targetField, buffer);
let n = Number(buffer);
let max = targetField.getAttribute("max");
let maxLength = targetField.getAttribute("maxlength");
if (buffer.length >= maxLength || n * 10 > max) {
buffer = "";
this.advanceToNextField();
}
targetField.setAttribute("typeBuffer", buffer);
if (!this.isAnyFieldEmpty()) {
this.setInputValueFromFields();
}
}
}
incrementFieldValue(aTargetField, aTimes) {
let value = this.getFieldValue(aTargetField);
// Use current date if field is empty.
if (this.isEmpty(value)) {
let now = new Date();
if (aTargetField == this.mYearField) {
value = now.getFullYear();
} else if (aTargetField == this.mMonthField) {
value = now.getMonth() + 1;
} else if (aTargetField == this.mDayField) {
value = now.getDate();
} else {
this.log("Field not supported in incrementFieldValue.");
return;
}
}
let min = Number(aTargetField.getAttribute("min"));
let max = Number(aTargetField.getAttribute("max"));
value += Number(aTimes);
if (value > max) {
value -= max - min + 1;
} else if (value < min) {
value += max - min + 1;
}
this.setFieldValue(aTargetField, value);
}
handleKeyboardNav(aEvent) {
if (!this.isEditable()) {
return;
}
let targetField = aEvent.originalTarget;
let key = aEvent.key;
// Home/End key does nothing on year field.
if (targetField == this.mYearField && (key == "Home" || key == "End")) {
return;
}
switch (key) {
case "ArrowUp":
this.incrementFieldValue(targetField, 1);
break;
case "ArrowDown":
this.incrementFieldValue(targetField, -1);
break;
case "PageUp": {
let interval = targetField.getAttribute("pginterval");
this.incrementFieldValue(targetField, interval);
break;
}
case "PageDown": {
let interval = targetField.getAttribute("pginterval");
this.incrementFieldValue(targetField, 0 - interval);
break;
}
case "Home":