File

projects/netgrif-components-core/src/lib/search/models/category/autocomplete-category.ts

Description

Represents a Search Category whose values are a known set. The value selection is done with an autocomplete field.

Extends

Category

Implements

AutocompleteOptions

Index

Properties
Methods
Accessors

Constructor

Protected constructor(pfqlKeywords: Array, allowedOperators: Array<Operator<any>>, translationPath: string, log: LoggerService, operatorService: OperatorService, resourceTypePrefix: ResourceTypeQueryPrefix)
Parameters :
Name Type Optional
pfqlKeywords Array<string> No
allowedOperators Array<Operator<any>> No
translationPath string No
log LoggerService No
operatorService OperatorService No
resourceTypePrefix ResourceTypeQueryPrefix No

Properties

Protected _options$
Type : BehaviorSubject<Array<SearchAutocompleteOption<Array<T>>>>
Protected _optionsMap
Type : Map<string | Array<T>>

Autocomplete categories usually require a map to represent mapping of display names of their options to objects that are needed to construct their queries.

You are not required to use this map when you implement your own Category, but it comes with helpful functions and might save you some time.

See options() and addToMap().

Protected _generatedPredicate$
Type : BehaviorSubject<ElementaryPredicate | undefined>
Inherited from Category
Defined in Category:70

Emit a new Predicate if the Category is in a state that it can be created. Emits undefined if the Category is not in such state.

Protected _operandsFormControls
Type : Array<FormControl>
Inherited from Category
Defined in Category:49

Stores the FormControl objects that are pushed into the observable when the number of operands changes.

Protected _operandsFormControls$
Type : ReplaySubject<Array | undefined>
Inherited from Category
Defined in Category:54

Contains the FormControl objects that can be used to input search arguments.

Protected Readonly _OPERATOR_INPUT
Type : ConfigurationInput
Inherited from Category
Defined in Category:75

Utility variable that can be used as value for the configurationInputs$ Observable.

Protected _operatorFormControl
Type : FormControl
Inherited from Category
Defined in Category:44

Contains the FormControl object that is used to drive the operator selection.

The category can subscribe to it if it wishes to react to the selection change by the user.

Protected _operatorTemplate$
Type : BehaviorSubject<Array | undefined>
Inherited from Category
Defined in Category:59

Contains the operator template parts that make up the operands GUI.

Protected _trackByIdGenerator
Type : IncrementingCounter
Inherited from Category
Defined in Category:64

Generates IDs for template parts supplied to ng for.

Public Readonly translationPath
Type : string
Inherited from Category
Defined in Category:91
path to the translation string

Methods

Protected addToMap
addToMap(key: any, value: T)

Adds a new entry or pushes value into an existing entry. When a new entry is created, it is created as an Array of one element.

Parameters :
Name Type Optional Description
key any No

where in the map should the value be added

value T No

the value that should be added to the map

Returns : void
Protected Abstract createOptions
createOptions()

Populates the _options field with options for this category.

You must call this method yourself in an appropriate place of Category creation.

Returns : void
Protected createSearchAutocompleteOption
createSearchAutocompleteOption(text: string, value: Array)
Parameters :
Name Type Optional
text string No
value Array<T> No
Returns : SearchAutocompleteOption<Array<T>>
Protected deserializeOperandValue
deserializeOperandValue(text)
Inherited from Category
Defined in Category:171

This method throws na error if the serialized value is not one of the autocomplete options.

Parameters :
Name Optional Description
text No

the serialized output of the serializeOperandValue() method

Returns : Observable<any>

the deserialized value, that can be set as FormControl value

This method throws na error if the serialized value is not one of the autocomplete options.

destroy
destroy()
Inherited from Category
Defined in Category:51
Returns : void
Public filterOptions
filterOptions(userInput: Observable)

The function that is used to filter shown options in the autocomplete field.

By default the options that start with the input string are returned (case insensitive).

By default a new value is emitted, whenever either the user input or the base set of options changes.

Parameters :
Name Type Optional Description
userInput Observable<string | SearchAutocompleteOption> No

user search input

Returns : Observable<Array<SearchAutocompleteOption<Array<T>>>>

options that satisfy the autocomplete condition

Protected isOperandValueSelected
isOperandValueSelected(newValue: SearchAutocompleteOption> | string)
Inherited from Category
Defined in Category:138
Parameters :
Name Type Optional
newValue SearchAutocompleteOption<Array<T>> | string No
Returns : boolean
Protected serializeOperandValue
serializeOperandValue(valueFormControl: FormControl)
Inherited from Category
Defined in Category:161
Parameters :
Name Type Optional
valueFormControl FormControl No
Protected transformCategoryValue
transformCategoryValue(value: SearchAutocompleteOption> | string)
Inherited from Category
Defined in Category:154

Performs a transformation of the FormControl value before passing it into the selected Operator for query generation. It is mostly useful only for AutocompleteCategories, where the selected value of the FormControl is an object.

The default AutocompleteCategory implementation returns the SearchAutocompleteOption value attribute.

Parameters :
Name Type Optional Description
value SearchAutocompleteOption<Array<T>> | string No

the FormControlValue

Returns : Array | string

the value used for query generation

Protected updateOptions
updateOptions()

Publishes a new value in the _options$ Subject generated from the _optionsMap.

The default implementation iterates trough the _optionsMap and creates options with the keys as text and values as value.

Returns : void
Public clearOperatorSelection
clearOperatorSelection()
Inherited from Category
Defined in Category:391

Deselects the currently selected operator (if any)

Returns : void
Protected Abstract createConfigurationFilterTextSegments
createConfigurationFilterTextSegments()
Inherited from Category
Defined in Category:570

an Array containing text segments representing the configuration inputs of this category

Public createFilterTextSegments
createFilterTextSegments()
Inherited from Category
Defined in Category:556

an Array containing text segments representing the content of the predicate generated by this category

Protected createOperandFilterTextSegment
createOperandFilterTextSegment(operandIndex: number)
Inherited from Category
Defined in Category:592
Parameters :
Name Type Optional
operandIndex number No
Returns : FilterTextSegment

filter text segment representing the operand value at the specified index

Protected createOperatorFilterTextSegments
createOperatorFilterTextSegments()
Inherited from Category
Defined in Category:575

an Array containing text segments representing the operators with operands of this category

Public Abstract duplicate
duplicate()
Inherited from Category
Defined in Category:401

Creates a duplicate of the current category object. Note that a duplicate is NOT a clone. The state of the returned category is not necessarily the same as the state of this category.

Returns : Category<T>

a category instance of the same type as this category in its initial state.

Public generatePredicate
generatePredicate(userInput: Array)
Inherited from Category
Defined in Category:356

Calls the generateQuery method and creates an ElementaryPredicate with the result. arity of the selected Operator.

Parameters :
Name Type Optional Description
userInput Array<T> No

values entered by the user. The length of the array should match the arity of the selected Operator.

Predicate with {@link Query} generated by this object's [generateQuery]{@link Category.generateQuery} method

Protected generateQuery
generateQuery(userInput: Array)
Inherited from Category
Defined in Category:342

Calls the createQuery method on the selected Operator.

Throws an Error if no Operator is selected.

Override this method if the query should be generated in some other way. arity of the selected Operator.

Parameters :
Name Type Optional Description
userInput Array<T> No

values entered by the user. The length of the array should match the arity of the selected Operator.

Returns : Query

the Query generated by the selected Operator

Protected initializeCategory
initializeCategory()
Inherited from Category
Defined in Category:448

This method is calle in the constructor. Apart from calling this method, the constructor only creates instances to fill the protected fields of this class.

The default implementation manages creation of operand FormControl instances and manages subscriptions to them.

You can override this method to change the initialization of your category without having to rewrite the base constructor from scratch.

Returns : void
Public isOperatorSelected
isOperatorSelected()
Inherited from Category
Defined in Category:384
Returns : boolean

whether an operator is currently selected or not.

Protected isSelectedOperator
isSelectedOperator(operatorClass: Type)
Inherited from Category
Defined in Category:617

Checks for selected operator

Parameters :
Name Type Optional Description
operatorClass Type<any> No

the operator to be checked

Returns : boolean

boolean of the statement

Public loadFromPfqlExpression
loadFromPfqlExpression(expression: SimpleExpression)
Inherited from Category
Defined in Category:412

Loads the category state from a PFQL expression.

This method attempts to select an operator based on the expression's operator type and then sets the operands from the expression's operand values. If the operator cannot be selected, the method returns immediately.

Parameters :
Name Type Optional Description
expression SimpleExpression No

the PFQL simple expression containing the operator and operand values

Returns : Observable<void>

an Observable that emits void when the loading is complete

Protected operandValueChanges
operandValueChanges(operandIndex: number)
Inherited from Category
Defined in Category:487

The method that is (by default) called whenever an operand FormControl changes its value.

Parameters :
Name Type Optional Description
operandIndex number No

the index of the operand that changed its value

Returns : void
Public reset
reset()
Inherited from Category
Defined in Category:325

Resets the state of the Category, deselecting any selected category and removing other state information if the Category defines them.

This method can be used to reset the state of the category after each predicate constructed, effectively turning the category instance into a predicate builder.

Returns : void
Public selectDefaultOperator
selectDefaultOperator()
Inherited from Category
Defined in Category:367

Selects the default operator that should be used for query generation, when no Operator selection is provided to the user.

The default implementation selects the first operator in the _allowedOperators array.

See selectOperator() for more information.

Returns : void
Public selectOperator
selectOperator(operatorIndex: number)
Inherited from Category
Defined in Category:286

Changes the state of the Category. Category can create queries when an Operator is selected.

This method is useful if you want to use the Category class as predicate builder.

should be selected

Parameters :
Name Type Optional Description
operatorIndex number No

index in the allowedOperators array of the Operator that should be selected

Returns : void
Protected selectOperatorFromPfqlExpression
selectOperatorFromPfqlExpression(expression: SimpleExpression)
Inherited from Category
Defined in Category:429

Selects an operator from the category's allowed operators based on the PFQL expression's operator type.

This method searches for an operator in the allowed operators array that matches the type specified in the PFQL expression. If a matching operator is found, it is selected. If no match is found, an error is logged.

Parameters :
Name Type Optional Description
expression SimpleExpression No

the PFQL simple expression containing the operator type to select

Returns : boolean

true if a matching operator was found and selected, false otherwise

Abstract serializeClass
[object Object],[object Object],[object Object]
serializeClass()
Inherited from Category
Defined in Category:515

the category class in a serializable form

Public setOperands
setOperands(userInput: Array)
Inherited from Category
Defined in Category:304

Changes the state of the Category and generates a query if all necessary operands were set.

If you are using the category as a builder. Consider using the generatePredicate() method instead.

arity of the selected Operator.

Parameters :
Name Type Optional Description
userInput Array<T> No

values entered by the user. The length of the array should match the arity of the selected Operator.

Returns : void

Accessors

options
getoptions()

Options the user can select from for this search Category.

Returns : Array<SearchAutocompleteOption<Array<T>>>
options$
getoptions$()

An Observable of the options the user can select from for this search Category.

The Observable is updated when the base set of options changes, not when the available options are filtered, see filterOptions().

The Observable initially contains an empty array and the options may appear at a later point in time (based on the concrete AutocompleteCategory subclass implementation)

Returns : Observable<Array<SearchAutocompleteOption<Array<T>>>>
import {Category} from './category';
import {Operator} from '../operator/operator';
import {LoggerService} from '../../../logger/services/logger.service';
import {SearchInputType} from './search-input-type';
import {SearchAutocompleteOption} from './search-autocomplete-option';
import {BehaviorSubject, combineLatest, Observable, ReplaySubject} from 'rxjs';
import {filter, map, startWith, take} from 'rxjs/operators';
import {AutocompleteOptions} from './autocomplete-options';
import {FormControl} from '@angular/forms';
import {OperatorService} from '../../operator-service/operator.service';
import {ResourceTypeQueryPrefix} from "./resource-type-query-prefix";

/**
 * Represents a Search Category whose values are a known set. The value selection is done with an autocomplete field.
 *
 * @typeparam T type of the object that the autocomplete option values use and in turn is used to generate queries
 */
export abstract class AutocompleteCategory<T> extends Category<Array<T> | string> implements AutocompleteOptions {

    /**
     * Autocomplete categories usually require a map to represent mapping of display names
     * of their options to objects that are needed to construct their queries.
     *
     * You are not required to use this map when you implement your own Category,
     * but it comes with helpful functions and might save you some time.
     *
     * See [options()]{@link AutocompleteCategory#options} and [addToMap()]{@link AutocompleteCategory#addToMap}.
     */
    protected _optionsMap: Map<string, Array<T>>;

    protected _options$: BehaviorSubject<Array<SearchAutocompleteOption<Array<T>>>>;

    private readonly _timeoutId: number;

    protected constructor(pfqlKeywords: Array<string>,
                          allowedOperators: Array<Operator<any>>,
                          translationPath: string,
                          log: LoggerService,
                          operatorService: OperatorService,
                          resourceTypePrefix: ResourceTypeQueryPrefix) {
        super(pfqlKeywords, allowedOperators, translationPath, SearchInputType.AUTOCOMPLETE, log, operatorService, resourceTypePrefix);
        this._optionsMap = new Map<string, Array<T>>();
        this._options$ = new BehaviorSubject<Array<SearchAutocompleteOption<Array<T>>>>([]);
        // timeout is used to bypass javascript object initialization bugs.
        // Injected properties of inherited classes were not set in the function call.
        this._timeoutId = setTimeout(() => {
            this.createOptions();
        });
    }

    destroy() {
        super.destroy();
        this._options$.complete();
        clearTimeout(this._timeoutId);
    }

    /**
     * Options the user can select from for this search Category.
     */
    public get options(): Array<SearchAutocompleteOption<Array<T>>> {
        return this._options$.value;
    }

    /**
     * An Observable of the options the user can select from for this search Category.
     *
     * The Observable is updated when the base set of options changes, not when the available options are
     * filtered, see [filterOptions()]{@link AutocompleteCategory#filterOptions}.
     *
     * The Observable initially contains an empty array and the options may appear at a later point in time
     * (based on the concrete AutocompleteCategory subclass implementation)
     */
    public get options$(): Observable<Array<SearchAutocompleteOption<Array<T>>>> {
        return this._options$.asObservable();
    }

    /**
     * Publishes a new value in the [_options$]{@link AutocompleteCategory#_options$} Subject generated from the
     * [_optionsMap]{@link AutocompleteCategory#_optionsMap}.
     *
     * The default implementation iterates trough the [_optionsMap]{@link AutocompleteCategory#_optionsMap} and
     * creates options with the keys as [text]{@link SearchAutocompleteOption#text}
     * and values as [value]{@link SearchAutocompleteOption#value}.
     */
    protected updateOptions(): void {
        const result = [];
        for (const entry of this._optionsMap.entries()) {
            result.push(this.createSearchAutocompleteOption(entry[0], entry[1]));
        }
        this._options$.next(result);
    }

    /**
     * Populates the [_options]{@link AutocompleteCategory#_options} field with options for this category.
     *
     * You must call this method yourself in an appropriate place of Category creation.
     */
    protected abstract createOptions(): void;

    /**
     * The function that is used to filter shown options in the autocomplete field.
     *
     * By default the options that start with the input string are returned (case insensitive).
     *
     * By default a new value is emitted, whenever either the user input or the base set of options changes.
     * @param userInput user search input
     * @returns options that satisfy the autocomplete condition
     */
    public filterOptions(userInput: Observable<string | SearchAutocompleteOption<Array<T>>>):
        Observable<Array<SearchAutocompleteOption<Array<T>>>> {
        return combineLatest([
            userInput.pipe(
                startWith(''),
                map(input => typeof input === 'string' ? input.toLocaleLowerCase() : input.text)
            ),
            this.options$
        ]).pipe(
            map(([input, options]) => {
                return options.filter(o => o.text.toLocaleLowerCase().startsWith(input));
            })
        );
    }

    /**
     * Adds a new entry or pushes value into an existing entry.
     * When a new entry is created, it is created as an Array of one element.
     * @param key where in the map should the value be added
     * @param value the value that should be added to the map
     */
    protected addToMap(key: any, value: T): void {
        if (this._optionsMap.has(key)) {
            this._optionsMap.get(key).push(value);
        } else {
            this._optionsMap.set(key, [value]);
        }
    }

    protected isOperandValueSelected(newValue: SearchAutocompleteOption<Array<T>> | string): boolean {
        if (this.inputType === SearchInputType.TEXT) {
            return !!newValue;
        }

        return !(!newValue || typeof newValue === 'string');
    }

    /**
     * Performs a transformation of the `FormControl` value before passing it into the selected `Operator` for query generation.
     * It is mostly useful only for AutocompleteCategories, where the selected value of the FormControl is an object.
     *
     * The default AutocompleteCategory implementation returns the {@link SearchAutocompleteOption} `value` attribute.
     * @param value the FormControlValue
     * @returns the value used for query generation
     */
    protected transformCategoryValue(value: SearchAutocompleteOption<Array<T>> | string): Array<T> | string {
        if (this.inputType === SearchInputType.TEXT) {
            return value as string;
        }
        return (value as SearchAutocompleteOption<Array<T>>).value;
    }

    protected serializeOperandValue(valueFormControl: FormControl): unknown {
        return (valueFormControl.value as SearchAutocompleteOption<unknown>).text;
    }

    /**
     * @param text the serialized output of the [serializeOperandValue()]{@link Category#serializeOperandValue} method
     * @returns the deserialized value, that can be set as FormControl value
     *
     * This method throws na error if the serialized value is not one of the autocomplete options.
     */
    protected deserializeOperandValue(text: unknown): Observable<any> {
        const result$ = new ReplaySubject(1);
        this.options$.pipe(filter(o => o.length > 0), take(1)).subscribe(() => {
            const value = this._optionsMap.get(text as string);
            if (value === undefined) {
                throw new Error(`The serialized autocomplete value '${value
                }' does not map to any autocomplete options and cannot be deserialized!`);
            }
            result$.next(this.createSearchAutocompleteOption(text as string, value));
            result$.complete();
        });
        return result$.asObservable();
    }

    protected createSearchAutocompleteOption(text: string, value: Array<T>): SearchAutocompleteOption<Array<T>> {
        return {text, value};
    }
}

results matching ""

    No results matching ""