/**
 * DevExtreme (cjs/__internal/ui/m_drop_down_box.js)
 * Version: 23.2.6 (build 24140-0112)
 * Build date: Sun May 19 2024
 *
 * Copyright (c) 2012 - 2024 Developer Express Inc. ALL RIGHTS RESERVED
 * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
 */
"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.default = void 0;
var _component_registrator = _interopRequireDefault(require("../../core/component_registrator"));
var _devices = _interopRequireDefault(require("../../core/devices"));
var _dom_adapter = _interopRequireDefault(require("../../core/dom_adapter"));
var _element = require("../../core/element");
var _renderer = _interopRequireDefault(require("../../core/renderer"));
var _common = require("../../core/utils/common");
var _deferred = require("../../core/utils/deferred");
var _extend = require("../../core/utils/extend");
var _iterator = require("../../core/utils/iterator");
var _type = require("../../core/utils/type");
var _events_engine = _interopRequireDefault(require("../../events/core/events_engine"));
var _index = require("../../events/utils/index");
var _ui = _interopRequireDefault(require("../../ui/drop_down_editor/ui.drop_down_editor"));
var _ui2 = _interopRequireDefault(require("../../ui/editor/ui.data_expression"));
var _utils = require("../../ui/overlay/utils");
var _selectors = require("../../ui/widget/selectors");

function _interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    }
}
const {
    getActiveElement: getActiveElement
} = _dom_adapter.default;
const DROP_DOWN_BOX_CLASS = "dx-dropdownbox";
const ANONYMOUS_TEMPLATE_NAME = "content";
const realDevice = _devices.default.real();
const DropDownBox = _ui.default.inherit({
    _supportedKeys() {
        return (0, _extend.extend)({}, this.callBase(), {
            tab(e) {
                if (!this.option("opened")) {
                    return
                }
                const $tabbableElements = this._getTabbableElements();
                const $focusableElement = e.shiftKey ? $tabbableElements.last() : $tabbableElements.first();
                $focusableElement && _events_engine.default.trigger($focusableElement, "focus");
                e.preventDefault()
            }
        })
    },
    _getTabbableElements() {
        return this._getElements().filter(_selectors.tabbable)
    },
    _getElements() {
        return (0, _renderer.default)(this.content()).find("*")
    },
    _getDefaultOptions() {
        return (0, _extend.extend)(this.callBase(), {
            acceptCustomValue: false,
            contentTemplate: "content",
            openOnFieldClick: true,
            displayValueFormatter: value => Array.isArray(value) ? value.join(", ") : value,
            useHiddenSubmitElement: true
        })
    },
    _getAnonymousTemplateName: () => "content",
    _initTemplates() {
        this.callBase()
    },
    _initMarkup() {
        this._initDataExpressions();
        this.$element().addClass("dx-dropdownbox");
        this.callBase()
    },
    _setSubmitValue() {
        const value = this.option("value");
        const submitValue = this._shouldUseDisplayValue(value) ? this._displayGetter(value) : value;
        this._getSubmitElement().val(submitValue)
    },
    _shouldUseDisplayValue(value) {
        return "this" === this.option("valueExpr") && (0, _type.isObject)(value)
    },
    _sortValuesByKeysOrder(orderedKeys, values) {
        const sortedValues = values.sort((a, b) => orderedKeys.indexOf(a.itemKey) - orderedKeys.indexOf(b.itemKey));
        return sortedValues.map(x => x.itemDisplayValue)
    },
    _renderInputValue() {
        this._rejectValueLoading();
        const values = [];
        if (!this._dataSource) {
            this.callBase(values);
            return (new _deferred.Deferred).resolve()
        }
        const currentValue = this._getCurrentValue();
        let keys = null !== currentValue && void 0 !== currentValue ? currentValue : [];
        keys = Array.isArray(keys) ? keys : [keys];
        const itemLoadDeferreds = (0, _iterator.map)(keys, key => {
            const deferred = new _deferred.Deferred;
            this._loadItem(key).always(item => {
                const displayValue = this._displayGetter(item);
                if ((0, _type.isDefined)(displayValue)) {
                    values.push({
                        itemKey: key,
                        itemDisplayValue: displayValue
                    })
                } else if (this.option("acceptCustomValue")) {
                    values.push({
                        itemKey: key,
                        itemDisplayValue: key
                    })
                }
                deferred.resolve()
            });
            return deferred
        });
        const callBase = this.callBase.bind(this);
        return _deferred.when.apply(this, itemLoadDeferreds).always(() => {
            const orderedValues = this._sortValuesByKeysOrder(keys, values);
            this.option("displayValue", orderedValues);
            callBase(values.length && orderedValues)
        })
    },
    _loadItem(value) {
        const deferred = new _deferred.Deferred;
        const that = this;
        const selectedItem = (0, _common.grep)(this.option("items") || [], item => this._isValueEquals(this._valueGetter(item), value))[0];
        if (void 0 !== selectedItem) {
            deferred.resolve(selectedItem)
        } else {
            this._loadValue(value).done(item => {
                deferred.resolve(item)
            }).fail(args => {
                if (null === args || void 0 === args ? void 0 : args.shouldSkipCallback) {
                    return
                }
                if (that.option("acceptCustomValue")) {
                    deferred.resolve(value)
                } else {
                    deferred.reject()
                }
            })
        }
        return deferred.promise()
    },
    _popupTabHandler(e) {
        if ("tab" !== (0, _index.normalizeKeyName)(e)) {
            return
        }
        const $firstTabbable = this._getTabbableElements().first().get(0);
        const $lastTabbable = this._getTabbableElements().last().get(0);
        const $target = e.target;
        const moveBackward = !!($target === $firstTabbable && e.shiftKey);
        const moveForward = !!($target === $lastTabbable && !e.shiftKey);
        if (moveBackward || moveForward) {
            this.close();
            _events_engine.default.trigger(this._input(), "focus");
            if (moveBackward) {
                e.preventDefault()
            }
        }
    },
    _renderPopupContent() {
        if ("content" === this.option("contentTemplate")) {
            return
        }
        const contentTemplate = this._getTemplateByOption("contentTemplate");
        if (!(contentTemplate && this.option("contentTemplate"))) {
            return
        }
        const $popupContent = this._popup.$content();
        const templateData = {
            value: this._fieldRenderData(),
            component: this
        };
        $popupContent.empty();
        contentTemplate.render({
            container: (0, _element.getPublicElement)($popupContent),
            model: templateData
        })
    },
    _canShowVirtualKeyboard: () => realDevice.mac,
    _isNestedElementActive() {
        const activeElement = getActiveElement();
        return activeElement && this._popup.$content().get(0).contains(activeElement)
    },
    _shouldHideOnParentScroll() {
        return "desktop" === realDevice.deviceType && this._canShowVirtualKeyboard() && this._isNestedElementActive()
    },
    _popupHiddenHandler() {
        this.callBase();
        this._popupPosition = void 0
    },
    _popupPositionedHandler(e) {
        this.callBase(e);
        this._popupPosition = e.position
    },
    _getDefaultPopupPosition(isRtlEnabled) {
        const {
            my: my,
            at: at
        } = this.callBase(isRtlEnabled);
        return {
            my: my,
            at: at,
            offset: {
                v: -1
            },
            collision: "flipfit"
        }
    },
    _popupConfig() {
        const {
            focusStateEnabled: focusStateEnabled
        } = this.option();
        return (0, _extend.extend)(this.callBase(), {
            tabIndex: -1,
            dragEnabled: false,
            focusStateEnabled: focusStateEnabled,
            contentTemplate: "content",
            hideOnParentScroll: this._shouldHideOnParentScroll.bind(this),
            position: (0, _extend.extend)(this.option("popupPosition"), {
                of: this.$element()
            }),
            _ignoreFunctionValueDeprecation: true,
            maxHeight: function() {
                var _a;
                const popupLocation = null === (_a = this._popupPosition) || void 0 === _a ? void 0 : _a.v.location;
                return (0, _utils.getElementMaxHeightByWindow)(this.$element(), popupLocation)
            }.bind(this)
        })
    },
    _popupShownHandler() {
        this.callBase();
        const $firstElement = this._getTabbableElements().first();
        _events_engine.default.trigger($firstElement, "focus")
    },
    _setCollectionWidgetOption: _common.noop,
    _optionChanged(args) {
        this._dataExpressionOptionChanged(args);
        switch (args.name) {
            case "dataSource":
                this._renderInputValue();
                break;
            case "displayValue":
                this.option("text", args.value);
                break;
            case "displayExpr":
                this._renderValue();
                break;
            case "contentTemplate":
                this._invalidate();
                break;
            default:
                this.callBase(args)
        }
    }
}).include(_ui2.default);
(0, _component_registrator.default)("dxDropDownBox", DropDownBox);
var _default = DropDownBox;
exports.default = _default;
