import {
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
HostListener,
Input,
OnInit,
Output,
ViewChild
} from '@angular/core';
import {AbstractControl} from '@angular/forms';
import {MatAutocompleteTrigger} from '@angular/material/autocomplete';
import {InputComponent} from "../input/input.component";
import {ClickEvent} from "../../utils/click/click-outside-or-esc.directive";
@Component({
selector: '[search-input]',
template: `
`
})
export class SearchInputComponent implements OnInit {
@Input() disabled: boolean = false;
@Input() searchInputClass: string = 'inner';
@Input() iconPosition: 'left' | 'right' = 'right';
@Input() searchControl: AbstractControl;
@Input() value: string;
@Output() valueChange = new EventEmitter();
@Input() options: string[] = [];
@Input() placeholder: string;
@Input() expandable: boolean = false;
@Output() searchEmitter: EventEmitter = new EventEmitter();
@ViewChild('searchInput') searchInput: ElementRef;
@ViewChild('input') input: InputComponent;
public expanded: boolean = true;
public initialized: boolean = false;
constructor(private cdr: ChangeDetectorRef) {
}
@HostListener('window:keydown.enter', ['$event'])
enter(event: KeyboardEvent) {
if(this.input.focused && !this.input.opened) {
event.preventDefault();
this.search(event);
} else {
this.input.enter(event);
event.stopPropagation();
this.search(event);
}
}
click(event: ClickEvent) {
if(this.expandable && !this.disabled) {
this.expand(!event.clicked);
}
}
ngOnInit() {
this.expanded = !this.expandable;
this.initialized = true;
}
expand(value: boolean) {
this.expanded = value;
this.cdr.detectChanges();
if(this.expanded) {
this.input.focus(true);
}
}
public search(event) {
if(!this.disabled) {
this.searchEmitter.emit();
if(this.expandable) {
this.expand(!this.expanded);
}
event.stopPropagation();
}
}
public reset() {
if(this.searchControl){
this.searchControl.setValue('');
} else {
this.valueChange.emit('');
}
setTimeout(() => {
this.input.focus(true);
}, 100)
}
get hidden(): boolean {
return !this.expanded && (!this.searchControl?.value && !this.value);
}
/** @deprecated all*/
@Input()
showSearch: boolean = true;
@Input()
control: AbstractControl;
@Input()
loading: boolean = false;
@Input()
selected: any;
@Input()
list: any = null;
@Input()
colorClass: string = 'portal-color';
@Input()
bordered: boolean = false;
@Input()
toggleTitle: string = 'search';
@ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger;
@Output()
resetEmitter: EventEmitter = new EventEmitter();
@Output()
closeEmitter: EventEmitter = new EventEmitter();
/** @deprecated*/
closeSearch() {
}
}