-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathvaadin-text-field-mixin.html
1074 lines (945 loc) · 31.1 KB
/
vaadin-text-field-mixin.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
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
<!--
@license
Copyright (c) 2017 Vaadin Ltd.
This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
-->
<link rel="import" href="../../polymer/lib/utils/async.html">
<link rel="import" href="../../polymer/lib/utils/debounce.html">
<dom-module id="vaadin-text-field-shared-styles">
<template>
<style>
:host {
display: inline-flex;
outline: none;
}
:host::before {
content: "\2003";
width: 0;
display: inline-block;
/* Size and position this element on the same vertical position as the input-field element
to make vertical align for the host element work as expected */
}
:host([hidden]) {
display: none !important;
}
.vaadin-text-field-container,
.vaadin-text-area-container {
display: flex;
flex-direction: column;
min-width: 100%;
max-width: 100%;
width: var(--vaadin-text-field-default-width, 12em);
}
[part="label"]:empty {
display: none;
}
[part="input-field"] {
display: flex;
align-items: center;
flex: auto;
}
.vaadin-text-field-container [part="input-field"] {
flex-grow: 0;
}
/* Reset the native input styles */
[part="value"],
[part="input-field"] ::slotted(input),
[part="input-field"] ::slotted(textarea) {
-webkit-appearance: none;
-moz-appearance: none;
outline: none;
margin: 0;
padding: 0;
border: 0;
border-radius: 0;
min-width: 0;
font: inherit;
font-size: 1em;
line-height: normal;
color: inherit;
background-color: transparent;
/* Disable default invalid style in Firefox */
box-shadow: none;
}
[part="input-field"] ::slotted(*) {
flex: none;
}
[part="value"],
[part="input-field"] ::slotted(input),
[part="input-field"] ::slotted(textarea),
/* Slotted by vaadin-select-text-field */
[part="input-field"] ::slotted([part="value"]) {
flex: auto;
white-space: nowrap;
overflow: hidden;
width: 100%;
height: 100%;
}
[part="input-field"] ::slotted(textarea) {
resize: none;
}
[part="value"]::-ms-clear,
[part="input-field"] ::slotted(input)::-ms-clear {
display: none;
}
[part="clear-button"] {
cursor: default;
}
[part="clear-button"]::before {
content: "✕";
}
</style>
</template>
</dom-module>
<script>
/**
* @namespace Vaadin
*/
window.Vaadin = window.Vaadin || {};
const HOST_PROPS = {
default: ['list', 'autofocus', 'pattern', 'autocapitalize', 'autocorrect', 'maxlength',
'minlength', 'name', 'placeholder', 'autocomplete', 'title', 'disabled', 'readonly', 'required'],
accessible: ['invalid']
};
const PROP_TYPE = {
DEFAULT: 'default',
ACCESSIBLE: 'accessible'
};
/**
* @polymerMixin
* @memberof Vaadin
*/
Vaadin.TextFieldMixin = subclass => class VaadinTextFieldMixin extends subclass {
static get properties() {
return {
/**
* Whether the value of the control can be automatically completed by the browser.
* List of available options at:
* https://developer.mozilla.org/en/docs/Web/HTML/Element/input#attr-autocomplete
*/
autocomplete: {
type: String
},
/**
* This is a property supported by Safari that is used to control whether
* autocorrection should be enabled when the user is entering/editing the text.
* Possible values are:
* on: Enable autocorrection.
* off: Disable autocorrection.
* @type {!TextFieldAutoCorrect | undefined}
*/
autocorrect: {
type: String
},
/**
* This is a property supported by Safari and Chrome that is used to control whether
* autocapitalization should be enabled when the user is entering/editing the text.
* Possible values are:
* characters: Characters capitalization.
* words: Words capitalization.
* sentences: Sentences capitalization.
* none: No capitalization.
* @type {!TextFieldAutoCapitalize | undefined}
*/
autocapitalize: {
type: String
},
/**
* Specify that the value should be automatically selected when the field gains focus.
* @type {boolean}
*/
autoselect: {
type: Boolean,
value: false
},
/**
* Set to true to display the clear icon which clears the input.
* @attr {boolean} clear-button-visible
* @type {boolean}
*/
clearButtonVisible: {
type: Boolean,
value: false
},
/**
* Error to show when the input value is invalid.
* @attr {string} error-message
* @type {string}
*/
errorMessage: {
type: String,
value: '',
observer: '_errorMessageChanged'
},
/**
* Object with translated strings used for localization. Has
* the following structure and default values:
*
* ```
* {
* // Translation of the clear icon button accessible label
* clear: 'Clear'
* }
* ```
* @type {{clear: string}}
*/
i18n: {
type: Object,
value: () => {
return {
clear: 'Clear'
};
}
},
/**
* String used for the label element.
* @type {string}
*/
label: {
type: String,
value: '',
observer: '_labelChanged'
},
/**
* String used for the helper text.
* @attr {string} helper-text
* @type {string | null}
*/
helperText: {
type: String,
value: '',
observer: '_helperTextChanged'
},
/**
* Maximum number of characters (in Unicode code points) that the user can enter.
*/
maxlength: {
type: Number
},
/**
* Minimum number of characters (in Unicode code points) that the user can enter.
*/
minlength: {
type: Number
},
/**
* The name of the control, which is submitted with the form data.
*/
name: {
type: String
},
/**
* A hint to the user of what can be entered in the control.
*/
placeholder: {
type: String
},
/**
* This attribute indicates that the user cannot modify the value of the control.
*/
readonly: {
type: Boolean,
reflectToAttribute: true
},
/**
* Specifies that the user must fill in a value.
*/
required: {
type: Boolean,
reflectToAttribute: true
},
/**
* The initial value of the control.
* It can be used for two-way data binding.
* @type {string}
*/
value: {
type: String,
value: '',
observer: '_valueChanged',
notify: true
},
/**
* Whether the input element has a non-empty value.
*
* @protected
*/
_hasInputValue: {
type: Boolean,
value: false,
observer: '_hasInputValueChanged',
},
/**
* This property is set to true when the control value is invalid.
* @type {boolean}
*/
invalid: {
type: Boolean,
reflectToAttribute: true,
notify: true,
value: false
},
/**
* Specifies that the text field has value.
* @attr {boolean} has-value
*/
hasValue: {
type: Boolean,
reflectToAttribute: true
},
/**
* When set to true, user is prevented from typing a value that
* conflicts with the given `pattern`.
* @attr {boolean} prevent-invalid-input
*/
preventInvalidInput: {
type: Boolean
},
/**
* A pattern matched against individual characters the user inputs.
* When set, the field will prevent:
* - `keyDown` events if the entered key doesn't match `/^_enabledCharPattern$/`
* - `paste` events if the pasted text doesn't match `/^_enabledCharPattern*$/`
* - `drop` events if the dropped text doesn't match `/^_enabledCharPattern*$/`
*
* For example, to enable entering only numbers and minus signs,
* `_enabledCharPattern = "[\\d-]"`
* @protected
*/
_enabledCharPattern: String,
/** @private */
_labelId: String,
/** @private */
_helperTextId: String,
/** @private */
_errorId: String,
/** @private */
_inputId: String,
/** @private */
_hasSlottedHelper: Boolean
};
}
static get observers() {
return ['_stateChanged(disabled, readonly, clearButtonVisible, hasValue)',
'_hostPropsChanged(' + HOST_PROPS.default.join(', ') + ')',
'_hostAccessiblePropsChanged(' + HOST_PROPS.accessible.join(', ') + ')',
'_getActiveErrorId(invalid, errorMessage, _errorId, helperText, _helperTextId, _hasSlottedHelper)',
'_getActiveLabelId(label, _labelId, _inputId)',
'__observeOffsetHeight(errorMessage, invalid, label, helperText)',
'__enabledCharPatternChanged(_enabledCharPattern)'
];
}
/**
* @return {HTMLElement | undefined}
* @protected
*/
get focusElement() {
if (!this.shadowRoot) {
return;
}
const slotted = this.querySelector(`${this._slottedTagName}[slot="${this._slottedTagName}"]`);
if (slotted) {
return slotted;
}
return this.shadowRoot.querySelector('[part="value"]');
}
/**
* @return {HTMLElement | undefined}}
* @protected
*/
get inputElement() {
return this.focusElement;
}
/**
* @return {string}
* @protected
*/
get _slottedTagName() {
return 'input';
}
/** @protected */
_createConstraintsObserver() {
// This complex observer needs to be added dynamically here (instead of defining it above in the `get observers()`)
// so that it runs after complex observers of inheriting classes. Otherwise e.g. `_stepOrMinChanged()` observer of
// vaadin-number-field would run after this and the `min` and `step` properties would not yet be propagated to
// the `inputElement` when this runs.
this._createMethodObserver('_constraintsChanged(required, minlength, maxlength, pattern)');
}
/**
* A property for accessing the input element's value.
*
* Override this getter if the property is different from the default `value` one.
*
* @protected
* @return {string}
*/
get _inputElementValueProperty() {
return 'value';
}
/**
* The input element's value.
*
* @protected
* @return {string}
*/
get _inputElementValue() {
return this.inputElement ? this.inputElement[this._inputElementValueProperty] : undefined;
}
/**
* The input element's value.
*
* @protected
*/
set _inputElementValue(value) {
if (this.inputElement) {
this.inputElement[this._inputElementValueProperty] = value;
}
}
/**
* Sets the `_hasInputValue` property based on the `input` event.
*
* @param {InputEvent} event
* @protected
*/
_setHasInputValue(event) {
this._hasInputValue = event.target.value.length > 0;
}
/**
* An input event listener used to update `_hasInputValue` property.
* Do not override this method.
*
* @param {Event} event
* @private
*/
__onInput(event) {
this._setHasInputValue(event);
this._onInput(event);
}
/** @private */
_onInput(e) {
if (this.__preventInput) {
e.stopImmediatePropagation();
this.__preventInput = false;
return;
}
if (this.preventInvalidInput) {
const input = this.inputElement;
if (input.value.length > 0 && !this.checkValidity()) {
input.value = this.value || '';
// add input-prevented attribute for 200ms
this.setAttribute('input-prevented', '');
this._inputDebouncer = Polymer.Debouncer.debounce(
this._inputDebouncer,
Polymer.Async.timeOut.after(200), () => {
this.removeAttribute('input-prevented');
});
return;
}
}
if (!e.__fromClearButton) {
this.__userInput = true;
}
this.value = e.target.value;
this.__userInput = false;
}
// NOTE(yuriy): Workaround needed for IE11 and Edge for proper displaying
// of the clear button instead of setting display property for it depending on state.
/** @private */
_stateChanged(disabled, readonly, clearButtonVisible, hasValue) {
if (!disabled &&
!readonly &&
clearButtonVisible &&
hasValue
) {
this.$.clearButton.removeAttribute('hidden');
} else {
this.$.clearButton.setAttribute('hidden', true);
}
}
/**
* Observer to notify about the change of private property.
*
* @private
*/
_hasInputValueChanged(hasValue, oldHasValue) {
if (hasValue || oldHasValue) {
this.dispatchEvent(new CustomEvent('has-input-value-changed'));
}
}
/**
* @param {!Event} e
* @protected
*/
_onChange(e) {
if (this._valueClearing) {
return;
}
// In the Shadow DOM, the `change` event is not leaked into the
// ancestor tree, so we must do this manually.
const changeEvent = new CustomEvent('change', {
detail: {
sourceEvent: e
},
bubbles: e.bubbles,
cancelable: e.cancelable,
});
this.dispatchEvent(changeEvent);
}
/**
* @param {unknown} newVal
* @param {unknown} oldVal
* @protected
*/
_valueChanged(newVal, oldVal) {
// setting initial value to empty string, skip validation
if (newVal === '' && oldVal === undefined) {
return;
}
if (newVal !== '' && newVal != null) {
this.hasValue = true;
} else {
this.hasValue = false;
}
if (this.__userInput) {
return;
} else if (newVal !== undefined) {
this._inputElementValue = newVal;
} else {
this.value = this._inputElementValue = '';
}
if (this.invalid) {
this.validate();
}
}
/** @private */
_labelChanged(label) {
this._setOrToggleAttribute('has-label', !!label, this);
}
/** @private */
_helperTextChanged(helperText) {
this._setOrToggleAttribute('has-helper', !!helperText, this);
}
/** @private */
_errorMessageChanged(errorMessage) {
this._setOrToggleAttribute('has-error-message', !!errorMessage, this);
}
/** @private */
_onHelperSlotChange() {
const slottedNodes = this.shadowRoot.querySelector(`[name="helper"]`).assignedNodes({flatten: true});
// Only has slotted helper if not a text node
// Text nodes are added by the helperText prop and not the helper slot
// The filter is added due to shady DOM triggering this callback on helperText prop change
this._hasSlottedHelper = slottedNodes.filter(node => node.nodeType !== 3).length;
if (this._hasSlottedHelper) {
this.setAttribute('has-helper', 'slotted');
} else if (this.helperText === '' || this.helperText === null) {
this.removeAttribute('has-helper');
}
}
/** @private */
_onSlotChange() {
const slotted = this.querySelector(`${this._slottedTagName}[slot="${this._slottedTagName}"]`);
if (this.value) {
this._inputElementValue = this.value;
this.validate();
}
if (slotted && !this._slottedInput) {
this._validateSlottedValue(slotted);
this._addInputListeners(slotted);
this._addIEListeners(slotted);
this._slottedInput = slotted;
} else if (!slotted && this._slottedInput) {
this._removeInputListeners(this._slottedInput);
this._removeIEListeners(this._slottedInput);
this._slottedInput = undefined;
}
Object.keys(PROP_TYPE).map(key => PROP_TYPE[key]).forEach(type =>
this._propagateHostAttributes(HOST_PROPS[type].map(attr => this[attr]), type));
}
/** @private */
_hostPropsChanged(...attributesValues) {
this._propagateHostAttributes(attributesValues, PROP_TYPE.DEFAULT);
}
/** @private */
_hostAccessiblePropsChanged(...attributesValues) {
this._propagateHostAttributes(attributesValues, PROP_TYPE.ACCESSIBLE);
}
/** @private */
_validateSlottedValue(slotted) {
if (slotted.value !== this.value) {
console.warn('Please define value on the vaadin-text-field component!');
slotted.value = '';
}
}
/** @private */
_propagateHostAttributes(attributesValues, type) {
const input = this.inputElement;
const attributeNames = HOST_PROPS[type];
if (type === PROP_TYPE.ACCESSIBLE) {
attributeNames.forEach((attr, index) => {
this._setOrToggleAttribute(attr, attributesValues[index], input);
this._setOrToggleAttribute(`aria-${attr}`, attributesValues[index] ? 'true' : false, input);
});
} else {
attributeNames.forEach((attr, index) => {
this._setOrToggleAttribute(attr, attributesValues[index], input);
});
}
}
/** @private */
_setOrToggleAttribute(name, value, node) {
if (!name || !node) {
return;
}
if (value) {
node.setAttribute(name, (typeof value === 'boolean') ? '' : value);
} else {
node.removeAttribute(name);
}
}
/**
* @param {boolean | undefined} required
* @param {number | undefined} minlength
* @param {number | undefined} maxlength
* @param {string | undefined} maxlength
* @protected
*/
_constraintsChanged(required, minlength, maxlength, pattern) {
if (!this.invalid) {
return;
}
if (!required && !minlength && !maxlength && !pattern) {
this._setInvalid(false);
} else {
this.validate();
}
}
/**
* Returns true if the current input value satisfies all constraints (if any)
* @return {boolean}
*/
checkValidity() {
// Note (Yuriy): `__forceCheckValidity` is used in containing components (i.e. `vaadin-date-picker`) in order
// to force the checkValidity instead of returning the previous invalid state.
if (this.required || this.pattern || this.maxlength || this.minlength || this.__forceCheckValidity) {
return this.inputElement.checkValidity();
} else {
return !this.invalid;
}
}
/** @private */
_addInputListeners(node) {
node.addEventListener('input', this._boundOnInput);
node.addEventListener('change', this._boundOnChange);
node.addEventListener('blur', this._boundOnBlur);
node.addEventListener('focus', this._boundOnFocus);
node.addEventListener('paste', this._boundOnPaste);
node.addEventListener('drop', this._boundOnDrop);
node.addEventListener('beforeinput', this._boundOnBeforeInput);
}
/** @private */
_removeInputListeners(node) {
node.removeEventListener('input', this._boundOnInput);
node.removeEventListener('change', this._boundOnChange);
node.removeEventListener('blur', this._boundOnBlur);
node.removeEventListener('focus', this._boundOnFocus);
node.removeEventListener('paste', this._boundOnPaste);
node.removeEventListener('drop', this._boundOnDrop);
node.removeEventListener('beforeinput', this._boundOnBeforeInput);
}
/** @protected */
ready() {
super.ready();
this._createConstraintsObserver();
this._boundOnInput = this.__onInput.bind(this);
this._boundOnChange = this._onChange.bind(this);
this._boundOnBlur = this._onBlur.bind(this);
this._boundOnFocus = this._onFocus.bind(this);
this._boundOnPaste = this._onPaste.bind(this);
this._boundOnDrop = this._onDrop.bind(this);
this._boundOnBeforeInput = this._onBeforeInput.bind(this);
const defaultInput = this.shadowRoot.querySelector('[part="value"]');
this._slottedInput = this.querySelector(`${this._slottedTagName}[slot="${this._slottedTagName}"]`);
this._addInputListeners(defaultInput);
this._addIEListeners(defaultInput);
if (this._slottedInput) {
this._addIEListeners(this._slottedInput);
this._addInputListeners(this._slottedInput);
}
this.shadowRoot.querySelector('[name="input"], [name="textarea"]')
.addEventListener('slotchange', this._onSlotChange.bind(this));
this._onHelperSlotChange();
this.shadowRoot.querySelector('[name="helper"]').addEventListener('slotchange', this._onHelperSlotChange.bind(this));
if (!(window.ShadyCSS && window.ShadyCSS.nativeCss)) {
this.updateStyles();
}
this.$.clearButton.addEventListener('mousedown', () => this._valueClearing = true);
this.$.clearButton.addEventListener('mouseleave', () => this._valueClearing = false);
this.$.clearButton.addEventListener('click', this._onClearButtonClick.bind(this));
this.addEventListener('keydown', this._onKeyDown.bind(this));
var uniqueId = Vaadin.TextFieldMixin._uniqueId = 1 + Vaadin.TextFieldMixin._uniqueId || 0;
this._errorId = `${this.constructor.is}-error-${uniqueId}`;
this._labelId = `${this.constructor.is}-label-${uniqueId}`;
this._helperTextId = `${this.constructor.is}-helper-${uniqueId}`;
this._inputId = `${this.constructor.is}-input-${uniqueId}`;
// Lumo theme defines a max-height transition for the "error-message"
// part on invalid state change.
this.shadowRoot.querySelector('[part="error-message"]')
.addEventListener('transitionend', () => {
this.__observeOffsetHeight();
});
}
/**
* @param {boolean} invalid
* @protected
*/
_setInvalid(invalid) {
if (this._shouldSetInvalid(invalid)) {
this.invalid = invalid;
}
}
/**
* Override this method to define whether the given `invalid` state should be set.
*
* @param {boolean} _invalid
* @return {boolean}
* @protected
*/
_shouldSetInvalid(_invalid) {
return true;
}
/**
* Validates the field and sets the `invalid` property based on the result.
*
* The method fires a `validated` event with the result of the validation.
*
* @return {boolean} True if the value is valid.
*/
validate() {
const isValid = this.checkValidity();
this._setInvalid(!isValid);
this.dispatchEvent(new CustomEvent('validated', {detail: {valid: isValid}}));
return isValid;
}
clear() {
this._hasInputValue = false;
this.value = '';
}
/** @private */
_onBlur() {
this.validate();
}
/** @private */
_onFocus() {
if (this.autoselect) {
this.inputElement.select();
// iOS 9 workaround: https://stackoverflow.com/a/7436574
setTimeout(() => {
try {
this.inputElement.setSelectionRange(0, 9999);
} catch (e) {
// The workaround may cause errors on different input types.
// Needs to be suppressed. See https://github.com/vaadin/flow/issues/6070
}
});
}
}
/** @private */
_onClearButtonClick(e) {
e.preventDefault();
// NOTE(yuriy): This line won't affect focus on the host. Cannot be properly tested.
this.inputElement.focus();
this.clear();
this._valueClearing = false;
if (navigator.userAgent.match(/Trident/)) {
// Disable IE input" event prevention here, we want the input event from
// below to propagate normally.
this.__preventInput = false;
}
const inputEvent = new Event('input', {bubbles: true, composed: true});
inputEvent.__fromClearButton = true;
const changeEvent = new Event('change', {bubbles: !this._slottedInput});
changeEvent.__fromClearButton = true;
this.inputElement.dispatchEvent(inputEvent);
this.inputElement.dispatchEvent(changeEvent);
}
/**
* @param {!KeyboardEvent} e
* @protected
*/
_onKeyDown(e) {
if (e.keyCode === 27 && this.clearButtonVisible) {
const dispatchChange = !!this.value;
this.clear();
dispatchChange && this.inputElement.dispatchEvent(new Event('change', {bubbles: !this._slottedInput}));
}
if (this._enabledCharPattern && !this.__shouldAcceptKey(e)) {
e.preventDefault();
}
}
/** @private */
__shouldAcceptKey(event) {
return (event.metaKey || event.ctrlKey)
|| !event.key // allow typing anything if event.key is not supported
|| event.key.length !== 1 // allow "Backspace", "ArrowLeft" etc.
|| this.__enabledCharRegExp.test(event.key);
}
/** @private */
_onPaste(e) {
if (this._enabledCharPattern) {
const pastedText = (e.clipboardData || window.clipboardData).getData('text');
if (!this.__enabledTextRegExp.test(pastedText)) {
e.preventDefault();
}
}
}
/** @private */
_onDrop(e) {
if (this._enabledCharPattern) {
const draggedText = e.dataTransfer.getData('text');
if (!this.__enabledTextRegExp.test(draggedText)) {
e.preventDefault();
}
}
}
/** @private */
_onBeforeInput(e) {
// The `beforeinput` event covers all the cases for `_enabledCharPattern`: keyboard, pasting and dropping,
// but it is still experimental technology so we can't rely on it. It's used here just as an additional check,
// because it seems to be the only way to detect and prevent specific keys on mobile devices. See issue #429.
if (this._enabledCharPattern && e.data && !this.__enabledTextRegExp.test(e.data)) {
e.preventDefault();
}
}
/** @private */
__enabledCharPatternChanged(_enabledCharPattern) {
this.__enabledCharRegExp = _enabledCharPattern && new RegExp('^' + _enabledCharPattern + '$');
this.__enabledTextRegExp = _enabledCharPattern && new RegExp('^' + _enabledCharPattern + '*$');
}
/** @private */
_addIEListeners(node) {
/* istanbul ignore if */
if (navigator.userAgent.match(/Trident/)) {
// IE11 dispatches `input` event in following cases:
// - focus or blur, when placeholder attribute is set
// - placeholder attribute value changed
// https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/101220/
this._shouldPreventInput = () => {
this.__preventInput = true;
requestAnimationFrame(() => {
this.__preventInput = false;
});
};
node.addEventListener('focusin', this._shouldPreventInput);
node.addEventListener('focusout', this._shouldPreventInput);
this._createPropertyObserver('placeholder', this._shouldPreventInput);
}
}
/** @private */
_removeIEListeners(node) {
/* istanbul ignore if */
if (navigator.userAgent.match(/Trident/)) {
node.removeEventListener('focusin', this._shouldPreventInput);
node.removeEventListener('focusout', this._shouldPreventInput);
}
}
/** @private */
_getActiveErrorId(invalid, errorMessage, errorId, helperText, helperTextId, hasSlottedHelper) {
const ids = [];
if (helperText || hasSlottedHelper) {
ids.push(helperTextId);
}
if (errorMessage && invalid) {
ids.push(errorId);
}
this._setOrToggleAttribute('aria-describedby', ids.join(' '), this.focusElement);
}
/** @private */
_getActiveLabelId(label, _labelId, _inputId) {
let ids = _inputId;
if (label) {
ids = `${_labelId} ${_inputId}`;
}
this.focusElement.setAttribute('aria-labelledby', ids);
}
/** @private */
_getErrorMessageAriaHidden(invalid, errorMessage, errorId) {
return (!(errorMessage && invalid ? errorId : undefined)).toString();
}
/** @private */
_dispatchIronResizeEventIfNeeded(sizePropertyName, value) {
const previousSizePropertyName = '__previous' + sizePropertyName;
if (this[previousSizePropertyName] !== undefined
&& this[previousSizePropertyName] !== value) {
this.dispatchEvent(
new CustomEvent('iron-resize', {bubbles: true, composed: true})
);
}
this[previousSizePropertyName] = value;
}