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

atinc / ngx-tethys / 619c26d5-4c42-4f73-9fb7-3d179982de6e

20 Oct 2023 05:55AM UTC coverage: 90.212% (-0.006%) from 90.218%
619c26d5-4c42-4f73-9fb7-3d179982de6e

push

circleci

ggxxgxq
fix(input-number): fix input number suffix not effect #POR-8982

5166 of 6385 branches covered (0.0%)

Branch coverage included in aggregate %.

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

13037 of 13793 relevant lines covered (94.52%)

972.83 hits per line

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

97.27
/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

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

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

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

60
    private autoStepTimer: any;
61

102✔
62
    private hostFocusControl = useHostFocusControl();
33✔
63

1✔
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
129✔
82
     */
2✔
83
    @Input() thyPlaceholder: string = '';
2✔
84

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

241✔
91
    /**
241✔
92
     * 最大值
93
     * @default Infinity
94
     */
268✔
95
    @Input() set thyMax(value: number) {
162✔
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
        }
268✔
101
    }
268✔
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
    }
118

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

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

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

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

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

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

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

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

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

11✔
158
    private isFocused: boolean;
159

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

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

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

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

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

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

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

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

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

273✔
244
    onKeyDown(e: KeyboardEvent): void {
60✔
245
        if (e.keyCode === UP_ARROW) {
246
            this.up(e);
213✔
247
            this.stop();
213✔
248
        } else if (e.keyCode === DOWN_ARROW) {
105✔
249
            this.down(e);
250
            this.stop();
213✔
251
        } else if (e.keyCode === ENTER) {
5✔
252
            this.displayValue = this.formatterValue(this.validValue);
253
        }
213✔
254
    }
3✔
255

256
    stop() {
213✔
257
        if (this.autoStepTimer) {
258
            clearTimeout(this.autoStepTimer);
259
        }
730✔
260
        this.displayValue = this.toNumber(this.displayValue);
261
    }
262

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

399
    ngOnDestroy() {
400
        this.hostFocusControl.destroy();
401
    }
402
}
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

© 2025 Coveralls, Inc