import { r as registerInstance, c as createEvent, h, H as Host, g as getElement } from './index-ClISz4NF.js';
import { g as govForm, c as FormMultiSelectClass, d as FormMultiselectSizes } from './form-DvhJiKwA.js';
import { g as govHost, a as toBoolAttr, t as toBoolAttrIfDefined } from './template-CoD1xawt.js';
import { v as validateProp } from './props-CJZgTDla.js';
import { c as createID, r as removeDiacritics } from './string.utils-vN03FcXN.js';
import { p as propsValueToArray } from './array.utils-CJ0U_ONv.js';
import { t as tick } from './stencil.utils-Cjg0wpDG.js';
import { A as AttributeObserver, a as ariaAttributes } from './attribute-Bz_RzYFb.js';
import './sizes-BcQO4NH2.js';
import './utils-CQvUntGY.js';
import './constants-BegH8u6i.js';
import './colors-U40vKHrs.js';
import './constants-aqe7GX2n.js';
import './constants-CysDgoMA.js';
import './gov.log-BtqD9K8d.js';
import './helpers.types-DNztiAH0.js';

const GovFormMultiSelect = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.govFocus = createEvent(this, "gov-focus");
        this.govBlur = createEvent(this, "gov-blur");
        this.govChange = createEvent(this, "gov-change");
        this.govSelect = createEvent(this, "gov-select");
        this.govRemove = createEvent(this, "gov-remove");
        /**
         * Select’s size.
         */
        this.size = 'm';
        /**
         * Option to hide the list of selected items
         */
        this.hideSelectedList = false;
        /**
         * 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 select component disabled.
         * This prevents users from being able to interact with the select, and conveys its inactive state to assistive technologies.
         */
        this.disabled = false;
        /**
         * Custom message for when there is a blank sheet
         */
        this.messageEmpty = 'Nebyly nalezeny žádné výsledky';
        /**
         * Custom message for when data is loaded
         */
        this.messageLoading = 'Načítám...';
        this.selectedOptionsState = [];
        this.optionsState = [];
        this.inheritedAttributes = {};
        this.selectId = createID('GovSelect');
        this.listId = createID('GovMultiList');
        this.h = govHost(this.host);
        this.f = govForm(this.h);
    }
    validateSize(newValue) {
        validateProp(FormMultiselectSizes, newValue, FormMultiSelectClass.root);
    }
    watchOptions(newValue) {
        this.optionsState = propsValueToArray(newValue);
    }
    watchValue(newValue) {
        this.selectedOptionsState = propsValueToArray(newValue);
    }
    componentDidLoad() {
        this.attributeObserver = new AttributeObserver(this.host, (attributeName, newValue) => {
            this.onAriaAttributeChange(attributeName, newValue);
        });
        this.attributeObserver.startObserving(ariaAttributes);
        this.initAutocomplete();
    }
    componentWillLoad() {
        this.validateSize(this.size);
        this.optionsState = propsValueToArray(this.options);
        this.selectedOptionsState = propsValueToArray(this.value);
    }
    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 });
    }
    getAvailableOptions(ignoreFilter = false) {
        if (Array.isArray(this.optionsState) && this.optionsState.length) {
            if (ignoreFilter) {
                return this.optionsState;
            }
            return this.optionsState.filter((option) => {
                const selectedIndex = this.selectedValueIndex(option.value);
                return (selectedIndex !== -1 || (option === null || option === void 0 ? void 0 : option.disabled)) ? false : true;
            }).map((option) => { var _a; return ({ name: (_a = option.label) !== null && _a !== void 0 ? _a : option.value, value: option.value }); });
        }
        return Array.from(this.selectRef.querySelectorAll('option'))
            .filter((option) => {
            if (ignoreFilter) {
                return true;
            }
            const selectedIndex = this.selectedValueIndex(option.value);
            return !(option.disabled || option.selected || selectedIndex > -1);
        })
            .map((option) => ({ name: option.textContent, value: option.value }));
    }
    initAutocomplete() {
        var _a, _b, _c, _d, _e;
        (_a = this.autocompleteRef) === null || _a === void 0 ? void 0 : _a.addEventListener('gov-select', this.onSelectHandler.bind(this));
        (_b = this.autocompleteRef) === null || _b === void 0 ? void 0 : _b.addEventListener('gov-input', this.onInputHandler.bind(this));
        (_c = this.autocompleteRef) === null || _c === void 0 ? void 0 : _c.addEventListener('gov-focus', this.onFocusHandler.bind(this));
        (_d = this.autocompleteRef) === null || _d === void 0 ? void 0 : _d.addEventListener('gov-blur', this.onBlurHandler.bind(this));
        (_e = this.autocompleteRef) === null || _e === void 0 ? void 0 : _e.setSearchCallback(searchString => {
            return new Promise(resolve => {
                const data = this.getAvailableOptions();
                if (String(searchString).length === 0) {
                    return resolve(data);
                }
                resolve(data.filter(({ label, value }) => {
                    if (!label)
                        label = value;
                    return removeDiacritics(label).toLowerCase().indexOf(removeDiacritics(searchString).toLowerCase()) > -1;
                }));
            });
        }).finally();
    }
    selectedValueIndex(value) {
        return this.selectedOptionsState.findIndex((selected) => selected === value);
    }
    getOptionElement(value) {
        return this.selectRef.querySelector('option[value="' + value + '"]');
    }
    getOption(value) {
        var _a;
        return (_a = this.getAvailableOptions(true).find((option) => option.value === value)) !== null && _a !== void 0 ? _a : null;
    }
    selectOption(newOption, notify = true) {
        const index = this.selectedValueIndex(newOption);
        if (index === -1) {
            this.selectedOptionsState = [...this.selectedOptionsState, newOption];
            this.value = this.selectedOptionsState;
            if (notify) {
                this.govChange.emit({
                    component: FormMultiSelectClass.root,
                    value: this.selectedOptionsState,
                });
                this.govSelect.emit({
                    component: FormMultiSelectClass.root,
                    value: this.selectedOptionsState,
                });
            }
            const option = this.getOptionElement(newOption);
            if (option) {
                option.selected = true;
            }
        }
    }
    removeOption(removeOption, notify = true) {
        const index = this.selectedValueIndex(removeOption);
        if (index !== -1) {
            this.selectedOptionsState.splice(index, 1);
            this.selectedOptionsState = [...this.selectedOptionsState];
            this.value = this.selectedOptionsState;
            if (notify) {
                this.govChange.emit({
                    component: FormMultiSelectClass.root,
                    value: this.selectedOptionsState,
                });
                this.govRemove.emit({
                    component: FormMultiSelectClass.root,
                    value: this.selectedOptionsState,
                });
            }
            const option = this.getOptionElement(removeOption);
            if (option) {
                option.selected = false;
            }
        }
    }
    async componentDidRender() {
        this.f.passAttrToLabel('required', String(this.required));
        tick(() => {
            this.selectRef.querySelectorAll('option').forEach((option) => {
                if (option.selected) {
                    this.selectOption(option.value, false);
                }
            });
        });
    }
    render() {
        return (h(Host, { key: 'b5f6643779e88a7fd84c50e0e28a2e3df55ef5b1', class: FormMultiSelectClass.root, size: this.size }, h("div", { key: 'eac5219ecea75ffa80cf00e2ea7b657d011a4364', class: FormMultiSelectClass.wrap }, this.h.hasSlot('prefix') && h("slot", { key: '043326a3213e27ba4bd82fc07d807f5385cad621', name: "prefix" }), h("gov-form-autocomplete", { key: '908d9dd75e8eccf489bf02c38830742119f3f5a8', value: this.valueState, disabled: this.disabled, identifier: this.identifier || this.selectId, required: false, invalid: this.invalid, success: this.success, size: this.size, placeholder: this.placeholder, "message-empty": this.messageEmpty, "message-loading": this.messageLoading, ref: el => (this.autocompleteRef = el), minlength: 0, "aria-owns": this.listId }, this.success && h("gov-icon", { key: '5462998619176ad9b9fb64bb4cbfa64640b1882b', slot: "validation-icon", class: "validation-icon", name: "check-lg", type: "components" }), this.invalid && h("gov-icon", { key: '927ab032bef36a8de9dcbdc0b04fb9ba788ff3ef', slot: "validation-icon", class: "validation-icon", name: "exclamation-lg", type: "components" }), h("gov-icon", { key: '92064ab6e3af5b2614eabe328795602613e06fdb', slot: "icon-end", class: "arrow-icon", name: "chevron-down", type: "components" })), h("select", Object.assign({ key: 'e344464b72f03ab9cf5e9ccdbd5caaff913774f9', hidden: true, class: 'hidden-select-list', "aria-hidden": toBoolAttr(true), multiple: true, required: this.required, name: this.name, disabled: this.disabled, ref: el => (this.selectRef = el) }, this.inheritedAttributes, { "aria-disabled": toBoolAttrIfDefined(this.disabled), "aria-required": toBoolAttrIfDefined(this.required), "aria-invalid": toBoolAttrIfDefined(this.invalid) }), h("slot", { key: 'b7713729d23f54f2f7d9489bd816237565b87d43' }), Array.isArray(this.optionsState) && this.optionsState.map((option) => {
            var _a;
            const selectedOption = this.selectedValueIndex(option.value);
            return (h("option", { value: option.value, selected: selectedOption > -1, disabled: option === null || option === void 0 ? void 0 : option.disabled }, (_a = option.label) !== null && _a !== void 0 ? _a : option.value));
        })), this.h.hasSlot('sufix') && h("slot", { key: 'ae1452913889844708b397d9d6e66fa071f85522', name: "sufix" })), this.hideSelectedList === false ? (h("ul", { role: "listbox", id: this.listId, class: FormMultiSelectClass.list }, Array.isArray(this.selectedOptionsState) && this.selectedOptionsState.map(selected => {
            var _a;
            const option = this.getOption(selected);
            if (!option)
                return null;
            return (h("li", { class: FormMultiSelectClass.item, role: "option" }, (_a = option.label) !== null && _a !== void 0 ? _a : option.value, h("gov-button", { "aria-label": `Odebrat vybranou položku ${option.label}`, color: "primary", type: "base", size: this.size, "on-gov-click": () => this.onTagRemove(selected) }, h("gov-icon", { name: "x-lg", type: "components" }))));
        }))) : null));
    }
    onFocusHandler(e) {
        e.stopPropagation();
        this.focused = true;
        this.govFocus.emit({
            component: FormMultiSelectClass.root,
            originalEvent: e,
            value: this.selectedOptionsState,
        });
    }
    onBlurHandler(e) {
        e.stopPropagation();
        e.stopPropagation();
        this.focused = false;
        this.govBlur.emit({
            component: FormMultiSelectClass.root,
            originalEvent: e,
            value: this.selectedOptionsState,
        });
    }
    onInputHandler(e) {
        this.valueState = e.detail.value;
        e.stopPropagation();
    }
    onSelectHandler(e) {
        e.stopPropagation();
        const value = e.detail.selected;
        this.selectOption(value.value);
        this.valueState = '';
        this.autocompleteRef.clearValue().finally();
        this.autocompleteRef.focus();
    }
    onTagRemove(removeOption) {
        this.removeOption(removeOption);
    }
    /**
     * Returns the current state of the component
     */
    async setFocus(options) {
        return this.selectRef.focus(options);
    }
    /**
     * Sets the ordered value of the element
     */
    async setValue(value) {
        this.valueState = value;
    }
    /**
     * Returns an instance of the native html select element
     */
    async getRef() {
        return this.selectRef;
    }
    get host() { return getElement(this); }
    static get watchers() { return {
        "size": ["validateSize"],
        "options": ["watchOptions"],
        "value": ["watchValue"]
    }; }
};

export { GovFormMultiSelect as gov_form_multi_select };
//# sourceMappingURL=gov-form-multi-select.entry.js.map

//# sourceMappingURL=gov-form-multi-select.entry.js.map