// #region Imports
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var SelectElement_1;
import { ScrollerServiceLocator } from '../../../../Dom/Scroller';
import { on } from '@breadstone/mosaik-elements';
import { Appearanceable } from '../../../Behaviors/Appearanceable';
import { Clearable } from '../../../Behaviors/Clearable';
import { Disableable } from '../../../Behaviors/Disableable';
import { DropDownable } from '../../../Behaviors/DropDownable';
import { Invalidable } from '../../../Behaviors/Invalidable';
import { Labelable } from '../../../Behaviors/Labelable';
import { Valueable } from '../../../Behaviors/Valueable';
import { Variantable } from '../../../Behaviors/Variantable';
import { ClickOutsideController } from '../../../Controllers/ClickOutsideController';
import { IntlController } from '../../../../Intl/IntlController';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Component } from '../../../Decorators/ComponentDecorator';
import { Property } from '../../../Decorators/PropertyDecorator';
import { Watch } from '../../../Decorators/WatchDecorator';
import { Key } from '../../../Types/Key';
import { FloatingElement } from '../../Primitives/Floating/FloatingElement';
import { SelectorElement } from '../../Selectors/Abstracts/Selector/SelectorElement';
import { TextBoxElement } from '../TextBox/TextBoxElement';
import { selectElementTemplate } from './SelectElementTemplate';
import { SelectItemElement } from './SelectItemElement';
import { SelectItemGroupElement } from './SelectItemGroupElement';
import { selectElementJoyStyle } from './Themes/SelectElement.Joy';
import { selectElementRetroStyle } from './Themes/SelectElement.Retro';
import { selectElementCosmopolitanStyle } from './Themes/SelectElement.Cosmopolitan';
import { Themeable } from '../../../Behaviors/Themeable';
import { TextAlignment } from '../../../Types/TextAlignment';
import { PortalElement } from '../../Primitives/Portal/PortalElement';
import { Slottable } from '../../../Behaviors/Slottable';
import { SelectElementIntl } from './SelectElementIntl';
import { ButtonElement } from '../../Buttons/Button/ButtonElement';
import { EmptyStateElement } from '../../States/Empty/EmptyStateElement';
import { ProjectionController } from '../../Primitives/Portal/ProjectionController';
import { contains, Filterable, getMemberValue } from '../../../Behaviors/Filterable';
// #endregion
/**
 * Select - A UI element used for choosing from a list of options.
 *
 * @element mosaik-select
 *
 * @category Forms
 *
 * @fires cleared - Fired when the value is cleared.
 * @fires selectionChanged - Fired when the selection has changed.
 * @fires itemsChanged - Fired when the items has changed.
 *
 * @slot - The default menu slot.
 * @slot prefix - The prefix slot.
 * @slot suffix - The suffix slot.
 * @slot filter - The filter slot.
 *
 * @keyhandle UpArrow - Selects the previous item.
 * @keyhandle DownArrow - Selects the next item.
 * @keyhandle Space - Toggles the dropdown.
 * @keyhandle Enter - Toggles the dropdown.
 * @keyhandle Escape - Closes the dropdown if it is open, otherwise clears the value.
 * @keyhandle Tab - Closes the dropdown.
 *
 * @dependency {SelectItemElement} mosaik-select-item - SelectItemElement
 * @dependency {SelectItemGroupElement} mosaik-select-item-group - SelectItemGroupElement
 * @dependency {TextBoxElement} mosaik-text-box - TextBoxElement
 * @dependency {ButtonElement} mosaik-button - ButtonElement
 * @dependency {FloatingElement} mosaik-floating - FloatingElement
 * @dependency {PortalElement} mosaik-portal - PortalElement
 * @dependency {EmptyStateElement} mosaik-empty-state - EmptyStateElement
 *
 * @example
 * ```html
 * <mosaik-select label="Select a fruit">
 *     <mosaik-select-item value="apple" label="Apple"></mosaik-select-item>
 *     <mosaik-select-item value="banana" label="Banana"></mosaik-select-item>
 *     <mosaik-select-item value="cherry" label="Cherry"></mosaik-select-item>
 * </mosaik-select>
 * ```
 *
 * @public
 */
let SelectElement = SelectElement_1 = class SelectElement extends Slottable(DropDownable(Appearanceable(Variantable(Labelable(Clearable(Invalidable(Disableable(Valueable(Themeable(Filterable(SelectorElement))))))))))) {
    // #region Fields
    _inputElement;
    _floatingElement;
    _clickOutsideController;
    _intlController;
    _projectionController;
    _itemsClickSubscriptions;
    _isEditable;
    _isReadOnly;
    _value;
    _placeholder;
    _required;
    _textAlign;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        this._isEditable = false;
        this._isReadOnly = false;
        this._value = null;
        this._placeholder = '';
        this._required = false;
        this._textAlign = TextAlignment.Left;
        this._itemsClickSubscriptions = new Array();
        this._clickOutsideController = new ClickOutsideController(this, {
            ignored: () => [this._floatingElement],
            skipInitial: true,
            callback: () => this.close()
        });
        this._intlController = new IntlController(this, {
            factory: () => new SelectElementIntl()
        });
        this._projectionController = new ProjectionController(this, {
            slotName: '',
            targetSelector: '[part="projection"]',
            projecting: (element) => {
                element.setAttribute(`${SelectElement_1.is}-projection`, '');
            }
        });
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `{@link is}` property.
     * The `{@link is}` property represents natural name of this element.
     *
     * @public
     * @static
     * @readonly
     */
    static get is() {
        return 'mosaik-select';
    }
    /**
     * Gets or sets the `isEditable` property.
     *
     * @public
     * @attr
     */
    get isEditable() {
        return this._isEditable;
    }
    set isEditable(value) {
        if (this._isEditable !== value) {
            this._isEditable = value;
            this.requestUpdate('isEditable');
        }
    }
    /**
     * Gets or sets the `isReadOnly` property.
     *
     * @public
     * @attr
     */
    get isReadOnly() {
        return this._isReadOnly;
    }
    set isReadOnly(value) {
        if (this._isReadOnly !== value) {
            this._isReadOnly = value;
            this.requestUpdate('isReadOnly');
        }
    }
    /**
     * Gets or sets the `value` property.
     *
     * @public
     * @override
     */
    get value() {
        return this._value;
    }
    set value(value) {
        if (this._value !== value) {
            this._value = value;
            this.requestUpdate('value');
        }
    }
    /**
     * Gets or sets the `placeholder` property.
     *
     * @public
     */
    get placeholder() {
        return this._placeholder;
    }
    set placeholder(value) {
        if (this._placeholder !== value) {
            this._placeholder = value;
            this.requestUpdate('placeholder');
        }
    }
    /**
     * Determines whether the component is required or not.
     * If `true`, the component will require a value when submitted.
     *
     * @public
     * @attr
     */
    get required() {
        return this._required;
    }
    set required(value) {
        if (this._required !== value) {
            this._required = value;
            this.requestUpdate('required');
        }
    }
    /**
     * Determines the text alignment of the component.
     *
     * @public
     * @attr
     */
    get textAlign() {
        return this._textAlign;
    }
    set textAlign(value) {
        if (this._textAlign !== value) {
            this._textAlign = value;
            this.requestUpdate('textAlign');
        }
    }
    /**
     * Gets the items of the Select.
     *
     * @remark
     * It is important to override the base class property to ensure that only
     * {@link SelectItemElement} instances are returned.
     *
     * @public
     * @readonly
     * @ignore
     */
    get items() {
        // flat all items
        return this._projectionController.elements
            .flatMap((x) => x instanceof SelectItemGroupElement ? x.items : x)
            .filter((x) => x instanceof SelectItemElement);
    }
    /**
     * Returns the `intl` property.
     *
     * @public
     * @readonly
     */
    get intl() {
        return this._intlController.intl;
    }
    // #endregion
    // #region Methods
    /**
     * Resets the value, all kinds of validation and errors.
     *
     * @public
     */
    reset() {
        this.clear();
        this.invalid = false;
    }
    /**
     * Checks the validity of the element and returns `true` if it is valid; otherwise, `false`.
     *
     * @public
     * @override
     */
    checkValidity() {
        return this.shadowRoot
            ? this._inputElement.checkValidity()
            : true;
    }
    /**
     * Clears the value of the element but not the validation.
     *
     * @public
     * @override
     */
    clear(force) {
        const isCleared = super.clear(force);
        if (isCleared) {
            // clears the selection
            this.selectedItem = null;
            this.items.forEach((x) => x.isActive = false);
            this.emit('input', {
                bubbles: true,
                composed: true
            });
            this.emit('change', {
                bubbles: true,
                composed: true
            });
        }
        return isCleared;
    }
    /**
     * @public
     * @override
     */
    connectedCallback() {
        super.connectedCallback();
        this.keyboard
            .add([Key.UpArrow], () => this.selectPrevious(), undefined, { preventDefault: true })
            .add([Key.DownArrow], () => this.selectNext(), undefined, { preventDefault: true })
            .add([Key.Space, Key.Enter], () => this.toggle(), undefined, { preventDefault: true })
            .add([Key.Escape], () => {
            if (this.isDropDownOpen) {
                this.close();
            }
            else {
                this.clear();
            }
        }, undefined, { preventDefault: true })
            .add([Key.Tab], () => this.close());
    }
    /**
     * @protected
     * @template
     *
     * @param active - A value indicating whether the floating is active.
     */
    onFloatingActiveChanged(active) {
        // when the floating opens, we want to scroll to the selected item.
        if (active) {
            const activeItem = this.items.find((x) => x.isActive);
            const scrollable = this._floatingElement.getScrollableElement();
            if (activeItem) {
                requestAnimationFrame(() => {
                    ScrollerServiceLocator.current.scrollToElementInContainer(scrollable, activeItem, { behavior: 'instant' });
                });
            }
        }
    }
    /**
     * @protected
     * @override
     */
    onApplyTemplate() {
        super.onApplyTemplate();
        this._inputElement = this.getTemplatePart('input');
        this._floatingElement = this.getTemplatePart('popup');
    }
    /**
     * @protected
     * @override
     */
    onItemsChanged() {
        super.onItemsChanged();
        // reset all click handler if items are changed.
        this._itemsClickSubscriptions.forEach((x) => x.dispose());
        this.items.forEach((x) => {
            this._itemsClickSubscriptions.push(on(x, 'click', () => {
                if (x.disabled) {
                    return;
                }
                this.onSelectItem(x);
                // when a child is clicked, the popup closes, so we need to focus the input.
                requestAnimationFrame(() => {
                    this._inputElement.focus();
                });
            }, false));
        });
        this.initialSelection();
    }
    /**
     * @protected
     * @override
     */
    onSelectionChanged(oldIndex, newIndex) {
        super.onSelectionChanged(oldIndex, newIndex, () => {
            const current = this.selectedItem;
            // unselect siblings
            this.items.forEach((y) => y.isActive = false);
            if (current) {
                current.isActive = true;
                // eslint-disable-next-line @typescript-eslint/no-base-to-string
                this.value = String(current.value ?? current.label);
            }
        });
        this.requestUpdate();
        this.close();
    }
    /**
     * @protected
     */
    onValuePropertyChanged(_prev, next) {
        // try get item from value
        // 1. item label
        // 2. item value as string
        if (next) {
            const item = this.items.find((x) => x.label === this.value || x.value === this.value);
            if (item) {
                this.onSelectItem(item);
            }
        }
    }
    /**
     * @protected
     */
    onDisabledPropertyChanged(_prev, next) {
        this.items.forEach((x) => x.disabled = next ?? false);
        if (next) {
            this.close();
        }
    }
    /**
     * @protected
     */
    onIsDropDownOpenPropertyChanged(_prev, next) {
        if (next) {
            this._clickOutsideController.observe();
        }
        else {
            // reset filter when dropdown closes
            this.filter = '';
            this._clickOutsideController.unobserve();
        }
    }
    /**
     * @protected
     */
    onFilterPropertyChanged(_, next) {
        if (next) {
            this.items.forEach((x) => {
                const text = this.filterMemberPath
                    ? this.filterMemberPath
                        ? String(getMemberValue(x, this.filterMemberPath))
                        : ''
                    : x.displayText;
                const hasText = contains(text, next, true);
                x.hidden = !hasText;
            });
        }
        else {
            this.items.forEach((x) => {
                x.hidden = false;
            });
        }
    }
    /**
     * @private
     *
     * @param item - The item to select.
     * @param force - A value indicating whether to force the selection.
     */
    onSelectItem(item, force) {
        if (!item.isActive || force) {
            this.select(item);
            this.requestUpdate();
            this.close();
        }
    }
    /**
     * @private
     */
    initialSelection() {
        void this.updateComplete.then(() => {
            const item = this.items.find((x) => x.isActive || x.isSelected || x.label === this.value || x.value === this.value);
            if (item) {
                this.onSelectItem(item, true);
            }
        });
    }
};
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], SelectElement.prototype, "isEditable", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], SelectElement.prototype, "isReadOnly", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [Object])
], SelectElement.prototype, "value", null);
__decorate([
    Property({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], SelectElement.prototype, "placeholder", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], SelectElement.prototype, "required", null);
__decorate([
    Attribute({ type: TextAlignment }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], SelectElement.prototype, "textAlign", null);
__decorate([
    Watch('value', { waitUntilFirstUpdate: true }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", void 0)
], SelectElement.prototype, "onValuePropertyChanged", null);
__decorate([
    Watch('disabled', { waitUntilFirstUpdate: true }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Boolean, Boolean]),
    __metadata("design:returntype", void 0)
], SelectElement.prototype, "onDisabledPropertyChanged", null);
__decorate([
    Watch('isDropDownOpen', { waitUntilFirstUpdate: true }),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Boolean, Boolean]),
    __metadata("design:returntype", void 0)
], SelectElement.prototype, "onIsDropDownOpenPropertyChanged", null);
__decorate([
    Watch('filter'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", void 0)
], SelectElement.prototype, "onFilterPropertyChanged", null);
SelectElement = SelectElement_1 = __decorate([
    Component({
        selector: 'mosaik-select',
        template: selectElementTemplate,
        themes: {
            joy: selectElementJoyStyle,
            retro: selectElementRetroStyle,
            cosmopolitan: selectElementCosmopolitanStyle
        },
        host: {
            tabIndex: '0'
        },
        options: {
            mode: 'open',
            delegatesFocus: true
        },
        imports: [
            SelectItemElement,
            SelectItemGroupElement,
            TextBoxElement,
            ButtonElement,
            PortalElement,
            FloatingElement,
            EmptyStateElement,
            TextBoxElement
        ]
    }),
    __metadata("design:paramtypes", [])
], SelectElement);
export { SelectElement };
//# sourceMappingURL=SelectElement.js.map