/** * Bootstrap Multiselect (http://davidstutz.de/bootstrap-multiselect/) * * Apache License, Version 2.0: * Copyright (c) 2012 - 2022 David Stutz * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * BSD 3-Clause License: * Copyright (c) 2012 - 2022 David Stutz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of David Stutz nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (root, factory) { // check to see if 'knockout' AMD module is specified if using requirejs if (typeof define === 'function' && define.amd && typeof require === 'function' && typeof require.specified === 'function' && require.specified('knockout')) { // AMD. Register as an anonymous module. define(['jquery', 'knockout'], factory); } else { // Browser globals factory(root.jQuery, root.ko); } })(this, function ($, ko) { "use strict";// jshint ;_; if (typeof ko !== 'undefined' && ko.bindingHandlers && !ko.bindingHandlers.multiselect) { ko.bindingHandlers.multiselect = { after: ['options', 'value', 'selectedOptions', 'enable', 'disable'], init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { var $element = $(element); var config = ko.toJS(valueAccessor()); $element.multiselect(config); if (allBindings.has('options')) { var options = allBindings.get('options'); if (ko.isObservable(options)) { ko.computed({ read: function () { options(); setTimeout(function () { var ms = $element.data('multiselect'); if (ms) ms.updateOriginalOptions();//Not sure how beneficial this is. $element.multiselect('rebuild'); }, 1); }, disposeWhenNodeIsRemoved: element }); } } //value and selectedOptions are two-way, so these will be triggered even by our own actions. //It needs some way to tell if they are triggered because of us or because of outside change. //It doesn't loop but it's a waste of processing. if (allBindings.has('value')) { var value = allBindings.get('value'); if (ko.isObservable(value)) { ko.computed({ read: function () { value(); setTimeout(function () { $element.multiselect('refresh'); }, 1); }, disposeWhenNodeIsRemoved: element }).extend({ rateLimit: 100, notifyWhenChangesStop: true }); } } //Switched from arrayChange subscription to general subscription using 'refresh'. //Not sure performance is any better using 'select' and 'deselect'. if (allBindings.has('selectedOptions')) { var selectedOptions = allBindings.get('selectedOptions'); if (ko.isObservable(selectedOptions)) { ko.computed({ read: function () { selectedOptions(); setTimeout(function () { $element.multiselect('refresh'); }, 1); }, disposeWhenNodeIsRemoved: element }).extend({ rateLimit: 100, notifyWhenChangesStop: true }); } } var setEnabled = function (enable) { setTimeout(function () { if (enable) $element.multiselect('enable'); else $element.multiselect('disable'); }); }; if (allBindings.has('enable')) { var enable = allBindings.get('enable'); if (ko.isObservable(enable)) { ko.computed({ read: function () { setEnabled(enable()); }, disposeWhenNodeIsRemoved: element }).extend({ rateLimit: 100, notifyWhenChangesStop: true }); } else { setEnabled(enable); } } if (allBindings.has('disable')) { var disable = allBindings.get('disable'); if (ko.isObservable(disable)) { ko.computed({ read: function () { setEnabled(!disable()); }, disposeWhenNodeIsRemoved: element }).extend({ rateLimit: 100, notifyWhenChangesStop: true }); } else { setEnabled(!disable); } } ko.utils.domNodeDisposal.addDisposeCallback(element, function () { $element.multiselect('destroy'); }); }, update: function (element, valueAccessor, allBindings, viewModel, bindingContext) { var $element = $(element); var config = ko.toJS(valueAccessor()); $element.multiselect('setOptions', config); $element.multiselect('rebuild'); } }; } function forEach(array, callback) { for (var index = 0; index < array.length; ++index) { callback(array[index], index); } } var multiselectCount = 0; /** * Constructor to create a new multiselect using the given select. * * @param {jQuery} select * @param {Object} options * @returns {Multiselect} */ function Multiselect(select, options) { this.$select = $(select); this.options = this.mergeOptions($.extend({}, options, this.$select.data())); // Placeholder via data attributes if (this.$select.attr("data-placeholder")) { this.options.nonSelectedText = this.$select.data("placeholder"); } // Initialization. // We have to clone to create a new reference. this.originalOptions = this.$select.clone()[0].options; this.query = ''; this.searchTimeout = null; this.lastToggledInput = null; this.multiselectId = this.generateUniqueId() + '_' + multiselectCount; this.internalIdCount = 0; this.options.multiple = this.$select.attr('multiple') === "multiple"; this.options.onChange = $.proxy(this.options.onChange, this); this.options.onSelectAll = $.proxy(this.options.onSelectAll, this); this.options.onDeselectAll = $.proxy(this.options.onDeselectAll, this); this.options.onDropdownShow = $.proxy(this.options.onDropdownShow, this); this.options.onDropdownHide = $.proxy(this.options.onDropdownHide, this); this.options.onDropdownShown = $.proxy(this.options.onDropdownShown, this); this.options.onDropdownHidden = $.proxy(this.options.onDropdownHidden, this); this.options.onInitialized = $.proxy(this.options.onInitialized, this); this.options.onFiltering = $.proxy(this.options.onFiltering, this); // Build select all if enabled. this.buildContainer(); this.buildButton(); this.buildDropdown(); this.buildReset(); this.buildSelectAll(); this.buildDropdownOptions(); this.buildFilter(); this.buildButtons(); this.updateButtonText(); this.updateSelectAll(true); if (this.options.enableClickableOptGroups && this.options.multiple) { this.updateOptGroups(); } this.options.wasDisabled = this.$select.prop('disabled'); if (this.options.disableIfEmpty && $('option', this.$select).length <= 0 && !this.options.wasDisabled) { this.disable(true); } this.$select.wrap('').after(this.$container); this.$select.prop('tabindex', '-1'); if (this.options.widthSynchronizationMode !== 'never') { this.synchronizeButtonAndPopupWidth(); } this.$select.data('multiselect', this); this.options.onInitialized(this.$select, this.$container); } Multiselect.prototype = { defaults: { /** * Default text function will either print 'None selected' in case no * option is selected or a list of the selected options up to a length * of 3 selected options. * * @param {jQuery} options * @param {jQuery} select * @returns {String} */ buttonText: function (selectedOptions, select) { if (this.disabledText.length > 0 && select.prop('disabled')) { return this.disabledText; } else if (selectedOptions.length === 0) { return this.nonSelectedText; } else if (this.allSelectedText && selectedOptions.length === $('option', $(select)).length && $('option', $(select)).length !== 1 && this.multiple) { if (this.selectAllNumber) { return this.allSelectedText + ' (' + selectedOptions.length + ')'; } else { return this.allSelectedText; } } else if (this.numberDisplayed != 0 && selectedOptions.length > this.numberDisplayed) { return selectedOptions.length + ' ' + this.nSelectedText; } else { var selected = ''; var delimiter = this.delimiterText; selectedOptions.each(function () { var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text(); selected += label + delimiter; }); return selected.substr(0, selected.length - this.delimiterText.length); } }, /** * Updates the title of the button similar to the buttonText function. * * @param {jQuery} options * @param {jQuery} select * @returns {@exp;selected@call;substr} */ buttonTitle: function (options, select) { if (options.length === 0) { return this.nonSelectedText; } else { var selected = ''; var delimiter = this.delimiterText; options.each(function () { var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text(); selected += label + delimiter; }); return selected.substr(0, selected.length - this.delimiterText.length); } }, checkboxName: function (option) { return false; // no checkbox name }, /** * Create a label. * * @param {jQuery} element * @returns {String} */ optionLabel: function (element) { return $(element).attr('label') || $(element).text(); }, /** * Create a class. * * @param {jQuery} element * @returns {String} */ optionClass: function (element) { return $(element).attr('class') || ''; }, /** * Triggered on change of the multiselect. * * Not triggered when selecting/deselecting options manually. * * @param {jQuery} option * @param {Boolean} checked */ onChange: function (option, checked) { }, /** * Triggered when the dropdown is shown. * * @param {jQuery} event */ onDropdownShow: function (event) { }, /** * Triggered when the dropdown is hidden. * * @param {jQuery} event */ onDropdownHide: function (event) { }, /** * Triggered after the dropdown is shown. * * @param {jQuery} event */ onDropdownShown: function (event) { }, /** * Triggered after the dropdown is hidden. * * @param {jQuery} event */ onDropdownHidden: function (event) { }, /** * Triggered on select all. */ onSelectAll: function (selectedOptions) { }, /** * Triggered on deselect all. */ onDeselectAll: function (deselectedOptions) { }, /** * Triggered after initializing. * * @param {jQuery} $select * @param {jQuery} $container */ onInitialized: function ($select, $container) { }, /** * Triggered on filtering. * * @param {jQuery} $filter */ onFiltering: function ($filter) { }, enableHTML: false, buttonClass: 'custom-select', inheritClass: false, buttonWidth: 'auto', buttonContainer: '
', dropRight: false, dropUp: false, selectedClass: 'active', // Maximum height of the dropdown menu. // If maximum height is exceeded a scrollbar will be displayed. maxHeight: null, includeSelectAllOption: false, includeSelectAllIfMoreThan: 0, selectAllText: ' Select all', selectAllValue: 'multiselect-all', selectAllName: false, selectAllNumber: true, selectAllJustVisible: true, enableFiltering: false, enableCaseInsensitiveFiltering: false, enableFullValueFiltering: false, enableClickableOptGroups: false, enableCollapsibleOptGroups: false, collapseOptGroupsByDefault: false, filterPlaceholder: 'Search', // possible options: 'text', 'value', 'both' filterBehavior: 'text', includeFilterClearBtn: true, preventInputChangeEvent: false, nonSelectedText: 'None selected', nSelectedText: 'selected', allSelectedText: 'All selected', resetButtonText: 'Reset', numberDisplayed: 3, disableIfEmpty: false, disabledText: '', delimiterText: ', ', includeResetOption: false, includeResetDivider: false, resetText: 'Reset', indentGroupOptions: true, // possible options: 'never', 'always', 'ifPopupIsSmaller', 'ifPopupIsWider' widthSynchronizationMode: 'never', // possible options: 'left', 'center', 'right' buttonTextAlignment: 'center', enableResetButton: false, templates: { button: '', popupContainer: '', filter: '
', buttonGroup: '
', buttonGroupReset: '', option: '', divider: '', optionGroup: '', resetButton: '
' } }, constructor: Multiselect, /** * Builds the container of the multiselect. */ buildContainer: function () { this.$container = $(this.options.buttonContainer); if (this.options.widthSynchronizationMode !== 'never') { this.$container.on('show.bs.dropdown', $.proxy(function () { // the width needs to be synchronized again in case the width of the button changed in between this.synchronizeButtonAndPopupWidth(); this.options.onDropdownShow(); }, this)); } else { this.$container.on('show.bs.dropdown', this.options.onDropdownShow); } this.$container.on('hide.bs.dropdown', this.options.onDropdownHide); this.$container.on('shown.bs.dropdown', this.options.onDropdownShown); this.$container.on('hidden.bs.dropdown', this.options.onDropdownHidden); }, /** * Builds the button of the multiselect. */ buildButton: function () { this.$button = $(this.options.templates.button).addClass(this.options.buttonClass); if (this.$select.attr('class') && this.options.inheritClass) { this.$button.addClass(this.$select.attr('class')); } // Adopt active state. if (this.$select.prop('disabled')) { this.disable(); } else { this.enable(); } // Manually add button width if set. if (this.options.buttonWidth && this.options.buttonWidth !== 'auto') { this.$button.css({ 'width': '100%' //this.options.buttonWidth, }); this.$container.css({ 'width': this.options.buttonWidth }); } if (this.options.buttonTextAlignment) { switch (this.options.buttonTextAlignment) { case 'left': this.$button.addClass('text-left'); break; case 'center': this.$button.addClass('text-center'); break; case 'right': this.$button.addClass('text-right'); break; } } // Keep the tab index from the select. var tabindex = this.$select.attr('tabindex'); if (tabindex) { this.$button.attr('tabindex', tabindex); } this.$container.prepend(this.$button); }, /** * Builds the popup container representing the dropdown menu. */ buildDropdown: function () { // Build popup container. this.$popupContainer = $(this.options.templates.popupContainer); if (this.options.dropRight) { this.$container.addClass('dropright'); } else if (this.options.dropUp) { this.$container.addClass("dropup"); } // Set max height of dropdown menu to activate auto scrollbar. if (this.options.maxHeight) { // TODO: Add a class for this option to move the css declarations. this.$popupContainer.css({ 'max-height': this.options.maxHeight + 'px', 'overflow-y': 'auto', 'overflow-x': 'hidden' }); } if (this.options.widthSynchronizationMode !== 'never') { this.$popupContainer.css('overflow-x', 'hidden'); } this.$popupContainer.on("touchstart click", function (e) { e.stopPropagation(); }); this.$container.append(this.$popupContainer); }, synchronizeButtonAndPopupWidth: function () { if (!this.$popupContainer || this.options.widthSynchronizationMode === 'never') { return; } var buttonWidth = this.$button.outerWidth(); switch (this.options.widthSynchronizationMode) { case 'always': this.$popupContainer.css('min-width', buttonWidth); this.$popupContainer.css('max-width', buttonWidth); break; case 'ifPopupIsSmaller': this.$popupContainer.css('min-width', buttonWidth); break; case 'ifPopupIsWider': this.$popupContainer.css('max-width', buttonWidth); break; } }, /** * Build the dropdown options and binds all necessary events. * * Uses createDivider and createOptionValue to create the necessary options. */ buildDropdownOptions: function () { this.$select.children().each($.proxy(function (index, element) { var $element = $(element); // Support optgroups and options without a group simultaneously. var tag = $element.prop('tagName') .toLowerCase(); if ($element.prop('value') === this.options.selectAllValue) { return; } if (tag === 'optgroup') { this.createOptgroup(element); } else if (tag === 'option') { if ($element.data('role') === 'divider') { this.createDivider(); } else { this.createOptionValue(element, false); } } // Other illegal tags will be ignored. }, this)); // Bind the change event on the dropdown elements. $(this.$popupContainer).off('change', '> *:not(.multiselect-group) input[type="checkbox"], > *:not(.multiselect-group) input[type="radio"]'); $(this.$popupContainer).on('change', '> *:not(.multiselect-group) input[type="checkbox"], > *:not(.multiselect-group) input[type="radio"]', $.proxy(function (event) { var $target = $(event.target); var checked = $target.prop('checked') || false; var isSelectAllOption = $target.val() === this.options.selectAllValue; // Apply or unapply the configured selected class. if (this.options.selectedClass) { if (checked) { $target.closest('.multiselect-option') .addClass(this.options.selectedClass); } else { $target.closest('.multiselect-option') .removeClass(this.options.selectedClass); } } // Get the corresponding option. var id = $target.attr('id'); var $option = this.getOptionById(id); var $optionsNotThis = $('option', this.$select).not($option); var $checkboxesNotThis = $('input', this.$container).not($target); if (isSelectAllOption) { if (checked) { this.selectAll(this.options.selectAllJustVisible, true); } else { this.deselectAll(this.options.selectAllJustVisible, true); } } else { if (checked) { $option.prop('selected', true); if (this.options.multiple) { // Simply select additional option. $option.prop('selected', true); } else { // Unselect all other options and corresponding checkboxes. if (this.options.selectedClass) { $($checkboxesNotThis).closest('.dropdown-item').removeClass(this.options.selectedClass); } $($checkboxesNotThis).prop('checked', false); $optionsNotThis.prop('selected', false); // It's a single selection, so close. this.$button.click(); } if (this.options.selectedClass === "active") { $optionsNotThis.closest(".dropdown-item").css("outline", ""); } } else { // Unselect option. $option.prop('selected', false); } // To prevent select all from firing onChange: #575 this.options.onChange($option, checked); // Do not update select all or optgroups on select all change! this.updateSelectAll(); if (this.options.enableClickableOptGroups && this.options.multiple) { this.updateOptGroups(); } } this.$select.change(); this.updateButtonText(); if (this.options.preventInputChangeEvent) { return false; } }, this)); $('.multiselect-option', this.$popupContainer).off('mousedown'); $('.multiselect-option', this.$popupContainer).on('mousedown', function (e) { if (e.shiftKey) { // Prevent selecting text by Shift+click return false; } }); $(this.$popupContainer).off('touchstart click', '.multiselect-option, .multiselect-all, .multiselect-group'); $(this.$popupContainer).on('touchstart click', '.multiselect-option, .multiselect-all, .multiselect-group', $.proxy(function (event) { event.stopPropagation(); var $target = $(event.target); if (event.shiftKey && this.options.multiple) { if (!$target.is("input")) { // Handles checkbox selection manually (see https://github.com/davidstutz/bootstrap-multiselect/issues/431) event.preventDefault(); $target = $target.closest(".multiselect-option").find("input"); $target.prop("checked", !$target.prop("checked")); } var checked = $target.prop('checked') || false; if (this.lastToggledInput !== null && this.lastToggledInput !== $target) { // Make sure we actually have a range var from = this.$popupContainer.find(".multiselect-option:visible").index($target.closest(".multiselect-option")); var to = this.$popupContainer.find(".multiselect-option:visible").index(this.lastToggledInput.closest(".multiselect-option")); if (from > to) { // Swap the indices var tmp = to; to = from; from = tmp; } // Make sure we grab all elements since slice excludes the last index ++to; // Change the checkboxes and underlying options var range = this.$popupContainer.find(".multiselect-option:not(.multiselect-filter-hidden)").slice(from, to).find("input"); range.prop('checked', checked); if (this.options.selectedClass) { range.closest('.multiselect-option') .toggleClass(this.options.selectedClass, checked); } for (var i = 0, j = range.length; i < j; i++) { var $checkbox = $(range[i]); var $option = this.getOptionById($checkbox.attr('id')); $option.prop('selected', checked); } } // Trigger the select "change" event $target.trigger("change"); } else if (!$target.is('input')) { var $checkbox = $target.closest('.multiselect-option, .multiselect-all').find('.form-check-input'); if ($checkbox.length > 0) { if (this.options.multiple || !$checkbox.prop('checked')) { $checkbox.prop('checked', !$checkbox.prop('checked')); $checkbox.change(); } } else if (this.options.enableClickableOptGroups && this.options.multiple && !$target.hasClass("caret-container")) { var groupItem = $target; if (!groupItem.hasClass("multiselect-group")) { groupItem = $target.closest('.multiselect-group'); } $checkbox = groupItem.find(".form-check-input"); if ($checkbox.length > 0) { $checkbox.prop('checked', !$checkbox.prop('checked')); $checkbox.change(); } } event.preventDefault(); } // Remembers last clicked option var $input = $target.closest(".multiselect-option").find("input[type='checkbox'], input[type='radio']"); if ($input.length > 0) { this.lastToggledInput = $target; } else { this.lastToggledInput = null; } $target.blur(); }, this)); //Keyboard support. this.$container.off('keydown.multiselect').on('keydown.multiselect', $.proxy(function (event) { var $items = $(this.$container).find(".multiselect-option:not(.disabled), .multiselect-group:not(.disabled), .multiselect-all").filter(":visible"); var index = $items.index($items.filter(':focus')); var $search = $('.multiselect-search', this.$container); // keyCode 9 == Tab if (event.keyCode === 9 && this.$container.hasClass('show')) { this.$button.click(); } // keyCode 13 = Enter else if (event.keyCode == 13) { var $current = $items.eq(index); setTimeout(function () { $current.focus(); }, 1); } // keyCode 38 = Arrow Up else if (event.keyCode == 38) { if (index == 0 && !$search.is(':focus')) { setTimeout(function () { $search.focus(); }, 1); } } // keyCode 40 = Arrow Down else if (event.keyCode == 40) { if ($search.is(':focus')) { var $first = $items.eq(0); setTimeout(function () { $search.blur(); $first.focus(); }, 1); } else if (index == -1) { setTimeout(function () { $search.focus(); }, 1); } } }, this)); if (this.options.enableClickableOptGroups && this.options.multiple) { $(".multiselect-group input", this.$popupContainer).off("change"); $(".multiselect-group input", this.$popupContainer).on("change", $.proxy(function (event) { event.stopPropagation(); var $target = $(event.target); var checked = $target.prop('checked') || false; var $item = $(event.target).closest('.dropdown-item'); var $group = $item.nextUntil(".multiselect-group") .not('.multiselect-filter-hidden') .not('.disabled'); var $inputs = $group.find("input"); var $options = []; if (this.options.selectedClass) { if (checked) { $item.addClass(this.options.selectedClass); } else { $item.removeClass(this.options.selectedClass); } } $.each($inputs, $.proxy(function (index, input) { var $input = $(input); var id = $input.attr('id'); var $option = this.getOptionById(id); if (checked) { $input.prop('checked', true); $input.closest('.dropdown-item') .addClass(this.options.selectedClass); $option.prop('selected', true); } else { $input.prop('checked', false); $input.closest('.dropdown-item') .removeClass(this.options.selectedClass); $option.prop('selected', false); } $options.push($option); }, this)) // Cannot use select or deselect here because it would call updateOptGroups again. this.options.onChange($options, checked); this.$select.change(); this.updateButtonText(); this.updateSelectAll(); }, this)); } if (this.options.enableCollapsibleOptGroups) { let clickableSelector = this.options.enableClickableOptGroups ? ".multiselect-group .caret-container" : ".multiselect-group"; $(clickableSelector, this.$popupContainer).off("click"); $(clickableSelector, this.$popupContainer).on("click", $.proxy(function (event) { var $group = $(event.target).closest('.multiselect-group'); var $inputs = $group.nextUntil(".multiselect-group").not('.multiselect-filter-hidden'); var visible = true; $inputs.each(function () { visible = visible && !$(this).hasClass('multiselect-collapsible-hidden'); }); if (visible) { $inputs.hide().addClass('multiselect-collapsible-hidden'); $group.get(0).classList.add("closed"); } else { $inputs.show().removeClass('multiselect-collapsible-hidden'); $group.get(0).classList.remove("closed"); } }, this)); } }, /** * Create a checkbox container with input and label based on given values * @param {JQuery} $item * @param {String} label * @param {String} name * @param {String} value * @param {String} inputType * @returns {JQuery} */ createCheckbox: function ($item, labelContent, name, value, title, inputType, internalId) { var $wrapper = $(''); $wrapper.addClass("form-check"); var $checkboxLabel = $('