|
1 | | -import { Directive, Input, HostListener } from "@angular/core"; |
2 | | -import { NgxVibrationService } from "./ngx-vibration.service"; |
| 1 | +import { Directive, HostListener, Input } from '@angular/core'; |
| 2 | +import { NgxVibrationService } from './ngx-vibration.service'; |
3 | 3 |
|
4 | 4 | @Directive({ |
5 | 5 | selector: "[ngxVibration]", |
6 | 6 | }) |
7 | 7 | export class VibrationDirective { |
8 | | - @Input("ngxVibration") |
9 | | - vibratePattern: number[]; |
| 8 | + private vibratePattern: number[]; |
| 9 | + |
| 10 | + /** |
| 11 | + * Handle directive arguments |
| 12 | + * Accepts pattern or digits as string or number |
| 13 | + */ |
| 14 | + @Input('ngxVibration') |
| 15 | + set inputPattern(input: number[] | number | string) { |
| 16 | + if (typeof input === 'string') { |
| 17 | + if (input) { |
| 18 | + if (!input.match(/^\d+$/)) { |
| 19 | + // The input does not match a number |
| 20 | + throw new Error('At least one number is expected as vibration pattern'); |
| 21 | + } |
| 22 | + // Building the pattern from the given number |
| 23 | + this.vibratePattern = [parseInt(input, 10)]; |
| 24 | + } else { |
| 25 | + // No input was given, falling back to module config |
| 26 | + const defaultPattern = this.vibrationService.config?.defaultPattern; |
| 27 | + if (!defaultPattern) { |
| 28 | + throw new Error('No pattern provided in vibrate() call nor module configuration'); |
| 29 | + } |
| 30 | + this.vibratePattern = defaultPattern; |
| 31 | + } |
| 32 | + } else if (typeof input === 'number') { |
| 33 | + // Building the pattern from the given number |
| 34 | + this.vibratePattern = [input]; |
| 35 | + } else { |
| 36 | + this.vibratePattern = input; |
| 37 | + } |
| 38 | + } |
10 | 39 |
|
11 | 40 | constructor(private vibrationService: NgxVibrationService) {} |
12 | 41 |
|
|
0 commit comments