-
Notifications
You must be signed in to change notification settings - Fork 13
/
px-datetime-entry-cell.html
592 lines (563 loc) · 17.9 KB
/
px-datetime-entry-cell.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
<!--
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="../iron-a11y-keys-behavior/iron-a11y-keys-behavior.html" />
<link rel="import" href="px-datetime-validate.html" />
<link rel="import" href="px-datetime-behavior.html" />
<link rel="import" href="css/px-datetime-entry-cell-styles.html" />
<!--
Datetime input element. Includes iron-ally-keys-behavior to limit keystrokes to only valid characters.
### Usage
<px-datetime-entry-cell
id="cell{{index}}"
class="cell"
order='{{index}}'
moment-obj="[[momentObj]]"
moment-format='[[item]]'
time-zone="[[timeZone]]">
</px-datetime-entry-cell>
@element px-datetime-entry-cell
@homepage index.html
@demo index.html
-->
<dom-module id="px-datetime-entry-cell">
<template>
<style include="px-datetime-entry-cell-styles"></style>
<input
order="{{order}}"
class="datetime-entry-input text-input--bare"
on-focus="_handleFocus"
on-blur="_handleBlur"
on-paste="_handlePaste"
on-beforepaste="_beforePaste"
on-beforecopy="_beforeCopy"
on-copy="_handleCopy"
disabled="[[_getDisabled(momentFormat)]]"
type="[[_getType(_isNumber)]]"
pattern$="[[_getPattern(_isNumber)]]"
placeholder="[[_placeholderText(momentFormat)]]"
on-keypress="_keyPress"
max$="[[_max]]"
min$="[[_min]]"
step="1" />
</template>
</dom-module>
<script>
Polymer({
is: 'px-datetime-entry-cell',
behaviors: [
PxDatetimeBehavior.SingleMoment,
PxDatetimeBehavior.Validate,
Polymer.IronA11yKeysBehavior
],
properties: {
/**
* Moment format tokens for the format to display/validate this field against (see http://momentjs.com/docs/#/parsing/string-format/)
*
* Can only be configured statically; not data-bindable
*
*`example: 'YYYY'`
*
* @private
*/
momentFormat: {
type: String,
observer: '_formatChanged'
},
/**
* The separator character, passed down from px-datetime-entry
*
* @private
*/
symbol:{
type:String
},
/**
* Order number this cell is in px-datetime-entry, passed down from px-datetime-entry
*
* @private
*/
order: {
type: Number,
reflectToAttribute: true
},
/**
* Whether the cell is currently selected. Read-only.
*/
isSelected: {
type: Boolean,
readOnly: true,
notify: true,
value: false
},
/**
* Maximum numeric value for given field type.
*/
_max: {
type: Number,
computed: '_getMax(momentFormat)'
},
/**
* Minimum numeric value for given field type.
*/
_min: {
type: Number,
computed: '_getMin(momentFormat)'
},
/**
* Determine is the cell is a number
* based off the `momentFormat`
*/
_isNumber: {
type: Boolean,
computed: '_computeIsNumber(momentFormat)'
},
/**
* Number of characters the cell is allow to be
*/
_cellLength: {
type: Number,
value: 0
}
},
observers:[
'_updateInputValue(momentObj, timeZone)',
'_onResourcesUpdated(resources)'
],
/**
* Key bindings for iron-a11y-keys-behavior
*
* More keyBindings are added in _addGeneralKeyBindings
*
* @private
*/
keyBindings: {
'right' : '_moveFocusForward',
'left' : '_moveFocusBack'
},
/**
* On attached, set up key bindings.
*/
attached: function(){
this._addGeneralKeyBindings();
},
/**
* Clears the input value for the cell.
*/
clear: function() {
this.$$('.datetime-entry-input').value = '';
},
/**
* Sets the value of the cell to the current moment obj
*/
setValueFromMoment: function() {
//if moment is null (or somehow undefined) => clear
if(!this.momentObj) {
this.clear();
} else {
this.$$('.datetime-entry-input').value = this.momentObj.tz(this.timeZone).format(this.momentFormat);
}
},
_computeIsNumber: function(momentFormat) {
return !(/^(?:a|A|MMM|MMMM|Do|ddd|dddd|Z|ZZ)$/.test(momentFormat));
},
_getPattern: function() {
if(this._isNumber === undefined) {
return null;
}
if(this._isNumber) {
//should help with mobile keyboard (i.e get the number keyboard rather than the phone one)
return '[0-9]*';
} else {
return null;
}
},
/**
* Set the correct type of input field based on the momentFormat
*/
_getType: function() {
if(this._isNumber === undefined) {
return;
}
return this._isNumber ? 'tel' : 'text';
},
/**
* Disables the input field for time zone entry cells.
*/
_getDisabled: function(momentFormat) {
return (this.momentFormat === 'Z' || this.momentFormat === 'ZZ');
},
_formatChanged: function() {
if(this.momentFormat !== undefined) {
this._updateInputValue();
this._sizeInputs();
if(this.momentFormat === 'A' || this.momentFormat === 'a'){
this._cellLength = 2;
} else if(this.momentFormat !== 'Z' && this.momentFormat !== 'ZZ') {
this._cellLength = this.momentFormat.length;
} else {
//don't prevent timezone size
this._cellLength = -1;
}
}
},
/**
* Size the input fields based on the value or placeholder text
*/
_sizeInputs: function(){
//create a dummy canvas to measure string and make size the input correctly
var style = window.getComputedStyle(this.$$('.datetime-entry-input'), null),
fontSize = style.getPropertyValue('font-size'),
fontFamily = style.getPropertyValue('font-family'),
c = document.createElement('canvas'),
ctx=c.getContext('2d'),
length;
if(fontSize === "0px" || fontSize === "0" || fontSize === ""){
setTimeout(function(){
this._sizeInputs();
}.bind(this),50);
return;
}
ctx.font = fontSize + " " + fontFamily;
if(this.$$('.datetime-entry-input').value) {
length = ctx.measureText(this.$$('.datetime-entry-input').value.toUpperCase()).width + 1;
}
else {
// the extra width is needed for the placeholder ONLY on Edge and Firefox
length = ctx.measureText(this.$$('.datetime-entry-input').placeholder).width + 2;
}
length = Math.ceil(length);
this.$$('.datetime-entry-input').style['width'] = length + 'px';
},
/**
* Sets up regular key bindings
*/
_addGeneralKeyBindings: function(){
if(this.momentFormat === 'A' || this.momentFormat === 'a'){
this.addOwnKeyBinding('a p','_toggleAMPM');
this.addOwnKeyBinding('down up', '_toggleAMPM');
this.addOwnKeyBinding('backspace del','_preventDeleteDefault');
} else if(this.momentFormat !== 'Z' && this.momentFormat !== 'ZZ') {
this.addOwnKeyBinding('down up', '_wraparound');
}
},
/**
* Sets up separator keybindings
*/
_addSeparatorKeyBinding: function(){
var separator = (this.symbol.trim() === '') ? 'space' : this.symbol.trim();
this.addOwnKeyBinding(separator,'_moveFocusForward');
},
/**
* If `momentObj` or `timeZone` update, reflect this in the cell
*/
_updateInputValue: function() {
if(this.momentObj !== undefined && this.timeZone !== undefined) {
this.setValueFromMoment();
this._sizeInputs();
}
},
/**
* When resources is changed, update placeholder text and resize input if need.
*/
_onResourcesUpdated: function(resources) {
const entryInput = this.$$('.datetime-entry-input');
const currentPlaceholderText = entryInput.placeholder;
const nextPlaceholderText = this._placeholderText(this.momentFormat);
if (nextPlaceholderText !== currentPlaceholderText) {
entryInput.placeholder = nextPlaceholderText;
if (!this.momentObj) {
this._sizeInputs();
}
}
},
/**
* Fires when 'left' key is hit
*
* @event px-entry-cell-move
* @param {number} dir - Values -1
*/
_moveFocusBack : function(){
setTimeout(function(){
this.fire('px-entry-cell-move', { 'dir' : -1 });
}.bind(this),10);
},
/**
* Fires when 'right' key is hit
*
* @event px-entry-cell-move
* @param {number} dir - Values 1
*/
_moveFocusForward : function(){
setTimeout(function(){
this.fire('px-entry-cell-move', { 'dir' : 1 });
}.bind(this),10);
},
/**
* Propagate the focus event up to entry to apply inline edit styles if applicable.
*/
_handleFocus: function(evt) {
if(this.momentFormat !== 'Z' && this.momentFormat !== 'ZZ') {
this._setIsSelected(true);
}
this.fire('px-cell-focused');
},
/**
* Allow the user to loop through valid cell values
* ex If the momentFormat is MM the cell value can go from 12 to 1 by hitting the up arrow
*/
_wraparound: function(evt) {
var key = evt.detail.combo;
dtEntryValue = this.$$('.datetime-entry-input').value,
currentVal = dtEntryValue ? parseInt(dtEntryValue) : (this._min - 1),
isUpDown = false;
if(key === 'up') {
currentVal++;
currentVal = currentVal > this._max ? this._min : currentVal;
currentVal = currentVal < this._min ? this._min : currentVal;
this.$$('.datetime-entry-input').value = currentVal;
evt.preventDefault();
}
else if(key === 'down') {
currentVal--;
currentVal = currentVal > this._max ? this._max : currentVal;
currentVal = currentVal < this._min ? this._max : currentVal;
this.$$('.datetime-entry-input').value = currentVal;
evt.preventDefault();
}
},
/**
* Checks that the value has the correct number of digits for our format
* Autocomplete function
*/
_checkValue: function(){
//if our format requires two digits and we only have one, add a 0 in front
if(this.$$('.datetime-entry-input').value && this.$$('.datetime-entry-input').value.length === 1 &&
/^(?:MM|DD|HH|hh|kk|mm|ss|YY)$/.test(this.momentFormat)){
this.$$('.datetime-entry-input').value = '0' + this.$$('.datetime-entry-input').value;
}
//if the format is YYYY or Y and the input is 2 characters then convert the input to a 4 character year representation
else if(this.$$('.datetime-entry-input').value && this.$$('.datetime-entry-input').value.length === 2 && this.momentFormat === 'YYYY'){
var mo = Px.moment(this.$$('.datetime-entry-input').value, 'YY');
this.$$('.datetime-entry-input').value = mo.format(this.momentFormat);
}
else if(this.$$('.datetime-entry-input').value && this.momentFormat[0] === 'S' && this.$$('.datetime-entry-input').value.length < this.momentFormat.length){
var dtNumber = parseInt(this.$$('.datetime-entry-input').value);
dtNumber = dtNumber.toPrecision(this.momentFormat.length) * Math.pow(10, (this.momentFormat.length - this.$$('.datetime-entry-input').value.length));
this.$$('.datetime-entry-input').value = dtNumber.toString();
}
this._sizeInputs();
},
/**
* Fires on blur
*
* @event px-cell-blurred
*/
_handleBlur: function(evt) {
var ne = Polymer.dom(evt);
this._setIsSelected(false);
this._checkValue();
this.fire('px-cell-blurred');
},
/**
* Toggles AM & PM when up/down or A/P keys are pressed.
*/
_toggleAMPM : function(evt){
evt.preventDefault();
var ne = Polymer.dom(evt),
key = evt.detail.combo;
if(key === 'A' || key === 'a'){
this._setAMPM('AM');
this._moveFocusForward();
} else if(key === 'P' || key === 'p'){
this._setAMPM('PM');
this._moveFocusForward();
} else if(key === 'up' || key === 'down'){
if(this.$$('.datetime-entry-input').value === 'AM' || this.$$('.datetime-entry-input').value === 'am'){
this._setAMPM('PM');
} else {
this._setAMPM('AM');
}
}
},
/**
* Sets the AM/PM value.
*/
_setAMPM: function(ampm){
var mo = Px.moment.tz('01:00:00 ' + ampm, 'hh:mm:ss ' + this.momentFormat, this.timeZone);
this.$$('.datetime-entry-input').value = mo.tz(this.timeZone).format(this.momentFormat);
},
/**
* Prevent the delete button from navigating back
*/
_preventDeleteDefault: function(evt){
evt.preventDefault();
this.clear();
},
/**
* If the momentFormat format is not 'Z', 'ZZ', 'X', 'x', 'A' or 'a' then return the momentFormat
* Note: placeholder text supports i18n
*/
_placeholderText: function(momentFormat){
var phText = {
'Z': String.fromCharCode(177) + 'xx:xx',
'ZZ': String.fromCharCode(177) + 'xxxx',
'X': 'epoch time (s)',
'x': 'epoch time (ms)',
'a': 'AM',
'A': 'AM'
};
let text = momentFormat;
if(phText[momentFormat]){
text = phText[momentFormat];
}
return this.localize(text);
},
/**
* Handles before copy event
*
* @event px-request-datetime-entry-copy
* @param {string} dir - Values clipboardData
*/
/**
* Handles before copy event, used for IE instead of the copy event
*/
_beforeCopy: function(evt) {
//IE only
if(!evt.clipboardData) {
this.fire('px-request-datetime-entry-copy', window.clipboardData);
}
},
/**
* Handles before paste event, used for IE instead of the paste event
*/
_beforePaste: function(evt) {
//IE stores the data in window.clipboardData
if(!evt.clipboardData) {
this.fire('px-request-datetime-entry-paste', window.clipboardData);
}
},
/**
* Handles paste event
*/
_handlePaste: function(evt){
//IE stores the data in window.clipboardData and will deal with it on _beforePaste
if(evt.clipboardData) {
this.fire('px-request-datetime-entry-paste', evt.clipboardData);
}
evt.preventDefault();
},
/**
* Handles copy event
*/
_handleCopy: function(evt){
//IE stores the data in window.clipboardData and will deal with it on _beforePaste
if(evt.clipboardData) {
this.fire('px-request-datetime-entry-copy', evt.clipboardData);
}
evt.preventDefault();
},
/**
* Format strings and setting/modification strings are different (?!?!)
* This method converts one to the other
*/
_convertMomentFormat: function(){
var momentTypeConversion = {
'Y' : 'y', //years
'M' : 'M', //months
'D' : 'd', // days
'H' : 'h', //hours
'h' : 'h', //hours
'k' : 'h', //hours
'm' : 'm', //minutes
's' : 's', //seconds
'X' : 's', //seconds
'S' : 'ms', //milliseconds
'x' : 'ms' //milliseconds
};
// take the first char of the moment format and convert it to the other format
return momentTypeConversion[this.momentFormat[0]]
},
/**
* Set the max value a token can be
*/
_getMax: function(momentFormat) {
if( /^(?:M|MM|h|hh)$/.test(momentFormat) ) {
return 12;
}
if( /^(?:D|DD)$/.test(momentFormat) ) {
return 31;
}
if( /^(?:H|HH)$/.test(momentFormat) ) {
return 23;
}
if( /^(?:k|kk)$/.test(momentFormat) ) {
return 24;
}
if( /^(?:m|mm|ss|s)$/.test(momentFormat) ) {
return 59;
}
if(momentFormat === "S") {
return 9;
}
if(momentFormat === "SS") {
return 99;
}
if(momentFormat === "SSS") {
return 999;
}
if(momentFormat === "YY") {
return 99;
}
if(momentFormat === "YYYY") {
return 9999;
}
return '';
},
/**
* Set the min value a token can be
*/
_getMin: function(momentFormat) {
if( /^(?:YY|YYYY|X|x|H|HH|m|mm|s|ss|S|SS|SSS)$/.test(momentFormat) ) {
return 0;
}
if( /^(?:M|MM|D|DD|h|hh|k|kk)$/.test(momentFormat) ) {
return 1;
}
return '';
},
_keyPress: function(evt) {
if(evt.key !== 'Backspace' && evt.key !== 'Delete' && evt.key !== 'Cut' && evt.key !== 'Copy' && evt.key !== 'ArrowLeft' && evt.key !== 'ArrowRight') {
//AM PM, only accept A and P
if((this.momentFormat === 'A' || this.momentFormat === 'a') && !/[aApP]/.test(evt.key)) {
evt.preventDefault();
return;
}
//ensure for numbers we only accept digits
if(this._isNumber && !/[0-9]/.test(evt.key)) {
evt.preventDefault();
return;
}
//already at full length, delete current value and let this new value be applied
if(this._cellLength !== -1 && this.$$('.datetime-entry-input').value.length === this._cellLength) {
this.$$('.datetime-entry-input').value = '';
this._addSeparatorKeyBinding();
}
// if it is full, we're done with this cell, go to the next
if(this.$$('.datetime-entry-input').value.length === this._cellLength - 1) {
this._moveFocusForward();
}
}
}
});
</script>