-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpx-datetime-field.html
627 lines (602 loc) · 19.7 KB
/
px-datetime-field.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
<!--
Copyright (c) 2018, General Electric
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.
-->
<link rel="import" href="../polymer/polymer.html"/>
<link rel="import" href="../px-datetime-common/px-datetime-entry.html"/>
<link rel="import" href="../px-datetime-common/px-datetime-behavior.html"/>
<link rel="import" href="../px-datetime-common/px-datetime-validate.html"/>
<link rel="import" href="../px-datetime-common/px-datetime-buttons.html"/>
<link rel="import" href="../px-datetime-common/px-datetime-button-behavior.html"/>
<link rel="import" href="../px-overlay/px-overlay-behavior.html"/>
<link rel="import" href="css/px-datetime-field-styles.html"/>
<!--
The datetime components rely on [Moment.js](https://momentjs.com/) and [Moment Timezone](https://momentjs.com/timezone/).
### Usage
<px-datetime-field></px-datetime-field>
### Styling
The following custom property is available for styling. Please also refer to px-forms-design for additional variables that can be used to customize the field's appearance.
Custom property | Description
:----------------|:-------------
`--px-datetime-field-background-color` | Background color for field and validation
`--px-datetime-field-height` | Sets the height of the input field
`px-input` css variables | Impacts the input text, border, and background colors
`px-validation-error` css variables | Impacts validation error text and background color
@element px-datetime-field
@blurb Element providing solution to no problem in particular.
@homepage index.html
@demo index.html
-->
<dom-module id="px-datetime-field">
<template>
<style include="px-datetime-field-styles"></style>
<div class$="{{_getWrapClass(allowWrap)}} flex">
<div class$="{{_getButtonMarginClass(showButtons, allowWrap)}}">
<div id="fieldWrapper" class$="{{_getWrapperClass(isValid, _forcedFailedClass, isSelected, _dropdownActive, _dropdownHoverFix)}}">
<template is="dom-if" if="[[!hideDate]]">
<px-datetime-entry
id="date"
class$="{{_getEntryDateClass(hideDate, hideTime, hideIcon)}}"
date-or-time="Date"
moment-format="{{dateFormat}}"
moment-obj="{{momentObj}}"
is-selected="{{isSelected}}"
hide-icon="{{hideIcon}}"
time-zone="{{timeZone}}"
show-time-zone="{{_showTimeZoneInDate(hideTime, showTimeZone)}}"
block-future-dates="{{blockFutureDates}}"
block-past-dates="{{blockPastDates}}"
min-date="{{minDate}}"
max-date="{{maxDate}}"
resources="[[resources]]"
language="[[language]]"
formats="[[formats]]"
hoist="[[hoist]]"
container-type="[[containerType]]">
</px-datetime-entry>
</template>
<template is="dom-if" if="[[!hideTime]]">
<px-datetime-entry
id="time"
date-or-time="Time"
moment-format="{{timeFormat}}"
show-time-zone="{{showTimeZone}}"
moment-obj="{{momentObj}}"
hide-icon="{{hideIcon}}"
time-zone="{{timeZone}}"
is-selected="{{isSelected}}"
block-future-dates="{{blockFutureDates}}"
block-past-dates="{{blockPastDates}}"
min-date="{{minDate}}"
max-date="{{maxDate}}"
resources="[[resources]]"
language="[[language]]"
formats="[[formats]]"
hoist="[[hoist]]"
container-type="[[containerType]]">
</px-datetime-entry>
</template>
</div>
<template is="dom-if" if="[[_showValidation(isValid, hideValidationMessage)]]">
<div class="form-field__help validation-error dt-validation-text">{{_validationErrorMessage}}</div>
</template>
</div>
<template is="dom-if" if="{{showButtons}}">
<px-datetime-buttons
resources="[[resources]]"
language="[[language]]"
formats="[[formats]]">
</px-datetime-buttons>
</template>
</div>
</template>
</dom-module>
<script>
Polymer({
is: 'px-datetime-field',
behaviors: [
PxDatetimeBehavior.SingleMoment,
PxDatetimeBehavior.Buttons,
PxDatetimeBehavior.Validate,
PxOverlayBehavior.sharedProperties
],
properties: {
/**
* Moment format string for the DATE format to display/validate this field against
* Year, month, and day (support YYYY, YY, M, MM, D, DD)
* (see http://momentjs.com/docs/#/parsing/string/)
*/
dateFormat: {
type: String,
value: 'YYYY-MM-DD'
},
/**
* Moment format string for the TIME format to display/validate this field against.
* Hour, minute, second, millisecond, am/pm, and offset tokens
* (see http://momentjs.com/docs/#/parsing/string/)
*/
timeFormat: {
type: String,
value: 'HH:mm:ss'
},
/**
*
* The format of displaying the time zone:
* - `dropdown`: shows the time zone as a dropdown which the user can use to select a different time zone. Only contains a subset of all time zones
* - `extendedDropdown`: shows the time zone as a dropdown which the user can use to select a different time zone. Contains all existing time zones (588)
* - `text`: shows the time zone as text, non editable
* - `abbreviatedText`: shows the time zone as an abbreviated text, non editable (such as PST, EST...)
*/
showTimeZone: {
type: String,
value: ''
},
/**
* Controls whether time is displayed in the field.
*/
hideTime: {
type: Boolean,
value: false
},
/**
* Controls whether date is displayed in the field.
*/
hideDate: {
type: Boolean,
value: false
},
/**
* Controls whether the calendar/clock icon are displayed in the field.
*/
hideIcon: {
type: Boolean,
value: false
},
/**
* Controls whether the buttons will wrap under the field if
* the horizontal space is too small.
*/
allowWrap: {
type: Boolean,
value: false
},
/**
* If true, the field will be invalid if empty.
*/
required: {
type: Boolean,
value: false
},
/**
* Reflects if the date shown is valid.
* @private
*/
dateIsValid: {
type: Boolean,
value: true
},
/**
* Reflects if the time shown is valid.
* @private
*/
timeIsValid: {
type: Boolean,
value: true,
notify: true
},
/**
* Reflects if the input field is valid.
* Set in _validationField()
* @private
*/
fieldIsValid: {
type: Boolean,
value: true
},
/**
* Computed from `fieldIsValid`, `dateIsValid`, `timeIsValid`.
* All of them must valid for `isValid` to be true.
*/
isValid: {
type: Boolean,
computed: `_getIsValid(fieldIsValid, dateIsValid, timeIsValid)`
},
/**
* Determines whether to display the validation message or not.
* Use mostly by `datetime-range-field`.
*/
hideValidationMessage:{
type: Boolean,
value: false
},
/**
* Holds the error message when the field in not valid
*/
_validationErrorMessage: {
type: String,
value: ''
},
/**
* Used to determine if the 'validation-failed' class needs to be applied to '_getWrapperClass'
* This attribute is set by `px-datetime-range-field`
*/
_forcedFailedClass: {
type: Boolean,
value: false
},
/**
* True if any cell is currently selected.
* @private
*/
isSelected: {
type: Boolean,
value: false,
notify: true
},
/**
* Used to prevents the momentObjs from being set.
* Used by `px-datetime-range-field`.
*/
preventApply: {
type: Boolean,
value: false
},
/**
* Toggles the `dt-dropdown-is-active` class
*/
_dropdownActive: {
type: Boolean,
value: false
},
/**
* Toggles the `.dt-text-field--hover-fix` class
*/
_dropdownHoverFix: {
type: Boolean,
value: false
},
/**
* This will prevent the date cell from being focused
* when the calendar icon is clicked
*
* Used by `px-datetime-picker`
* @private
*/
preventCellFocus: {
type: Boolean,
value: false
},
/**
* Specifies if the dropdown content should get hoisted to a container in order to escape its current stacking context
*/
hoist: {
type: Boolean,
value: false
}
},
listeners: {
'px-datetime-entry-icon-clicked':'_iconClicked',
'px-next-field': '_nextFieldRequired',
'px-previous-field': '_previousFieldRequired',
'px-datetime-button-clicked': '_dateTimeButtons',
'px-validation-message' : '_handleValidationMessage',
'px-dropdown-focused': '_handleDropdownFocus',
'px-dropdown-blurred': '_handleDropdownBlur',
'px-moment-valid': '_handleValidMoment',
'px-moment-invalid': '_handleInvalidMoment',
'blur': '_applyChanges'
},
observers: [
'_validateSetMomentObj(momentObj)'
],
/*
* Will only show the dropdown in the date entry if `hideTime`
* and `showTimeZone` are true
*/
_showTimeZoneInDate: function(hideTime, showTimeZone) {
if(hideTime || hideTime === true) {
return showTimeZone;
}else {
return '';
}
},
/**
* Key bindings for iron-a11y-keys-behavior
* @private
*/
keyBindings: {
'esc' : '_onEsc',
'enter': '_onEnter'
},
/*
* Jumps from the date entry to time entry when using arrow keys
*/
_nextFieldRequired: function(evt) {
var date = this.$$('#date');
//if this comes from date do some logic, otherwise let it propagate
if (date && evt.detail.dateOrTime === 'Date') {
if (!this.hideTime) {
this.$$('#time')._focusCell(0);
evt.stopPropagation();
evt.stopImmediatePropagation();
}
}
},
/*
* Jumps from the time entry to date entry when using arrow keys
*/
_previousFieldRequired: function (evt) {
var time = this.$$('#time');
//if this comes from time do some logic, otherwise let it propagate
if (time && evt.detail.dateOrTime === 'Time') {
if (!this.hideDate) {
this.$$('#date')._focusLastCell();
evt.stopPropagation();
evt.stopImmediatePropagation();
}
}
},
/*
*/
focus: function (){
this._focusFirstEntry();
},
/*
*/
_focusFirstEntry: function (forceTimeFocus) {
if (!this.hideDate && !forceTimeFocus) {
this.$$('#date')._focusCell(0);
} else {
this.$$('#time')._focusCell(0);
}
},
/*
*/
_focusLastEntry: function () {
if (!this.hideTime) {
this.$$('#time')._focusLastCell();
} else {
this.$$('#date')._focusLastCell();
}
},
/**
* Toggles classes causing the buttons to wrap under the field
*/
_getWrapClass: function (allowWrap) {
if (allowWrap) {
return "flex--wrap";
}
},
/**
* Adds a margin right if the buttons are showing
*/
_getButtonMarginClass: function (showButtons, allowWrap) {
var classList = "dt-field-validation-wrapper ";
if (showButtons) {
classList += "u-mr- ";
if (allowWrap) {
classList += "u-pb+";
}
}
return classList;
},
/**
* event that watches when the dropdown has focus
*/
_handleDropdownFocus: function (e) {
e.stopPropagation();
this.set('_dropdownActive', true);
},
/**
* event that watches when the dropdown loses focus
*/
_handleDropdownBlur: function (e) {
e.stopPropagation();
this.set('_dropdownActive', false);
this._handleHoverFix();
},
/**
* when dt-field is detached set `_dropdownFocused` to false.
* prevents the dropdown from being stuck in a focused state
*/
detached: function () {
this._dropdownFocused = false;
},
/**
* This is a quick fix.
* In order to make dt-field look like an input field we have to overwrite some css on #fieldWrapper.
*
* There is a hover state on #fieldWrapper and px-dropdown is a child of #fieldWrapper;
* therefore, when dropdown is opened the hover to #fieldWrapper is extended.
* This causes a flash of gray when the user selects a time zone with the mouse.
* In order to prevent this flash we need to overwrite the hover state by added
* `.dt-text-field--hover-fix` to #fieldWrapper.
*
* The true issue is that we can't listen to px-dropdown.opened because there is a timing issue
* when px-dropdown.opened is set to false vs when the dropdown is not longer visible. This causes the flash.
* We couldn't find any other events that don't have a timing issue.
*/
_handleHoverFix: function () {
this.set('_dropdownHoverFix', true);
this.async(function () {
this.set('_dropdownHoverFix', false);
}, 1000);
},
/**
* isValid & _forcedFailedClass - determines whether to show the validation error classes
* isSelected - sets the styles when an entryCell is selected
* _dropdownActive - overwrites the styles when the dropdown is focused
* _dropdownHoverFix - overwrites the styles when the user selects an item in the dropdown
*/
_getWrapperClass: function (isValid, _forcedFailedClass, isSelected, _dropdownActive, _dropdownHoverFix) {
var classList = "flex flex--middle dt-text-field ";
if (isValid === false || _forcedFailedClass === true) {
classList += "validation-error validation-failed ";
} else if (isSelected) {
classList += "dt-is-selected ";
} else if (_dropdownActive) {
classList += "dt-dropdown-is-active ";
} else if (_dropdownHoverFix) {
classList += "dt-text-field--hover-fix ";
}
return classList;
},
/**
* Adds a right margin if both entries are showing
*/
_getEntryDateClass: function (hideDate, hideTime, hideIcon) {
var classList = "";
if (hideDate === false && hideTime === false && hideIcon === true) {
classList += "u-mr+ ";
} else if (hideDate === false && hideTime === false) {
classList += "u-mr- ";
}
return classList;
},
/**
* Run validation on a moment object that has been set from the outside
* This will set or unset validation errors
*/
_validateSetMomentObj: function(momentObj) {
if(momentObj === undefined) {return; }
this._validateMomentObj(momentObj);
},
/**
* computes `isValid`
*/
_getIsValid: function (fieldIsValid, dateIsValid, timeIsValid) {
return fieldIsValid && dateIsValid && timeIsValid;
},
/**
* Reflects the error message changes to _validationErrorMessage
*/
_handleValidationMessage: function (e) {
this.set('_validationErrorMessage', e.detail.validationErrorMessage);
},
/**
* Helper function for a dom-if
* Determines whether to display the validation error
*/
_showValidation: function (isValid, hideValidationMessage) {
var showValidation = !isValid;
if (hideValidationMessage) { showValidation = false};
return showValidation;
},
/**
* Handles validation coming from `_validateInput()`
* Set `dateIsValid` and `timeIsValid` to true as needed
* Runs validation if buttons are hidden and field is valid
*/
_handleValidMoment: function (evt) {
if(evt.detail && evt.detail.element && evt.detail.element.id === 'date') {
this.dateIsValid = true;
}
if(evt.detail && evt.detail.element && evt.detail.element.id === 'time') {
this.timeIsValid = true;
}
if(evt.detail && evt.detail.element && evt.detail.element.nodeName === 'PX-DATETIME-FIELD') {
this.dateIsValid = true;
this.timeIsValid = true;
}
//block evt from _validationField to avoid infite loop
if (!this.showButtons && evt.detail.element.nodeName !== 'PX-DATETIME-FIELD') {
var origin = "_momentChanged"
this._applyChanges(origin);
}
},
/**
* Sets `isValid`, `dateIsValid`, and `timeIsValid` to false as needed.
*/
_handleInvalidMoment: function(evt) {
this.IsValid = false;
if(evt.detail && evt.detail.element && evt.detail.element.id === 'date') {
this.dateIsValid = false;
}
if(evt.detail && evt.detail.element && evt.detail.element.id === 'time') {
this.timeIsValid = false;
}
},
/*
* Focuses select to the next cell when an icon is clicked
*/
_iconClicked: function (evt) {
if (evt.detail.dateOrTime === "Date" && !this.preventCellFocus) {
this.$$('#date')._focusCell(0);
}
else if (evt.detail.dateOrTime === "Time"){
this.$$('#time')._focusCell(0);
}
},
/**
* Determines whether to apply or cancel the changes
* based on the event
*/
_dateTimeButtons: function (evt) {
if (evt.detail.action) {
this._applyChanges();
}
else {
this._cancelChanges();
}
},
/**
* Runs `_cancelChanges()`
*/
_onEsc: function () {
this._cancelChanges();
},
/**
* Runs `_applyChanges()` and blurs the field
*/
_onEnter: function(evt) {
this._applyChanges();
this.blur();
},
/**
* Sets the momentObj if the field is valid, preventApply is not true,
* and the new and old momentObjs are not the same.
*/
_applyChanges: function (origin) {
var dateEntry = Polymer.dom(this.root).querySelector('#date');
var timeEntry = Polymer.dom(this.root).querySelector('#time');
if (this.momentObj === undefined || (dateEntry === null && !this.hideDate) || (timeEntry === null && !this.hideTime)) { return; }
var newMomentObj = this._validateField(origin);
if(this.preventApply && newMomentObj && newMomentObj !== "FieldSame") {
this.fire('px-field-valid', {"momentObj": newMomentObj});
}
else {
if(newMomentObj === "FieldBlank"){
this._validField();
this.set('momentObj', null);
this.fire('px-moment-changed');
}
else if(newMomentObj && newMomentObj !== "FieldSame") {
this.set('momentObj', newMomentObj);
this.fire('px-moment-changed');
}
}
},
/**
* Clear field or reset to previous moment objs
*/
_cancelChanges: function () {
var entries = Polymer.dom(this.root).querySelectorAll('px-datetime-entry');
if (this.momentObj === null) {
entries.forEach(function (entry) { entry.clear(); });
}
else {
entries.forEach(function (entry) { entry.setValueFromMoment(); });
}
this._validateField();
this.blur();
}
});
</script>