forked from vaadin/vaadin-date-picker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vaadin-date-picker-behavior.html
718 lines (614 loc) · 21.4 KB
/
vaadin-date-picker-behavior.html
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
<link rel="import" href="../iron-form-element-behavior/iron-form-element-behavior.html">
<link rel="import" href="../iron-validatable-behavior/iron-validatable-behavior.html">
<link rel="import" href="../iron-a11y-keys-behavior/iron-a11y-keys-behavior.html">
<link rel="import" href="vaadin-date-picker-helper.html">
<script>
window.vaadin = window.vaadin || {};
vaadin.elements = vaadin.elements || {};
vaadin.elements.datepicker = vaadin.elements.datepicker || {};
/** @polymerBehavior vaadin.elements.datepicker.DatePickerBehavior */
vaadin.elements.datepicker.DatePickerBehaviorImpl = {
observers: [
'_selectedDateChanged(_selectedDate, i18n.formatDate)',
'_validateInput(_selectedDate, _minDate, _maxDate)',
'_focusedDateChanged(_focusedDate, i18n.formatDate)',
'_announceFocusedDate(_focusedDate, opened, _ignoreAnnounce)'
],
properties: {
/**
* The current selected date.
*/
_selectedDate: {
type: Date
},
_focusedDate: Date,
/**
* The value for this element.
*
* Supported date formats:
* - ISO 8601 `"YYYY-MM-DD"` (default)
* - 6-digit extended ISO 8601 `"+YYYYYY-MM-DD"`, `"-YYYYYY-MM-DD"`
*
* @type {String}
*/
value: {
type: String,
observer: '_valueChanged'
},
/**
* Indicates whether this date picker has a value.
*/
hasValue: {
type: Boolean,
computed: '_hasValue(value)',
reflectToAttribute: true
},
/**
* Date which should be visible when there is no value selected.
*
* The same date formats as for the `value` property are supported.
*/
initialPosition: String,
/**
* The label for this element.
*/
label: String,
/**
* Set true to open the date selector overlay.
*/
opened: {
type: Boolean,
reflectToAttribute: true,
notify: true
},
/**
* Set true to display ISO-8601 week numbers in the calendar. Notice that
* displaying week numbers is only supported when `i18n.firstDayOfWeek`
* is 1 (Monday).
*/
showWeekNumbers: {
type: Boolean
},
_fullscreen: {
value: false,
observer: '_fullscreenChanged'
},
_fullscreenMediaQuery: {
value: '(max-width: 420px), (max-height: 420px)'
},
// An array of ancestor elements whose -webkit-overflow-scrolling is forced from value
// 'touch' to value 'auto' in order to prevent them from clipping the dropdown. iOS only.
_touchPrevented: Array,
/**
* The object used to localize this component.
* To change the default localization, replace the entire
* _i18n_ object or just the property you want to modify.
*
* The object has the following JSON structure and default values:
{
// An array with the full names of months starting
// with January.
monthNames: [
'January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September',
'October', 'November', 'December'
],
// An array of weekday names starting with Sunday. Used
// in screen reader announcements.
weekdays: [
'Sunday', 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday'
],
// An array of short weekday names starting with Sunday.
// Displayed in the calendar.
weekdaysShort: [
'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
],
// An integer indicating the first day of the week
// (0 = Sunday, 1 = Monday, etc.).
firstDayOfWeek: 0,
// Used in screen reader announcements along with week
// numbers, if they are displayed.
week: 'Week',
// Translation of the Calendar icon button title.
calendar: 'Calendar',
// Translation of the Clear icon button title.
clear: 'Clear',
// Translation of the Today shortcut button text.
today: 'Today',
// Translation of the Cancel button text.
cancel: 'Cancel',
// A function to format given `Date` object as
// date string.
formatDate: function(d) {
// returns a string representation of the given
// Date object in 'MM/DD/YYYY' -format
},
// A function to parse the given text to a `Date`
// object. Must properly parse (at least) text
// formatted by `formatDate`.
// Setting the property to null will disable
// keyboard input feature.
parseDate: function(text) {
// Parses a string in 'MM/DD/YY', 'MM/DD' or 'DD' -format to
// a Date object
}
// A function to format given `monthName` and
// `fullYear` integer as calendar title string.
formatTitle: function(monthName, fullYear) {
return monthName + ' ' + fullYear;
}
}
*
* @default {English/US}
*/
i18n: {
type: Object,
value: function() {
return {
monthNames: [
'January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September', 'October', 'November', 'December'
],
weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
weekdaysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
firstDayOfWeek: 0,
week: 'Week',
calendar: 'Calendar',
clear: 'Clear',
today: 'Today',
cancel: 'Cancel',
formatDate: function(d) {
var year = d.getFullYear();
var yearString = year.toString();
if (yearString.length < 3 && year >= 0) {
yearString = (year < 10 ? '000' : '00') + year;
}
return (d.getMonth() + 1) + '/' + d.getDate() + '/' + yearString;
},
parseDate: function(text) {
var parts = text.split('/');
var today = new Date();
var date, month = today.getMonth(), year = today.getFullYear();
if (parts.length === 3) {
year = parseInt(parts[2]);
if (parts[2].length < 3 && year >= 0) {
year += year < 50 ? 2000 : 1900;
}
month = parseInt(parts[0]) - 1;
date = parseInt(parts[1]);
} else if (parts.length === 2) {
month = parseInt(parts[0]) - 1;
date = parseInt(parts[1]);
} else if (parts.length === 1) {
date = parseInt(parts[0]);
}
if (date !== undefined) {
var result = new Date(0, 0); // Wrong date (1900-01-01), but with midnight in local time
result.setFullYear(year);
result.setMonth(month);
result.setDate(date);
return result;
}
},
formatTitle: function(monthName, fullYear) {
return monthName + ' ' + fullYear;
}
};
}
},
/**
* The earliest date that can be selected. All earlier dates will be disabled.
*
* Supported date formats:
* - ISO 8601 `"YYYY-MM-DD"` (default)
* - 6-digit extended ISO 8601 `"+YYYYYY-MM-DD"`, `"-YYYYYY-MM-DD"`
*
* @type {String}
*/
min: {
type: String,
observer: '_minChanged'
},
/**
* The latest date that can be selected. All later dates will be disabled.
*
* Supported date formats:
* - ISO 8601 `"YYYY-MM-DD"` (default)
* - 6-digit extended ISO 8601 `"+YYYYYY-MM-DD"`, `"-YYYYYY-MM-DD"`
*
* @type {String}
*/
max: {
type: String,
observer: '_maxChanged'
},
/**
* The earliest date that can be selected. All earlier dates will be disabled.
*/
_minDate: {
type: Date,
value: null
},
/**
* The latest date that can be selected. All later dates will be disabled.
*/
_maxDate: {
type: Date,
value: null
},
_noInput: {
type: Boolean,
computed: '_isNoInput(_fullscreen, i18n, i18n.*, _ios)'
},
_ios: {
type: Boolean,
value: navigator.userAgent.match(/iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/)
},
_ignoreAnnounce: {
value: true
},
_focusOverlayOnOpen: Boolean,
/**
* When datepicker is opened, we're setting body pointer-events to none
* to make the datepicker behave in "modal" way. This variable keeps the
* previous state of body pointer-events to restore it when datepicker is
* closed.
*/
_documentPointerEvents: String
},
created: function() {
this._boundOnScroll = this._onScroll.bind(this);
},
listeners: {
'tap': 'open',
'touchend': '_preventDefault',
'keydown': '_onKeydown',
'close': '_close',
'date-tap': '_close',
'focus-input': '_focusAndSelect'
},
ready: function() {
// The value property is also defined in IronFormElementBehavior, which
// will mix up the default value if set in the property.
if (this.value === undefined) {
this.value = '';
}
},
/**
* Opens the dropdown.
*/
open: function() {
this._updateAlignmentAndPosition();
if (!this.disabled && !this.readonly) {
this.$.dropdown.open();
}
},
_close: function(e) {
if (e) {
e.stopPropagation();
}
this.inputElement.focus();
this.close();
},
/**
* Closes the dropdown.
*/
close: function() {
this.$.dropdown.close();
},
/**
* @property inputElement
* @type HTMLElement
*/
get inputElement() {
return this._input();
},
_parseDate: function(str) {
// Parsing with RegExp to ensure correct format
var parts = /^(\d{4}|[-+]\d{6})-(\d{2})-(\d{2})$/.exec(str);
if (!parts) {
return;
}
var date = new Date(0, 0); // Wrong date (1900-01-01), but with midnight in local time
date.setFullYear(parseInt(parts[1], 10));
date.setMonth(parseInt(parts[2], 10) - 1);
date.setDate(parseInt(parts[3], 10));
return date;
},
_isNoInput: function() {
return this._fullscreen || !this.i18n.parseDate || this._ios;
},
_formatISO: function(date) {
return date instanceof Date ?
(new Date(date.getTime() - date.getTimezoneOffset() * 60000)).toISOString().split('T')[0] :
'';
},
_selectedDateChanged: function(selectedDate, formatDate) {
this.value = this._formatISO(selectedDate);
this._focusedDate = selectedDate;
this._inputValue = selectedDate ? formatDate(selectedDate) : '';
},
_focusedDateChanged: function(focusedDate, formatDate) {
if (!this._ignoreFocusedDateChange && !this._noInput) {
this._inputValue = focusedDate ? formatDate(focusedDate) : '';
}
},
_hasValue: function(value) {
return !!value;
},
_handleDateChange: function(property, value, oldValue) {
if (!value) {
this[property] = null;
return;
}
var date = this._parseDate(value);
if (!date) {
this.value = oldValue;
return;
}
if (!(this[property] instanceof Date) ||
date.getFullYear() !== this[property].getFullYear() ||
date.getMonth() !== this[property].getMonth() ||
date.getDate() !== this[property].getDate()) {
this[property] = date;
}
},
_valueChanged: function(value, oldValue) {
this._handleDateChange('_selectedDate', value, oldValue);
},
_minChanged: function(value, oldValue) {
this._handleDateChange('_minDate', value, oldValue);
},
_maxChanged: function(value, oldValue) {
this._handleDateChange('_maxDate', value, oldValue);
},
_updateAlignmentAndPosition: function() {
var viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
this.$.dropdown.positionTarget = this._fullscreen ? document.documentElement : this;
var viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var bottomAlign = this.getBoundingClientRect().top > viewportHeight / 2;
var rightAlign = this.getBoundingClientRect().left + this.clientWidth / 2 > viewportWidth / 2;
this.$.dropdown.verticalAlign = bottomAlign ? 'bottom' : 'top';
this.$.dropdown.horizontalAlign = this._fullscreen ? null : rightAlign ? 'right' : 'left';
// Previously used verticalOffset property has been recently deprecated
// in favor of using top and bottom margins.
if (this._fullscreen) {
this.$.dropdown.style.marginTop = 0;
this.$.dropdown.style.marginBottom = 0;
} else {
this.$.dropdown.style.marginTop = (bottomAlign ? 10 : this.clientHeight + 2) + 'px';
this.$.dropdown.style.marginBottom = (bottomAlign ? this.clientHeight : 10) + 'px';
}
this.$.dropdown.refit();
},
_fullscreenChanged: function() {
if (this.$.dropdown.opened) {
this._updateAlignmentAndPosition();
}
},
_onOverlayOpened: function() {
var parsedInitialPosition = this._parseDate(this.initialPosition);
var initialPosition = this._selectedDate || this.$.overlay.initialPosition ||
parsedInitialPosition || new Date();
if (parsedInitialPosition ||
vaadin.elements.datepicker.DatePickerHelper._dateAllowed(initialPosition, this._minDate, this._maxDate)) {
this.$.overlay.initialPosition = initialPosition;
} else {
this.$.overlay.initialPosition =
vaadin.elements.datepicker.DatePickerHelper._getClosestDate(initialPosition, [this._minDate, this._maxDate]);
}
this.$.overlay.scrollToDate(this.$.overlay.focusedDate || this.$.overlay.initialPosition);
// Have a default focused date
this._ignoreFocusedDateChange = true;
this.$.overlay.focusedDate = this.$.overlay.focusedDate || this.$.overlay.initialPosition;
this._ignoreFocusedDateChange = false;
window.addEventListener('scroll', this._boundOnScroll, true);
// We cannot use iron-resize event because 1- we fire it, 2- it's fired
// many times, 3- causes heigth and scroll issues in safari.
window.addEventListener('resize', this._boundOnScroll, true);
// Checking if the browser supports webkitOverflowScrolling
if (document.createElement('div').style.webkitOverflowScrolling === '') {
this._touchPrevented = this._preventWebkitOverflowScrollingTouch(this.parentElement);
}
if (this._focusOverlayOnOpen) {
this.$.overlay.focus();
this._focusOverlayOnOpen = false;
} else {
this._focus();
}
this.updateStyles();
// Set body pointer-events to 'none' to disable mouse interactions with
// other document nodes (datepicker is "modal")
this._documentPointerEvents = document.body.style.pointerEvents;
document.body.style.pointerEvents = 'none';
this._ignoreAnnounce = false;
},
// A hack needed for iOS to prevent dropdown from being clipped in an
// ancestor container with -webkit-overflow-scrolling: touch;
_preventWebkitOverflowScrollingTouch: function(element) {
var result = [];
while (element) {
if (window.getComputedStyle(element).webkitOverflowScrolling === 'touch') {
var oldInlineValue = element.style.webkitOverflowScrolling;
element.style.webkitOverflowScrolling = 'auto';
result.push({
element: element,
oldInlineValue: oldInlineValue
});
}
element = element.parentElement;
}
return result;
},
_onOverlayClosed: function() {
this._ignoreAnnounce = true;
window.removeEventListener('scroll', this._boundOnScroll, true);
window.removeEventListener('resize', this._boundOnScroll, true);
if (this._touchPrevented) {
this._touchPrevented.forEach(function(prevented) {
prevented.element.style.webkitOverflowScrolling = prevented.oldInlineValue;
});
this._touchPrevented = [];
}
this.updateStyles();
// Restore the initial body pointer-events
document.body.style.pointerEvents = this._documentPointerEvents;
// Select the parsed input or focused date
this._ignoreFocusedDateChange = true;
if (this.i18n.parseDate) {
var inputValue = this._inputValue;
var parsedDate = this.i18n.parseDate(inputValue);
if (this._isValidDate(parsedDate)) {
this._selectedDate = parsedDate;
} else {
this._selectedDate = null;
this._inputValue = inputValue;
}
} else if (this._focusedDate) {
this._selectedDate = this._focusedDate;
}
this._ignoreFocusedDateChange = false;
var input = window.unwrap ? window.unwrap(this.inputElement) : this.inputElement;
if ((this.shadowRoot && this.shadowRoot.activeElement === input) || document.activeElement === input) {
input.selectionStart = input.selectionEnd;
}
this.validate();
},
detached: function() {
this._onOverlayClosed();
},
_onScroll: function(e) {
if (e.target === window || !this.$.overlay.contains(e.target)) {
this.$.dropdown.style.bottom = 'auto';
this.$.dropdown.resetFit();
this._updateAlignmentAndPosition();
this.$.dropdown.fire('iron-resize');
}
},
_preventCancelOnComponentAccess: function(e) {
var event = Polymer.dom(e.detail);
if (/tap|mousedown|touchstart/.test(e.detail.type) && event.path.indexOf(this) > -1) {
e.preventDefault();
}
},
_focus: function() {
if (this._noInput) {
this.$.overlay.focus();
} else {
this.inputElement.focus();
}
},
_focusAndSelect: function() {
if (!this._noInput) {
this._focus();
this.inputElement.setSelectionRange(0, this._inputValue.length);
}
},
_preventDefault: function(e) {
e.preventDefault();
},
/**
* Keyboard Navigation
*/
_eventKey: function(e) {
var keys = ['down', 'up', 'enter', 'esc', 'tab'];
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
if (Polymer.IronA11yKeysBehavior.keyboardEventMatchesKeys(e, k)) {
return k;
}
}
},
_isValidDate: function(d) {
return d && !isNaN(d.getTime());
},
_onKeydown: function(e) {
if (this._noInput) {
// The input element cannot be readonly as it would conflict with
// the required attribute. Both are not allowed on an input element.
// Therefore we prevent default on most keydown events.
var allowedKeys = [
9 // tab
];
if (allowedKeys.indexOf(e.keyCode) === -1) {
e.preventDefault();
}
}
switch (this._eventKey(e)) {
case 'down':
case 'up':
// prevent scrolling the page with arrows
e.preventDefault();
if (this.opened) {
this.$.overlay.focus();
this.$.overlay._onKeydown(e);
} else {
this._focusOverlayOnOpen = true;
this.open();
}
break;
case 'enter':
if (this.$.overlay.focusedDate) {
this._selectedDate = this.$.overlay.focusedDate;
}
this.close();
break;
case 'esc':
this._focusedDate = this._selectedDate;
this._close();
break;
case 'tab':
if (this.opened) {
e.preventDefault();
// Clear the selection range (remains visible on IE)
this.inputElement.setSelectionRange(0, 0);
if (e.shiftKey) {
this.$.overlay.focusCancel();
} else {
this.$.overlay.focus();
this.$.overlay.revealDate(this._focusedDate);
}
}
break;
}
},
_validateInput: function(date, min, max) {
if (date && (min || max)) {
this.invalid = !vaadin.elements.datepicker.DatePickerHelper._dateAllowed(date, min, max);
}
},
_userInputValueChanged: function() {
var parsedDate = this.i18n.parseDate && this.i18n.parseDate(this._inputValue);
if (this._isValidDate(parsedDate)) {
this._ignoreFocusedDateChange = true;
this._focusedDate = parsedDate;
this._ignoreFocusedDateChange = false;
}
if (!this.opened) {
this.open();
// iOS needs a refit after input blur animation has finished
this.$.dropdown.async(this.$.dropdown.refit, 500);
}
},
_announceFocusedDate: function(_focusedDate, opened, _ignoreAnnounce) {
if (opened && !_ignoreAnnounce) {
this.$.overlay.announceFocusedDate();
}
}
};
/** @polymerBehavior vaadin.elements.datepicker.DatePickerBehavior */
vaadin.elements.datepicker.DatePickerBehavior = [
Polymer.IronFormElementBehavior,
Polymer.IronValidatableBehavior,
Polymer.IronA11yKeysBehavior,
vaadin.elements.datepicker.DatePickerBehaviorImpl
];
/**
* Fired when the value changes.
*
* @event value-changed
* @param {Object} detail
* @param {String} detail.value the date value or an empty `String`.
*/
</script>