import React from 'react' ; import { debounce } from 'lodash' ; import { withOpenSearchDashboards , OpenSearchDashboardsReactContextValue , } from '../../../../../opensearch_dashboards_react/public' ; import { IDataPluginServices , IIndexPattern , IFieldType } from '../../..' ; import { UI_SETTINGS } from '../../../../common' ; export interface PhraseSuggestorProps { opensearchDashboards : OpenSearchDashboardsReactContextValue < IDataPluginServices > ; indexPattern : IIndexPattern ; field ? : IFieldType ; } export interface PhraseSuggestorState { suggestions : string [ ] ; isLoading : boolean ; } /**
 * Since both "phrase" and "phrases" filter inputs suggest values (if enabled and the field is
 * aggregatable), we pull out the common logic for requesting suggestions into this component
 * which both of them extend.
 */ export class PhraseSuggestorUI < T extends PhraseSuggestorProps > extends React . Component < T , PhraseSuggestorState > { private services = this . props . opensearchDashboards . services ; private abortController ? : AbortController ; public state : PhraseSuggestorState = { suggestions : [ ] , isLoading : false , } ; public componentDidMount ( ) { this . updateSuggestions ( ) ; } public componentWillUnmount ( ) { if ( this . abortController ) this . abortController . abort ( ) ; } protected isSuggestingValues ( ) { const shouldSuggestValues = this . services . uiSettings . get ( UI_SETTINGS . FILTERS_EDITOR_SUGGEST_VALUES ) ; const { field } = this . props ; return shouldSuggestValues && field && field . aggregatable && field . type === 'string' ; } protected onSearchChange = ( value ) => { this . updateSuggestions ( `${ value }` ) ; } ; protected updateSuggestions = debounce ( async ( query = '' ) => { if ( this . abortController ) this . abortController . abort ( ) ; this . abortController = new AbortController ( ) ; const { indexPattern , field } = this . props as PhraseSuggestorProps ; if ( ! field || ! this . isSuggestingValues ( ) ) { return ; } this . setState ( { isLoading : true } ) ; const suggestions = await this . services . data . autocomplete . getValueSuggestions ( { indexPattern , field , query , signal : this . abortController . signal , } ) ; this . setState ( { suggestions , isLoading : false } ) ; } , 500 ) ; } export const PhraseSuggestor = withOpenSearchDashboards ( PhraseSuggestorUI as any ) ;