Project

General

Profile

1 61381 k.triantaf
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" [attr.uk-tooltip]="option.label">
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" [attr.uk-tooltip]="option.label">
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" [attr.uk-tooltip]="option.label">
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
    this.focusEmitter.emit(this.focused);
225
  }
226
227
  ngOnInit(): void {
228
    this.reset();
229
  }
230
231
  ngOnChanges(changes: SimpleChanges) {
232
    if (changes.formControl) {
233
      this.reset();
234
    }
235
  }
236
237
  get formAsArray(): FormArray {
238
    return (<FormArray>this.formControl);
239
  }
240
241
  reset() {
242
    this.secure = true;
243
    this.unsubscribe();
244
    this.initValue = HelperFunctions.copy(this.formControl.value);
245
    if(this.type === 'logoURL') {
246
      this.secure = (!this.initValue || this.initValue.includes('https://'));
247
    }
248
    if (this.type === 'chips' || this.type === 'autocomplete') {
249
      if(this.options) {
250
        this.filteredOptions = of(this.options);
251
        this.searchControl = new FormControl('', this.validators);
252
        this.subscriptions.push(this.searchControl.valueChanges.subscribe(value => {
253
          setTimeout(() => {
254
            this.searchInput.nativeElement.focus();
255
            this.searchInput.nativeElement.value = value;
256
          },0);
257
        }));
258
        this.filteredOptions = this.searchControl.valueChanges.pipe(startWith(''),
259
          map(option => this.filter(option)));
260
      }
261
    }
262
    if (this.formControl && this.formControl.validator) {
263
      let validator = this.formControl.validator({} as AbstractControl);
264
      this.required = (validator && validator.required);
265
    }
266
    this.subscriptions.push(this.formControl.valueChanges.subscribe(value => {
267
      value = (value === '') ? null : value;
268
      if(this.type === 'logoURL') {
269
        this.secure = (!value || value.includes('https://'));
270
      }
271
      if (this.initValue === value || (this.initValue === '' && value === null)) {
272
        this.formControl.markAsPristine();
273
      }
274
      if(this.searchControl) {
275
        this.searchControl.setValue(null);
276
      }
277
    }));
278
    if (!this.formControl.value) {
279
      this.formControl.setValue((this.type === "checkbox")?false:'');
280
    }
281
  }
282
283
  unsubscribe() {
284
    this.subscriptions.forEach(subscription => {
285
      if (subscription instanceof Subscription) {
286
        subscription.unsubscribe();
287
      }
288
    });
289
  }
290
291
  openSelect() {
292
    if (this.select) {
293
      this.select.open();
294
    }
295
  }
296
297
  ngOnDestroy(): void {
298
    this.unsubscribe();
299
  }
300
301
  stopPropagation() {
302
    event.stopPropagation();
303
  }
304
305
  removed(index: number) {
306
    this.formAsArray.removeAt(index);
307
    this.formAsArray.markAsDirty();
308
    this.searchControl.setValue('');
309
    this.stopPropagation();
310
  }
311
312
  selected(event: MatAutocompleteSelectedEvent): void {
313
    this.formAsArray.push(new FormControl(event.option.value));
314
    this.formAsArray.markAsDirty();
315
    this.searchControl.setValue('');
316
    this.stopPropagation();
317
  }
318
319
  private filter(value: string): Option[] {
320
    let options = this.options;
321
    if(this.type === "chips") {
322
      options = options.filter(option => !this.formAsArray.value.find(value =>  HelperFunctions.equals(option.value, value)));
323
    }
324
    if ((!value || value.length == 0)) {
325
      return (this.showOptionsOnEmpty)?options:[];
326
    }
327
    const filterValue = value.toString().toLowerCase();
328
    return options.filter(option => option.label.toLowerCase().indexOf(filterValue) != -1);
329
  }
330
331
  add(event: MatChipInputEvent) {
332
    if (this.addExtraChips && event.value && this.searchControl.valid) {
333
      this.stopPropagation();
334
      this.formAsArray.push(new FormControl(event.value, this.validators));
335
      this.formAsArray.markAsDirty();
336
      this.searchControl.setValue('');
337
      this.searchInput.nativeElement.value = '';
338
    }
339
  }
340
341
  getLabel(value: any) {
342
    let option = this.options.find(option => HelperFunctions.equals(option.value, value));
343
    return (option) ? option.label : value;
344
  }
345
346
  resetSearch(event: any) {
347
    event.stopPropagation();
348
    this.searchControl.setValue('');
349
    this.formControl.setValue(null);
350
  }
351
}