import { Component, OnInit, Input, ViewChild, AfterViewInit } from '@angular/core'; import { FormControl, UntypedFormControl, FormsModule, ReactiveFormsModule } from '@angular/forms'; import {Observable} from 'rxjs'; import {startWith, map} from 'rxjs/operators'; import { MatAutocompleteTrigger, MatAutocomplete } from '@angular/material/autocomplete'; import { PlotService, PlotType, AutocompleteResult, Suggestion, ResultMode } from '../plot.service'; import { MatInput } from '@angular/material/input'; import { NgFor, AsyncPipe } from '@angular/common'; import { MatOption } from '@angular/material/core'; @Component({ selector: 'pdb-query-autocomplete', templateUrl: './query-autocomplete.component.html', styleUrls: ['./query-autocomplete.component.scss'], standalone: true, imports: [MatInput, FormsModule, MatAutocompleteTrigger, ReactiveFormsModule, MatAutocomplete, NgFor, MatOption, AsyncPipe] }) export class QueryAutocompleteComponent implements OnInit { queryField = new FormControl(new Suggestion("","",0)); suggestions = new UntypedFormControl(); filteredSuggestions!: Observable; query : string = ""; suggestionFetcherEnabled = true; @ViewChild(MatAutocompleteTrigger) autocomplete!: MatAutocompleteTrigger; constructor(private plotService: PlotService) { } ngOnInit() { this.query = ""; this.queryField.valueChanges.subscribe((value) =>{ if (value != null) { if (typeof value == "string") { this.query = value; }else{ this.query = value.newQuery; const el : HTMLInputElement = document.getElementById('query-autocomplete-input'); el.selectionStart=value.newCaretPosition; el.selectionEnd=value.newCaretPosition; } if (this.suggestionFetcherEnabled) { this.fetchSuggestions(value.newCaretPosition); } } }); this.filteredSuggestions = this.suggestions.valueChanges.pipe( map(value => value) ); } onKey(event: any) { //console.log(event); if (event.key == "ArrowDown" || event.key == "ArrowUp"){ return; } const caretIndex = event.srcElement.selectionStart +1; this.fetchSuggestions(caretIndex); } fetchSuggestions(caretIndex: number){ const that = this; const query = typeof this.queryField.value == "string" ? this.queryField.value : this.queryField.value!.newQuery; this.plotService .autocomplete(query, caretIndex, ResultMode.CUT_AT_DOT) .subscribe({ next: (data: AutocompleteResult) => { that.suggestions.setValue(data.proposals); that.autocomplete.openPanel(); }, error: (error:any) => console.log(error) } ); } displaySuggestion(suggestion?: Suggestion): string { return suggestion ? suggestion.newQuery : ''; } }