Project

General

Profile

1
import {
2
  Component,
3
  ElementRef,
4
  EventEmitter,
5
  HostListener,
6
  Input,
7
  OnChanges,
8
  OnDestroy,
9
  OnInit,
10
  Output,
11
  SimpleChanges,
12
  ViewChild
13
} from "@angular/core";
14
import {AbstractControl, FormArray, FormControl, ValidatorFn} from "@angular/forms";
15
import {HelperFunctions} from "../../utils/HelperFunctions.class";
16
import {Observable, of, Subscription} from "rxjs";
17
import {MatSelect} from "@angular/material/select";
18
import {MatAutocompleteSelectedEvent} from "@angular/material/autocomplete";
19
import {map, startWith} from "rxjs/operators";
20
import {MatChipInputEvent} from "@angular/material/chips";
21

    
22

    
23
export interface Option {
24
  icon?: string,
25
  iconClass?: string,
26
  value: any,
27
  label: string
28
}
29

    
30
@Component({
31
  selector: '[dashboard-input]',
32
  template: `
33
    <div *ngIf="label && type != 'checkbox'"
34
         class="uk-text-bold uk-form-label uk-margin-small-bottom">{{label + (required ? ' *' : '')}}</div>
35
    <div *ngIf="hint" class="uk-margin-bottom uk-form-hint">{{hint}}</div>
36
    <div class="uk-grid uk-flex" [ngClass]="'uk-flex-' + flex" [class.uk-grid-small]="gridSmall" uk-grid>
37
      <ng-content></ng-content>
38
      <div [class.uk-hidden]="hideControl" class="uk-width-expand uk-position-relative"
39
           [class.uk-flex-first]="!extraLeft">
40
        <ng-template [ngIf]="icon && formControl.enabled">
41
          <span class="uk-text-muted" [ngClass]="iconLeft?('left'):'right'">
42
            <icon [name]="icon"></icon>
43
          </span>
44
        </ng-template>
45
        <ng-template [ngIf]="formControl.disabled">
46
          <span class="uk-text-muted left">
47
            <icon [name]="'lock'"></icon>
48
          </span>
49
        </ng-template>
50
        <ng-template [ngIf]="type === 'text' || type === 'URL' || type === 'logoURL'">
51
          <div [ngClass]="inputClass"
52
               [class.uk-form-danger]="formControl.invalid && formControl.touched"
53
               [attr.uk-tooltip]="formControl.disabled?'title: This field is not editable; pos: bottom-left':null">
54
            <input #input class="uk-input" [placeholder]="placeholder" [formControl]="formControl">
55
          </div>
56
        </ng-template>
57
        <ng-template [ngIf]="type === 'textarea'">
58
          <div [ngClass]="inputClass" class="uk-padding-remove-right"
59
               [class.uk-form-danger]="formControl.invalid && formControl.touched"
60
               [attr.uk-tooltip]="formControl.disabled?'title: This field is not editable; pos: bottom-left':null">
61
              <textarea class="uk-textarea"
62
                        [rows]="rows" [placeholder]="placeholder"
63
                        [formControl]="formControl">
64
              </textarea>
65
              <div class="tools" [class.focused]="focused">
66
                <ng-content select="[options]"></ng-content>
67
              </div>
68
          </div>
69
        </ng-template>
70
        <ng-template [ngIf]="type === 'select'">
71
          <div [ngClass]="inputClass"
72
               [attr.uk-tooltip]="formControl.disabled?'title: This field is not editable; pos: bottom-left':null"
73
               [class.clickable]="formControl.enabled"
74
               [class.uk-form-danger]="formControl.invalid && formControl.touched" (click)="openSelect()">
75
            <mat-form-field class="uk-width-1-1">
76
              <mat-select #select [required]="required" [value]="null"
77
                          (openedChange)="stopPropagation()" [formControl]="formControl"
78
                          [disableOptionCentering]="true">
79
                <mat-option *ngIf="placeholder" class="uk-hidden" [value]="''">{{placeholder}}</mat-option>
80
                <mat-option *ngFor="let option of options" [value]="option.value">
81
                  {{option.label}}
82
                </mat-option>
83
              </mat-select>
84
            </mat-form-field>
85
          </div>
86
        </ng-template>
87
        <ng-template [ngIf]="type === 'autocomplete'">
88
          <div [ngClass]="inputClass"
89
               [attr.uk-tooltip]="formControl.disabled?'title: This field is not editable; pos: bottom-left':null"
90
               [class.clickable]="formControl.enabled"
91
               [class.uk-form-danger]="formControl.invalid && formControl.touched" (click)="openSelect()">
92
            <mat-form-field class="uk-width-1-1">
93
              <mat-chip-list #chipList>
94
                <mat-chip *ngIf="formControl.value" [selectable]="false" [removable]="removable"
95
                          [attr.uk-tooltip]="getLabel(formControl.value)">
96
                  <span class="uk-flex uk-flex-middle uk-width-1-1">
97
                    <span class="uk-width-expand uk-text-truncate" [class.uk-text-small]="smallChip">{{getLabel(formControl.value)}}</span>
98
                    <icon name="remove_circle" class="mat-chip-remove" [flex]="true" [ratio]="smallChip?0.8:1"
99
                          (click)="resetSearch($event)"></icon>
100
                  </span>
101
                </mat-chip>
102
                <div [class.uk-hidden]="formControl.value" class="uk-width-expand uk-position-relative chip-input">
103
                  <input #searchInput [formControl]="searchControl" [matAutocomplete]="auto"
104
                         [matChipInputFor]="chipList" [matAutocompleteConnectedTo]="origin">
105
                  <div *ngIf="placeholder && !searchInput.value" class="placeholder uk-width-1-1"
106
                       (click)="searchInput.focus()">{{placeholder}}</div>
107
                </div>
108
                <div class="uk-width-1-1 uk-invisible" matAutocompleteOrigin #origin="matAutocompleteOrigin"></div>
109
              </mat-chip-list>
110
              <mat-autocomplete #auto="matAutocomplete" (optionSelected)="formControl.setValue($event.option.value)" [class]="panelClass" [panelWidth]="panelWidth">
111
                <mat-option *ngFor="let option of filteredOptions | async" [value]="option.value">
112
                  {{option.label}}
113
                </mat-option>
114
              </mat-autocomplete>
115
            </mat-form-field>
116
          </div>
117
        </ng-template>
118
        <ng-template [ngIf]="type === 'chips'">
119
          <div [ngClass]="inputClass"
120
               [attr.uk-tooltip]="formControl.disabled?'title: This field is not editable; pos: bottom-left':null"
121
               [class.clickable]="formControl.enabled"
122
               [class.uk-form-danger]="formControl.invalid && searchControl.invalid && searchControl.touched" (click)="openSelect()">
123
            <mat-form-field class="uk-width-1-1">
124
              <mat-chip-list #chipList>
125
                <mat-chip *ngFor="let chip of formAsArray.controls; let i=index" [selectable]="false"
126
                          [removable]="removable" [attr.uk-tooltip]="getLabel(chip.value)">
127
                  <span class="uk-flex uk-flex-middle uk-width-1-1">
128
                    <span class="uk-width-expand uk-text-truncate" [class.uk-text-small]="smallChip">{{getLabel(chip.value)}}</span>
129
                    <icon name="remove_circle" class="mat-chip-remove" [flex]="true" [ratio]="smallChip?0.8:1" (click)="removed(i)"></icon>
130
                  </span>
131
                </mat-chip>
132
                <div class="uk-width-expand uk-position-relative chip-input">
133
                  <input #searchInput style="width: calc(100% - 8px) !important;" [formControl]="searchControl" [matAutocomplete]="auto"
134
                         [matChipInputFor]="chipList" [matAutocompleteConnectedTo]="origin"
135
                         [matChipInputAddOnBlur]="addExtraChips && searchControl.value"
136
                         (matChipInputTokenEnd)="add($event)">
137
                  <div *ngIf="placeholder && !searchControl.value" class="placeholder uk-width-1-1"
138
                       (click)="searchInput.focus()">{{placeholder}}</div>
139
                </div>
140
                <div class="uk-width-1-1 uk-invisible" matAutocompleteOrigin #origin="matAutocompleteOrigin"></div>
141
              </mat-chip-list>
142
              <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)" [class]="panelClass" [panelWidth]="panelWidth">
143
                <mat-option *ngFor="let option of filteredOptions | async" [value]="option.value">
144
                  {{option.label}}
145
                </mat-option>
146
              </mat-autocomplete>
147
            </mat-form-field>
148
          </div>
149
        </ng-template>
150
        <span *ngIf="formControl.invalid && formControl.touched" class="uk-text-danger input-message">
151
          <span *ngIf="formControl.errors.error">{{formControl.errors.error}}</span>
152
          <span *ngIf="type === 'URL' || type === 'logoURL'">Please provide a valid URL (e.g. https://example.com)</span>
153
        </span>
154
        <span class="uk-text-danger input-message">
155
          <ng-content select="[error]"></ng-content>
156
        </span>
157
        <span *ngIf="formControl.valid" class="uk-text-warning input-message">
158
          <ng-content select="[warning]"></ng-content>
159
          <span *ngIf="!secure">
160
            <span class="uk-text-bold">Note:</span> Prefer urls like "<span class="uk-text-bold">https://</span>example.com/my-secure-image.png"
161
                instead of "<span class="uk-text-bold">http://</span>example.com/my-image.png".
162
                <span class="uk-text-bold">Browsers may not load non secure content.</span>
163
          </span>
164
        </span>
165
        <span class="input-message">
166
          <ng-content select="[note]"></ng-content>
167
        </span>
168
      </div>
169
    </div>
170
    <mat-checkbox *ngIf="type === 'checkbox'" [formControl]="formControl">{{label}}</mat-checkbox>
171
  `,
172
  styleUrls: ['input.component.css']
173
})
174
export class InputComponent implements OnInit, OnDestroy, OnChanges {
175
  /** Basic information */
176
  @Input('formInput') formControl: AbstractControl;
177
  @Input('type') type: 'text' | 'URL' | 'logoURL' | 'autocomplete' | 'textarea' | 'select' | 'checkbox' | 'chips' = 'text';
178
  @Input('label') label: string;
179
  /** Text */
180
  @ViewChild('input') input: ElementRef;
181
  /** Textarea options */
182
  @Input('rows') rows: number = 3;
183
  /** Select | chips available options */
184
  @Input('options') options: Option[] = [];
185
  @Input('hint') hint = null;
186
  @Input('placeholder') placeholder = '';
187
  @Input() inputClass: string = 'input-box';
188
  /** Extra element Right or Left of the input */
189
  @Input() extraLeft: boolean = true;
190
  @Input() gridSmall: boolean = false;
191
  @Input() hideControl: boolean = false;
192
  @Input() flex: 'middle' | 'top' | 'bottom' = 'middle';
193
  /** Icon Right or Left on the input */
194
  @Input() icon: string = null;
195
  @Input() iconLeft: boolean = false;
196
  /** Chip options */
197
  @Input() removable: boolean = true;
198
  @Input() addExtraChips: boolean = false;
199
  @Input() smallChip: boolean = false;
200
  @Input() panelWidth: number = 300;
201
  @Input() panelClass: string = null;
202
  @Input() showOptionsOnEmpty: boolean = true;
203
  @Input() validators: ValidatorFn[];
204
  @Output() focusEmitter: EventEmitter<boolean> = new EventEmitter<boolean>();
205
  /** LogoUrl information */
206
  public secure: boolean = true;
207
  /** Internal basic information */
208
  public required: boolean = false;
209
  private initValue: any;
210
  /** Chips && Autocomplete*/
211
  public filteredOptions: Observable<Option[]>;
212
  public searchControl: FormControl;
213
  private subscriptions: any[] = [];
214
  @ViewChild('select') select: MatSelect;
215
  @ViewChild('searchInput') searchInput: ElementRef;
216
  focused: boolean = false;
217
  
218
  constructor(private elementRef: ElementRef) {
219
  }
220
  
221
  @HostListener('document:click', ['$event'])
222
  clickOut(event) {
223
    this.focused = !!this.elementRef.nativeElement.contains(event.target);
224
    if(!this.focused && this.input) {
225
      this.input.nativeElement.setSelectionRange(0,0);
226
    }
227
    this.focusEmitter.emit(this.focused);
228
  }
229
  
230
  ngOnInit(): void {
231
    this.reset();
232
  }
233
  
234
  ngOnChanges(changes: SimpleChanges) {
235
    if (changes.formControl) {
236
      this.reset();
237
    }
238
  }
239
  
240
  get formAsArray(): FormArray {
241
    return (<FormArray>this.formControl);
242
  }
243
  
244
  reset() {
245
    this.secure = true;
246
    this.unsubscribe();
247
    this.initValue = HelperFunctions.copy(this.formControl.value);
248
    if(this.type === 'logoURL') {
249
      this.secure = (!this.initValue || this.initValue.includes('https://'));
250
    }
251
    if (this.type === 'chips' || this.type === 'autocomplete') {
252
      if(this.options) {
253
        this.filteredOptions = of(this.options);
254
        this.searchControl = new FormControl('', this.validators);
255
        this.subscriptions.push(this.searchControl.valueChanges.subscribe(value => {
256
          setTimeout(() => {
257
            this.searchInput.nativeElement.focus();
258
            this.searchInput.nativeElement.value = value;
259
          },0);
260
        }));
261
        this.filteredOptions = this.searchControl.valueChanges.pipe(startWith(''),
262
          map(option => this.filter(option)));
263
      }
264
    }
265
    if (this.formControl && this.formControl.validator) {
266
      let validator = this.formControl.validator({} as AbstractControl);
267
      this.required = (validator && validator.required);
268
    }
269
    this.subscriptions.push(this.formControl.valueChanges.subscribe(value => {
270
      value = (value === '') ? null : value;
271
      if(this.type === 'logoURL') {
272
        this.secure = (!value || value.includes('https://'));
273
      }
274
      if (this.initValue === value || (this.initValue === '' && value === null)) {
275
        this.formControl.markAsPristine();
276
      }
277
      if(this.searchControl) {
278
        this.searchControl.setValue(null);
279
      }
280
    }));
281
    if (!this.formControl.value) {
282
      this.formControl.setValue((this.type === "checkbox")?false:'');
283
    }
284
  }
285
  
286
  unsubscribe() {
287
    this.subscriptions.forEach(subscription => {
288
      if (subscription instanceof Subscription) {
289
        subscription.unsubscribe();
290
      }
291
    });
292
  }
293
  
294
  openSelect() {
295
    if (this.select) {
296
      this.select.open();
297
    }
298
  }
299
  
300
  ngOnDestroy(): void {
301
    this.unsubscribe();
302
  }
303
  
304
  stopPropagation() {
305
    event.stopPropagation();
306
  }
307
  
308
  removed(index: number) {
309
    this.formAsArray.removeAt(index);
310
    this.formAsArray.markAsDirty();
311
    this.searchControl.setValue('');
312
    this.stopPropagation();
313
  }
314
  
315
  selected(event: MatAutocompleteSelectedEvent): void {
316
    this.formAsArray.push(new FormControl(event.option.value));
317
    this.formAsArray.markAsDirty();
318
    this.searchControl.setValue('');
319
    this.stopPropagation();
320
  }
321
  
322
  private filter(value: string): Option[] {
323
    let options = this.options;
324
    if(this.type === "chips") {
325
      options = options.filter(option => !this.formAsArray.value.find(value =>  HelperFunctions.equals(option.value, value)));
326
    }
327
    if ((!value || value.length == 0)) {
328
      return (this.showOptionsOnEmpty)?options:[];
329
    }
330
    const filterValue = value.toString().toLowerCase();
331
    return options.filter(option => option.label.toLowerCase().indexOf(filterValue) != -1);
332
  }
333
  
334
  add(event: MatChipInputEvent) {
335
    if (this.addExtraChips && event.value && this.searchControl.valid) {
336
      this.stopPropagation();
337
      this.formAsArray.push(new FormControl(event.value, this.validators));
338
      this.formAsArray.markAsDirty();
339
      this.searchControl.setValue('');
340
      this.searchInput.nativeElement.value = '';
341
    }
342
  }
343
  
344
  getLabel(value: any) {
345
    let option = this.options.find(option => HelperFunctions.equals(option.value, value));
346
    return (option) ? option.label : value;
347
  }
348
  
349
  resetSearch(event: any) {
350
    event.stopPropagation();
351
    this.searchControl.setValue('');
352
    this.formControl.setValue(null);
353
  }
354
}
(2-2/3)