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

atinc / ngx-tethys / 143e4048-15a8-40d8-8345-f0aa483e9421

07 Sep 2023 05:53AM UTC coverage: 90.191%. Remained the same
143e4048-15a8-40d8-8345-f0aa483e9421

push

circleci

web-flow
feat: support focus(tabindex) for colorPicker, slider, rate, radio, checkbox and switch #INFR-9451

5163 of 6383 branches covered (0.0%)

Branch coverage included in aggregate %.

62 of 62 new or added lines in 13 files covered. (100.0%)

13034 of 13793 relevant lines covered (94.5%)

970.71 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 { TabIndexDisabledControlValueAccessorMixin, InputBoolean, InputNumber, useHostFocusControl } from 'ngx-tethys/core';
2
import { ThyMaxDirective, ThyMinDirective } from 'ngx-tethys/form';
3
import { ThyIconComponent } from 'ngx-tethys/icon';
4
import { ThyInputComponent, ThyInputDirective } from 'ngx-tethys/input';
5
import { ThyAutofocusDirective } from 'ngx-tethys/shared';
6
import { DOWN_ARROW, ENTER, isNumber, isUndefinedOrNull, UP_ARROW, isFloat } 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

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

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

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

60
    private autoStepTimer: any;
61

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

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

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

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

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

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

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

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

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

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

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

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

154
    private innerMax: number = Infinity;
155

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

12✔
158
    private isFocused: boolean;
1✔
159

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

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

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

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

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

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

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

9✔
222
    onModelChange(value: string): void {
9✔
223
        const parseValue = this.parser(value);
224
        const validValue = this.getCurrentValidValue(parseValue);
225
        if (this.validValue !== validValue) {
3✔
226
            this.updateValidValue(validValue);
3✔
227
            this.onChangeFn(this.validValue);
228
        }
229
    }
234✔
230

234✔
231
    onInput(input?: ThyInputComponent) {
146✔
232
        const value = input.value;
233
        if (this.isInputNumber(value)) {
234
            this.activeValue = value;
88✔
235
        } else {
236
            this.displayValue = this.activeValue;
237
            input.value = this.displayValue;
238
        }
268✔
239
    }
240

241
    onInputFocus(event?: Event) {
242
        this.activeValue = this.parser(this.displayValue.toString());
243
        if (!this.isFocused) {
244
            this.isFocused = true;
245
            this.thyFocus.emit(event);
239✔
246
        }
239✔
247
    }
47✔
248

249
    onKeyDown(e: KeyboardEvent): void {
192✔
250
        if (e.keyCode === UP_ARROW) {
192✔
251
            this.up(e);
91✔
252
            this.stop();
253
        } else if (e.keyCode === DOWN_ARROW) {
192✔
254
            this.down(e);
2✔
255
            this.stop();
256
        } else if (e.keyCode === ENTER) {
192✔
257
            this.displayValue = this.formatterValue(this.validValue);
2✔
258
        }
259
    }
192✔
260

261
    stop() {
262
        if (this.autoStepTimer) {
632✔
263
            clearTimeout(this.autoStepTimer);
264
        }
265
    }
203✔
266

91✔
267
    step(type: Type, e: MouseEvent | KeyboardEvent): void {
268
        this.stop();
112✔
269
        e.preventDefault();
112✔
270
        if (this.thyDisabled) {
12✔
271
            return;
272
        }
100✔
273
        const value = this.validValue as number;
274
        let val;
275
        if (type === Type.up) {
25✔
276
            val = this.upStep(value);
277
        } else if (type === Type.down) {
278
            val = this.downStep(value);
90✔
279
        }
280
        const outOfRange = val > this.thyMax || val < this.thyMin;
1✔
281
        val = this.getCurrentValidValue(val);
282
        this.updateValidValue(val);
283
        this.onChangeFn(this.validValue);
1✔
284
        this.displayValue = this.formatterValue(val);
285
        if (outOfRange) {
286
            return;
287
        }
288
        this.autoStepTimer = setTimeout(() => {
289
            (this[Type[type]] as (e: MouseEvent | KeyboardEvent) => void)(e);
290
        }, 300);
291
    }
292

293
    upStep(value: number): number {
294
        const precisionFactor = this.getPrecisionFactor(value);
295
        const precision = this.getMaxPrecision(value);
296
        const result = ((precisionFactor * value + precisionFactor * this.thyStep) / precisionFactor).toFixed(precision);
297
        return this.toNumber(result);
298
    }
1✔
299

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

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

319
    getPrecisionFactor(activeValue: string | number): number {
320
        const precision = this.getMaxPrecision(activeValue);
321
        return Math.pow(10, precision);
322
    }
323

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

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

343
    down(e: MouseEvent | KeyboardEvent) {
344
        this.inputElement.nativeElement.focus();
345
        this.step(Type.down, e);
346
    }
347

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

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

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

381
        return this.toNumber(val);
382
    }
383

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

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

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

403
    ngOnDestroy() {
404
        this.hostFocusControl.destroy();
405
    }
406
}
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