import { Component, EventEmitter, Input, Output, TemplateRef, } from '@angular/core';
import { FormControl, UntypedFormControl } from '@angular/forms';
import { fuzzySort } from '@aztrix/helpers';
import { BehaviorSubject, combineLatest, of } from 'rxjs';
import { distinctUntilChanged, startWith, switchMap, tap } from 'rxjs/operators';
import * as i0 from "@angular/core";
import * as i1 from "@angular/common";
import * as i2 from "@angular/material/form-field";
import * as i3 from "@angular/material/select";
import * as i4 from "@angular/material/core";
import * as i5 from "ngx-mat-select-search";
import * as i6 from "@angular/forms";
import * as i7 from "@aztrix/components/button";
import * as i8 from "@aztrix/icons";
import * as i9 from "@angular/material/chips";
import * as i10 from "@aztrix/translate";
import * as i11 from "./pipes/option-by-value.pipe";
import * as i12 from "./pipes/value-by-option.pipe";
export class SelectSearchComponent {
    constructor() {
        this.form = new FormControl();
        this.multiple = false;
        this.canAddNew = false;
        this.required = false;
        this.appearance = 'outline';
        this.disabled = false;
        this.addNewValue = new EventEmitter();
        this.formFilterControl = new UntypedFormControl('');
        this.options$ = new BehaviorSubject([]);
        this.searchedOptions = [];
        this.searchResults$ = combineLatest([
            this.options$,
            this.formFilterControl.valueChanges.pipe(startWith('')),
        ]).pipe(distinctUntilChanged(), switchMap(([options, query]) => {
            if (this.searchCallback$) {
                return this.searchCallback$(options, query);
            }
            else {
                return of(fuzzySort(options, query, this.keys || []));
            }
        }), tap((options) => {
            if (!this.options?.length) {
                this.searchedOptions = options;
                if (!this.searchedOptions.find((o) => {
                    if (this.valueCallback) {
                        return this.valueCallback(o) === this.form?.value;
                    }
                    else {
                        return o === this.form?.value;
                    }
                })) {
                    this.form?.reset();
                }
            }
        }));
    }
    ngOnChanges(changes) {
        if (changes.options && this.options && Array.isArray(this.options)) {
            this.options$.next(this.options);
            this.searchedOptions = this.options;
        }
    }
    removeSelection(value) {
        if (Array.isArray(this.form.value)) {
            const selectedOptions = this.form.value;
            const newOptions = selectedOptions.filter((option) => option !== value);
            this.form.setValue(newOptions);
        }
        else {
            this.form.setValue(undefined);
        }
    }
    clearValue() {
        this.form.setValue(null);
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: SelectSearchComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "17.3.12", type: SelectSearchComponent, selector: "ax-select-search", inputs: { form: "form", options: "options", placeholder: "placeholder", optionTemplate: "optionTemplate", selectedValueTemplate: "selectedValueTemplate", multiple: "multiple", label: "label", keys: "keys", canAddNew: "canAddNew", required: "required", appearance: "appearance", errorsTemplate: "errorsTemplate", prefixTemplate: "prefixTemplate", disabled: "disabled", valueCallback: "valueCallback", searchCallback$: "searchCallback$" }, outputs: { addNewValue: "addNewValue" }, usesOnChanges: true, ngImport: i0, template: "<mat-form-field\n  class=\"c-input\"\n  appearance=\"outline\"\n  [ngClass]=\"{'remove-subtext': !errorsTemplate}\"\n  [appearance]=\"appearance\"\n>\n  <mat-label *ngIf=\"label\">{{ label }}</mat-label>\n  <mat-select\n    [formControl]=\"form\"\n    [placeholder]=\"placeholder\"\n    [multiple]=\"multiple\"\n    [disabled]=\"disabled\"\n  >\n    <mat-select-trigger>\n      <ng-container *ngIf=\"multiple\">\n        <ng-container *ngTemplateOutlet=\"chipsList\"></ng-container>\n      </ng-container>\n      <ng-container *ngIf=\"!multiple\">\n        <ng-container\n          *ngTemplateOutlet=\"\n            selectedValueTemplate;\n            context: {$implicit: form?.value | optionByValue: searchedOptions : valueCallback}\n          \"\n        ></ng-container>\n      </ng-container>\n    </mat-select-trigger>\n    <mat-option *ngIf=\"(keys && keys.length) || searchCallback$\">\n      <ngx-mat-select-search\n        [formControl]=\"formFilterControl\"\n        [placeholderLabel]=\"'label.search' | translate\"\n        [noEntriesFoundLabel]=\"'search.results.absence' | translate\"\n      >\n        <ax-icon class=\"icon\" name=\"close\" ngxMatSelectSearchClear></ax-icon>\n      </ngx-mat-select-search>\n    </mat-option>\n    <mat-option *ngIf=\"!required\" [value]=\"null\" (click)=\"removeSelection()\">\n      <div class=\"option-wrapper\">\n        {{ 'label.none' | translate }}\n      </div>\n    </mat-option>\n    <mat-option\n      class=\"add-new\"\n      *ngIf=\"canAddNew\"\n      [disabled]=\"true\"\n      [value]=\"null\"\n      (click)=\"addNewValue.emit()\"\n    >\n      <div class=\"option-wrapper\">\n        <ax-icon class=\"icon\" name=\"plus\"></ax-icon>{{ 'label.add' | translate }}\n      </div>\n    </mat-option>\n    <mat-option\n      *ngFor=\"let result of searchResults$ | async\"\n      [value]=\"result | valueByOption: valueCallback\"\n    >\n      <div class=\"option-wrapper\">\n        <ng-container\n          *ngTemplateOutlet=\"optionTemplate; context: {$implicit: result}\"\n        ></ng-container>\n      </div>\n    </mat-option>\n  </mat-select>\n\n  <button\n    axButton\n    icon-button\n    matSuffix\n    aria-label=\"Clear\"\n    *ngIf=\"form?.value && !disabled\"\n    (click)=\"clearValue()\"\n  >\n    <ax-icon class=\"icon\" name=\"close\"></ax-icon>\n  </button>\n\n  <mat-error>\n    <ng-container *ngTemplateOutlet=\"errorsTemplate\"></ng-container>\n  </mat-error>\n\n  <span matPrefix>\n    <ng-container *ngTemplateOutlet=\"prefixTemplate\"></ng-container>\n  </span>\n</mat-form-field>\n\n<ng-template #chipsList>\n  <mat-chip-listbox>\n    <mat-chip\n      *ngFor=\"let value of form.value\"\n      [removable]=\"true\"\n      (removed)=\"removeSelection(value)\"\n    >\n      <ng-container\n        *ngTemplateOutlet=\"\n          selectedValueTemplate;\n          context: {$implicit: value | optionByValue: searchedOptions : valueCallback}\n        \"\n      ></ng-container>\n      <ax-icon matChipRemove class=\"icon\" name=\"close\"></ax-icon>\n    </mat-chip>\n  </mat-chip-listbox>\n</ng-template>\n", styles: [":host{width:100%}::ng-deep .mat-mdc-select-panel-wrap .mat-mdc-select-panel{max-width:180px}.icon{width:1rem;height:1rem}.option-wrapper{display:flex;align-items:center;width:100%;gap:.5rem}.option-wrapper .icon{vertical-align:middle}.option-wrapper span{max-width:100%;white-space:normal;line-height:1.2}:host ::ng-deep .mat-select-trigger{height:auto;min-height:1.125em}::ng-deep .mat-mdc-option.add-new[aria-disabled=true]{cursor:pointer;pointer-events:all}::ng-deep .mat-mdc-option.add-new[aria-disabled=true]:hover{background:#0000000a;color:var(--font-color)}::ng-deep .mat-mdc-option.add-new.mdc-list-item--disabled .mdc-list-item__primary-text{opacity:1}::ng-deep .add-new .mat-pseudo-checkbox{display:none}::ng-deep .add-new .mat-pseudo-checkbox .mat-mdc-option[aria-disabled=true]{cursor:pointer}::ng-deep mat-option.mat-mdc-option.mat-active{background:transparent}\n"], dependencies: [{ kind: "directive", type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i1.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "component", type: i2.MatFormField, selector: "mat-form-field", inputs: ["hideRequiredMarker", "color", "floatLabel", "appearance", "subscriptSizing", "hintLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i2.MatLabel, selector: "mat-label" }, { kind: "directive", type: i2.MatError, selector: "mat-error, [matError]", inputs: ["id"] }, { kind: "directive", type: i2.MatPrefix, selector: "[matPrefix], [matIconPrefix], [matTextPrefix]", inputs: ["matTextPrefix"] }, { kind: "directive", type: i2.MatSuffix, selector: "[matSuffix], [matIconSuffix], [matTextSuffix]", inputs: ["matTextSuffix"] }, { kind: "component", type: i3.MatSelect, selector: "mat-select", inputs: ["aria-describedby", "panelClass", "disabled", "disableRipple", "tabIndex", "hideSingleSelectionIndicator", "placeholder", "required", "multiple", "disableOptionCentering", "compareWith", "value", "aria-label", "aria-labelledby", "errorStateMatcher", "typeaheadDebounceInterval", "sortComparator", "id", "panelWidth"], outputs: ["openedChange", "opened", "closed", "selectionChange", "valueChange"], exportAs: ["matSelect"] }, { kind: "directive", type: i3.MatSelectTrigger, selector: "mat-select-trigger" }, { kind: "component", type: i4.MatOption, selector: "mat-option", inputs: ["value", "id", "disabled"], outputs: ["onSelectionChange"], exportAs: ["matOption"] }, { kind: "component", type: i5.MatSelectSearchComponent, selector: "ngx-mat-select-search", inputs: ["placeholderLabel", "type", "closeIcon", "closeSvgIcon", "noEntriesFoundLabel", "clearSearchInput", "searching", "disableInitialFocus", "enableClearOnEscapePressed", "preventHomeEndKeyPropagation", "disableScrollToActiveOnOptionsChanged", "ariaLabel", "showToggleAllCheckbox", "toggleAllCheckboxChecked", "toggleAllCheckboxIndeterminate", "toggleAllCheckboxTooltipMessage", "toggleAllCheckboxTooltipPosition", "hideClearSearchButton", "alwaysRestoreSelectedOptionsMulti", "recreateValuesArray"], outputs: ["toggleAll"] }, { kind: "directive", type: i5.MatSelectSearchClearDirective, selector: "[ngxMatSelectSearchClear]" }, { kind: "directive", type: i6.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i6.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "directive", type: i7.ButtonDirective, selector: "[axButton]", inputs: ["color", "labelHideMobile", "smallButton", "bigButton", "fullWidth", "filled", "outline", "icon-button", "hoverLabel", "hover", "lowercase", "disabled"] }, { kind: "component", type: i8.IconComponent, selector: "ax-icon", inputs: ["name", "inline"] }, { kind: "component", type: i9.MatChip, selector: "mat-basic-chip, [mat-basic-chip], mat-chip, [mat-chip]", inputs: ["role", "id", "aria-label", "aria-description", "value", "color", "removable", "highlighted", "disableRipple", "disabled", "tabIndex"], outputs: ["removed", "destroyed"], exportAs: ["matChip"] }, { kind: "component", type: i9.MatChipListbox, selector: "mat-chip-listbox", inputs: ["multiple", "aria-orientation", "selectable", "compareWith", "required", "hideSingleSelectionIndicator", "value"], outputs: ["change"] }, { kind: "directive", type: i9.MatChipRemove, selector: "[matChipRemove]" }, { kind: "pipe", type: i1.AsyncPipe, name: "async" }, { kind: "pipe", type: i10.TranslatePipe, name: "translate" }, { kind: "pipe", type: i11.OptionByValuePipe, name: "optionByValue" }, { kind: "pipe", type: i12.ValueByOptionPipe, name: "valueByOption" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: SelectSearchComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ax-select-search', template: "<mat-form-field\n  class=\"c-input\"\n  appearance=\"outline\"\n  [ngClass]=\"{'remove-subtext': !errorsTemplate}\"\n  [appearance]=\"appearance\"\n>\n  <mat-label *ngIf=\"label\">{{ label }}</mat-label>\n  <mat-select\n    [formControl]=\"form\"\n    [placeholder]=\"placeholder\"\n    [multiple]=\"multiple\"\n    [disabled]=\"disabled\"\n  >\n    <mat-select-trigger>\n      <ng-container *ngIf=\"multiple\">\n        <ng-container *ngTemplateOutlet=\"chipsList\"></ng-container>\n      </ng-container>\n      <ng-container *ngIf=\"!multiple\">\n        <ng-container\n          *ngTemplateOutlet=\"\n            selectedValueTemplate;\n            context: {$implicit: form?.value | optionByValue: searchedOptions : valueCallback}\n          \"\n        ></ng-container>\n      </ng-container>\n    </mat-select-trigger>\n    <mat-option *ngIf=\"(keys && keys.length) || searchCallback$\">\n      <ngx-mat-select-search\n        [formControl]=\"formFilterControl\"\n        [placeholderLabel]=\"'label.search' | translate\"\n        [noEntriesFoundLabel]=\"'search.results.absence' | translate\"\n      >\n        <ax-icon class=\"icon\" name=\"close\" ngxMatSelectSearchClear></ax-icon>\n      </ngx-mat-select-search>\n    </mat-option>\n    <mat-option *ngIf=\"!required\" [value]=\"null\" (click)=\"removeSelection()\">\n      <div class=\"option-wrapper\">\n        {{ 'label.none' | translate }}\n      </div>\n    </mat-option>\n    <mat-option\n      class=\"add-new\"\n      *ngIf=\"canAddNew\"\n      [disabled]=\"true\"\n      [value]=\"null\"\n      (click)=\"addNewValue.emit()\"\n    >\n      <div class=\"option-wrapper\">\n        <ax-icon class=\"icon\" name=\"plus\"></ax-icon>{{ 'label.add' | translate }}\n      </div>\n    </mat-option>\n    <mat-option\n      *ngFor=\"let result of searchResults$ | async\"\n      [value]=\"result | valueByOption: valueCallback\"\n    >\n      <div class=\"option-wrapper\">\n        <ng-container\n          *ngTemplateOutlet=\"optionTemplate; context: {$implicit: result}\"\n        ></ng-container>\n      </div>\n    </mat-option>\n  </mat-select>\n\n  <button\n    axButton\n    icon-button\n    matSuffix\n    aria-label=\"Clear\"\n    *ngIf=\"form?.value && !disabled\"\n    (click)=\"clearValue()\"\n  >\n    <ax-icon class=\"icon\" name=\"close\"></ax-icon>\n  </button>\n\n  <mat-error>\n    <ng-container *ngTemplateOutlet=\"errorsTemplate\"></ng-container>\n  </mat-error>\n\n  <span matPrefix>\n    <ng-container *ngTemplateOutlet=\"prefixTemplate\"></ng-container>\n  </span>\n</mat-form-field>\n\n<ng-template #chipsList>\n  <mat-chip-listbox>\n    <mat-chip\n      *ngFor=\"let value of form.value\"\n      [removable]=\"true\"\n      (removed)=\"removeSelection(value)\"\n    >\n      <ng-container\n        *ngTemplateOutlet=\"\n          selectedValueTemplate;\n          context: {$implicit: value | optionByValue: searchedOptions : valueCallback}\n        \"\n      ></ng-container>\n      <ax-icon matChipRemove class=\"icon\" name=\"close\"></ax-icon>\n    </mat-chip>\n  </mat-chip-listbox>\n</ng-template>\n", styles: [":host{width:100%}::ng-deep .mat-mdc-select-panel-wrap .mat-mdc-select-panel{max-width:180px}.icon{width:1rem;height:1rem}.option-wrapper{display:flex;align-items:center;width:100%;gap:.5rem}.option-wrapper .icon{vertical-align:middle}.option-wrapper span{max-width:100%;white-space:normal;line-height:1.2}:host ::ng-deep .mat-select-trigger{height:auto;min-height:1.125em}::ng-deep .mat-mdc-option.add-new[aria-disabled=true]{cursor:pointer;pointer-events:all}::ng-deep .mat-mdc-option.add-new[aria-disabled=true]:hover{background:#0000000a;color:var(--font-color)}::ng-deep .mat-mdc-option.add-new.mdc-list-item--disabled .mdc-list-item__primary-text{opacity:1}::ng-deep .add-new .mat-pseudo-checkbox{display:none}::ng-deep .add-new .mat-pseudo-checkbox .mat-mdc-option[aria-disabled=true]{cursor:pointer}::ng-deep mat-option.mat-mdc-option.mat-active{background:transparent}\n"] }]
        }], propDecorators: { form: [{
                type: Input
            }], options: [{
                type: Input
            }], placeholder: [{
                type: Input
            }], optionTemplate: [{
                type: Input
            }], selectedValueTemplate: [{
                type: Input
            }], multiple: [{
                type: Input
            }], label: [{
                type: Input
            }], keys: [{
                type: Input
            }], canAddNew: [{
                type: Input
            }], required: [{
                type: Input
            }], appearance: [{
                type: Input
            }], errorsTemplate: [{
                type: Input
            }], prefixTemplate: [{
                type: Input
            }], disabled: [{
                type: Input
            }], valueCallback: [{
                type: Input
            }], searchCallback$: [{
                type: Input
            }], addNewValue: [{
                type: Output
            }] } });
//# sourceMappingURL=data:application/json;base64, 