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

556 lines
21 KiB
TypeScript

import {
AfterViewInit, ChangeDetectorRef,
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 {Subscription} from "rxjs";
import {EnvProperties} from "../../utils/properties/env-properties";
import {properties} from "../../../../environments/environment";
import {ClickEvent} from "../../utils/click/click-outside-or-esc.directive";
export type InputType = 'text' | 'URL' | 'logoURL' | 'autocomplete' | 'autocomplete_soft' | 'textarea' | 'select' | 'chips';
export interface Option {
icon?: string,
iconClass?: string,
value: any,
label: string,
disabled?: boolean
}
export interface Placeholder {
label: string,
static?: boolean
}
declare var UIkit;
/**
* WARNING! dashboard-input selector is @deprecated, use input instead
*
* Autocomplete soft allows values that are not listed in options list. In order to work as expected
* avoid providing options with different label and value.
*
* */
@Component({
selector: '[dashboard-input], [input]',
template: `
<div *ngIf="formControl" [id]="id">
<div class="input-wrapper" [class.disabled]="formControl.disabled" [class.opened]="opened"
[class.focused]="focused" [ngClass]="inputClass" [class.hint]="hint"
[class.active]="(formAsControl?.value || type === 'select' || formAsArray?.length > 0 || getLabel(formAsControl?.value)) && !focused"
[class.danger]="(formControl.invalid && (formControl.touched || !!searchControl?.touched)) || (!!searchControl?.invalid && !!searchControl?.touched)">
<div #inputBox class="input-box" [class.select]="selectable" click-outside-or-esc
[class.static]="placeholderInfo?.static" (clickOutside)="click($event)">
<div *ngIf="!placeholderInfo?.static && placeholderInfo.label" class="placeholder">
<label>{{placeholderInfo.label}} <sup *ngIf="required">*</sup></label>
</div>
<div class="uk-flex" [class.uk-flex-middle]="type !== 'textarea'"
[attr.uk-tooltip]="(tooltip && !focused && type !== 'chips' && type !== 'textarea')?('title: ' + getLabel(formControl.value) + '; delay: 500; pos: bottom-left'):null">
<ng-template [ngIf]="type === 'text' || type === 'URL' || type === 'logoURL'">
<input #input class="input" [attr.placeholder]="placeholderInfo?.static?placeholderInfo.label:hint"
[formControl]="formAsControl" [class.uk-text-truncate]="!focused">
</ng-template>
<ng-template [ngIf]="type === 'textarea'">
<textarea #textArea class="input" [attr.placeholder]="placeholderInfo?.static?placeholderInfo.label:hint"
[rows]="rows" [formControl]="formAsControl"></textarea>
</ng-template>
<ng-template [ngIf]="type === 'select'">
<ng-container *ngIf="placeholderInfo?.static">
<div *ngIf="!getLabel(formControl.value)"
class="placeholder uk-text-truncate">{{placeholderInfo.label}}</div>
<div *ngIf="getLabel(formControl.value)"
class="input uk-text-truncate">{{getLabel(formControl.value)}}</div>
</ng-container>
<ng-container *ngIf="!placeholderInfo?.static">
<div *ngIf="!getLabel(formControl.value)" class="input uk-text-truncate">No value selected</div>
<div *ngIf="getLabel(formControl.value)"
class="input uk-text-truncate">{{getLabel(formControl.value)}}</div>
</ng-container>
</ng-template>
<ng-template [ngIf]="type === 'autocomplete'">
<input *ngIf="focused" [attr.placeholder]="placeholderInfo?.static?placeholderInfo.label:hint"
#searchInput class="input" [formControl]="searchControl" [class.uk-text-truncate]="!focused">
<div *ngIf="!focused" class="input uk-text-truncate">{{getLabel(formAsControl.value)}}</div>
</ng-template>
<ng-template [ngIf]="type === 'autocomplete_soft'">
<input #input class="input" [attr.placeholder]="placeholderInfo?.static?placeholderInfo.label:hint"
[formControl]="formAsControl" [class.uk-text-truncate]="!focused">
</ng-template>
<ng-template [ngIf]="type === 'chips'">
<div class="uk-grid uk-grid-small uk-grid-row-collapse uk-width-expand" uk-grid>
<div *ngFor="let chip of formAsArray.controls; let i=index" [class.uk-hidden]="!focused && i > 0"
class="chip">
<div class="uk-label uk-label-small uk-flex uk-flex-middle"
[attr.uk-tooltip]="(tooltip)?('title: ' + getLabel(chip.value) + '; delay: 500'):null">
<span class="uk-text-truncate uk-width-expand">{{getLabel(chip.value)}}</span>
<icon (click)="remove(i, $event)" class="uk-link-text uk-margin-small-left clickable" [flex]="true"
name="close" ratio="0.7"></icon>
</div>
</div>
<div *ngIf="searchControl && (focused || formAsArray.length === 0)"
class="uk-width-small uk-flex uk-flex-column uk-flex-center">
<input #searchInput class="input" [class.search]="searchControl.value"
[attr.placeholder]="placeholderInfo?.static?placeholderInfo.label:hint"
[formControl]="searchControl" [class.uk-text-truncate]="!focused">
</div>
<div *ngIf="!focused && formAsArray.length > 1"
class="uk-width-expand uk-flex uk-flex-column uk-flex-center more">
+ {{(formAsArray.length - 1)}} more
</div>
</div>
</ng-template>
<div
*ngIf="(formControl.disabled && disabledIcon) || icon || (type === 'select' && selectArrow) || type === 'autocomplete'"
class="uk-margin-left icon">
<icon *ngIf="formControl.disabled && disabledIcon" [name]="disabledIcon" [flex]="true"></icon>
<ng-template [ngIf]="formControl.enabled">
<icon *ngIf="!searchControl?.value && icon" [name]="icon" [flex]="true"></icon>
<icon *ngIf="!icon && type === 'select' && selectArrow" [name]="selectArrow" [flex]="true"></icon>
<button *ngIf="!!searchControl?.value && type === 'autocomplete'" class="uk-close uk-icon"
(click)="resetSearch($event)">
<icon [flex]="true" name="close"></icon>
</button>
</ng-template>
</div>
</div>
<div class="tools">
<ng-content select="[tools]"></ng-content>
</div>
</div>
</div>
<div class="options uk-dropdown" *ngIf="filteredOptions && filteredOptions.length > 0 && opened" #optionBox
uk-dropdown="pos: bottom-justify; mode: none; offset: 15; boundary-align: true;" [attr.boundary]="'#' + id">
<ul class="uk-nav uk-dropdown-nav">
<li *ngFor="let option of filteredOptions; let i=index"
[class.uk-active]="(formControl.value === option.value) || selectedIndex === i"
[attr.uk-tooltip]="(tooltip)?('title: ' + option.label + '; delay: 500'):null">
<a (click)="selectOption(option, $event)"
[class]="option.disabled ? 'uk-disabled uk-text-muted' : ''">{{option.label}}</a>
</li>
</ul>
</div>
</div>
<span *ngIf="formControl?.invalid && formControl?.touched" class="uk-text-danger">
<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>
`
})
export class InputComponent implements OnInit, OnDestroy, AfterViewInit, OnChanges {
private static INPUT_COUNTER: number = 0;
/** Deprecated options*/
/** @deprecated */
@Input('label') label: string;
/** @deprecated */
@Input() extraLeft: boolean = true;
/** @deprecated */
@Input() gridSmall: boolean = false;
/** @deprecated */
@Input() hideControl: boolean = false;
/** @deprecated */
@Input() flex: 'middle' | 'top' | 'bottom' = 'middle';
/** @deprecated */
@Input() iconLeft: boolean = false;
/** @deprecated */
@Input() removable: boolean = true;
/** @deprecated */
@Input() smallChip: boolean = false;
/** @deprecated */
@Input() panelWidth: number = 300;
/** @deprecated */
@Input() panelClass: string = null;
/** Basic information */
@Input('formInput') formControl: AbstractControl;
@Input('type') type: InputType = 'text';
@Input() validators: ValidatorFn[] | ValidatorFn;
@Input() disabled: boolean = false;
@Input() disabledIcon: string = 'lock';
@Input() value: any | any[];
@Output() valueChange = new EventEmitter<any | any[]>();
@Input() hint: string;
@Input() tooltip: boolean = false;
/** Text */
@ViewChild('input') input: ElementRef;
/** Textarea options */
@ViewChild('textArea') textArea: ElementRef;
@Input('rows') rows: number = 3;
/** Select | Autocomplete | chips available options */
@Input() selectArrow: string = 'arrow_drop_down';
@Input() selectedIndex: number = 0;
@Input() selectable: boolean = false;
/** Chips && Autocomplete*/
public filteredOptions: Option[] = [];
public searchControl: FormControl;
/** Use modifier's class(es) to change view of your Input */
@Input() inputClass: string = 'inner';
/** Icon on the input */
@Input() icon: string = null;
/** Chip options */
@Input() addExtraChips: boolean = false;
@Input() showOptionsOnEmpty: boolean = true;
@Output() focusEmitter: EventEmitter<boolean> = new EventEmitter<boolean>();
/** LogoUrl information */
public secure: boolean = true;
/** Internal basic information */
public id: string;
public placeholderInfo: Placeholder = {label: '', static: true};
public required: boolean = false;
public focused: boolean = false;
public opened: boolean = false;
public properties: EnvProperties = properties;
private initValue: any;
private optionsArray: Option[] = [];
private subscriptions: any[] = [];
@ViewChild('inputBox') inputBox: ElementRef;
@ViewChild('optionBox') optionBox: ElementRef;
@ViewChild('searchInput') searchInput: ElementRef;
@Input()
set placeholder(placeholder: string | Placeholder) {
if (typeof placeholder === 'string') {
this.placeholderInfo = {label: placeholder, static: false};
} else {
if (placeholder.static && (this.type === 'autocomplete' || this.type === 'chips' || this.hint)) {
placeholder.static = false;
console.debug('Static placeholder is not available in this type of input and if hint is available.');
}
this.placeholderInfo = placeholder;
}
}
@Input()
set options(options: (Option | string | number) []) {
this.optionsArray = options.map(option => {
if (typeof option === 'string' || typeof option === 'number') {
return {
label: option.toString(),
value: option
};
} else {
return option;
}
});
if(this.type === "select") {
if (this.optionsArray.length > 7) {
this.type = 'autocomplete';
this.showOptionsOnEmpty = true;
this.icon = this.selectArrow;
}
this.selectable = true;
this.tooltip = true;
}
}
constructor(private elementRef: ElementRef, private cdr: ChangeDetectorRef) {
if (elementRef.nativeElement.hasAttribute('dashboard-input') && this.properties.environment === "development") {
console.warn("'dashboard-input' selector is deprecated; use 'input' instead.");
}
}
@HostListener('window:keydown.arrowUp', ['$event'])
arrowUp(event: KeyboardEvent) {
if (this.opened) {
event.preventDefault();
if (this.selectedIndex > 0) {
this.selectedIndex--;
this.optionBox.nativeElement.scrollBy(0, -34);
}
}
}
@HostListener('window:keydown.arrowDown', ['$event'])
arrowDown(event: KeyboardEvent) {
if (this.opened) {
event.preventDefault();
if (this.selectedIndex < (this.filteredOptions.length - 1)) {
this.selectedIndex++;
this.optionBox.nativeElement.scrollBy(0, 34);
}
}
}
@HostListener('window:keydown.enter', ['$event'])
enter(event: KeyboardEvent) {
if (this.opened) {
event.preventDefault();
if (this.filteredOptions[this.selectedIndex]) {
this.selectOption(this.filteredOptions[this.selectedIndex], event);
this.open(false);
}
}
}
click(event: ClickEvent) {
this.focus(!event.clicked, event);
}
ngOnInit() {
InputComponent.INPUT_COUNTER++;
this.id = 'input-' + InputComponent.INPUT_COUNTER;
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() {
this.reset();
}
ngOnChanges(changes: SimpleChanges) {
if (this.formControl) {
if (changes.value) {
this.formControl.setValue(this.value);
}
if (changes.formControl || changes.validators || changes.options) {
this.reset();
}
if (changes.disabled) {
if (this.disabled) {
this.formControl.disable();
} else {
this.formControl.enable();
}
}
}
}
ngOnDestroy(): void {
this.unsubscribe();
}
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.optionsArray) {
this.filteredOptions = this.filter('');
this.cdr.detectChanges();
}
if (this.type === 'chips' || this.type === 'autocomplete') {
if (!this.searchControl) {
this.searchControl = new FormControl('', this.validators);
}
this.subscriptions.push(this.searchControl.valueChanges.subscribe(value => {
this.filteredOptions = this.filter(value);
this.cdr.detectChanges();
if (this.focused) {
this.open(true);
setTimeout(() => {
this.searchInput.nativeElement.focus();
this.searchInput.nativeElement.value = value;
}, 0);
}
}));
}
if (this.formControl.validator) {
let validator = this.formControl.validator({} as AbstractControl);
this.required = (validator && validator.required);
}
this.subscriptions.push(this.formControl.valueChanges.subscribe(value => {
if (this.formControl.enabled) {
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();
} else {
this.formControl.markAsDirty();
}
if (this.type === 'autocomplete_soft') {
this.filteredOptions = this.filter(value);
this.cdr.detectChanges();
if (this.focused) {
this.open(true);
}
}
if ((this.value && value && this.value !== value) || (!this.value && value) || this.value && !value) {
this.valueChange.emit(this.formControl.value);
}
}
}));
if (this.input) {
this.input.nativeElement.disabled = this.formControl.disabled;
}
}
unsubscribe() {
this.subscriptions.forEach(subscription => {
if (subscription instanceof Subscription) {
subscription.unsubscribe();
}
});
}
remove(index: number, event) {
if (this.focused) {
this.formAsArray.removeAt(index);
this.formAsArray.markAsDirty();
this.focus(true);
this.searchControl.setValue('');
event.stopPropagation();
}
}
private filter(value: string): Option[] {
let options = this.optionsArray;
if (this.type === "chips") {
options = options.filter(option => !this.formAsArray.value.find(value => HelperFunctions.equals(option.value, value)));
}
if ((!value || value.length == 0)) {
this.selectedIndex = 0;
return (this.showOptionsOnEmpty) ? options : [];
}
const filterValue = value.toString().toLowerCase();
options = options.filter(option => option.label.toLowerCase().indexOf(filterValue) != -1);
this.selectedIndex = options.findIndex(option => option.value === this.formControl.value);
if (this.selectedIndex === -1) {
this.selectedIndex = 0;
}
return options;
}
add(event) {
if (this.addExtraChips && this.searchControl.value && this.searchControl.valid) {
if (event) {
event.stopPropagation();
}
this.formAsArray.push(new FormControl(this.searchControl.value, this.validators));
this.formAsArray.markAsDirty();
}
this.searchControl.setValue('');
}
getLabel(value: any) {
let option = this.optionsArray.find(option => HelperFunctions.equals(option.value, value));
return (option) ? option.label : (value);
}
focus(value: boolean, event = null) {
if (this.focused) {
this.formControl.markAsTouched();
}
this.focused = value;
this.cdr.detectChanges();
if (this.focused) {
if (this.input) {
this.input.nativeElement.focus();
} else if (this.textArea) {
this.textArea.nativeElement.focus();
} else if (this.searchInput) {
this.searchInput.nativeElement.focus();
}
if (this.selectArrow) {
this.open(!this.opened);
} else if (this.type !== 'autocomplete' || this.showOptionsOnEmpty || !this.formControl.value) {
this.open(true);
}
} else {
this.open(false);
if (this.input) {
this.input.nativeElement.blur();
} else if (this.textArea) {
this.textArea.nativeElement.blur();
} else if (this.searchInput) {
this.searchInput.nativeElement.blur();
}
if (this.searchControl) {
this.add(event);
}
}
this.focusEmitter.emit(this.focused);
}
open(value: boolean) {
this.opened = value && this.formControl.enabled;
this.cdr.detectChanges();
if (this.optionBox && this.opened) {
this.selectedIndex = this.filteredOptions.findIndex(option => option.value === this.formControl.value);
if (this.selectedIndex === -1) {
this.selectedIndex = 0;
}
UIkit.dropdown(this.optionBox.nativeElement).show();
} else {
if (this.optionBox) {
UIkit.dropdown(this.optionBox.nativeElement).hide();
this.focused = false;
}
}
}
resetSearch(event: any) {
event.stopPropagation();
this.searchControl.setValue('');
}
selectOption(option: Option, event) {
if (this.formControl.enabled) {
if (this.formAsControl) {
this.formAsControl.setValue(option.value);
} else if (this.formAsArray) {
this.formAsArray.push(new FormControl(option.value));
this.formAsArray.markAsDirty();
event.stopPropagation();
this.focus(true);
this.searchControl.setValue('');
}
}
}
}