import { r as registerInstance, c as createEvent, h, H as Host, g as getElement } from './index-ClISz4NF.js';
import { a as toBoolAttr, b as booleanString } from './template-CoD1xawt.js';
import { v as validateProp } from './props-CJZgTDla.js';
import { c as createID } from './string.utils-vN03FcXN.js';
import { d as delay, t as throttle, h as has } from './utils-CQvUntGY.js';
import { F as FormAutocompleteClass, a as FormAutocompleteSizes } from './constants-aqe7GX2n.js';
import { p as propsValueToArray } from './array.utils-CJ0U_ONv.js';
import { A as AttributeObserver, a as ariaAttributes } from './attribute-Bz_RzYFb.js';
import { i as inheritAriaAttributes } from './accessibility-wqNV8djF.js';
import './gov.log-BtqD9K8d.js';
import './sizes-BcQO4NH2.js';
import './helpers.types-DNztiAH0.js';

const GovFormAutocomplete = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.govFocus = createEvent(this, "gov-focus");
        this.govBlur = createEvent(this, "gov-blur");
        this.govInput = createEvent(this, "gov-input");
        this.govSelect = createEvent(this, "gov-select");
        this.templateResolver = item => item[this.nameKey];
        /**
         * Value of input
         */
        this.value = '';
        /**
         * Input’s size.
         */
        this.size = 'm';
        /**
         * Main key name in the object
         */
        this.nameKey = 'name';
        /**
         * Set whether the input is required or not. Please note that this is necessary for accessible inputs when the user is required to fill them.
         * When using this property you need to also set “novalidate” attribute to your form element to prevent browser from displaying its own validation errors.
         */
        this.required = false;
        /**
         * Makes the input component disabled.
         * This prevents users from being able to interact with the select, and conveys its inactive state to assistive technologies.
         */
        this.disabled = false;
        /**
         * Minimum length (number of characters) of value
         */
        this.minlength = 3;
        /**
         * Input throttle in milliseconds
         */
        this.throttleTime = 200;
        /**
         * Custom message for when there is a blank sheet
         */
        this.messageEmpty = 'Nebyly nalezeny žádné výsledky';
        this.processing = false;
        this.arrowCounter = -1;
        this.list = [];
        this.inheritedAttributes = {};
        this.listBoxId = createID('GovListBox');
    }
    validateSize(newValue) {
        validateProp(FormAutocompleteSizes, newValue, FormAutocompleteClass.root);
    }
    watchOptions(newValue) {
        this.setOptions(propsValueToArray(newValue)).catch();
    }
    onArrowUp() {
        if (this.arrowCounter > 0) {
            this.arrowCounter = this.arrowCounter - 1;
            this.moveToView().finally();
        }
    }
    onArrowDown() {
        if (this.arrowCounter < this.list.length - 1) {
            this.arrowCounter = this.arrowCounter + 1;
            this.moveToView().finally();
        }
    }
    async moveToView() {
        await delay(200);
        const heightOfList = this.listRef.offsetHeight;
        const selected = this.listRef.querySelector('li[aria-selected="true"]');
        if (selected && heightOfList) {
            const offsetTop = selected.offsetTop;
            this.listRef.scrollTo({ top: offsetTop, behavior: 'smooth' });
        }
    }
    doSearch() {
        if (Number.isInteger(this.minlength) && this.isValueAccepted === false && this.minlength) {
            this.list = [];
            this.arrowCounter = -1;
            this.processing = false;
            return;
        }
        if (this.searchCallback) {
            this.processing = true;
            this.searchCallback(this.value)
                .then(response => (this.list = response))
                .catch(() => (this.list = []))
                .finally(() => {
                this.arrowCounter = -1;
                this.processing = false;
            });
        }
    }
    clearList() {
        const areOptions = propsValueToArray(this.options);
        if (areOptions.length === 0) {
            this.list = [];
        }
    }
    get isValueAccepted() {
        if (typeof this.value === 'string') {
            return this.value.length >= this.minlength;
        }
        else {
            return false;
        }
    }
    componentDidLoad() {
        this.attributeObserver = new AttributeObserver(this.host, (attributeName, newValue) => {
            this.onAriaAttributeChange(attributeName, newValue);
        });
        this.attributeObserver.startObserving(ariaAttributes);
    }
    componentWillLoad() {
        this.validateSize(this.size);
        this.inheritedAttributes = inheritAriaAttributes(this.host);
    }
    disconnectedCallback() {
        var _a;
        (_a = this.attributeObserver) === null || _a === void 0 ? void 0 : _a.stopObserving();
    }
    onAriaAttributeChange(attributeName, newValue) {
        this.host.removeAttribute(attributeName);
        this.inheritedAttributes = Object.assign(Object.assign({}, this.inheritedAttributes), { [attributeName]: newValue });
    }
    render() {
        return (h(Host, { key: 'e702056161cca6e00f2e7753b1b07dfdeee78438', class: FormAutocompleteClass.root, size: this.size }, h("gov-form-input", Object.assign({ key: '6ba7c775e0a67486f2c10a1d972860a986e44a3d', placeholder: this.placeholder, name: this.name, disabled: this.disabled, readonly: this.readonly, autocomplete: false, size: this.size, required: this.required, invalid: this.invalid, success: this.success, role: 'searchbox', value: this.value, minlength: this.minlength, maxlength: this.maxlength, "on-gov-input": throttle(this.onInputHandler.bind(this), this.throttleTime), "on-gov-keyup": this.onKeyUpHandler.bind(this), "on-gov-keydown": this.onKeyDownHandler.bind(this), "on-gov-focus": this.onFocusHandler.bind(this), "on-gov-blur": this.onBlurHandler.bind(this) }, this.inheritedAttributes, { "aria-autocomplete": 'list', "aria-owns": [this.listBoxId, this.inheritedAttributes['aria-owns']].join(' '), "aria-expanded": booleanString(this.list.length && this.focused ? true : false), ref: el => (this.inputRef = el) }), h("slot", { key: '1f36342107c398db15ec13d8d1ecd8306dc62505', name: "validation-icon" }), h("slot", { key: '26bc01a6995f090e605677dbfbe6260c79f70d00', name: "icon-end" })), h("ul", { key: 'c42a658906dd0815e3c94aa451ee7a4fa7091bd3', class: FormAutocompleteClass.list, role: 'listbox', "aria-hidden": toBoolAttr(!this.focused), hidden: !this.focused, id: this.listBoxId, ref: el => (this.listRef = el) }, this.focused && this.list.length === 0 && this.processing === false && this.isValueAccepted && this.messageEmpty ? (h("li", { class: FormAutocompleteClass.empty }, this.messageEmpty)) : null, this.focused && this.processing === true && this.isValueAccepted ? (h("li", { class: FormAutocompleteClass.loading }, h("gov-skeleton", { size: "m" }))) : null, this.focused ? this.list.map((item, index) => {
            const isSelected = this.arrowCounter === index;
            return (h("li", { class: FormAutocompleteClass.item, innerHTML: this.templateResolver(item, isSelected), role: 'option', "aria-posinset": index, tabindex: isSelected ? 0 : -1, "aria-setsize": this.list.length, onTouchStart: (e) => this.onSelectHandler(e, index), onMouseDown: (e) => this.onSelectHandler(e, index), "aria-selected": toBoolAttr(isSelected) }, h("slot", { name: "list-item-left" }), h("slot", { name: "list-item-right" })));
        }) : null)));
    }
    onFocusHandler(e) {
        this.focused = true;
        this.arrowCounter = -1;
        if (this.isValueAccepted && this.searchCallback) {
            this.doSearch();
        }
        e.stopPropagation();
        this.govFocus.emit({
            originalEvent: e,
            component: FormAutocompleteClass.root,
            value: this.value,
            selected: null,
        });
    }
    onBlurHandler(e) {
        this.focused = false;
        this.clearList();
        this.arrowCounter = -1;
        e.stopPropagation();
        this.govBlur.emit({
            originalEvent: e,
            component: FormAutocompleteClass.root,
            value: this.value,
            selected: null,
        });
    }
    onInputHandler(e) {
        this.value = e.target.value;
        e.stopPropagation();
        this.govInput.emit({
            originalEvent: e,
            component: FormAutocompleteClass.root,
            value: this.value,
            selected: null,
        });
        this.doSearch();
    }
    onSelectHandler(e, index = -1) {
        let selected = null;
        if (index > -1) {
            selected = this.list[index];
        }
        else if (has(this.arrowCounter, this.list)) {
            selected = this.list[this.arrowCounter];
        }
        if (selected) {
            this.govSelect.emit({
                component: FormAutocompleteClass.root,
                value: this.value,
                selected: selected,
                originalEvent: e,
            });
            this.clearList();
            if (has(this.nameKey, selected) && typeof selected[this.nameKey] === 'string') {
                this.value = selected[this.nameKey];
            }
        }
    }
    onKeyUpHandler(e) {
        const event = e.detail.originalEvent;
        e.stopPropagation();
        event.stopPropagation();
        if (event.keyCode === 38)
            this.onArrowUp();
        else if (event.keyCode === 40)
            this.onArrowDown();
        else if (event.keyCode === 13) {
            e.preventDefault();
            event.preventDefault();
            this.onSelectHandler(e);
        }
    }
    onKeyDownHandler(e) {
        const event = e.detail.originalEvent;
        e.stopPropagation();
        event.stopPropagation();
        if (event.keyCode === 13) {
            e.preventDefault();
            event.preventDefault();
        }
    }
    /**
     * Focus main input element
     */
    async setFocus(options) {
        return this.inputRef.focus(options);
    }
    /**
     * Blur main input element
     */
    async setBlur() {
        return this.inputRef.blur();
    }
    /**
     * Set options for list
     */
    async setOptions(options) {
        this.list = Array.isArray(options) ? options : [];
        this.arrowCounter = -1;
    }
    /**
     * Clears whisperer value
     */
    async clearValue() {
        this.value = '';
        this.inputRef.value = '';
        await this.inputRef.clearValue();
    }
    /**
     * Clears whisperer value
     */
    async setProcessing(status) {
        this.processing = status;
    }
    /**
     * Set a custom asynchronous function for the whisperer
     */
    async setSearchCallback(callback) {
        this.searchCallback = callback;
    }
    /**
     * Setting a custom whisper result template
     * @param callback
     */
    async setTemplateResolver(callback) {
        this.templateResolver = callback;
    }
    get host() { return getElement(this); }
    static get watchers() { return {
        "size": ["validateSize"],
        "options": ["watchOptions"]
    }; }
};

export { GovFormAutocomplete as gov_form_autocomplete };
//# sourceMappingURL=gov-form-autocomplete.entry.js.map

//# sourceMappingURL=gov-form-autocomplete.entry.js.map