• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

atinc / ngx-tethys / c34d266c-8f9b-4fba-b7d6-82a51fa6faf1

25 Oct 2023 10:21AM UTC coverage: 90.218% (-0.004%) from 90.222%
c34d266c-8f9b-4fba-b7d6-82a51fa6faf1

push

circleci

web-flow
fix(input-number): fix input non-number show error #INFR-10053 (#2862)

5169 of 6389 branches covered (0.0%)

Branch coverage included in aggregate %.

1 of 1 new or added line in 1 file covered. (100.0%)

13046 of 13801 relevant lines covered (94.53%)

972.46 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.28
/src/input-number/input-number.component.ts
1
import { InputBoolean, InputNumber, TabIndexDisabledControlValueAccessorMixin, useHostFocusControl } from 'ngx-tethys/core';
2
import { ThyMaxDirective, ThyMinDirective } from 'ngx-tethys/form';
3
import { ThyIconComponent } from 'ngx-tethys/icon';
4
import { ThyInputDirective } from 'ngx-tethys/input';
5
import { ThyAutofocusDirective } from 'ngx-tethys/shared';
6
import { DOWN_ARROW, ENTER, isFloat, isNumber, isUndefinedOrNull, UP_ARROW } from 'ngx-tethys/util';
7

8
import { FocusOrigin } from '@angular/cdk/a11y';
9
import {
10
    ChangeDetectorRef,
11
    Component,
12
    ElementRef,
13
    EventEmitter,
1✔
14
    forwardRef,
1✔
15
    Input,
1✔
16
    OnChanges,
2✔
17
    OnDestroy,
18
    OnInit,
19
    Output,
20
    SimpleChanges,
21
    ViewChild
22
} from '@angular/core';
1✔
23
import { ControlValueAccessor, FormsModule, NG_VALUE_ACCESSOR } from '@angular/forms';
24

108✔
25
type InputSize = 'xs' | 'sm' | 'md' | 'lg' | '';
108✔
26

4✔
27
enum Type {
4✔
28
    up,
29
    down
30
}
31

935✔
32
/**
33
 * 数字输入框
34
 * @name thy-input-number
108✔
35
 * @order 10
108✔
36
 */
4✔
37
@Component({
4✔
38
    selector: 'thy-input-number',
39
    templateUrl: './input-number.component.html',
40
    providers: [
41
        {
937✔
42
            provide: NG_VALUE_ACCESSOR,
43
            useExisting: forwardRef(() => ThyInputNumberComponent),
44
            multi: true
104✔
45
        }
104✔
46
    ],
104✔
47
    standalone: true,
104✔
48
    imports: [ThyIconComponent, ThyInputDirective, ThyAutofocusDirective, FormsModule, ThyMinDirective, ThyMaxDirective],
104✔
49
    host: {
104✔
50
        class: 'thy-input-number',
104✔
51
        '[attr.tabindex]': 'tabIndex'
104✔
52
    }
104✔
53
})
104✔
54
export class ThyInputNumberComponent
104✔
55
    extends TabIndexDisabledControlValueAccessorMixin
104✔
56
    implements ControlValueAccessor, OnChanges, OnInit, OnDestroy
57
{
58
    @ViewChild('input', { static: true }) inputElement: ElementRef<any>;
104✔
59

60
    private autoStepTimer: any;
61

104✔
62
    private hostFocusControl = useHostFocusControl();
36✔
63

4✔
64
    validValue: number | string;
65

32✔
66
    displayValue: number | string;
25✔
67

22✔
68
    disabledUp = false;
69

70
    disabledDown = false;
71

7✔
72
    activeValue: string = '';
6✔
73

6✔
74
    /**
6✔
75
     * 是否自动聚焦
6✔
76
     * @default false
77
     */
78
    @Input() @InputBoolean() thyAutoFocus: boolean;
79

80
    /**
81
     * 输入框的placeholder
131✔
82
     */
2✔
83
    @Input() thyPlaceholder: string = '';
2✔
84

2✔
85
    /**
86
     * 是否禁用
87
     * @default false
88
     */
245✔
89
    @Input() @InputBoolean() thyDisabled: boolean;
245✔
90

245✔
91
    /**
245✔
92
     * 最大值
93
     * @default Infinity
94
     */
272✔
95
    @Input() set thyMax(value: number) {
166✔
96
        this.innerMax = isNumber(value) ? value : this.innerMax;
97
        if (this.displayValue || this.displayValue === 0) {
106✔
98
            const val = Number(this.displayValue);
105✔
99
            this.disabledUp = val >= this.innerMax;
100
        }
272✔
101
    }
272✔
102

106✔
103
    get thyMax() {
106✔
104
        return this.innerMax;
19✔
105
    }
106

106✔
107
    /**
18✔
108
     * 最小值
109
     * @default -Infinity
110
     */
111
    @Input() set thyMin(value: number) {
112
        this.innerMin = isNumber(value) ? value : this.innerMin;
21✔
113
        if (this.displayValue || this.displayValue === 0) {
18✔
114
            const val = Number(this.displayValue);
115
            this.disabledDown = val <= this.innerMin;
116
        }
3✔
117
    }
3✔
118

119
    get thyMin() {
21✔
120
        return this.innerMin;
21✔
121
    }
21✔
122

14✔
123
    /**
14✔
124
     * 每次改变步数,可以为小数
125
     */
126
    @Input() @InputNumber() thyStep = 1;
127

23✔
128
    /**
23✔
129
     * 输入框大小
15✔
130
     * @type xs | sm | md | lg
15✔
131
     */
132
    @Input() thySize: InputSize;
133

134
    /**
3✔
135
     * 数值精度
1✔
136
     */
1✔
137
    @Input() thyPrecision: number;
138

2✔
139
    /**
1✔
140
     * 数值后缀
1✔
141
     */
142
    @Input() thySuffix: string;
1!
143

1✔
144
    /**
145
     * 焦点失去事件
146
     */
147
    @Output() thyBlur = new EventEmitter<Event>();
25✔
148

19✔
149
    /**
150
     * 焦点激活事件
25✔
151
     */
152
    @Output() thyFocus = new EventEmitter<Event>();
153

12✔
154
    private innerMax: number = Infinity;
12✔
155

12✔
156
    private innerMin: number = -Infinity;
1✔
157

158
    private isFocused: boolean;
11✔
159

160
    constructor(private cdr: ChangeDetectorRef) {
11✔
161
        super();
8✔
162
    }
163

3!
164
    setDisabledState?(isDisabled: boolean): void {
3✔
165
        this.thyDisabled = isDisabled;
166
    }
11✔
167

11✔
168
    ngOnInit() {
11✔
169
        this.hostFocusControl.focusChanged = (origin: FocusOrigin) => {
11✔
170
            if (this.thyDisabled) {
11✔
171
                return;
11!
172
            }
×
173

174
            if (origin) {
11✔
175
                if (!this.isFocused) {
×
176
                    this.inputElement.nativeElement.focus();
177
                }
178
            } else {
179
                if (this.isFocused) {
8✔
180
                    this.displayValue = this.formatterValue(this.validValue);
8✔
181
                    this.onTouchedFn();
8✔
182
                    this.thyBlur.emit();
8✔
183
                    this.isFocused = false;
184
                }
185
            }
3✔
186
        };
3✔
187
    }
3✔
188

3✔
189
    ngOnChanges(changes: SimpleChanges) {
190
        if (changes.thySuffix && !changes.thySuffix.isFirstChange()) {
191
            const validValue = this.getCurrentValidValue(this.validValue);
22✔
192
            this.updateValidValue(validValue);
18✔
193
            this.displayValue = this.formatterValue(validValue);
194
        }
4✔
195
    }
4✔
196

4!
197
    writeValue(value: number | string): void {
×
198
        const _value = this.getCurrentValidValue(value);
199
        this.updateValidValue(_value);
4✔
200
        this.displayValue = this.formatterValue(_value);
201
        this.cdr.markForCheck();
202
    }
11✔
203

11✔
204
    updateValidValue(value: number | string): void {
205
        if (this.isNotValid(value)) {
206
            this.validValue = '';
8✔
207
        } else if (this.validValue !== value) {
208
            this.validValue = value;
8✔
209
        }
2✔
210
        this.disabledUp = this.disabledDown = false;
211
        if (value || value === 0) {
6✔
212
            const val = Number(value);
213
            if (val >= this.thyMax) {
6✔
214
                this.disabledUp = true;
2✔
215
            }
216
            if (val <= this.thyMin) {
6✔
217
                this.disabledDown = true;
218
            }
219
        }
9✔
220
    }
9✔
221

222
    onModelChange(value: string): void {
223
        if (this.isInputNumber(value)) {
3✔
224
            this.activeValue = value;
3✔
225
        } else {
226
            this.displayValue = this.activeValue;
227
            this.inputElement.nativeElement.value = this.displayValue;
265✔
228
        }
265✔
229
        const parseValue = this.parser(value);
163✔
230
        const validValue = this.getCurrentValidValue(parseValue);
231
        if (this.validValue !== validValue) {
232
            this.updateValidValue(validValue);
102✔
233
            this.onChangeFn(this.validValue);
234
        }
235
    }
236

308✔
237
    onInputFocus(event?: Event) {
238
        this.activeValue = this.parser(this.displayValue.toString());
239
        if (!this.isFocused) {
240
            this.isFocused = true;
241
            this.thyFocus.emit(event);
242
        }
243
    }
277✔
244

277✔
245
    onKeyDown(e: KeyboardEvent): void {
62✔
246
        if (e.keyCode === UP_ARROW) {
247
            this.up(e);
215✔
248
            this.stop();
215✔
249
        } else if (e.keyCode === DOWN_ARROW) {
107✔
250
            this.down(e);
251
            this.stop();
215✔
252
        } else if (e.keyCode === ENTER) {
5✔
253
            this.displayValue = this.formatterValue(this.validValue);
254
        }
215✔
255
    }
3✔
256

257
    stop() {
215✔
258
        if (this.autoStepTimer) {
259
            clearTimeout(this.autoStepTimer);
260
        }
738✔
261
        this.displayValue = this.toNumber(this.displayValue);
262
    }
263

251✔
264
    step(type: Type, e: MouseEvent | KeyboardEvent): void {
110✔
265
        this.stop();
266
        e.preventDefault();
141✔
267
        if (this.thyDisabled) {
141✔
268
            return;
15✔
269
        }
270
        const value = this.validValue as number;
126✔
271
        let val;
272
        if (type === Type.up) {
273
            val = this.upStep(value);
42✔
274
        } else if (type === Type.down) {
275
            val = this.downStep(value);
276
        }
104✔
277
        const outOfRange = val > this.thyMax || val < this.thyMin;
278
        val = this.getCurrentValidValue(val);
1✔
279
        this.updateValidValue(val);
280
        this.onChangeFn(this.validValue);
281
        this.displayValue = this.formatterValue(val);
1✔
282
        if (outOfRange) {
283
            return;
284
        }
285
        this.autoStepTimer = setTimeout(() => {
286
            (this[Type[type]] as (e: MouseEvent | KeyboardEvent) => void)(e);
287
        }, 300);
288
    }
289

290
    upStep(value: number): number {
291
        const precisionFactor = this.getPrecisionFactor(value);
292
        const precision = this.getMaxPrecision(value);
293
        const result = ((precisionFactor * value + precisionFactor * this.thyStep) / precisionFactor).toFixed(precision);
294
        return this.toNumber(result);
295
    }
296

1✔
297
    downStep(value: number): number {
298
        const precisionFactor = this.getPrecisionFactor(value);
299
        const precision = Math.abs(this.getMaxPrecision(value));
300
        const result = ((precisionFactor * value - precisionFactor * this.thyStep) / precisionFactor).toFixed(precision);
1✔
301
        return this.toNumber(result);
302
    }
303

304
    getMaxPrecision(value: string | number): number {
1✔
305
        if (!isUndefinedOrNull(this.thyPrecision)) {
306
            return this.thyPrecision;
307
        }
308
        const stepPrecision = this.getPrecision(this.thyStep);
1✔
309
        const currentValuePrecision = this.getPrecision(value as number);
310
        if (!value) {
311
            return stepPrecision;
312
        }
313
        return Math.max(currentValuePrecision, stepPrecision);
314
    }
315

104✔
316
    getPrecisionFactor(activeValue: string | number): number {
317
        const precision = this.getMaxPrecision(activeValue);
318
        return Math.pow(10, precision);
319
    }
320

321
    getPrecision(value: number): number {
322
        const valueString = value.toString();
323
        // 0.0000000004.toString() = 4e10  => 10
324
        if (valueString.indexOf('e-') >= 0) {
325
            return parseInt(valueString.slice(valueString.indexOf('e-') + 2), 10);
326
        }
327
        let precision = 0;
328
        // 1.2222 =>  4
329
        if (valueString.indexOf('.') >= 0) {
330
            precision = valueString.length - valueString.indexOf('.') - 1;
331
        }
332
        return precision;
333
    }
334

335
    up(e: MouseEvent | KeyboardEvent) {
336
        this.inputElement.nativeElement.focus();
337
        this.step(Type.up, e);
338
    }
339

340
    down(e: MouseEvent | KeyboardEvent) {
341
        this.inputElement.nativeElement.focus();
342
        this.step(Type.down, e);
343
    }
344

345
    formatterValue(value: number | string) {
346
        const parseValue = this.parser(`${value}`);
347
        if (parseValue) {
348
            return this.thySuffix ? `${parseValue} ${this.thySuffix}` : parseValue;
349
        } else {
350
            return '';
351
        }
352
    }
353

354
    parser(value: string) {
355
        return value
356
            .trim()
357
            .replace(/。/g, '.')
358
            .replace(/[^\w\.-]+/g, '')
359
            .replace(this.thySuffix, '');
360
    }
361

362
    getCurrentValidValue(value: string | number): number | string {
363
        let val = value;
364
        if (value === '' || value === undefined) {
365
            return '';
366
        }
367
        val = parseFloat(value as string);
368
        if (this.isNotValid(val)) {
369
            val = this.validValue;
370
        }
371
        if ((val as number) < this.thyMin) {
372
            val = this.thyMin;
373
        }
374
        if ((val as number) > this.thyMax) {
375
            val = this.thyMax;
376
        }
377

378
        return this.toNumber(val);
379
    }
380

381
    isNotValid(num: string | number): boolean {
382
        return isNaN(num as number) || num === '' || num === null || !!(num && num.toString().indexOf('.') === num.toString().length - 1);
383
    }
384

385
    toNumber(num: string | number): number {
386
        if (this.isNotValid(num)) {
387
            return num as number;
388
        }
389
        const numStr = String(num);
390
        if (numStr.indexOf('.') >= 0 && !isUndefinedOrNull(this.thyPrecision)) {
391
            return Number(Number(num).toFixed(this.thyPrecision));
392
        }
393
        return Number(num);
394
    }
395

396
    isInputNumber(value: string) {
397
        return isFloat(value) || /^[-+Ee]$|^([-+.]?[0-9])*(([.]|[.eE])?[eE]?[+-]?)?$|^$/.test(value);
398
    }
399

400
    ngOnDestroy() {
401
        this.hostFocusControl.destroy();
402
    }
403
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc