"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
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);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UISelect = void 0;
var custom_multiple_selection_1 = require("./select2-adapters/custom-multiple-selection");
var aurelia_i18n_1 = require("aurelia-i18n");
var aurelia_framework_1 = require("aurelia-framework");
var aurelia_framework_2 = require("aurelia-framework");
var aurelia_templating_1 = require("aurelia-templating");
var data_source_1 = require("../../data/data-source");
var ui_internal_1 = require("../../utils/ui-internal");
var base_input_1 = require("./base-input");
var data_context_1 = require("../../data/data-context");
require("select2");
var custom_ajax_adapter_1 = require("./select2-adapters/custom-ajax-adapter");
var custom_attach_body_1 = require("./select2-adapters/custom-attach-body");
var custom_dropdown_adapter_1 = require("./select2-adapters/custom-dropdown-adapter");
var aurelia_event_aggregator_1 = require("aurelia-event-aggregator");
var custom_allow_clear_1 = require("./select2-adapters/custom-allow-clear");
var config_1 = require("../../config");
var UISelect = exports.UISelect = (function (_super) {
    __extends(UISelect, _super);
    function UISelect(element, targetInstruction, datacontext, i18n, bindingEngine, taskQueue, eventAggregator, config) {
        var _this_1 = _super.call(this, element) || this;
        _this_1.datacontext = datacontext;
        _this_1.i18n = i18n;
        _this_1.bindingEngine = bindingEngine;
        _this_1.taskQueue = taskQueue;
        _this_1.eventAggregator = eventAggregator;
        _this_1.config = config;
        _this_1.placeholder = "";
        _this_1.dataSource = null;
        _this_1.optionsValue = "id";
        _this_1.allowClear = true;
        _this_1.pageSize = 25;
        _this_1.onChange = function () { };
        _this_1.onReady = function () { };
        _this_1.selectionTitle = true;
        _this_1.dropdownAutoWidth = false;
        _this_1.isFocus = false;
        _this_1.callNumber = 0;
        _this_1.ignoreChange = false;
        _this_1.closeOnFooterClick = false;
        _this_1.closeOnHeaderClick = false;
        _this_1.clickableElements = [];
        _this_1.onChangeCollectionObserverDisposables = [];
        _this_1.submitOnLoad = {
            isLoading: false,
            isSubmitting: false
        };
        _this_1.localEntityMatcher = function (a, b) {
            var a_id = a != null && a.id != null ? a.id : a;
            var b_id = b != null && b.id != null ? b.id : b;
            if (a_id == "")
                a_id = 0;
            if (b_id == "")
                b_id = 0;
            return (a_id != null && b_id != null && a_id.toString != null && b_id.toString != null) ? a_id.toString() === b_id.toString() : a_id == b_id;
        };
        _this_1.getTemplateFromSelect2 = function (select2Data) {
            var _a;
            if (((_a = _this_1.itemTemplate) === null || _a === void 0 ? void 0 : _a.length) > 0 && select2Data.data != null) {
                var view = ui_internal_1.UIInternal.compileTemplate(_this_1.itemTemplate, _this_1, select2Data.data);
                if (view.attached != null)
                    view.attached();
                return view.fragment;
            }
            return select2Data.text;
        };
        _this_1.getTemplateSelection = function (select2Data) {
            var _a;
            if (((_a = _this_1.selectionTemplate) === null || _a === void 0 ? void 0 : _a.length) > 0) {
                var overrideContext = (0, aurelia_framework_1.createOverrideContext)(_this_1.bindingContext, _this_1.parentContext);
                var view = ui_internal_1.UIInternal.compileTemplate(_this_1.selectionTemplate, _this_1, (0, aurelia_framework_1.createOverrideContext)(select2Data, overrideContext));
                if (view.attached != null)
                    view.attached();
                return view.fragment.textContent.trim().length > 0 ? view.fragment : select2Data.text;
            }
            return select2Data.text;
        };
        _this_1.closeOnClickHandler = function () { _this_1.close(); };
        _this_1.itemTemplate = _this_1.getTemplate(targetInstruction, "itemTemplate");
        _this_1.headerTemplate = _this_1.getTemplate(targetInstruction, "headerTemplate");
        _this_1.footerTemplate = _this_1.getTemplate(targetInstruction, "footerTemplate");
        _this_1.closeOnFooterClick = targetInstruction.elementInstruction["closeOnFooterClick"];
        _this_1.closeOnHeaderClick = targetInstruction.elementInstruction["closeOnHeaderClick"];
        _this_1.selectionTemplate = _this_1.getTemplate(targetInstruction, "selectionTemplate");
        _this_1.multiple = element.hasAttribute("multiple");
        _this_1.tags = element.hasAttribute("tags");
        if (element.hasAttribute('on-selected-size')) {
            _this_1.onSelectedSize = element.getAttribute('on-selected-size');
        }
        return _this_1;
    }
    Object.defineProperty(UISelect.prototype, "isFocusClass", {
        get: function () {
            if (this.disabled === false && this.isDisabled === false && this.readonly === false && this.isFocus === true) {
                return 'ui-select--focus';
            }
            return '';
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(UISelect.prototype, "isMultipleClass", {
        get: function () {
            if (this.multiple === true) {
                return 'ui-select--multiple';
            }
            return '';
        },
        enumerable: false,
        configurable: true
    });
    UISelect.prototype.bind = function (bindingContext, overrideContext) {
        var _a;
        _super.prototype.bind.call(this);
        this.bindingContext = bindingContext;
        this.parentContext = overrideContext;
        if (hasParent(this.element, "ui-table")) {
            this.valueChanged(this.value, null);
        }
        (_a = this.focusSearchWhenOpen) !== null && _a !== void 0 ? _a : (this.focusSearchWhenOpen = this.config.globalConfig.uiSelectFocusSearchWhenOpen);
    };
    UISelect.prototype.attached = function () {
        var _this_1 = this;
        ui_internal_1.UIInternal.queueMicroTask(function () {
            var _a, _b, _c, _d;
            _this_1.buildSelect2();
            _this_1.setupSelect2EventsHandler();
            if (_this_1.value != null && Object.keys(_this_1.value).length > 0 && Object.keys(_this_1.value).indexOf('id') > -1) {
                _this_1.$select.val(_this_1.value.id + "").trigger("change");
            }
            else {
                _this_1.$select.val(_this_1.value).trigger("change");
            }
            if (Array.isArray(_this_1.value)) {
                var observer_1 = _this_1.bindingEngine.collectionObserver(_this_1.value);
                _this_1.onChangeCollectionObserverDisposables.push(observer_1.subscribe(function () {
                    var _a;
                    (_a = _this_1.$select) === null || _a === void 0 ? void 0 : _a.val(_this_1.value).trigger("change");
                    _this_1.callOnChangeCallback(_this_1.value);
                }));
            }
            if (((_a = _this_1.headerTemplate) === null || _a === void 0 ? void 0 : _a.length) > 0) {
                var $searchfield = _this_1.select2Instance.$dropdown.find(".select2-search").first();
                var view = ui_internal_1.UIInternal.compileTemplate(_this_1.headerTemplate, _this_1, (0, aurelia_framework_1.createOverrideContext)(_this_1.bindingContext, _this_1.parentContext));
                if (_this_1.closeOnHeaderClick) {
                    (_b = view.fragment.childNodes) === null || _b === void 0 ? void 0 : _b.forEach(function (child) {
                        child.addEventListener('click', _this_1.closeOnClickHandler);
                        _this_1.clickableElements.push(child);
                    });
                }
                $searchfield.after($(view.fragment));
            }
            if (((_c = _this_1.footerTemplate) === null || _c === void 0 ? void 0 : _c.length) > 0) {
                var $searchresults = _this_1.select2Instance.$dropdown.find(".select2-results").first();
                var view = ui_internal_1.UIInternal.compileTemplate(_this_1.footerTemplate, _this_1.bindingContext, (0, aurelia_framework_1.createOverrideContext)(_this_1.bindingContext, _this_1.parentContext));
                if (_this_1.closeOnFooterClick) {
                    (_d = view.fragment.childNodes) === null || _d === void 0 ? void 0 : _d.forEach(function (child) {
                        child.addEventListener('click', _this_1.closeOnClickHandler);
                        _this_1.clickableElements.push(child);
                    });
                }
                $searchresults.after($(view.fragment));
            }
            var observer = new MutationObserver(function (mutations) {
                mutations.forEach(function (mutation) {
                    if (mutation.attributeName === "class") {
                        var attributeValue = $(mutation.target).prop(mutation.attributeName);
                        if (attributeValue.indexOf('select2-container--open') > -1 || attributeValue.indexOf('select2-container--focus') > -1) {
                            _this_1.isFocus = true;
                        }
                        else {
                            _this_1.isFocus = false;
                        }
                    }
                });
            });
            observer.observe(_this_1.select2Instance.$container.get(0), {
                attributes: true
            });
            if (_this_1.value) {
                _this_1.resizeSelection(true);
            }
            _this_1.manageSelectionTitle();
            ui_internal_1.UIInternal.nextTick(function () { return _this_1.onReady(); });
        });
        this.changeLanguageSubscription = this.eventAggregator.subscribe(ui_internal_1.UIInternal.EVT_CHANGE_LANGUAGE, function () {
            _this_1.changeLanguage();
        });
    };
    UISelect.prototype.setupSelect2EventsHandler = function () {
        var _this_1 = this;
        var _this = this;
        var eventHandler = function (e) { return _this_1.onKeyPressed(e); };
        var getSearchField = function () { return document.getElementsByClassName('select2-search__field')[0]; };
        this.$select.on('select2:closing', function (e) {
            var _a;
            $(e.target).data("select2").$selection.one('focus focusin', function (e) {
                e.stopPropagation();
            });
            if (false == _this.multiple) {
                if (_this.submitOnLoad.isLoading && _this.submitOnLoad.isSubmitting) {
                    e.stopPropagation();
                }
                else {
                    (_a = getSearchField()) === null || _a === void 0 ? void 0 : _a.removeEventListener('keydown', eventHandler, true);
                }
            }
        });
        this.$select.on('select2:open', function (e) {
            var _a, _b, _c;
            if (e.currentTarget.tagName.toUpperCase() == 'SELECT') {
                if (_this.focusSearchWhenOpen) {
                    (_a = $('.select2-search--dropdown input.select2-search__field').get(0)) === null || _a === void 0 ? void 0 : _a.focus();
                    $('.select2-search--dropdown input.select2-search__field').trigger('focus');
                    setTimeout(function () {
                        var _a;
                        (_a = $('.select2-search--dropdown input.select2-search__field').get(0)) === null || _a === void 0 ? void 0 : _a.focus();
                        $('.select2-search--dropdown input.select2-search__field').trigger('focus');
                    }, 0);
                }
                else {
                    (_b = $('.select2-search--dropdown input.select2-search__field').get(0)) === null || _b === void 0 ? void 0 : _b.blur();
                    $('.select2-search--dropdown input.select2-search__field').trigger('blur');
                    setTimeout(function () {
                        var _a;
                        (_a = $('.select2-search--dropdown input.select2-search__field').get(0)) === null || _a === void 0 ? void 0 : _a.blur();
                        $('.select2-search--dropdown input.select2-search__field').trigger('blur');
                    }, 0);
                }
                if (false == _this.multiple) {
                    (_c = getSearchField()) === null || _c === void 0 ? void 0 : _c.addEventListener('keydown', eventHandler, true);
                }
            }
        });
    };
    UISelect.prototype.onKeyPressed = function (event) {
        if (this.multiple) {
            return true;
        }
        else if (event.key == 'Enter') {
            if (this.submitOnLoad.isLoading) {
                event.stopPropagation();
                event.preventDefault();
                this.submitOnLoad.isSubmitting = true;
                return false;
            }
        }
        else if (event.key.length == 1
            || ['Backspace', 'Clear', 'Delete', 'EraseEof', 'Insert', 'Paste', 'Undo', 'Redo'].indexOf(event.key) >= 0) {
            this.submitOnLoad.isLoading = true;
        }
        return true;
    };
    UISelect.prototype.getTemplate = function (targetInstruction, templatePropertyName) {
        if (targetInstruction.elementInstruction[templatePropertyName] == null)
            return null;
        return "<template>" + targetInstruction.elementInstruction[templatePropertyName] + "</template>";
    };
    UISelect.prototype.changeLanguage = function () {
        var _this_1 = this;
        ui_internal_1.UIInternal.nextTick(function () { return _this_1.buildSelect2(); });
    };
    UISelect.prototype.buildSelect2 = function () {
        var options = this.fillOptions();
        this.$select = $(this.inputEl).select2(options);
        this.select2Instance = this.$select.data("select2");
    };
    UISelect.prototype.fillOptions = function () {
        var _this_1 = this;
        var options = {};
        options.placeholder = this.placeholder;
        var minimumInputLength = 0;
        if (this.dataSource != null) {
            var ds_1 = this.dataSource;
            $.extend(options, {
                ajax: {
                    dataType: 'json',
                    delay: 250,
                    data: function (params) {
                        return {
                            q: params.term,
                            page: params.page
                        };
                    },
                    processResults: function (data, page) {
                        var selected = _this_1.value ? ((Array.isArray(_this_1.value) ? _this_1.value : [_this_1.value]).map(function (x) { return x.id ? x.id : x; })) : [];
                        var cleanData = data.results.map(function (item) {
                            if (_this_1.optionsValue != null && _this_1.optionsText != null) {
                                var treated_1 = {
                                    id: item[_this_1.optionsValue],
                                    text: ui_internal_1.UIInternal.getValue(item, _this_1.optionsText),
                                    data: item
                                };
                                return selected.find(function (id) { return id == treated_1.id; }) != null ? null : treated_1;
                            }
                        });
                        var result = {
                            results: cleanData.filter(function (o) { return !!o; }),
                            pagination: {
                                more: data.more
                            }
                        };
                        if (false == _this_1.multiple && _this_1.submitOnLoad.isSubmitting) {
                            _this_1.submitOnLoad.isSubmitting = false;
                            if (result.results.length > 0) {
                                ui_internal_1.UIInternal.nextTick(function () {
                                    _this_1.value = result.results[0].id;
                                    _this_1.valueChanged(_this_1.value, null);
                                    _this_1.close();
                                });
                            }
                        }
                        return result;
                    },
                    transport: function (params, success, failure) {
                        _this_1.submitOnLoad.isLoading = true;
                        var fail = function () {
                            _this_1.submitOnLoad.isLoading = false;
                        };
                        var currentPage = params.data.page != null ? params.data.page : 1;
                        var startRow = (currentPage - 1) * _this_1.pageSize;
                        var endRow = startRow + _this_1.pageSize;
                        var currentCallNumber = ++_this_1.callNumber;
                        var callBack = function (rowsThisPage, lastRow) {
                            if (currentCallNumber == _this_1.callNumber) {
                                _this_1.submitOnLoad.isLoading = false;
                                success({
                                    results: rowsThisPage,
                                    more: lastRow > endRow
                                });
                            }
                        };
                        var p = {
                            startRow: startRow,
                            endRow: endRow,
                            successCallback: callBack,
                            failCallback: failure,
                            sortModel: [
                                { colId: _this_1.replaceTranslation(_this_1.optionsText), sort: 'ASC' }
                            ]
                        };
                        var sortModel = _this_1.getSortModelFromSortColumn(_this_1.sortColumn);
                        if (sortModel != null && sortModel.length > 0) {
                            p.sortModel = sortModel;
                        }
                        ds_1.getRowsForSelect2(p, params.data.q, _this_1.evalFilterProperties);
                        return ds_1;
                    }
                }
            });
        }
        options.escapeMarkup = function (markup) { return markup; };
        options.minimumInputLength = minimumInputLength;
        options.closeOnSelect = true;
        options.tags = this.tags;
        options.language = {
            errorLoading: function () { return _this_1.i18n.tr("select2.errorLoading", { ns: "common" }); },
            inputTooShort: function () { return _this_1.i18n.tr("select2.inputTooShort", { ns: "common" }); },
            loadingMore: function () { return _this_1.i18n.tr("select2.loadingMore", { ns: "common" }); },
            noResults: function () { return _this_1.i18n.tr("select2.noResults", { ns: "common" }); },
            searching: function () { return _this_1.i18n.tr("select2.searching", { ns: "common" }); }
        };
        this.setupSelect2CustomAdapters(options);
        options.templateSelection = this.getTemplateSelection;
        options.templateResult = this.getTemplateFromSelect2;
        options.width = "100%";
        options.dropdownAutoWidth = this.dropdownAutoWidth;
        return options;
    };
    Object.defineProperty(UISelect.prototype, "evalFilterProperties", {
        get: function () {
            var _this_1 = this;
            if (this.filterProperties != null && this.filterProperties.length > 0) {
                var filterProperties = eval(this.filterProperties);
                return filterProperties.map(function (x) { return _this_1.replaceTranslation(x); });
            }
            return [];
        },
        enumerable: false,
        configurable: true
    });
    UISelect.prototype.setupSelect2CustomAdapters = function (options) {
        var _a;
        var Utils = jQuery.fn.select2.amd.require('select2/utils');
        if (options.dropdownAdapter == null) {
            if (options.multiple) {
                options.dropdownAdapter = custom_dropdown_adapter_1.CustomDropdownAdapter;
            }
            else {
                var Search = jQuery.fn.select2.amd.require('select2/dropdown/search');
                var SearchableDropdown = Utils.Decorate(custom_dropdown_adapter_1.CustomDropdownAdapter, Search);
                options.dropdownAdapter = SearchableDropdown;
            }
            if (options.minimumResultsForSearch !== 0) {
                var MinimumResultsForSearch = jQuery.fn.select2.amd.require('select2/dropdown/minimumResultsForSearch');
                options.dropdownAdapter = Utils.Decorate(options.dropdownAdapter, MinimumResultsForSearch);
            }
            if (options.closeOnSelect) {
                var CloseOnSelect = jQuery.fn.select2.amd.require('select2/dropdown/closeOnSelect');
                options.dropdownAdapter = Utils.Decorate(options.dropdownAdapter, CloseOnSelect);
            }
            if (((_a = this.dropdownCssClass) === null || _a === void 0 ? void 0 : _a.length) > 0) {
                options.dropdownCssClass = this.dropdownCssClass;
            }
            if (options.dropdownCssClass != null) {
                var DropdownCSS = jQuery.fn.select2.amd.require('select2/dropdown/dropdownCss');
                options.dropdownAdapter = Utils.Decorate(options.dropdownAdapter, DropdownCSS);
            }
            options.dropdownAdapter = Utils.Decorate(options.dropdownAdapter, custom_attach_body_1.customAttachBody);
        }
        if (options.dataAdapter == null) {
            var ArrayData = jQuery.fn.select2.amd.require('select2/data/array');
            var SelectData = jQuery.fn.select2.amd.require('select2/data/select');
            var MinimumInputLength = jQuery.fn.select2.amd.require('select2/data/minimumInputLength');
            var MaximumInputLength = jQuery.fn.select2.amd.require('select2/data/maximumInputLength');
            var MaximumSelectionLength = jQuery.fn.select2.amd.require('select2/data/maximumSelectionLength');
            var Tokenizer = jQuery.fn.select2.amd.require('select2/data/tokenizer');
            var Tags = jQuery.fn.select2.amd.require('select2/data/tags');
            if (options.ajax != null) {
                options.dataAdapter = custom_ajax_adapter_1.CustomAjaxAdapter;
            }
            else if (options.data != null) {
                options.dataAdapter = ArrayData;
            }
            else {
                options.dataAdapter = custom_ajax_adapter_1.CustomSelectAdapter;
            }
            if (options.minimumInputLength > 0) {
                options.dataAdapter = Utils.Decorate(options.dataAdapter, MinimumInputLength);
            }
            if (options.maximumInputLength > 0) {
                options.dataAdapter = Utils.Decorate(options.dataAdapter, MaximumInputLength);
            }
            if (options.maximumSelectionLength > 0) {
                options.dataAdapter = Utils.Decorate(options.dataAdapter, MaximumSelectionLength);
            }
            if (options.tags) {
                options.dataAdapter = Utils.Decorate(options.dataAdapter, Tags);
            }
            if (options.tokenSeparators != null || options.tokenizer != null) {
                options.dataAdapter = Utils.Decorate(options.dataAdapter, Tokenizer);
            }
        }
        options.multiple = this.multiple;
        options.allowClear = this.allowClear;
        if (options.selectionAdapter == null) {
            var SingleSelection = jQuery.fn.select2.amd.require('select2/selection/single');
            var SelectionSearch = jQuery.fn.select2.amd.require('select2/selection/search');
            var Placeholder = jQuery.fn.select2.amd.require('select2/selection/placeholder');
            var SelectionCSS = jQuery.fn.select2.amd.require('select2/selection/selectionCss');
            var EventRelay = jQuery.fn.select2.amd.require('select2/selection/eventRelay');
            if (options.multiple) {
                options.selectionAdapter = custom_multiple_selection_1.CustomMultipleSelection;
                options.selectionAdapter = Utils.Decorate(options.selectionAdapter, SelectionSearch);
            }
            else {
                options.selectionAdapter = SingleSelection;
            }
            if (options.allowClear) {
                options.selectionAdapter = Utils.Decorate(options.selectionAdapter, custom_allow_clear_1.CustomAllowClear);
            }
            if (options.placeholder != null) {
                options.selectionAdapter = Utils.Decorate(options.selectionAdapter, Placeholder);
            }
            if (options.selectionCssClass != null) {
                options.selectionAdapter = Utils.Decorate(options.selectionAdapter, SelectionCSS);
            }
            options.selectionAdapter = Utils.Decorate(options.selectionAdapter, EventRelay);
        }
    };
    UISelect.prototype.getSortModelFromSortColumn = function (sortColumn) {
        var _this_1 = this;
        if (sortColumn == null || sortColumn.length == 0)
            return null;
        var sortModel = [];
        if (sortColumn.indexOf(',') > -1) {
            var sortColumns = sortColumn.split(',');
            sortColumns.forEach(function (col) {
                sortModel.push({
                    colId: _this_1.replaceTranslation(col),
                    sort: _this_1.getSortDirection(col)
                });
            });
        }
        else {
            sortModel.push({
                colId: this.replaceTranslation(sortColumn),
                sort: this.getSortDirection(sortColumn)
            });
        }
        return sortModel;
    };
    UISelect.prototype.getSortDirection = function (col) {
        if (col.indexOf(' ') > -1) {
            return col.split(' ')[1];
        }
        else
            return 'ASC';
    };
    UISelect.prototype.replaceTranslation = function (col) {
        if (col.indexOf('_translation') > -1) {
            return col.replace('_translation', this.datacontext.translatePropertyName);
        }
        return col;
    };
    UISelect.prototype.resizeSelection = function (hasSelection) {
        if (this.onSelectedSize != null) {
            var el = $(this.element).find('.select2-selection');
            el.css('height', hasSelection ? this.onSelectedSize : '');
        }
    };
    UISelect.prototype.valueChanged = function (newVal, oldVal) {
        var _this_1 = this;
        if (this.$select) {
            if (newVal != oldVal) {
                var $options = $(this.element).find('option');
                var Utils_1 = jQuery.fn.select2.amd.require('select2/utils');
                $options.each(function (index, element) { return Utils_1.RemoveData(element); });
                if (this.value != null && Object.keys(this.value).length > 0 && Object.keys(this.value).indexOf('id') > -1) {
                    this.taskQueue.queueMicroTask(function () {
                        _this_1.$select.val(newVal.id).trigger("change");
                        _this_1.callOnChangeCallback(newVal);
                        _this_1.resizeSelection(true);
                    });
                }
                else {
                    ui_internal_1.UIInternal.queueTask(function () {
                        if (newVal == null) {
                            _this_1.$select.val('').trigger("change");
                            _this_1.select2Instance.$selection.find('.select2-selection__clear').remove();
                            _this_1.callOnChangeCallback('');
                            _this_1.resizeSelection(false);
                        }
                        else {
                            _this_1.$select.val(newVal).trigger("change");
                            _this_1.callOnChangeCallback(newVal);
                            _this_1.resizeSelection(true);
                        }
                        _this_1.manageSelectionTitle();
                    });
                }
            }
        }
    };
    UISelect.prototype.placeholderChanged = function (newVal, oldVal) {
        var _this_1 = this;
        if (this.$select) {
            if (newVal != oldVal) {
                ui_internal_1.UIInternal.queueTask(function () {
                    _this_1.$select.select2(_this_1.fillOptions());
                });
            }
        }
    };
    UISelect.prototype.dataSourceChanged = function (newVal, oldVal) {
        if (this.$select) {
            if (newVal != oldVal) {
                this.$select.select2(this.fillOptions());
            }
        }
    };
    UISelect.prototype.close = function () {
        this.$select.select2('close');
    };
    UISelect.prototype.open = function () {
        this.$select.select2('open');
    };
    UISelect.prototype.manageSelectionTitle = function () {
        if (this.selectionTitle == false || this.selectionTitle == 'false') {
            var elementWithTitle = this.select2Instance.$container.find('.select2-selection__rendered');
            if (elementWithTitle != null) {
                elementWithTitle.removeAttr('title');
            }
        }
    };
    UISelect.prototype.detached = function () {
        var _this_1 = this;
        var _a, _b;
        this.close();
        (_a = this.clickableElements) === null || _a === void 0 ? void 0 : _a.forEach(function (elem) { return elem.removeEventListener("click", _this_1.closeOnClickHandler); });
        this.onChangeCollectionObserverDisposables.forEach(function (d) { return d.dispose(); });
        (_b = this.changeLanguageSubscription) === null || _b === void 0 ? void 0 : _b.dispose();
    };
    UISelect.prototype.callOnChangeCallback = function (value) {
        if (this.onChange) {
            this.onChange({ value: value });
        }
    };
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.twoWay }),
        __metadata("design:type", Object)
    ], UISelect.prototype, "value", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.twoWay }),
        __metadata("design:type", String)
    ], UISelect.prototype, "placeholder", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.toView }),
        __metadata("design:type", data_source_1.GridDataSource)
    ], UISelect.prototype, "dataSource", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.oneTime }),
        __metadata("design:type", String)
    ], UISelect.prototype, "optionsValue", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.oneTime }),
        __metadata("design:type", String)
    ], UISelect.prototype, "optionsText", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.oneTime }),
        __metadata("design:type", Object)
    ], UISelect.prototype, "createOptions", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.oneTime }),
        __metadata("design:type", String)
    ], UISelect.prototype, "sortColumn", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.oneTime }),
        __metadata("design:type", String)
    ], UISelect.prototype, "filterProperties", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.twoWay }),
        __metadata("design:type", String)
    ], UISelect.prototype, "itemTemplate", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.twoWay }),
        __metadata("design:type", String)
    ], UISelect.prototype, "headerTemplate", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.twoWay }),
        __metadata("design:type", String)
    ], UISelect.prototype, "footerTemplate", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.toView }),
        __metadata("design:type", Boolean)
    ], UISelect.prototype, "allowClear", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.oneTime }),
        __metadata("design:type", Number)
    ], UISelect.prototype, "pageSize", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.twoWay }),
        __metadata("design:type", String)
    ], UISelect.prototype, "dropdownCssClass", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.toView }),
        __metadata("design:type", Function)
    ], UISelect.prototype, "onChange", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.toView }),
        __metadata("design:type", Function)
    ], UISelect.prototype, "onReady", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.oneTime }),
        __metadata("design:type", Object)
    ], UISelect.prototype, "selectionTitle", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.oneTime }),
        __metadata("design:type", Boolean)
    ], UISelect.prototype, "dropdownAutoWidth", void 0);
    __decorate([
        (0, aurelia_templating_1.bindable)({ defaultBindingMode: aurelia_framework_1.bindingMode.oneTime }),
        __metadata("design:type", Boolean)
    ], UISelect.prototype, "focusSearchWhenOpen", void 0);
    __decorate([
        aurelia_framework_1.observable,
        __metadata("design:type", Boolean)
    ], UISelect.prototype, "isFocus", void 0);
    __decorate([
        (0, aurelia_framework_1.computedFrom)("isFocus"),
        __metadata("design:type", String),
        __metadata("design:paramtypes", [])
    ], UISelect.prototype, "isFocusClass", null);
    __decorate([
        (0, aurelia_framework_1.computedFrom)("multiple"),
        __metadata("design:type", String),
        __metadata("design:paramtypes", [])
    ], UISelect.prototype, "isMultipleClass", null);
    UISelect = __decorate([
        (0, aurelia_templating_1.customElement)('ui-select'),
        (0, aurelia_framework_2.processContent)(makePartReplacementFromContent),
        __metadata("design:paramtypes", [Element, aurelia_framework_1.TargetInstruction, data_context_1.Datacontext, aurelia_i18n_1.I18N, aurelia_framework_1.BindingEngine, aurelia_framework_1.TaskQueue, aurelia_event_aggregator_1.EventAggregator, config_1.Config])
    ], UISelect);
    return UISelect;
}(base_input_1.BaseInput));
function makePartReplacementFromContent(_viewCompiler, _viewResources, element, instruction) {
    var content = element.firstElementChild;
    instruction.inheritBindingContext = true;
    if (content) {
        var template_1 = document.createElement('template');
        template_1.setAttribute('replace-part', 'options');
        element.children.forEach(function (child) {
            if (child instanceof HTMLOptionElement) {
                template_1.content.appendChild(child.cloneNode(true));
            }
            else if (child.tagName.toUpperCase() === "UI-SELECT-ITEM-TEMPLATE") {
                instruction.itemTemplate = child.innerHTML;
            }
            else if (child.tagName.toUpperCase() === "UI-SELECT-HEADER-TEMPLATE") {
                instruction.headerTemplate = child.innerHTML;
                if (child.hasAttribute("close-on-click")) {
                    instruction.closeOnHeaderClick = true;
                }
            }
            else if (child.tagName.toUpperCase() === "UI-SELECT-FOOTER-TEMPLATE") {
                instruction.footerTemplate = child.innerHTML;
                if (child.hasAttribute("close-on-click")) {
                    instruction.closeOnFooterClick = true;
                }
            }
            else if (child.tagName.toUpperCase() === "UI-SELECT-SELECTION-TEMPLATE") {
                instruction.selectionTemplate = child.innerHTML;
            }
        });
        while (element.firstChild) {
            element.removeChild(element.firstChild);
        }
        element.appendChild(template_1);
        return true;
    }
}

//# sourceMappingURL=ui-select.js.map
