openaire-library/sharedComponents/input/input.component.ts

434 lines
17 KiB
TypeScript
Raw Normal View History

import {
AfterViewInit,
Component,
ElementRef,
EventEmitter,
HostListener,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges,
ViewChild
} from "@angular/core";
import {AbstractControl, FormArray, FormControl, ValidatorFn} from "@angular/forms";
import {HelperFunctions} from "../../utils/HelperFunctions.class";
import {Observable, of, Subscription} from "rxjs";
import {MatSelect} from "@angular/material/select";
import {MatAutocompleteSelectedEvent} from "@angular/material/autocomplete";
import {map, startWith} from "rxjs/operators";
import {MatChipInputEvent} from "@angular/material/chips";
import {EnvProperties} from "../../utils/properties/env-properties";
import {properties} from "../../../../environments/environment";
export interface Option {
icon?: string,
iconClass?: string,
value: any,
label: string
}
/**
* WARNING! dashboard-input selector is @deprecated, use input instead
*
* */
@Component({
selector: '[dashboard-input], [input]',
template: `
<div class="input-container" [ngClass]="inputClass" [class.disabled]="formControl.disabled"
[class.focused]="(focused && type !== 'select') || formControl.value" [class.opened]="opened">
<div #inputBox class="input-wrapper" [class.select]="type === 'select'">
<div class="placeholder">
<label>{{placeholder}} <sup *ngIf="required">*</sup></label>
</div>
<div class="uk-flex" [class.uk-flex-middle]="type !== 'textarea'">
<ng-template [ngIf]="type === 'text' || type === 'URL' || type === 'logoURL'">
<input #input class="input" [formControl]="formAsControl">
</ng-template>
<ng-template [ngIf]="type === 'textarea'">
<textarea #textArea class="input" [rows]="rows" [formControl]="formAsControl"></textarea>
</ng-template>
<ng-template [ngIf]="type === 'select'">
<div class="input">{{getLabel(formControl.value)}}</div>
</ng-template>
<div *ngIf="formControl.disabled || icon || type === 'select'" class="uk-margin-small-left uk-margin-right">
<icon *ngIf="formControl.disabled" [name]="'lock'" [flex]="true"></icon>
<icon *ngIf="formControl.enabled && icon" [name]="icon" [flex]="true"></icon>
<icon *ngIf="formControl.enabled && !icon" name="arrow_drop_down" [flex]="true"></icon>
</div>
</div>
<div class="tools">
<ng-content select="[tools]"></ng-content>
</div>
</div>
<div #optionBox class="options">
<ul *ngIf="options?.length > 1">
<li *ngFor="let option of options" [class.uk-active]="formControl.value === option.value">
<a (click)="selectOption(option)">{{option.label}}</a>
</li>
</ul>
</div>
</div>
<!--<ng-template [ngIf]="type === 'select'">
<div [ngClass]="inputClass"
[attr.uk-tooltip]="formControl.disabled?'title: This field is not editable; pos: bottom-left':null"
[class.clickable]="formControl.enabled"
[class.uk-form-danger]="formControl.invalid && formControl.touched" (click)="openSelect()">
<mat-form-field class="uk-width-1-1">
<mat-select #select [required]="required" [value]="null"
(openedChange)="stopPropagation()" [formControl]="formAsControl"
[disableOptionCentering]="true">
<mat-option *ngIf="placeholder" class="uk-hidden" [value]="''">{{placeholder}}</mat-option>
<mat-option *ngFor="let option of options" [value]="option.value"
[attr.uk-tooltip]="(tooltip) ? option.label : null">
{{option.label}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
</ng-template>-->
<ng-template [ngIf]="type === 'autocomplete'">
<div [ngClass]="inputClass"
[attr.uk-tooltip]="formControl.disabled?'title: This field is not editable; pos: bottom-left':null"
[class.clickable]="formControl.enabled"
[class.uk-form-danger]="formControl.invalid && formControl.touched" (click)="openSelect()">
<mat-form-field class="uk-width-1-1">
<mat-chip-list #chipList>
<mat-chip *ngIf="formControl.value" [selectable]="false" [removable]="removable"
[attr.uk-tooltip]="getLabel(formControl.value)">
<span class="uk-flex uk-flex-middle uk-width-1-1">
<span class="uk-width-expand uk-text-truncate"
[class.uk-text-small]="smallChip">{{getLabel(formControl.value)}}</span>
<icon name="remove_circle" class="mat-chip-remove" [flex]="true" [ratio]="smallChip?0.8:1"
(click)="resetSearch($event)"></icon>
</span>
</mat-chip>
<div [class.uk-hidden]="formControl.value" class="uk-width-expand uk-position-relative chip-input">
<input #searchInput [formControl]="searchControl" [matAutocomplete]="auto"
[matChipInputFor]="chipList" [matAutocompleteConnectedTo]="origin">
<div *ngIf="placeholder && !searchInput.value" class="placeholder uk-width-1-1"
(click)="searchInput.focus()">{{placeholder}}</div>
</div>
<div class="uk-width-1-1 uk-invisible" matAutocompleteOrigin #origin="matAutocompleteOrigin"></div>
</mat-chip-list>
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="formControl.setValue($event.option.value)"
[class]="panelClass" [panelWidth]="panelWidth">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option.value"
[attr.uk-tooltip]="option.label">
{{option.label}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</div>
</ng-template>
<ng-template [ngIf]="type === 'chips'">
<div [ngClass]="inputClass"
[attr.uk-tooltip]="formControl.disabled?'title: This field is not editable; pos: bottom-left':null"
[class.clickable]="formControl.enabled"
[class.uk-form-danger]="formControl.invalid && searchControl.invalid && searchControl.touched"
(click)="openSelect()">
<mat-form-field class="uk-width-1-1">
<mat-chip-list #chipList>
<mat-chip *ngFor="let chip of formAsArray.controls; let i=index" [selectable]="false"
[removable]="removable" [attr.uk-tooltip]="getLabel(chip.value)">
<span class="uk-flex uk-flex-middle uk-width-1-1">
<span class="uk-width-expand uk-text-truncate"
[class.uk-text-small]="smallChip">{{getLabel(chip.value)}}</span>
<icon name="remove_circle" class="mat-chip-remove" [flex]="true" [ratio]="smallChip?0.8:1"
(click)="removed(i)"></icon>
</span>
</mat-chip>
<div class="uk-width-expand uk-position-relative chip-input">
<input #searchInput style="width: calc(100% - 8px) !important;" [formControl]="searchControl"
[matAutocomplete]="auto"
[matChipInputFor]="chipList" [matAutocompleteConnectedTo]="origin"
[matChipInputAddOnBlur]="addExtraChips && searchControl.value"
(matChipInputTokenEnd)="add($event)">
<div *ngIf="placeholder && !searchControl.value" class="placeholder uk-width-1-1"
(click)="searchInput.focus()">{{placeholder}}</div>
</div>
<div class="uk-width-1-1 uk-invisible" matAutocompleteOrigin #origin="matAutocompleteOrigin"></div>
</mat-chip-list>
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)" [class]="panelClass"
[panelWidth]="panelWidth">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option.value"
[attr.uk-tooltip]="option.label">
{{option.label}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</div>
</ng-template>
<span *ngIf="formControl.invalid && formControl.touched" class="uk-text-danger input-message">
<span *ngIf="formControl.errors.error">{{formControl.errors.error}}</span>
<span
*ngIf="type === 'URL' || type === 'logoURL'">Please provide a valid URL (e.g. https://example.com)</span>
</span>
<span class="uk-text-danger uk-text-small">
<ng-content select="[error]"></ng-content>
</span>
<span *ngIf="formControl.valid" class="uk-text-warning uk-text-small">
<ng-content select="[warning]"></ng-content>
<span *ngIf="!secure">
<span class="uk-text-bold">Note:</span> Prefer urls like "<span class="uk-text-bold">https://</span>example.com/my-secure-image.png"
instead of "<span class="uk-text-bold">http://</span>example.com/my-image.png".
<span class="uk-text-bold">Browsers may not load non secure content.</span>
</span>
</span>
<span class="uk-text-small">
<ng-content select="[note]"></ng-content>
</span>
`,
styleUrls: ['input.component.css']
})
export class InputComponent implements OnInit, OnDestroy, AfterViewInit, OnChanges {
/** Basic information */
@Input('formInput') formControl: AbstractControl;
@Input('type') type: 'text' | 'URL' | 'logoURL' | 'autocomplete' | 'textarea' | 'select' | 'chips' = 'text';
@Input() value: any | any[];
@Output() valueChange = new EventEmitter<any | any[]>();
/** @deprecated */
@Input('label') label: string;
/** Text */
@ViewChild('input') input: ElementRef;
/** Textarea options */
@ViewChild('textArea') textArea: ElementRef;
@Input('rows') rows: number = 3;
/** Select | chips available options */
@Input('options') options: Option[] = [];
/** @deprecated */
@Input('hint') hint = null;
@Input('placeholder') placeholder = '';
@Input() inputClass: string = 'inner';
/** Extra element Right or Left of the input */
/** @deprecated */
@Input() extraLeft: boolean = true;
/** @deprecated */
@Input() gridSmall: boolean = false;
/** @deprecated */
@Input() hideControl: boolean = false;
/** @deprecated */
@Input() flex: 'middle' | 'top' | 'bottom' = 'middle';
/** Icon on the input */
@Input() icon: string = null;
/** @deprecated */
@Input() iconLeft: boolean = false;
/** Chip options */
@Input() removable: boolean = true;
@Input() addExtraChips: boolean = false;
@Input() smallChip: boolean = false;
@Input() panelWidth: number = 300;
@Input() panelClass: string = null;
@Input() showOptionsOnEmpty: boolean = true;
@Input() validators: ValidatorFn[] | ValidatorFn;
@Input() disabled: boolean = false;
@Output() focusEmitter: EventEmitter<boolean> = new EventEmitter<boolean>();
/** LogoUrl information */
public secure: boolean = true;
/** Internal basic information */
public required: boolean = false;
public focused: boolean = false;
public opened: boolean = false;
public properties: EnvProperties = properties;
private initValue: any;
private subscriptions: any[] = [];
/** Chips && Autocomplete*/
public filteredOptions: Observable<Option[]>;
public searchControl: FormControl;
@Input() tooltip: boolean = true;
@ViewChild('inputBox') inputBox: ElementRef;
@ViewChild('optionBox') optionBox: ElementRef;
@ViewChild('searchInput') searchInput: ElementRef;
constructor(private elementRef: ElementRef) {
if (elementRef.nativeElement.hasAttribute('dashboard-input') && this.properties.environment === "development") {
console.warn("'dashboard-input' selector is deprecated; use 'input' instead.");
}
}
@HostListener('document:click', ['$event'])
click(event) {
this.focused = (this.inputBox && this.inputBox.nativeElement.contains(event.target));
if (this.focused) {
if(this.input) {
this.input.nativeElement.focus();
} else if(this.textArea) {
this.textArea.nativeElement.focus();
}
this.open(!this.opened);
} else {
this.open(false);
}
this.focusEmitter.emit(this.focused);
}
ngOnInit() {
if(!this.formControl) {
if(Array.isArray(this.value)) {
this.formControl = new FormArray([]);
this.value.forEach(value => {
this.formAsArray.push(new FormControl(value, this.validators));
});
} else {
this.formControl = new FormControl(this.value);
this.formControl.setValidators(this.validators);
}
if(this.disabled) {
this.formControl.disable();
}
}
}
ngAfterViewInit() {
/** If options are available set max-height base on input-wrapper height */
if(this.options && this.options.length > 1) {
this.elementRef.nativeElement.style.maxHeight = this.inputBox.nativeElement.clientHeight + 'px';
}
this.reset();
}
ngOnChanges(changes: SimpleChanges) {
if (changes.formControl || changes.validators) {
this.reset();
}
}
get formAsControl(): FormControl {
if (this.formControl instanceof FormControl) {
return this.formControl;
} else {
return null;
}
}
get formAsArray(): FormArray {
if (this.formControl instanceof FormArray) {
return this.formControl;
} else {
return null;
}
}
reset() {
this.secure = true;
this.unsubscribe();
this.initValue = HelperFunctions.copy(this.formControl.value);
if (this.type === 'logoURL') {
this.secure = (!this.initValue || this.initValue.includes('https://'));
}
if (this.type === 'chips' || this.type === 'autocomplete') {
if (this.options) {
this.filteredOptions = of(this.options);
this.searchControl = new FormControl('', this.validators);
this.subscriptions.push(this.searchControl.valueChanges.subscribe(value => {
setTimeout(() => {
this.searchInput.nativeElement.focus();
this.searchInput.nativeElement.value = value;
}, 0);
}));
this.filteredOptions = this.searchControl.valueChanges.pipe(startWith(''),
map(option => this.filter(option)));
}
}
if (this.formControl && this.formControl.validator) {
let validator = this.formControl.validator({} as AbstractControl);
this.required = (validator && validator.required);
}
this.subscriptions.push(this.formControl.valueChanges.subscribe(value => {
value = (value === '') ? null : value;
if (this.type === 'logoURL') {
this.secure = (!value || value.includes('https://'));
}
if (this.initValue === value || (this.initValue === '' && value === null)) {
this.formControl.markAsPristine();
}
if (this.searchControl) {
this.searchControl.setValue(null);
}
this.value = this.formControl.value;
this.valueChange.emit(this.value);
}));
if (this.input) {
this.input.nativeElement.disabled = this.formControl.disabled;
}
}
unsubscribe() {
this.subscriptions.forEach(subscription => {
if (subscription instanceof Subscription) {
subscription.unsubscribe();
}
});
}
ngOnDestroy(): void {
this.unsubscribe();
}
stopPropagation() {
event.stopPropagation();
}
removed(index: number) {
this.formAsArray.removeAt(index);
this.formAsArray.markAsDirty();
this.searchControl.setValue('');
this.stopPropagation();
}
selected(event: MatAutocompleteSelectedEvent): void {
this.formAsArray.push(new FormControl(event.option.value));
this.formAsArray.markAsDirty();
this.searchControl.setValue('');
this.stopPropagation();
}
private filter(value: string): Option[] {
let options = this.options;
if (this.type === "chips") {
options = options.filter(option => !this.formAsArray.value.find(value => HelperFunctions.equals(option.value, value)));
}
if ((!value || value.length == 0)) {
return (this.showOptionsOnEmpty) ? options : [];
}
const filterValue = value.toString().toLowerCase();
return options.filter(option => option.label.toLowerCase().indexOf(filterValue) != -1);
}
add(event: MatChipInputEvent) {
if (this.addExtraChips && event.value && this.searchControl.valid) {
this.stopPropagation();
this.formAsArray.push(new FormControl(event.value, this.validators));
this.formAsArray.markAsDirty();
this.searchControl.setValue('');
this.searchInput.nativeElement.value = '';
}
}
getLabel(value: any) {
let option = this.options.find(option => HelperFunctions.equals(option.value, value));
return (option) ? option.label : value;
}
open(value: boolean) {
this.opened = value && this.formControl.enabled;
setTimeout(() => {
this.optionBox.nativeElement.style.overflow = this.opened?'auto':'hidden';
}, this.opened?200:0);
}
resetSearch(event: any) {
event.stopPropagation();
this.searchControl.setValue('');
this.formControl.markAsDirty();
this.formControl.setValue(null);
}
selectOption(option: Option) {
if(this.formAsControl) {
this.formAsControl.setValue(option.value);
}
}
}