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} 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':''">
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':''">
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 class="uk-width-1-1" [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 && formControl.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 class="uk-width-1-1" [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
  /** Custom messages */
197
  @Input() warning: string = null;
198
  @Input() note: string = null;
199
  /** Chip options */
200
  @Input() removable: boolean = true;
201
  @Input() addExtraChips: boolean = false;
202
  @Input() smallChip: boolean = false;
203
  @Input() panelWidth: number = 300;
204
  @Input() panelClass: string = null;
205
  @Input() showOptionsOnEmpty: boolean = true;
206
  @Output() focusEmitter: EventEmitter<boolean> = new EventEmitter<boolean>();
207
  /** LogoUrl information */
208
  public secure: boolean = true;
209
  /** Internal basic information */
210
  public required: boolean = false;
211
  private initValue: any;
212
  /** Chips && Autocomplete*/
213
  public filteredOptions: Observable<Option[]>;
214
  public searchControl: FormControl;
215
  private subscriptions: any[] = [];
216
  @ViewChild('select') select: MatSelect;
217
  @ViewChild('searchInput') searchInput: ElementRef;
218
  focused: boolean = false;
219
  
220
  constructor(private elementRef: ElementRef) {
221
  }
222
  
223
  @HostListener('document:click', ['$event'])
224
  clickOut(event) {
225
    this.focused = !!this.elementRef.nativeElement.contains(event.target);
226
    if(!this.focused && this.input) {
227
      this.input.nativeElement.setSelectionRange(0,0);
228
    }
229
    this.focusEmitter.emit(this.focused);
230
  }
231
  
232
  ngOnInit(): void {
233
    this.reset();
234
  }
235
  
236
  ngOnChanges(changes: SimpleChanges) {
237
    if (changes.formControl) {
238
      this.reset();
239
    }
240
  }
241
  
242
  get formAsArray(): FormArray {
243
    return (<FormArray>this.formControl);
244
  }
245
  
246
  reset() {
247
    this.secure = true;
248
    this.unsubscribe();
249
    this.initValue = HelperFunctions.copy(this.formControl.value);
250
    if(this.type === 'logoURL') {
251
      this.secure = (!this.initValue || this.initValue.includes('https://'));
252
    }
253
    if (this.type === 'chips' || this.type === 'autocomplete') {
254
      if(!this.options) {
255
        console.error('Please provide options to continue');
256
      } else {
257
        this.filteredOptions = of(this.options);
258
        this.searchControl = new FormControl('');
259
        this.subscriptions.push(this.searchControl.valueChanges.subscribe(value => {
260
          setTimeout(() => {
261
            this.searchInput.nativeElement.focus();
262
            this.searchInput.nativeElement.value = value;
263
          },0);
264
        }));
265
        this.filteredOptions = this.searchControl.valueChanges.pipe(startWith(''),
266
          map(option => this.filter(option)));
267
      }
268
    }
269
    if (this.formControl && this.formControl.validator) {
270
      let validator = this.formControl.validator({} as AbstractControl);
271
      this.required = (validator && validator.required);
272
    }
273
    this.subscriptions.push(this.formControl.valueChanges.subscribe(value => {
274
      value = (value === '') ? null : value;
275
      if(this.type === 'logoURL') {
276
        this.secure = (!value || value.includes('https://'));
277
      }
278
      if (this.initValue === value || (this.initValue === '' && value === null)) {
279
        this.formControl.markAsPristine();
280
      }
281
      if(this.searchControl) {
282
        this.searchControl.setValue(null);
283
      }
284
    }));
285
    if (!this.formControl.value) {
286
      this.formControl.setValue('');
287
    }
288
  }
289
  
290
  unsubscribe() {
291
    this.subscriptions.forEach(subscription => {
292
      if (subscription instanceof Subscription) {
293
        subscription.unsubscribe();
294
      }
295
    });
296
  }
297
  
298
  openSelect() {
299
    if (this.select) {
300
      this.select.open();
301
    }
302
  }
303
  
304
  ngOnDestroy(): void {
305
    this.unsubscribe();
306
  }
307
  
308
  stopPropagation() {
309
    event.stopPropagation();
310
  }
311
  
312
  removed(index: number) {
313
    this.formAsArray.removeAt(index);
314
    this.formAsArray.markAsDirty();
315
    this.searchControl.setValue('');
316
    this.stopPropagation();
317
  }
318
  
319
  selected(event: MatAutocompleteSelectedEvent): void {
320
    this.formAsArray.push(new FormControl(event.option.value));
321
    this.formAsArray.markAsDirty();
322
    this.searchControl.setValue('');
323
    this.stopPropagation();
324
  }
325
  
326
  private filter(value: string): Option[] {
327
    let options = this.options;
328
    if(this.type === "chips") {
329
      options = options.filter(option => !this.formAsArray.value.find(value => option.value === value));
330
    }
331
    if ((!value || value.length == 0)) {
332
      return (this.showOptionsOnEmpty)?options:[];
333
    }
334
    const filterValue = value.toString().toLowerCase();
335
    return options.filter(option => option.label.toLowerCase().indexOf(filterValue) != -1);
336
  }
337
  
338
  add(event: MatChipInputEvent) {
339
    if (this.addExtraChips && event.value) {
340
      this.stopPropagation();
341
      this.formAsArray.push(new FormControl(event.value));
342
      this.formAsArray.markAsDirty();
343
      this.searchControl.setValue('');
344
      this.searchInput.nativeElement.value = '';
345
    }
346
  }
347
  
348
  getLabel(value: any) {
349
    let option = this.options.find(option => option.value === value);
350
    return (option) ? option.label : value;
351
  }
352
  
353
  resetSearch(event: any) {
354
    event.stopPropagation();
355
    this.searchControl.setValue('');
356
    this.formControl.setValue(null);
357
  }
358
}
(2-2/3)