import * as i0 from '@angular/core';
import { Directive, InjectionToken, inject, DestroyRef, EventEmitter, TemplateRef, Component, ViewEncapsulation, ChangeDetectionStrategy, Inject, Host, Optional, ViewChild, ContentChildren, Input, Output, forwardRef, afterNextRender, NgModule } from '@angular/core';
import * as i2$1 from '@angular/cdk/bidi';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import * as i1$1 from '@angular/cdk/overlay';
import { Overlay, OverlayConfig, OverlayModule } from '@angular/cdk/overlay';
import { _getEventTarget } from '@angular/cdk/platform';
import { TemplatePortal } from '@angular/cdk/portal';
import * as i4 from '@angular/cdk/scrolling';
import * as i2 from '@angular/common';
import { DOCUMENT, NgClass } from '@angular/common';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { ESCAPE, ENTER, TAB, DOWN_ARROW, UP_ARROW } from '@koobiq/cdk/keycodes';
import { KBQ_OPTION_PARENT_COMPONENT, KbqOption, KbqOptgroup, KBQ_WINDOW, KbqOptionSelectionChange, defaultOffsetY, KbqOptionModule } from '@koobiq/components/core';
import * as i1 from '@koobiq/components/form-field';
import { defer, merge, Subscription, Subject, of, fromEvent } from 'rxjs';
import { delay, filter, take, switchMap, map, tap } from 'rxjs/operators';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ActiveDescendantKeyManager } from '@koobiq/cdk/a11y';

/**
 * Directive applied to an element to make it usable
 * as a connection point for an autocomplete panel.
 */
class KbqAutocompleteOrigin {
    constructor(elementRef) {
        this.elementRef = elementRef;
    }
    /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: KbqAutocompleteOrigin, deps: [{ token: i0.ElementRef }], target: i0.ɵɵFactoryTarget.Directive }); }
    /** @nocollapse */ static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "18.2.14", type: KbqAutocompleteOrigin, selector: "[kbqAutocompleteOrigin]", exportAs: ["kbqAutocompleteOrigin"], ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: KbqAutocompleteOrigin, decorators: [{
            type: Directive,
            args: [{
                    selector: '[kbqAutocompleteOrigin]',
                    exportAs: 'kbqAutocompleteOrigin'
                }]
        }], ctorParameters: () => [{ type: i0.ElementRef }] });

/**
 * Autocomplete IDs need to be unique across components, so this counter exists outside of
 * the component definition.
 */
let uniqueAutocompleteIdCounter = 0;
class KbqAutocompleteSelectedEvent {
    constructor(source, option) {
        this.source = source;
        this.option = option;
    }
}
/** Injection token to be used to override the default options for `kbq-autocomplete`. */
const KBQ_AUTOCOMPLETE_DEFAULT_OPTIONS = new InjectionToken('kbq-autocomplete-default-options', {
    providedIn: 'root',
    factory: KBQ_AUTOCOMPLETE_DEFAULT_OPTIONS_FACTORY
});
function KBQ_AUTOCOMPLETE_DEFAULT_OPTIONS_FACTORY() {
    return { autoActiveFirstOption: true };
}
class KbqAutocomplete {
    /**
     * Takes classes set on the host kbq-autocomplete element and applies them to the panel
     * inside the overlay container to allow for easy styling.
     */
    get classList() {
        return this._classList;
    }
    set classList(value) {
        if (value && value.length) {
            value.split(' ').forEach((className) => (this._classList[className.trim()] = true));
            this.elementRef.nativeElement.className = '';
        }
    }
    /**
     * Whether the first option should be highlighted when the autocomplete panel is opened.
     * Can be configured globally through the `KBQ_AUTOCOMPLETE_DEFAULT_OPTIONS` token.
     */
    get autoActiveFirstOption() {
        return this._autoActiveFirstOption;
    }
    set autoActiveFirstOption(value) {
        this._autoActiveFirstOption = coerceBooleanProperty(value);
    }
    get isOpen() {
        return this._isOpen && this.showPanel;
    }
    set isOpen(value) {
        this._isOpen = value;
    }
    get openOnFocus() {
        return this._openOnFocus;
    }
    set openOnFocus(value) {
        this._openOnFocus = value;
    }
    constructor(changeDetectorRef, elementRef, defaults, parentFormField) {
        this.changeDetectorRef = changeDetectorRef;
        this.elementRef = elementRef;
        this.parentFormField = parentFormField;
        this.destroyRef = inject(DestroyRef);
        /** Unique ID to be used by autocomplete trigger's "aria-owns" property. */
        this.id = `kbq-autocomplete-${uniqueAutocompleteIdCounter++}`;
        /** Whether the autocomplete panel should be visible, depending on option length. */
        this.showPanel = false;
        /** Function that maps an option's control value to its display value in the trigger. */
        this.displayWith = null;
        /** Event that is emitted whenever an option from the list is selected. */
        this.optionSelected = new EventEmitter();
        /** Event that is emitted when the autocomplete panel is opened. */
        this.opened = new EventEmitter();
        /** Event that is emitted when the autocomplete panel is closed. */
        this.closed = new EventEmitter();
        this._classList = {};
        this._isOpen = false;
        this._openOnFocus = true;
        this._autoActiveFirstOption = !!defaults.autoActiveFirstOption;
    }
    ngAfterContentInit() {
        this.keyManager = new ActiveDescendantKeyManager(this.options);
        this.setVisibility();
        this.parentFormField?.control.ngControl?.valueChanges
            ?.pipe(delay(0), filter((value) => value === null || value === undefined || value === ''), takeUntilDestroyed(this.destroyRef))
            .subscribe(() => {
            this.options.filter(({ selected }) => selected).forEach((option) => option.deselect(false));
        });
    }
    setScrollTop(scrollTop) {
        if (this.panel) {
            this.panel.nativeElement.scrollTop = scrollTop;
        }
    }
    getScrollTop() {
        return this.panel ? this.panel.nativeElement.scrollTop : 0;
    }
    setVisibility() {
        this.showPanel = !!this.options.length;
        this._classList['kbq-autocomplete_visible'] = this.showPanel;
        this._classList['kbq-autocomplete_hidden'] = !this.showPanel;
        this.updateFocusClass();
        this.changeDetectorRef.markForCheck();
    }
    emitSelectEvent(option) {
        const event = new KbqAutocompleteSelectedEvent(this, option);
        this.optionSelected.emit(event);
    }
    onKeydown(event) {
        this.keyManager.onKeydown(event);
        this.updateFocusClass();
    }
    updateFocusClass() {
        this._classList['cdk-keyboard-focused'] = this.parentFormField?.focusOrigin === 'keyboard';
    }
    /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: KbqAutocomplete, deps: [{ token: i0.ChangeDetectorRef }, { token: i0.ElementRef }, { token: KBQ_AUTOCOMPLETE_DEFAULT_OPTIONS }, { token: i1.KbqFormField, host: true, optional: true }], target: i0.ɵɵFactoryTarget.Component }); }
    /** @nocollapse */ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.14", type: KbqAutocomplete, selector: "kbq-autocomplete", inputs: { displayWith: "displayWith", panelWidth: "panelWidth", classList: ["class", "classList"], autoActiveFirstOption: "autoActiveFirstOption", openOnFocus: "openOnFocus" }, outputs: { optionSelected: "optionSelected", opened: "opened", closed: "closed" }, host: { classAttribute: "kbq-autocomplete" }, providers: [
            {
                provide: KBQ_OPTION_PARENT_COMPONENT,
                useExisting: KbqAutocomplete
            }
        ], queries: [{ propertyName: "options", predicate: KbqOption, descendants: true }, { propertyName: "optionGroups", predicate: KbqOptgroup }], viewQueries: [{ propertyName: "template", first: true, predicate: TemplateRef, descendants: true, static: true }, { propertyName: "panel", first: true, predicate: ["panel"], descendants: true }], exportAs: ["kbqAutocomplete"], ngImport: i0, template: "<ng-template>\n    <div #panel role=\"listbox\" class=\"kbq-autocomplete-panel kbq-scrollbar\" [id]=\"id\" [ngClass]=\"classList\">\n        <ng-content />\n    </div>\n</ng-template>\n", styles: [".kbq-autocomplete-panel{visibility:hidden;position:relative;overflow:hidden auto;-webkit-overflow-scrolling:touch;box-sizing:border-box;min-width:100%;width:100%;max-width:none;border-radius:var(--kbq-autocomplete-size-panel-border-radius, var(--kbq-size-border-radius));max-height:var(--kbq-autocomplete-size-panel-max-height);padding:var(--kbq-size-xxs)}.kbq-autocomplete-panel.kbq-autocomplete_visible{visibility:visible}.kbq-autocomplete-panel.kbq-autocomplete_hidden{visibility:hidden}.kbq-autocomplete-panel .kbq-option{position:relative}.kbq-autocomplete-panel .kbq-option:before,.kbq-autocomplete-panel .kbq-option:after{position:absolute;content:\"\";width:var(--kbq-size-xxs);height:calc(100% + var(--kbq-size-3xs) * 2)}.kbq-autocomplete-panel .kbq-option:before{right:calc(100% + var(--kbq-size-3xs))}.kbq-autocomplete-panel .kbq-option:after{left:calc(100% + var(--kbq-size-3xs))}.kbq-autocomplete-panel .kbq-divider-horizontal{margin-top:-1px}.kbq-autocomplete-panel{box-shadow:var(--kbq-select-panel-dropdown-shadow);background:var(--kbq-select-panel-dropdown-background)}\n", ".kbq-autocomplete-panel{--kbq-autocomplete-size-panel-padding: var(--kbq-size-xxs) 0;--kbq-autocomplete-size-panel-max-height: 256px;--kbq-autocomplete-size-panel-border-radius: var(--kbq-size-border-radius);--kbq-select-panel-dropdown-background: var(--kbq-background-card);--kbq-select-panel-dropdown-shadow: var(--kbq-shadow-popup)}\n"], dependencies: [{ kind: "directive", type: i2.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: KbqAutocomplete, decorators: [{
            type: Component,
            args: [{ selector: 'kbq-autocomplete', exportAs: 'kbqAutocomplete', host: {
                        class: 'kbq-autocomplete'
                    }, encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, providers: [
                        {
                            provide: KBQ_OPTION_PARENT_COMPONENT,
                            useExisting: KbqAutocomplete
                        }
                    ], template: "<ng-template>\n    <div #panel role=\"listbox\" class=\"kbq-autocomplete-panel kbq-scrollbar\" [id]=\"id\" [ngClass]=\"classList\">\n        <ng-content />\n    </div>\n</ng-template>\n", styles: [".kbq-autocomplete-panel{visibility:hidden;position:relative;overflow:hidden auto;-webkit-overflow-scrolling:touch;box-sizing:border-box;min-width:100%;width:100%;max-width:none;border-radius:var(--kbq-autocomplete-size-panel-border-radius, var(--kbq-size-border-radius));max-height:var(--kbq-autocomplete-size-panel-max-height);padding:var(--kbq-size-xxs)}.kbq-autocomplete-panel.kbq-autocomplete_visible{visibility:visible}.kbq-autocomplete-panel.kbq-autocomplete_hidden{visibility:hidden}.kbq-autocomplete-panel .kbq-option{position:relative}.kbq-autocomplete-panel .kbq-option:before,.kbq-autocomplete-panel .kbq-option:after{position:absolute;content:\"\";width:var(--kbq-size-xxs);height:calc(100% + var(--kbq-size-3xs) * 2)}.kbq-autocomplete-panel .kbq-option:before{right:calc(100% + var(--kbq-size-3xs))}.kbq-autocomplete-panel .kbq-option:after{left:calc(100% + var(--kbq-size-3xs))}.kbq-autocomplete-panel .kbq-divider-horizontal{margin-top:-1px}.kbq-autocomplete-panel{box-shadow:var(--kbq-select-panel-dropdown-shadow);background:var(--kbq-select-panel-dropdown-background)}\n", ".kbq-autocomplete-panel{--kbq-autocomplete-size-panel-padding: var(--kbq-size-xxs) 0;--kbq-autocomplete-size-panel-max-height: 256px;--kbq-autocomplete-size-panel-border-radius: var(--kbq-size-border-radius);--kbq-select-panel-dropdown-background: var(--kbq-background-card);--kbq-select-panel-dropdown-shadow: var(--kbq-shadow-popup)}\n"] }]
        }], ctorParameters: () => [{ type: i0.ChangeDetectorRef }, { type: i0.ElementRef }, { type: undefined, decorators: [{
                    type: Inject,
                    args: [KBQ_AUTOCOMPLETE_DEFAULT_OPTIONS]
                }] }, { type: i1.KbqFormField, decorators: [{
                    type: Host
                }, {
                    type: Optional
                }] }], propDecorators: { template: [{
                type: ViewChild,
                args: [TemplateRef, { static: true }]
            }], panel: [{
                type: ViewChild,
                args: ['panel', { static: false }]
            }], options: [{
                type: ContentChildren,
                args: [KbqOption, { descendants: true }]
            }], optionGroups: [{
                type: ContentChildren,
                args: [KbqOptgroup]
            }], displayWith: [{
                type: Input
            }], panelWidth: [{
                type: Input
            }], optionSelected: [{
                type: Output
            }], opened: [{
                type: Output
            }], closed: [{
                type: Output
            }], classList: [{
                type: Input,
                args: ['class']
            }], autoActiveFirstOption: [{
                type: Input
            }], openOnFocus: [{
                type: Input
            }] } });

/**
 * The following style constants are necessary to save here in order
 * to properly calculate the scrollTop of the panel. Because we are not
 * actually focusing the active item, scroll must be handled manually.
 */
/** The total height of the autocomplete panel. */
const AUTOCOMPLETE_PANEL_HEIGHT = 256;
/** Injection token that determines the scroll handling while the autocomplete panel is open. */
const KBQ_AUTOCOMPLETE_SCROLL_STRATEGY = new InjectionToken('kbq-autocomplete-scroll-strategy');
function KBQ_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY(overlay) {
    return () => overlay.scrollStrategies.reposition();
}
const KBQ_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY_PROVIDER = {
    provide: KBQ_AUTOCOMPLETE_SCROLL_STRATEGY,
    deps: [Overlay],
    useFactory: KBQ_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY
};
/**
 * Provider that allows the autocomplete to register as a ControlValueAccessor.
 * @docs-private
 */
const KBQ_AUTOCOMPLETE_VALUE_ACCESSOR = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => KbqAutocompleteTrigger),
    multi: true
};
/**
 * Creates an error to be thrown when attempting to use an autocomplete trigger without a panel.
 * @docs-private
 */
function getKbqAutocompleteMissingPanelError() {
    return Error('Attempting to open an undefined instance of `kbq-autocomplete`. ' +
        'Make sure that the id passed to the `kbqAutocomplete` is correct and that ' +
        "you're attempting to open it after the ngAfterContentInit hook.");
}
class KbqAutocompleteTrigger {
    /** The currently active option, coerced to MatOption type. */
    get activeOption() {
        return this.autocomplete?.keyManager?.activeItem;
    }
    get panelOpen() {
        return this.overlayAttached && this.autocomplete.showPanel;
    }
    /**
     * Whether the autocomplete is disabled. When disabled, the element will
     * act as a regular input and the user won't be able to open the panel.
     */
    get autocompleteDisabled() {
        return this._autocompleteDisabled;
    }
    set autocompleteDisabled(value) {
        this._autocompleteDisabled = coerceBooleanProperty(value);
    }
    constructor(elementRef, viewContainerRef, changeDetectorRef, overlay, zone, scrollStrategy, dir, formField, 
    // @breaking-change 8.0.0 Make `_viewportRuler` required.
    viewportRuler) {
        this.elementRef = elementRef;
        this.viewContainerRef = viewContainerRef;
        this.changeDetectorRef = changeDetectorRef;
        this.overlay = overlay;
        this.zone = zone;
        this.dir = dir;
        this.formField = formField;
        this.viewportRuler = viewportRuler;
        this.document = inject(DOCUMENT);
        this.optionSelections = defer(() => {
            if (this.autocomplete && this.autocomplete.options) {
                return merge(...this.autocomplete.options.map((option) => option.onSelectionChange));
            }
            // If there are any subscribers before `ngAfterViewInit`, the `autocomplete` will be undefined.
            // Return a stream that we'll replace with the real one once everything is in place.
            return this.zone.onStable.asObservable().pipe(take(1), switchMap(() => this.optionSelections));
        });
        /**
         * `autocomplete` attribute to be set on the input element.
         * @docs-private
         */
        this.autocompleteAttribute = 'off';
        /**
         * Event handler for input blur events.
         * Determines whether the blur event is triggered outside the specific target
         * @returns A boolean indicating if the blur event happened outside the target element
         */
        this.onInputBlur = (event) => {
            const target = event.relatedTarget;
            return !target || target.tagName !== 'KBQ-OPTION';
        };
        this._autocompleteDisabled = false;
        this.overlayAttached = false;
        this.componentDestroyed = false;
        /** Subscription to viewport size changes. */
        this.viewportSubscription = Subscription.EMPTY;
        /**
         * Whether the autocomplete can open the next time it is focused. Used to prevent a focused,
         * closed autocomplete from being reopened if the user switches to another browser tab and then
         * comes back.
         */
        this.canOpenOnNextFocus = true;
        /** Stream of keyboard events that can close the panel. */
        this.closeKeyEventStream = new Subject();
        this.window = inject(KBQ_WINDOW);
        /** `View -> model callback called when value changes` */
        this.onChange = () => { };
        /** `View -> model callback called when autocomplete has been touched` */
        this.onTouched = () => { };
        /**
         * Event handler for when the window is blurred. Needs to be an
         * arrow function in order to preserve the context.
         */
        this.windowBlurHandler = () => {
            // If the user blurred the window while the autocomplete is focused, it means that it'll be
            // refocused when they come back. In this case we want to skip the first focus event, if the
            // pane was closed, in order to avoid reopening it unintentionally.
            this.canOpenOnNextFocus = this.document.activeElement !== this.elementRef.nativeElement || this.panelOpen;
        };
        afterNextRender(() => {
            zone.runOutsideAngular(() => this.window.addEventListener('blur', this.windowBlurHandler));
        });
        this.scrollStrategy = scrollStrategy;
    }
    ngAfterViewInit() {
        if (this.autocomplete) {
            this.autocomplete.keyManager?.change.subscribe(() => {
                if (this.panelOpen) {
                    this.scrollActiveOptionIntoView();
                    this.elementRef.nativeElement.focus();
                }
                else if (!this.panelOpen && this.autocomplete.keyManager.activeItem) {
                    this.autocomplete.keyManager.activeItem?.selectViaInteraction();
                }
            });
        }
    }
    ngOnDestroy() {
        this.window.removeEventListener('blur', this.windowBlurHandler);
        this.viewportSubscription.unsubscribe();
        this.componentDestroyed = true;
        this.destroyPanel();
        this.closeKeyEventStream.complete();
    }
    /** Opens the autocomplete suggestion panel. */
    openPanel() {
        this.attachOverlay();
    }
    closePanel() {
        if (!this.overlayAttached) {
            return;
        }
        if (this.panelOpen) {
            this.autocomplete.closed.emit();
        }
        this.autocomplete.isOpen = this.overlayAttached = false;
        if (this.overlayRef && this.overlayRef.hasAttached()) {
            this.overlayRef.detach();
            this.closingActionsSubscription.unsubscribe();
        }
        // Note that in some cases this can end up being called after the component is destroyed.
        // Add a check to ensure that we don't try to run change detection on a destroyed view.
        if (!this.componentDestroyed) {
            // We need to trigger change detection manually, because
            // `fromEvent` doesn't seem to do it at the proper time.
            // This ensures that the label is reset when the
            // user clicks outside.
            this.changeDetectorRef.detectChanges();
        }
    }
    /**
     * Updates the position of the autocomplete suggestion panel to ensure that it fits all options
     * within the viewport.
     */
    updatePosition() {
        if (this.overlayAttached) {
            this.overlayRef.updatePosition();
        }
    }
    /**
     * A stream of actions that should close the autocomplete panel, including
     * when an option is selected, on blur, and when TAB is pressed.
     */
    get panelClosingActions() {
        return merge(this.optionSelections, this.autocomplete.keyManager.tabOut.pipe(filter(() => this.overlayAttached)), this.closeKeyEventStream, this.getOutsideClickStream(), this.overlayRef ? this.overlayRef.detachments().pipe(filter(() => this.overlayAttached)) : of()).pipe(
        // Normalize the output so we return a consistent type.
        map((event) => (event instanceof KbqOptionSelectionChange ? event : null)));
    }
    // Implemented as part of ControlValueAccessor.
    writeValue(value) {
        Promise.resolve(null).then(() => this.setTriggerValue(value));
    }
    // Implemented as part of ControlValueAccessor.
    // eslint-disable-next-line @typescript-eslint/ban-types
    registerOnChange(fn) {
        this.onChange = fn;
    }
    // Implemented as part of ControlValueAccessor.
    // eslint-disable-next-line @typescript-eslint/ban-types
    registerOnTouched(fn) {
        this.onTouched = fn;
    }
    // Implemented as part of ControlValueAccessor.
    setDisabledState(isDisabled) {
        this.elementRef.nativeElement.disabled = isDisabled;
    }
    handleKeydown(event) {
        const keyCode = event.keyCode;
        // Prevent the default action on all escape key presses. This is here primarily to bring IE
        // in line with other browsers. By default, pressing escape on IE will cause it to revert
        // the input value to the one that it had on focus, however it won't dispatch any events
        // which means that the model value will be out of sync with the view.
        if (keyCode === ESCAPE) {
            event.preventDefault();
        }
        if (this.activeOption && keyCode === ENTER && this.panelOpen) {
            this.activeOption.selectViaInteraction();
            this.resetActiveItem();
            event.preventDefault();
        }
        else if (this.autocomplete) {
            const prevActiveItem = this.autocomplete.keyManager.activeItem;
            if (this.panelOpen || keyCode === TAB) {
                this.autocomplete.onKeydown(event);
            }
            else if (!this.panelOpen && keyCode === DOWN_ARROW && this.canOpen()) {
                this.openPanel();
            }
            const isArrowKey = keyCode === UP_ARROW || keyCode === DOWN_ARROW;
            if (isArrowKey && event.shiftKey && this.autocomplete.keyManager.activeItem !== prevActiveItem) {
                this.autocomplete.keyManager.activeItem?.selectViaInteraction();
            }
        }
    }
    handleInput(event) {
        const target = event.target;
        let value = target.value;
        // Based on `NumberValueAccessor` from forms.
        if (target.type === 'number') {
            value = value === '' ? null : parseFloat(value);
        }
        // If the input has a placeholder, IE will fire the `input` event on page load,
        // focus and blur, in addition to when the user actually changed the value. To
        // filter out all of the extra events, we save the value on focus and between
        // `input` events, and we check whether it changed.
        // See: https://connect.microsoft.com/IE/feedback/details/885747/
        if (this.previousValue !== value) {
            this.previousValue = value;
            this.onChange(value);
            if (this.canOpen() && this.document.activeElement === event.target) {
                this.openPanel();
            }
        }
    }
    handleFocus() {
        if (!this.canOpenOnNextFocus) {
            this.canOpenOnNextFocus = true;
        }
        else if (!this.panelOpen && this.canOpen() && this.autocomplete.openOnFocus) {
            this.previousValue = this.elementRef.nativeElement.value;
            this.attachOverlay();
        }
    }
    handleClick($event) {
        if (!this.panelOpen && this.canOpen() && this.document.activeElement === $event.target) {
            this.openPanel();
        }
    }
    scrollActiveOptionIntoView() {
        this.autocomplete.keyManager.activeItem?.focus();
    }
    /** Stream of clicks outside of the autocomplete panel. */
    getOutsideClickStream() {
        return merge(fromEvent(this.document, 'click'), fromEvent(this.document, 'auxclick'), fromEvent(this.document, 'touchend')).pipe(filter((event) => {
            const clickTarget = _getEventTarget(event);
            const formField = this.formField ? this.formField.elementRef.nativeElement : null;
            const customOrigin = this.connectedTo ? this.connectedTo.elementRef.nativeElement : null;
            return (this.overlayAttached &&
                clickTarget !== this.elementRef.nativeElement &&
                (!formField || !formField.contains(clickTarget)) &&
                (!customOrigin || !customOrigin.contains(clickTarget)) &&
                !!this.overlayRef &&
                !this.overlayRef.overlayElement.contains(clickTarget));
        }));
    }
    /**
     * This method listens to a stream of panel closing actions and resets the
     * stream every time the option list changes.
     */
    subscribeToClosingActions() {
        const firstStable = this.zone.onStable.asObservable().pipe(take(1));
        const optionChanges = this.autocomplete.options.changes.pipe(tap(() => this.positionStrategy.reapplyLastPosition()), 
        // Defer emitting to the stream until the next tick, because changing
        // bindings in here will cause "changed after checked" errors.
        delay(0));
        // When the zone is stable initially, and when the option list changes...
        return (merge(firstStable, optionChanges)
            .pipe(
        // create a new stream of panelClosingActions, replacing any previous streams
        // that were created, and flatten it so our stream only emits closing events...
        switchMap(() => {
            const wasOpen = this.panelOpen;
            this.resetActiveItem();
            this.autocomplete.setVisibility();
            if (this.panelOpen) {
                this.overlayRef.updatePosition();
                // If the `panelOpen` state changed, we need to make sure to emit the `opened`
                // event, because we may not have emitted it when the panel was attached. This
                // can happen if the users opens the panel and there are no options, but the
                // options come in slightly later or as a result of the value changing.
                if (wasOpen !== this.panelOpen) {
                    this.autocomplete.opened.emit();
                }
            }
            return this.panelClosingActions;
        }), 
        // when the first closing event occurs...
        take(1))
            // set the value, close the panel, and complete.
            .subscribe((event) => this.setValueAndClose(event)));
    }
    /** Destroys the autocomplete suggestion panel. */
    destroyPanel() {
        if (this.overlayRef) {
            this.closePanel();
            this.overlayRef.dispose();
            this.overlayRef = null;
        }
    }
    setTriggerValue(value) {
        const toDisplay = this.autocomplete && this.autocomplete.displayWith ? this.autocomplete.displayWith(value) : value;
        // Simply falling back to an empty string if the display value is falsy does not work properly.
        // The display value can also be the number zero and shouldn't fall back to an empty string.
        const inputValue = toDisplay != null ? toDisplay : '';
        // If it's used within a `MatFormField`, we should set it through the property so it can go
        // through change detection.
        if (this.formField) {
            this.formField.control.value = inputValue;
        }
        else {
            this.elementRef.nativeElement.value = inputValue;
        }
        this.previousValue = inputValue;
    }
    /** This method closes the panel, and if a value is specified, also sets the associated
     * control to that value. It will also mark the control as dirty if this interaction
     * stemmed from the user.
     */
    setValueAndClose(event) {
        if (event?.source) {
            this.clearPreviousSelectedOption(event.source);
            this.setTriggerValue(event.source.value);
            this.onChange(event.source.value);
            this.elementRef.nativeElement.focus();
            this.autocomplete.emitSelectEvent(event.source);
        }
        this.closePanel();
    }
    /** Clear any previous selected option and emit a selection change event for this option */
    clearPreviousSelectedOption(skip) {
        this.autocomplete.options.forEach((option) => {
            if (option !== skip && option.selected) {
                option.deselect();
            }
        });
    }
    attachOverlay() {
        if (!this.autocomplete) {
            throw getKbqAutocompleteMissingPanelError();
        }
        let overlayRef = this.overlayRef;
        if (!overlayRef) {
            this.portal = new TemplatePortal(this.autocomplete.template, this.viewContainerRef);
            overlayRef = this.overlay.create(this.getOverlayConfig());
            this.overlayRef = overlayRef;
            // Use the `keydownEvents` in order to take advantage of
            // the overlay event targeting provided by the CDK overlay.
            overlayRef.keydownEvents().subscribe((event) => {
                // Close when pressing ESCAPE or ALT + UP_ARROW, based on the a11y guidelines.
                // See: https://www.w3.org/TR/wai-aria-practices-1.1/#textbox-keyboard-interaction
                if (event.keyCode === ESCAPE || (event.keyCode === UP_ARROW && event.altKey)) {
                    this.resetActiveItem();
                    this.closeKeyEventStream.next();
                }
            });
            if (this.viewportRuler) {
                this.viewportSubscription = this.viewportRuler.change().subscribe(() => {
                    if (this.panelOpen && overlayRef) {
                        overlayRef.updateSize({ width: this.getPanelWidth() });
                    }
                });
            }
        }
        else {
            const position = overlayRef.getConfig().positionStrategy;
            // Update the trigger, panel width and direction, in case anything has changed.
            position.setOrigin(this.getConnectedElement());
            overlayRef.updateSize({ width: this.getPanelWidth() });
        }
        if (overlayRef && !overlayRef.hasAttached()) {
            overlayRef.attach(this.portal);
            this.closingActionsSubscription = this.subscribeToClosingActions();
        }
        const wasOpen = this.panelOpen;
        this.autocomplete.setVisibility();
        this.autocomplete.isOpen = this.overlayAttached = true;
        // We need to do an extra `panelOpen` check in here, because the
        // autocomplete won't be shown if there are no options.
        if (this.panelOpen && wasOpen !== this.panelOpen) {
            this.autocomplete.opened.emit();
        }
        this.zone.onStable
            .asObservable()
            .pipe(take(1))
            .subscribe(() => this.resetActiveItem());
    }
    getOverlayConfig() {
        return new OverlayConfig({
            positionStrategy: this.getOverlayPosition(),
            scrollStrategy: this.scrollStrategy(),
            width: this.getPanelWidth(),
            direction: this.dir
        });
    }
    getOverlayPosition() {
        this.positionStrategy = this.overlay
            .position()
            .flexibleConnectedTo(this.getConnectedElement())
            .withFlexibleDimensions(false)
            .withPush(false)
            .withPositions([
            {
                originX: 'start',
                originY: 'bottom',
                overlayX: 'start',
                overlayY: 'top',
                offsetY: defaultOffsetY
            },
            {
                originX: 'start',
                originY: 'top',
                overlayX: 'start',
                overlayY: 'bottom',
                offsetY: -defaultOffsetY
            }
        ]);
        return this.positionStrategy;
    }
    getConnectedElement() {
        if (this.connectedTo) {
            return this.connectedTo.elementRef;
        }
        return this.formField ? this.formField.getConnectedOverlayOrigin() : this.elementRef;
    }
    getPanelWidth() {
        return this.autocomplete.panelWidth || this.getHostWidth();
    }
    getHostWidth() {
        return this.getConnectedElement().nativeElement.getBoundingClientRect().width;
    }
    /**
     * Resets the active item to -1 so arrow events will activate the
     * correct options, or to 0 if the consumer opted into it.
     */
    resetActiveItem() {
        if (this.autocomplete.autoActiveFirstOption) {
            this.autocomplete.keyManager.setFirstItemActive();
        }
        else {
            this.autocomplete.keyManager.setActiveItem(-1);
        }
    }
    canOpen() {
        const element = this.elementRef.nativeElement;
        return !element.readOnly && !element.disabled && !this._autocompleteDisabled;
    }
    /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: KbqAutocompleteTrigger, deps: [{ token: i0.ElementRef }, { token: i0.ViewContainerRef }, { token: i0.ChangeDetectorRef }, { token: i1$1.Overlay }, { token: i0.NgZone }, { token: KBQ_AUTOCOMPLETE_SCROLL_STRATEGY }, { token: i2$1.Directionality, optional: true }, { token: i1.KbqFormField, host: true, optional: true }, { token: i4.ViewportRuler }], target: i0.ɵɵFactoryTarget.Directive }); }
    /** @nocollapse */ static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "18.2.14", type: KbqAutocompleteTrigger, selector: "input[kbqAutocomplete], textarea[kbqAutocomplete]", inputs: { autocomplete: ["kbqAutocomplete", "autocomplete"], connectedTo: ["kbqAutocompleteConnectedTo", "connectedTo"], autocompleteAttribute: ["autocomplete", "autocompleteAttribute"], autocompleteDisabled: ["kbqAutocompleteDisabled", "autocompleteDisabled"], onInputBlur: ["kbqAutocompleteOnBlur", "onInputBlur"] }, host: { listeners: { "focusin": "handleFocus()", "blur": "onTouched()", "input": "handleInput($event)", "keydown": "handleKeydown($event)", "click": "handleClick($event)" }, properties: { "attr.autocomplete": "autocompleteAttribute" }, classAttribute: "kbq-autocomplete-trigger" }, providers: [KBQ_AUTOCOMPLETE_VALUE_ACCESSOR], exportAs: ["kbqAutocompleteTrigger"], ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: KbqAutocompleteTrigger, decorators: [{
            type: Directive,
            args: [{
                    selector: `input[kbqAutocomplete], textarea[kbqAutocomplete]`,
                    host: {
                        class: 'kbq-autocomplete-trigger',
                        '[attr.autocomplete]': 'autocompleteAttribute',
                        // Note: we use `focusin`, as opposed to `focus`, in order to open the panel
                        // a little earlier. This avoids issues where IE delays the focusing of the input.
                        '(focusin)': 'handleFocus()',
                        '(blur)': 'onTouched()',
                        '(input)': 'handleInput($event)',
                        '(keydown)': 'handleKeydown($event)',
                        '(click)': 'handleClick($event)'
                    },
                    exportAs: 'kbqAutocompleteTrigger',
                    providers: [KBQ_AUTOCOMPLETE_VALUE_ACCESSOR]
                }]
        }], ctorParameters: () => [{ type: i0.ElementRef }, { type: i0.ViewContainerRef }, { type: i0.ChangeDetectorRef }, { type: i1$1.Overlay }, { type: i0.NgZone }, { type: undefined, decorators: [{
                    type: Inject,
                    args: [KBQ_AUTOCOMPLETE_SCROLL_STRATEGY]
                }] }, { type: i2$1.Directionality, decorators: [{
                    type: Optional
                }] }, { type: i1.KbqFormField, decorators: [{
                    type: Optional
                }, {
                    type: Host
                }] }, { type: i4.ViewportRuler }], propDecorators: { autocomplete: [{
                type: Input,
                args: ['kbqAutocomplete']
            }], connectedTo: [{
                type: Input,
                args: ['kbqAutocompleteConnectedTo']
            }], autocompleteAttribute: [{
                type: Input,
                args: ['autocomplete']
            }], autocompleteDisabled: [{
                type: Input,
                args: ['kbqAutocompleteDisabled']
            }], onInputBlur: [{
                type: Input,
                args: ['kbqAutocompleteOnBlur']
            }] } });

class KbqAutocompleteModule {
    /** @nocollapse */ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: KbqAutocompleteModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    /** @nocollapse */ static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: KbqAutocompleteModule, declarations: [KbqAutocomplete, KbqAutocompleteTrigger, KbqAutocompleteOrigin], imports: [KbqOptionModule,
            OverlayModule,
            NgClass], exports: [KbqAutocomplete,
            KbqOptionModule,
            KbqAutocompleteTrigger,
            KbqAutocompleteOrigin] }); }
    /** @nocollapse */ static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: KbqAutocompleteModule, providers: [KBQ_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY_PROVIDER], imports: [KbqOptionModule,
            OverlayModule, KbqOptionModule] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: KbqAutocompleteModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [
                        KbqOptionModule,
                        OverlayModule,
                        NgClass
                    ],
                    exports: [
                        KbqAutocomplete,
                        KbqOptionModule,
                        KbqAutocompleteTrigger,
                        KbqAutocompleteOrigin
                    ],
                    declarations: [KbqAutocomplete, KbqAutocompleteTrigger, KbqAutocompleteOrigin],
                    providers: [KBQ_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY_PROVIDER]
                }]
        }] });

/**
 * Generated bundle index. Do not edit.
 */

export { AUTOCOMPLETE_PANEL_HEIGHT, KBQ_AUTOCOMPLETE_DEFAULT_OPTIONS, KBQ_AUTOCOMPLETE_DEFAULT_OPTIONS_FACTORY, KBQ_AUTOCOMPLETE_SCROLL_STRATEGY, KBQ_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY, KBQ_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY_PROVIDER, KBQ_AUTOCOMPLETE_VALUE_ACCESSOR, KbqAutocomplete, KbqAutocompleteModule, KbqAutocompleteOrigin, KbqAutocompleteSelectedEvent, KbqAutocompleteTrigger, getKbqAutocompleteMissingPanelError };
//# sourceMappingURL=koobiq-components-autocomplete.mjs.map
