forked from syncfusion/ej2-javascript-ui-controls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumerictextbox.ts
1669 lines (1575 loc) · 68.3 KB
/
numerictextbox.ts
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
import { Component, EventHandler, Property, Event, Browser, L10n, EmitType, getUniqueID } from '@syncfusion/ej2-base';
import { NotifyPropertyChanges, INotifyPropertyChanged, BaseEventArgs } from '@syncfusion/ej2-base';
import { attributes, addClass, removeClass, detach, closest } from '@syncfusion/ej2-base';
import { isNullOrUndefined, getValue, formatUnit, setValue, merge } from '@syncfusion/ej2-base';
import { Internationalization, NumberFormatOptions, getNumericObject } from '@syncfusion/ej2-base';
import { NumericTextBoxModel } from './numerictextbox-model';
import { Input, InputObject, FloatLabelType } from '../input/input';
const ROOT: string = 'e-control-wrapper e-numeric';
const SPINICON: string = 'e-input-group-icon';
const SPINUP: string = 'e-spin-up';
const SPINDOWN: string = 'e-spin-down';
const ERROR: string = 'e-error';
const INCREMENT: string = 'increment';
const DECREMENT: string = 'decrement';
const INTREGEXP: RegExp = new RegExp('^(-)?(\\d*)$');
const DECIMALSEPARATOR: string = '.';
const COMPONENT: string = 'e-numerictextbox';
const CONTROL: string = 'e-control';
const NUMERIC_FOCUS: string = 'e-input-focus';
const HIDDENELEMENT: string = 'e-numeric-hidden';
const wrapperAttributes: string[] = ['title', 'style', 'class'];
let selectionTimeOut: number = 0;
/**
* Represents the NumericTextBox component that allows the user to enter only numeric values.
* ```html
* <input type='text' id="numeric"/>
* ```
* ```typescript
* <script>
* var numericObj = new NumericTextBox({ value: 10 });
* numericObj.appendTo("#numeric");
* </script>
* ```
*/
@NotifyPropertyChanges
export class NumericTextBox extends Component<HTMLInputElement> implements INotifyPropertyChanged {
/* Internal variables */
private container: HTMLElement;
private inputWrapper: InputObject;
private cloneElement: HTMLElement;
private hiddenInput: HTMLInputElement;
private spinUp: HTMLElement;
private spinDown: HTMLElement;
private formEle: HTMLElement;
private inputEleValue: number;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private timeOut: any;
private prevValue: number;
private isValidState: boolean;
private isFocused: boolean;
private isPrevFocused: boolean;
private instance: Internationalization;
private cultureInfo: NumberFormatOptions;
private inputStyle: string;
private inputName: string;
private decimalSeparator: string;
private angularTagName: string;
private intRegExp: RegExp;
private l10n: L10n;
private isCalled: boolean;
private prevVal: string;
private nextEle: string;
private cursorPosChanged: boolean;
private changeEventArgs: ChangeEventArgs;
private focusEventArgs: NumericFocusEventArgs;
private blurEventArgs: NumericBlurEventArgs;
private numericOptions: NumericTextBoxModel;
private isInteract: boolean;
private serverDecimalSeparator: string;
private preventChange: boolean = false;
private elementPrevValue: string;
private isDynamicChange: boolean = false;
private inputValue: number;
private clearButton: HTMLElement;
/*NumericTextBox Options */
/**
* Gets or Sets the CSS classes to root element of the NumericTextBox which helps to customize the
* complete UI styles for the NumericTextBox component.
*
* @default null
*/
@Property('')
public cssClass: string;
/**
* Sets the value of the NumericTextBox.
*
* @default null
* @aspType object
* @isGenericType true
*/
@Property(null)
public value: number;
/**
* Specifies a minimum value that is allowed a user can enter.
* For more information on min, refer to
* [min](../../numerictextbox/getting-started/#range-validation).
*
* @default null
* @aspType object
* @isGenericType true
* @deprecated
*/
@Property(-(Number.MAX_VALUE))
public min: number;
/**
* Specifies a maximum value that is allowed a user can enter.
* For more information on max, refer to
* [max](../../numerictextbox/getting-started/#range-validation).
*
* @default null
* @aspType object
* @isGenericType true
* @deprecated
*/
@Property(Number.MAX_VALUE)
public max: number;
/**
* Specifies the incremental or decremental step size for the NumericTextBox.
* For more information on step, refer to
* [step](../../numerictextbox/getting-started/#range-validation).
*
* @default 1
* @isGenericType true
*/
@Property(1)
public step: number;
/**
* Specifies the width of the NumericTextBox.
*
* @default null
*/
@Property(null)
public width: number | string;
/**
* Gets or sets the string shown as a hint/placeholder when the NumericTextBox is empty.
* It acts as a label and floats above the NumericTextBox based on the
* <b><a href="#floatlabeltype" target="_blank">floatLabelType.</a></b>
*
* @default null
*/
@Property(null)
public placeholder: string;
/**
* You can add the additional html attributes such as disabled, value etc., to the element.
* If you configured both property and equivalent html attribute then the component considers the property value.
* {% codeBlock src='numerictextbox/htmlAttributes/index.md' %}{% endcodeBlock %}
*
* @default {}
*/
@Property({})
public htmlAttributes: { [key: string]: string };
/**
* Specifies whether the up and down spin buttons should be displayed in NumericTextBox.
*
* @default true
*/
@Property(true)
public showSpinButton: boolean;
/**
* Sets a value that enables or disables the readonly state on the NumericTextBox. If it is true,
* NumericTextBox will not allow your input.
*
* @default false
*/
@Property(false)
public readonly: boolean;
/**
* Sets a value that enables or disables the NumericTextBox control.
*
* @default true
*/
@Property(true)
public enabled: boolean;
/**
* Specifies whether to show or hide the clear icon.
*
* @default false
*/
@Property(false)
public showClearButton: boolean;
/**
* Enable or disable persisting NumericTextBox state between page reloads. If enabled, the `value` state will be persisted.
*
* @default false
*/
@Property(false)
public enablePersistence: boolean;
/**
* Specifies the number format that indicates the display format for the value of the NumericTextBox.
* For more information on formats, refer to
* [formats](../../numerictextbox/formats/#standard-formats).
*
* @default 'n2'
*/
@Property('n2')
public format: string;
/**
* Specifies the number precision applied to the textbox value when the NumericTextBox is focused.
* For more information on decimals, refer to
* [decimals](../../numerictextbox/formats/#precision-of-numbers).
*
* @default null
*/
@Property(null)
public decimals: number;
/**
* Specifies the currency code to use in currency formatting.
* Possible values are the ISO 4217 currency codes, such as 'USD' for the US dollar,'EUR' for the euro.
*
* @default null
*/
@Property(null)
public currency: string;
/**
* Specifies the currency code to use in currency formatting.
* Possible values are the ISO 4217 currency codes, such as 'USD' for the US dollar,'EUR' for the euro.
*
* @default null
* @private
*/
@Property(null)
private currencyCode: string;
/**
* Specifies a value that indicates whether the NumericTextBox control allows the value for the specified range.
* If it is true, the input value will be restricted between the min and max range.
* The typed value gets modified to fit the range on focused out state.
* Else, it allows any value even out of range value,
* At that time of wrong value entered, the error class will be added to the component to highlight the error.
* {% codeBlock src='numerictextbox/strictMode/index.md' %}{% endcodeBlock %}
*
* @default true
*/
@Property(true)
public strictMode: boolean;
/**
* Specifies whether the decimals length should be restricted during typing.
*
* @default false
*/
@Property(false)
public validateDecimalOnType: boolean;
/**
* The <b><a href="#placeholder" target="_blank">placeholder</a></b> acts as a label
* and floats above the NumericTextBox based on the below values.
* Possible values are:
* * `Never` - Never floats the label in the NumericTextBox when the placeholder is available.
* * `Always` - The floating label always floats above the NumericTextBox.
* * `Auto` - The floating label floats above the NumericTextBox after focusing it or when enters the value in it.
*
* @default Never
*/
@Property('Never')
public floatLabelType: FloatLabelType;
/**
* Triggers when the NumericTextBox component is created.
*
* @event created
*/
@Event()
public created: EmitType<Object>;
/**
* Triggers when the NumericTextBox component is destroyed.
*
* @event destroyed
*/
@Event()
public destroyed: EmitType<Object>;
/**
* Triggers when the value of the NumericTextBox changes.
* The change event of the NumericTextBox component will be triggered in the following scenarios:
* * Changing the previous value using keyboard interaction and then focusing out of the component.
* * Focusing on the component and scrolling within the input.
* * Changing the value using the spin buttons.
* * Programmatically changing the value using the value property.
*
* @event change
*/
@Event()
public change: EmitType<ChangeEventArgs>;
/**
* Triggers when the NumericTextBox got focus in.
*
* @event focus
*/
@Event()
public focus: EmitType<NumericFocusEventArgs>;
/**
* Triggers when the NumericTextBox got focus out.
*
* @event blur
*/
@Event()
public blur: EmitType<NumericBlurEventArgs>;
/**
*
* @param {NumericTextBoxModel} options - Specifies the NumericTextBox model.
* @param {string | HTMLInputElement} element - Specifies the element to render as component.
* @private
*/
public constructor(options?: NumericTextBoxModel, element?: string | HTMLInputElement) {
super(options, <HTMLInputElement | string>element);
this.numericOptions = options;
}
protected preRender(): void {
this.isPrevFocused = false;
this.decimalSeparator = '.';
// eslint-disable-next-line no-useless-escape
this.intRegExp = new RegExp('/^(-)?(\d*)$/');
this.isCalled = false;
const ejInstance: Object = getValue('ej2_instances', this.element);
this.cloneElement = <HTMLElement>this.element.cloneNode(true);
removeClass([this.cloneElement], [CONTROL, COMPONENT, 'e-lib']);
this.angularTagName = null;
this.formEle = <HTMLFormElement>closest(this.element, 'form');
if (this.element.tagName === 'EJS-NUMERICTEXTBOX') {
this.angularTagName = this.element.tagName;
const input: HTMLElement = this.createElement('input');
let index: number = 0;
for (index; index < this.element.attributes.length; index++) {
const attributeName: string = this.element.attributes[index as number].nodeName;
if (attributeName !== 'id' && attributeName !== 'class') {
input.setAttribute(this.element.attributes[index as number].nodeName,
this.element.attributes[index as number].nodeValue);
input.innerHTML = this.element.innerHTML;
}
else if (attributeName === 'class') {
input.setAttribute(attributeName, this.element.className.split(' ').filter((item: string) => item.indexOf('ng-') !== 0).join(' '));
}
}
if (this.element.hasAttribute('name')) {
this.element.removeAttribute('name');
}
this.element.classList.remove('e-control', 'e-numerictextbox');
this.element.appendChild(input);
this.element = <HTMLInputElement>input;
setValue('ej2_instances', ejInstance, this.element);
}
attributes(this.element, { 'role': 'spinbutton', 'tabindex': '0', 'autocomplete': 'off'});
const localeText: object = {
incrementTitle: 'Increment value', decrementTitle: 'Decrement value', placeholder: this.placeholder
};
this.l10n = new L10n('numerictextbox', localeText, this.locale);
if (this.l10n.getConstant('placeholder') !== '') {
this.setProperties({ placeholder: this.placeholder || this.l10n.getConstant('placeholder') }, true);
}
if (!this.element.hasAttribute('id')) {
this.element.setAttribute('id', getUniqueID('numerictextbox'));
}
this.isValidState = true;
this.inputStyle = null;
this.inputName = null;
this.cultureInfo = {};
this.initCultureInfo();
this.initCultureFunc();
this.prevValue = this.value;
this.updateHTMLAttrToElement();
this.checkAttributes(false);
if (this.formEle) {
this.inputEleValue = this.value;
}
this.validateMinMax();
this.validateStep();
if (this.placeholder === null) {
this.updatePlaceholder();
}
}
/**
* To Initialize the control rendering
*
* @returns {void}
* @private
*/
public render(): void {
if (this.element.tagName.toLowerCase() === 'input') {
this.createWrapper();
if (this.showSpinButton) {
this.spinBtnCreation();
}
this.setElementWidth(this.width);
if (!this.container.classList.contains('e-input-group')) {
this.container.classList.add('e-input-group');
}
this.changeValue(this.value === null || isNaN(this.value) ?
null : this.strictMode ? this.trimValue(this.value) : this.value);
this.wireEvents();
if (this.value !== null && !isNaN(this.value)) {
if (this.decimals) {
this.setProperties({ value: this.roundNumber(this.value, this.decimals) }, true);
}
}
if (this.element.getAttribute('value') || this.value) {
this.element.setAttribute('value', this.element.value);
this.hiddenInput.setAttribute('value', this.hiddenInput.value);
}
this.elementPrevValue = this.element.value;
if (this.element.hasAttribute('data-val')) {
this.element.setAttribute('data-val', 'false');
}
if (!this.element.hasAttribute('aria-labelledby') && !this.element.hasAttribute('placeholder') && !this.element.hasAttribute('aria-label')) {
this.element.setAttribute('aria-label', 'numerictextbox');
}
if (!isNullOrUndefined(closest(this.element, 'fieldset') as HTMLFieldSetElement) && (closest(this.element, 'fieldset') as HTMLFieldSetElement).disabled) {
this.enabled = false;
}
this.renderComplete();
}
}
private checkAttributes(isDynamic: boolean): void {
const attributes: string[] = isDynamic ? isNullOrUndefined(this.htmlAttributes) ? [] : Object.keys(this.htmlAttributes) :
['value', 'min', 'max', 'step', 'disabled', 'readonly', 'style', 'name', 'placeholder'];
for (const prop of attributes) {
if (!isNullOrUndefined(this.element.getAttribute(prop))) {
switch (prop) {
case 'disabled':
if (( isNullOrUndefined(this.numericOptions) || (this.numericOptions['enabled'] === undefined)) || isDynamic) {
const enabled: boolean = this.element.getAttribute(prop) === 'disabled' || this.element.getAttribute(prop) === ''
|| this.element.getAttribute(prop) === 'true' ? false : true;
this.setProperties({ enabled: enabled }, !isDynamic);
}
break;
case 'readonly':
if (( isNullOrUndefined(this.numericOptions) || (this.numericOptions['readonly'] === undefined)) || isDynamic) {
const readonly: boolean = this.element.getAttribute(prop) === 'readonly' || this.element.getAttribute(prop) === ''
|| this.element.getAttribute(prop) === 'true' ? true : false;
this.setProperties({ readonly: readonly }, !isDynamic);
}
break;
case 'placeholder':
if (( isNullOrUndefined(this.numericOptions) || (this.numericOptions['placeholder'] === undefined)) || isDynamic) {
this.setProperties({placeholder: this.element.placeholder}, !isDynamic);
}
break;
case 'value':
if (( isNullOrUndefined(this.numericOptions) || (this.numericOptions['value'] === undefined)) || isDynamic){
const setNumber: number = this.instance.getNumberParser({ format: 'n' })(this.element.getAttribute(prop));
this.setProperties(setValue(prop, setNumber, {}), !isDynamic);
}
break;
case 'min':
if (( isNullOrUndefined(this.numericOptions) || (this.numericOptions['min'] === undefined)) || isDynamic) {
const minValue: number = this.instance.getNumberParser({ format: 'n' })(this.element.getAttribute(prop));
if (minValue !== null && !isNaN(minValue)) {
this.setProperties(setValue(prop, minValue, {}), !isDynamic);
}
}
break;
case 'max':
if (( isNullOrUndefined(this.numericOptions) || (this.numericOptions['max'] === undefined)) || isDynamic) {
const maxValue: number = this.instance.getNumberParser({ format: 'n' })(this.element.getAttribute(prop));
if (maxValue !== null && !isNaN(maxValue)) {
this.setProperties(setValue(prop, maxValue, {}), !isDynamic);
}
}
break;
case 'step':
if (( isNullOrUndefined(this.numericOptions) || (this.numericOptions['step'] === undefined)) || isDynamic) {
const stepValue: number = this.instance.getNumberParser({ format: 'n' })(this.element.getAttribute(prop));
if (stepValue !== null && !isNaN(stepValue)) {
this.setProperties(setValue(prop, stepValue, {}), !isDynamic);
}
}
break;
case 'style':
this.inputStyle = this.element.getAttribute(prop);
break;
case 'name':
this.inputName = this.element.getAttribute(prop);
break;
default: {
const value: number = this.instance.getNumberParser({ format: 'n' })(this.element.getAttribute(prop));
if ((value !== null && !isNaN(value)) || (prop === 'value')) {
this.setProperties(setValue(prop, value, {}), true);
}
}
break;
}
}
}
}
private updatePlaceholder(): void {
this.setProperties({ placeholder: this.l10n.getConstant('placeholder') }, true);
}
private initCultureFunc(): void {
this.instance = new Internationalization(this.locale);
}
private initCultureInfo(): void {
this.cultureInfo.format = this.format;
if (getValue('currency', this) !== null) {
setValue('currency', this.currency, this.cultureInfo);
this.setProperties({ currencyCode: this.currency }, true);
}
}
/* Wrapper creation */
private createWrapper(): void {
let updatedCssClassValue: string = this.cssClass;
if (!isNullOrUndefined(this.cssClass) && this.cssClass !== '') {
updatedCssClassValue = this.getNumericValidClassList(this.cssClass);
}
const inputObj: InputObject = Input.createInput(
{
element: this.element,
floatLabelType: this.floatLabelType,
properties: {
readonly: this.readonly,
placeholder: this.placeholder,
cssClass: updatedCssClassValue,
enableRtl: this.enableRtl,
showClearButton: this.showClearButton,
enabled: this.enabled
}
},
this.createElement
);
this.inputWrapper = inputObj;
this.container = inputObj.container;
this.container.setAttribute('class', ROOT + ' ' + this.container.getAttribute('class'));
this.updateHTMLAttrToWrapper();
if (this.readonly) {
attributes(this.element, { 'aria-readonly': 'true' });
}
this.hiddenInput = <HTMLInputElement>(this.createElement('input', { attrs: { type: 'text',
'validateHidden': 'true', 'aria-label': 'hidden', 'class': HIDDENELEMENT } }));
this.inputName = this.inputName !== null ? this.inputName : this.element.id;
this.element.removeAttribute('name');
if (this.isAngular && this.angularTagName === 'EJS-NUMERICTEXTBOX' && this.cloneElement.id.length > 0) {
attributes(this.hiddenInput, { 'name': this.cloneElement.id });
} else {
attributes(this.hiddenInput, { 'name': this.inputName });
}
this.container.insertBefore(this.hiddenInput, this.container.childNodes[1]);
this.updateDataAttribute(false);
if (this.inputStyle !== null) {
attributes(this.container, { 'style': this.inputStyle });
}
}
private updateDataAttribute(isDynamic: boolean) : void {
let attr: { [key: string]: string } = {};
if (!isDynamic) {
for (let a: number = 0; a < this.element.attributes.length; a++) {
attr[this.element.attributes[a as number].name] = this.element.getAttribute(this.element.attributes[a as number].name);
}
} else {
attr = this.htmlAttributes;
}
for (const key of Object.keys(attr)) {
if (key.indexOf('data') === 0 ) {
this.hiddenInput.setAttribute(key, attr[`${key}`]);
}
}
}
private updateHTMLAttrToElement(): void {
if ( !isNullOrUndefined(this.htmlAttributes)) {
for (const pro of Object.keys(this.htmlAttributes)) {
if (wrapperAttributes.indexOf(pro) < 0 ) {
this.element.setAttribute(pro, this.htmlAttributes[`${pro}`]);
}
}
}
}
private updateCssClass(newClass : string, oldClass : string) : void {
Input.setCssClass(this.getNumericValidClassList(newClass), [this.container], this.getNumericValidClassList(oldClass));
}
private getNumericValidClassList(numericClassName: string): string {
let result: string = numericClassName;
if (!isNullOrUndefined(numericClassName) && numericClassName !== '') {
result = (numericClassName.replace(/\s+/g, ' ')).trim();
}
return result;
}
private updateHTMLAttrToWrapper(): void {
if ( !isNullOrUndefined(this.htmlAttributes)) {
for (const pro of Object.keys(this.htmlAttributes)) {
if (wrapperAttributes.indexOf(pro) > -1 ) {
if (pro === 'class') {
const updatedClassValue : string = this.getNumericValidClassList(this.htmlAttributes[`${pro}`]);
if (updatedClassValue !== '') {
addClass([this.container], updatedClassValue.split(' '));
}
} else if (pro === 'style') {
let numericStyle: string = this.container.getAttribute(pro);
numericStyle = !isNullOrUndefined(numericStyle) ? (numericStyle + this.htmlAttributes[`${pro}`]) :
this.htmlAttributes[`${pro}`];
this.container.setAttribute(pro, numericStyle);
} else {
this.container.setAttribute(pro, this.htmlAttributes[`${pro}`]);
}
}
}
}
}
private setElementWidth(width: number | string): void {
if (!isNullOrUndefined(width)) {
if (typeof width === 'number') {
this.container.style.width = formatUnit(width);
} else if (typeof width === 'string') {
this.container.style.width = (width.match(/px|%|em/)) ? <string>(width) : <string>(formatUnit(width));
}
}
}
/* Spinner creation */
private spinBtnCreation(): void {
this.spinDown = Input.appendSpan(SPINICON + ' ' + SPINDOWN, this.container, this.createElement);
attributes(this.spinDown, {
'title': this.l10n.getConstant('decrementTitle')
});
this.spinUp = Input.appendSpan(SPINICON + ' ' + SPINUP, this.container, this.createElement);
attributes(this.spinUp, {
'title': this.l10n.getConstant('incrementTitle')
});
this.wireSpinBtnEvents();
}
private validateMinMax(): void {
if (!(typeof (this.min) === 'number' && !isNaN(this.min))) {
this.setProperties({ min: -(Number.MAX_VALUE) }, true);
}
if (!(typeof (this.max) === 'number' && !isNaN(this.max))) {
this.setProperties({ max: Number.MAX_VALUE }, true);
}
if (this.decimals !== null) {
if (this.min !== -(Number.MAX_VALUE)) {
this.setProperties(
{ min: this.instance.getNumberParser({ format: 'n' })(this.formattedValue(this.decimals, this.min)) }, true);
}
if (this.max !== (Number.MAX_VALUE)) {
this.setProperties(
{ max: this.instance.getNumberParser({ format: 'n' })(this.formattedValue(this.decimals, this.max)) }, true);
}
}
this.setProperties({ min: this.min > this.max ? this.max : this.min }, true);
if (this.min !== -(Number.MAX_VALUE)){
attributes(this.element, { 'aria-valuemin': this.min.toString()});
}
if (this.max !== (Number.MAX_VALUE)) {
attributes(this.element, { 'aria-valuemax': this.max.toString() });
}
}
private formattedValue(decimals: number, value: number): string {
return this.instance.getNumberFormat({
maximumFractionDigits: decimals,
minimumFractionDigits: decimals, useGrouping: false
})(value);
}
private validateStep(): void {
if (this.decimals !== null) {
this.setProperties({ step: this.instance.getNumberParser({ format: 'n' })(this.formattedValue(this.decimals, this.step)) }, true);
}
}
private action(operation: string, event: Event): void {
this.isInteract = true;
const value: number = this.isFocused ? this.instance.getNumberParser({ format: 'n' })(this.element.value) : this.value;
this.changeValue(this.performAction(value, this.step, operation));
this.raiseChangeEvent(event);
}
private checkErrorClass(): void {
if (this.isValidState) {
removeClass([this.container], ERROR);
} else {
addClass([this.container], ERROR);
}
attributes(this.element, { 'aria-invalid': this.isValidState ? 'false' : 'true' });
}
private bindClearEvent(): void {
if (this.showClearButton) {
EventHandler.add(this.inputWrapper.clearButton, 'mousedown touchstart', this.resetHandler, this);
}
}
protected resetHandler(e?: MouseEvent): void {
e.preventDefault();
if (!(this.inputWrapper.clearButton.classList.contains('e-clear-icon-hide')) || this.inputWrapper.container.classList.contains('e-static-clear')) {
this.clear(e);
}
this.isInteract = true;
this.raiseChangeEvent(e);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
private clear(event: MouseEvent): void {
this.setProperties({ value: null }, true);
this.setElementValue('');
this.hiddenInput.value = '';
const formElement: Element = closest(this.element, 'form');
if (formElement) {
const element: Element = this.element.nextElementSibling;
const keyupEvent: KeyboardEvent = document.createEvent('KeyboardEvent');
keyupEvent.initEvent('keyup', false, true);
element.dispatchEvent(keyupEvent);
}
}
protected resetFormHandler(): void {
if (this.element.tagName === 'EJS-NUMERICTEXTBOX') {
this.updateValue(null);
} else {
this.updateValue(this.inputEleValue);
}
}
private setSpinButton(): void {
if (!isNullOrUndefined(this.spinDown)) {
attributes(this.spinDown, {
'title': this.l10n.getConstant('decrementTitle'),
'aria-label': this.l10n.getConstant('decrementTitle')
});
}
if (!isNullOrUndefined(this.spinUp)) {
attributes(this.spinUp, {
'title': this.l10n.getConstant('incrementTitle'),
'aria-label': this.l10n.getConstant('incrementTitle')
});
}
}
private wireEvents(): void {
EventHandler.add(this.element, 'focus', this.focusHandler, this);
EventHandler.add(this.element, 'blur', this.focusOutHandler, this);
EventHandler.add(this.element, 'keydown', this.keyDownHandler, this);
EventHandler.add(this.element, 'keyup', this.keyUpHandler, this);
EventHandler.add(this.element, 'input', this.inputHandler, this);
EventHandler.add(this.element, 'keypress', this.keyPressHandler, this);
EventHandler.add(this.element, 'change', this.changeHandler, this);
EventHandler.add(this.element, 'paste', this.pasteHandler, this);
if (this.enabled) {
this.bindClearEvent();
if (this.formEle) {
EventHandler.add(this.formEle, 'reset', this.resetFormHandler, this);
}
}
}
private wireSpinBtnEvents(): void {
/* bind spin button events */
EventHandler.add(this.spinUp, Browser.touchStartEvent, this.mouseDownOnSpinner, this);
EventHandler.add(this.spinDown, Browser.touchStartEvent, this.mouseDownOnSpinner, this);
EventHandler.add(this.spinUp, Browser.touchEndEvent, this.mouseUpOnSpinner, this);
EventHandler.add(this.spinDown, Browser.touchEndEvent, this.mouseUpOnSpinner, this);
EventHandler.add(this.spinUp, Browser.touchMoveEvent, this.touchMoveOnSpinner, this);
EventHandler.add(this.spinDown, Browser.touchMoveEvent, this.touchMoveOnSpinner, this);
}
private unwireEvents(): void {
EventHandler.remove(this.element, 'focus', this.focusHandler);
EventHandler.remove(this.element, 'blur', this.focusOutHandler);
EventHandler.remove(this.element, 'keyup', this.keyUpHandler);
EventHandler.remove(this.element, 'input', this.inputHandler);
EventHandler.remove(this.element, 'keydown', this.keyDownHandler);
EventHandler.remove(this.element, 'keypress', this.keyPressHandler);
EventHandler.remove(this.element, 'change', this.changeHandler);
EventHandler.remove(this.element, 'paste', this.pasteHandler);
if (this.formEle) {
EventHandler.remove(this.formEle, 'reset', this.resetFormHandler);
}
}
private unwireSpinBtnEvents(): void {
/* unbind spin button events */
EventHandler.remove(this.spinUp, Browser.touchStartEvent, this.mouseDownOnSpinner);
EventHandler.remove(this.spinDown, Browser.touchStartEvent, this.mouseDownOnSpinner);
EventHandler.remove(this.spinUp, Browser.touchEndEvent, this.mouseUpOnSpinner);
EventHandler.remove(this.spinDown, Browser.touchEndEvent, this.mouseUpOnSpinner);
EventHandler.remove(this.spinUp, Browser.touchMoveEvent, this.touchMoveOnSpinner);
EventHandler.remove(this.spinDown, Browser.touchMoveEvent, this.touchMoveOnSpinner);
}
private changeHandler(event: Event): void {
event.stopPropagation();
if (!this.element.value.length) {
this.setProperties({ value: null }, true);
}
const parsedInput: number = this.instance.getNumberParser({ format: 'n' })(this.element.value);
this.updateValue(parsedInput, event);
}
private raiseChangeEvent(event?: Event): void {
this.inputValue = (isNullOrUndefined(this.inputValue) || isNaN(this.inputValue)) ? null : this.inputValue;
if (this.prevValue !== this.value || this.prevValue !== this.inputValue) {
const eventArgs: Object = {};
this.changeEventArgs = { value: this.value, previousValue: this.prevValue, isInteracted: this.isInteract,
isInteraction: this.isInteract, event: event };
if (event) {
this.changeEventArgs.event = event;
}
if (this.changeEventArgs.event === undefined) {
this.changeEventArgs.isInteracted = false;
this.changeEventArgs.isInteraction = false;
}
merge(eventArgs, this.changeEventArgs);
this.prevValue = this.value;
this.isInteract = false;
this.elementPrevValue = this.element.value;
this.preventChange = false;
this.trigger('change', eventArgs);
}
}
private pasteHandler(): void {
if (!this.enabled || this.readonly) {
return;
}
const beforeUpdate: string = this.element.value;
setTimeout(() => {
if (!this.numericRegex().test(this.element.value)) {
this.setElementValue(beforeUpdate);
}
});
}
private preventHandler(): void {
const iOS: boolean = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);
setTimeout(() => {
if (this.element.selectionStart > 0) {
const currentPos: number = this.element.selectionStart;
const prevPos: number = this.element.selectionStart - 1;
const start: number = 0;
const valArray: string[] = this.element.value.split('');
const numericObject: Object = getNumericObject(this.locale);
const decimalSeparator: string = getValue('decimal', numericObject);
const ignoreKeyCode: number = decimalSeparator.charCodeAt(0);
if (this.element.value[prevPos as number] === ' ' && this.element.selectionStart > 0 && !iOS) {
if (isNullOrUndefined(this.prevVal)) {
this.element.value = this.element.value.trim();
} else if (prevPos !== 0) {
this.element.value = this.prevVal;
} else if (prevPos === 0) {
this.element.value = this.element.value.trim();
}
this.element.setSelectionRange(prevPos, prevPos);
} else if (isNaN(parseFloat(this.element.value[this.element.selectionStart - 1])) &&
this.element.value[this.element.selectionStart - 1].charCodeAt(0) !== 45) {
if ((valArray.indexOf(this.element.value[this.element.selectionStart - 1]) !==
valArray.lastIndexOf(this.element.value[this.element.selectionStart - 1]) &&
this.element.value[this.element.selectionStart - 1].charCodeAt(0) === ignoreKeyCode) ||
this.element.value[this.element.selectionStart - 1].charCodeAt(0) !== ignoreKeyCode) {
this.element.value = this.element.value.substring(0, prevPos) +
this.element.value.substring(currentPos, this.element.value.length);
this.element.setSelectionRange(prevPos, prevPos);
if (isNaN(parseFloat(this.element.value[this.element.selectionStart - 1])) && this.element.selectionStart > 0
&& this.element.value.length) {
this.preventHandler();
}
}
} else if (isNaN(parseFloat(this.element.value[this.element.selectionStart - 2])) && this.element.selectionStart > 1 &&
this.element.value[this.element.selectionStart - 2].charCodeAt(0) !== 45) {
if ((valArray.indexOf(this.element.value[this.element.selectionStart - 2]) !==
valArray.lastIndexOf(this.element.value[this.element.selectionStart - 2]) &&
this.element.value[this.element.selectionStart - 2].charCodeAt(0) === ignoreKeyCode) ||
this.element.value[this.element.selectionStart - 2].charCodeAt(0) !== ignoreKeyCode) {
this.element.setSelectionRange(prevPos, prevPos);
this.nextEle = this.element.value[this.element.selectionStart];
this.cursorPosChanged = true;
this.preventHandler();
}
}
if (this.cursorPosChanged === true && this.element.value[this.element.selectionStart] === this.nextEle &&
isNaN(parseFloat(this.element.value[this.element.selectionStart - 1]))) {
this.element.setSelectionRange(this.element.selectionStart + 1, this.element.selectionStart + 1);
this.cursorPosChanged = false;
this.nextEle = null;
}
if (this.element.value.trim() === '') {
this.element.setSelectionRange(start, start);
}
if (this.element.selectionStart > 0) {
if ((this.element.value[this.element.selectionStart - 1].charCodeAt(0) === 45) && this.element.selectionStart > 1) {
if (!isNullOrUndefined(this.prevVal)) {
this.element.value = this.prevVal;
}
this.element.setSelectionRange(this.element.selectionStart, this.element.selectionStart);
}
if (this.element.value[this.element.selectionStart - 1] === decimalSeparator &&
this.decimals === 0 &&
this.validateDecimalOnType) {
this.element.value = this.element.value.substring(0, prevPos) +
this.element.value.substring(currentPos, this.element.value.length);
}
}
this.prevVal = this.element.value;
}
});
}
private keyUpHandler(): void {
if (!this.enabled || this.readonly) {
return;
}
const iOS: boolean = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);
if (!iOS && Browser.isDevice) {
this.preventHandler();
}
let parseValue: number = this.instance.getNumberParser({ format: 'n' })(this.element.value);
parseValue = parseValue === null || isNaN(parseValue) ? null : parseValue;
this.hiddenInput.value = parseValue || parseValue === 0 ? parseValue.toString() : null;
const formElement: Element = closest(this.element, 'form');
if (formElement) {
const element: Element = this.element.nextElementSibling;
const keyupEvent: KeyboardEvent = document.createEvent('KeyboardEvent');
keyupEvent.initEvent('keyup', false, true);
element.dispatchEvent(keyupEvent);
}
}
private inputHandler(event: KeyboardEvent): void {
const numerictextboxObj: any = null || this;
if (!this.enabled || this.readonly) {
return;
}
const iOS: boolean = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);
const fireFox: boolean = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
if ((fireFox || iOS) && Browser.isDevice) {
this.preventHandler();
}
/* istanbul ignore next */
if ( this.isAngular
&& this.element.value !== getValue('decimal', getNumericObject(this.locale))
&& this.element.value !== getValue('minusSign', getNumericObject(this.locale)) ) {
let parsedValue: number = this.instance.getNumberParser({ format: 'n' })(this.element.value);
parsedValue = isNaN(parsedValue) ? null : parsedValue;
numerictextboxObj.localChange({value: parsedValue});
this.preventChange = true;
}
if (this.isVue) {
let current: number = this.instance.getNumberParser({ format: 'n' })(this.element.value);
const previous: number = this.instance.getNumberParser({ format: 'n' })(this.elementPrevValue);
//EJ2-54963-if type "." or ".0" or "-.0" it converts to "0" automatically when binding v-model
const nonZeroRegex: RegExp = new RegExp('[^0-9]+$');
if (nonZeroRegex.test(this.element.value) ||
((this.elementPrevValue.indexOf('.') !== -1 || this.elementPrevValue.indexOf('-') !== -1) &&
this.element.value[this.element.value.length - 1] === '0')) {
current = this.value;
}
const eventArgs: object = {
event: event,
value: (current === null || isNaN(current) ? null : current),
previousValue: (previous === null || isNaN(previous) ? null : previous)
};
this.preventChange = true;
this.elementPrevValue = this.element.value;
this.trigger('input', eventArgs);
}
}
private keyDownHandler(event: KeyboardEvent): void {
if (!this.readonly) {
switch (event.keyCode) {
case 38:
event.preventDefault();
this.action(INCREMENT, event);
break;
case 40:
event.preventDefault();
this.action(DECREMENT, event);
break;
default: break;
}
}
}