@riophae/vue-treeselect
Version:
A multi-select component with nested options support for Vue.js
1,652 lines (1,426 loc) • 125 kB
JavaScript
/*!
* vue-treeselect v0.4.0 | (c) 2017-2019 Riophae Lee
* Released under the MIT License.
* https://vue-treeselect.js.org/
*/
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 16);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
module.exports = require("@babel/runtime/helpers/slicedToArray");
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = require("@babel/runtime/helpers/toConsumableArray");
/***/ }),
/* 2 */
/***/ (function(module, exports) {
module.exports = require("@babel/runtime/helpers/defineProperty");
/***/ }),
/* 3 */
/***/ (function(module, exports) {
module.exports = require("fuzzysearch");
/***/ }),
/* 4 */
/***/ (function(module, exports) {
module.exports = require("lodash/noop");
/***/ }),
/* 5 */
/***/ (function(module, exports) {
module.exports = require("lodash/debounce");
/***/ }),
/* 6 */
/***/ (function(module, exports) {
module.exports = require("watch-size");
/***/ }),
/* 7 */
/***/ (function(module, exports) {
module.exports = require("is-promise");
/***/ }),
/* 8 */
/***/ (function(module, exports) {
module.exports = require("lodash/once");
/***/ }),
/* 9 */
/***/ (function(module, exports) {
module.exports = require("lodash/identity");
/***/ }),
/* 10 */
/***/ (function(module, exports) {
module.exports = require("lodash/constant");
/***/ }),
/* 11 */
/***/ (function(module, exports) {
module.exports = require("@babel/runtime/helpers/typeof");
/***/ }),
/* 12 */
/***/ (function(module, exports) {
module.exports = require("lodash/last");
/***/ }),
/* 13 */
/***/ (function(module, exports) {
module.exports = require("babel-helper-vue-jsx-merge-props");
/***/ }),
/* 14 */
/***/ (function(module, exports) {
module.exports = require("vue");
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 16 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
// EXTERNAL MODULE: external "@babel/runtime/helpers/slicedToArray"
var slicedToArray_ = __webpack_require__(0);
var slicedToArray_default = /*#__PURE__*/__webpack_require__.n(slicedToArray_);
// EXTERNAL MODULE: external "@babel/runtime/helpers/toConsumableArray"
var toConsumableArray_ = __webpack_require__(1);
var toConsumableArray_default = /*#__PURE__*/__webpack_require__.n(toConsumableArray_);
// EXTERNAL MODULE: external "@babel/runtime/helpers/defineProperty"
var defineProperty_ = __webpack_require__(2);
var defineProperty_default = /*#__PURE__*/__webpack_require__.n(defineProperty_);
// EXTERNAL MODULE: external "fuzzysearch"
var external_fuzzysearch_ = __webpack_require__(3);
var external_fuzzysearch_default = /*#__PURE__*/__webpack_require__.n(external_fuzzysearch_);
// EXTERNAL MODULE: external "lodash/noop"
var noop_ = __webpack_require__(4);
var noop_default = /*#__PURE__*/__webpack_require__.n(noop_);
// CONCATENATED MODULE: ./src/utils/noop.js
// CONCATENATED MODULE: ./src/utils/warning.js
var warning_warning = process.env.NODE_ENV === 'production' ? noop_default.a : function warning(checker, complainer) {
if (!checker()) {
var _console;
var message = ['[Vue-Treeselect Warning]'].concat(complainer());
(_console = console).error.apply(_console, toConsumableArray_default()(message));
}
};
// CONCATENATED MODULE: ./src/utils/onLeftClick.js
function onLeftClick(mouseDownHandler) {
return function onMouseDown(evt) {
if (evt.type === 'mousedown' && evt.button === 0) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
mouseDownHandler.call.apply(mouseDownHandler, [this, evt].concat(args));
}
};
}
// CONCATENATED MODULE: ./src/utils/scrollIntoView.js
function scrollIntoView($scrollingEl, $focusedEl) {
var scrollingReact = $scrollingEl.getBoundingClientRect();
var focusedRect = $focusedEl.getBoundingClientRect();
var overScroll = $focusedEl.offsetHeight / 3;
if (focusedRect.bottom + overScroll > scrollingReact.bottom) {
$scrollingEl.scrollTop = Math.min($focusedEl.offsetTop + $focusedEl.clientHeight - $scrollingEl.offsetHeight + overScroll, $scrollingEl.scrollHeight);
} else if (focusedRect.top - overScroll < scrollingReact.top) {
$scrollingEl.scrollTop = Math.max($focusedEl.offsetTop - overScroll, 0);
}
}
// EXTERNAL MODULE: external "lodash/debounce"
var debounce_ = __webpack_require__(5);
var debounce_default = /*#__PURE__*/__webpack_require__.n(debounce_);
// CONCATENATED MODULE: ./src/utils/debounce.js
// EXTERNAL MODULE: external "watch-size"
var external_watch_size_ = __webpack_require__(6);
var external_watch_size_default = /*#__PURE__*/__webpack_require__.n(external_watch_size_);
// CONCATENATED MODULE: ./src/utils/removeFromArray.js
function removeFromArray(arr, elem) {
var idx = arr.indexOf(elem);
if (idx !== -1) arr.splice(idx, 1);
}
// CONCATENATED MODULE: ./src/utils/watchSize.js
var intervalId;
var registered = [];
var INTERVAL_DURATION = 100;
function run() {
intervalId = setInterval(function () {
registered.forEach(test);
}, INTERVAL_DURATION);
}
function stop() {
clearInterval(intervalId);
intervalId = null;
}
function test(item) {
var $el = item.$el,
listener = item.listener,
lastWidth = item.lastWidth,
lastHeight = item.lastHeight;
var width = $el.offsetWidth;
var height = $el.offsetHeight;
if (lastWidth !== width || lastHeight !== height) {
item.lastWidth = width;
item.lastHeight = height;
listener({
width: width,
height: height
});
}
}
function watchSizeForIE9($el, listener) {
var item = {
$el: $el,
listener: listener,
lastWidth: null,
lastHeight: null
};
var unwatch = function unwatch() {
removeFromArray(registered, item);
if (!registered.length) stop();
};
registered.push(item);
test(item);
run();
return unwatch;
}
function watchSize($el, listener) {
var isIE9 = document.documentMode === 9;
var locked = true;
var wrappedListener = function wrappedListener() {
return locked || listener.apply(void 0, arguments);
};
var implementation = isIE9 ? watchSizeForIE9 : external_watch_size_default.a;
var removeSizeWatcher = implementation($el, wrappedListener);
locked = false;
return removeSizeWatcher;
}
// CONCATENATED MODULE: ./src/utils/setupResizeAndScrollEventListeners.js
function findScrollParents($el) {
var $scrollParents = [];
var $parent = $el.parentNode;
while ($parent && $parent.nodeName !== 'BODY' && $parent.nodeType === document.ELEMENT_NODE) {
if (isScrollElment($parent)) $scrollParents.push($parent);
$parent = $parent.parentNode;
}
$scrollParents.push(window);
return $scrollParents;
}
function isScrollElment($el) {
var _getComputedStyle = getComputedStyle($el),
overflow = _getComputedStyle.overflow,
overflowX = _getComputedStyle.overflowX,
overflowY = _getComputedStyle.overflowY;
return /(auto|scroll|overlay)/.test(overflow + overflowY + overflowX);
}
function setupResizeAndScrollEventListeners($el, listener) {
var $scrollParents = findScrollParents($el);
window.addEventListener('resize', listener, {
passive: true
});
$scrollParents.forEach(function (scrollParent) {
scrollParent.addEventListener('scroll', listener, {
passive: true
});
});
return function removeEventListeners() {
window.removeEventListener('resize', listener, {
passive: true
});
$scrollParents.forEach(function ($scrollParent) {
$scrollParent.removeEventListener('scroll', listener, {
passive: true
});
});
};
}
// CONCATENATED MODULE: ./src/utils/isNaN.js
function isNaN_isNaN(x) {
return x !== x;
}
// EXTERNAL MODULE: external "is-promise"
var external_is_promise_ = __webpack_require__(7);
var external_is_promise_default = /*#__PURE__*/__webpack_require__.n(external_is_promise_);
// CONCATENATED MODULE: ./src/utils/isPromise.js
// EXTERNAL MODULE: external "lodash/once"
var once_ = __webpack_require__(8);
var once_default = /*#__PURE__*/__webpack_require__.n(once_);
// CONCATENATED MODULE: ./src/utils/once.js
// EXTERNAL MODULE: external "lodash/identity"
var identity_ = __webpack_require__(9);
var identity_default = /*#__PURE__*/__webpack_require__.n(identity_);
// CONCATENATED MODULE: ./src/utils/identity.js
// EXTERNAL MODULE: external "lodash/constant"
var constant_ = __webpack_require__(10);
var constant_default = /*#__PURE__*/__webpack_require__.n(constant_);
// CONCATENATED MODULE: ./src/utils/constant.js
// CONCATENATED MODULE: ./src/utils/createMap.js
var createMap = function createMap() {
return Object.create(null);
};
// EXTERNAL MODULE: external "@babel/runtime/helpers/typeof"
var typeof_ = __webpack_require__(11);
var typeof_default = /*#__PURE__*/__webpack_require__.n(typeof_);
// CONCATENATED MODULE: ./src/utils/deepExtend.js
function isPlainObject(value) {
if (value == null || typeof_default()(value) !== 'object') return false;
return Object.getPrototypeOf(value) === Object.prototype;
}
function copy(obj, key, value) {
if (isPlainObject(value)) {
obj[key] || (obj[key] = {});
deepExtend(obj[key], value);
} else {
obj[key] = value;
}
}
function deepExtend(target, source) {
if (isPlainObject(source)) {
var keys = Object.keys(source);
for (var i = 0, len = keys.length; i < len; i++) {
copy(target, keys[i], source[keys[i]]);
}
}
return target;
}
// EXTERNAL MODULE: external "lodash/last"
var last_ = __webpack_require__(12);
var last_default = /*#__PURE__*/__webpack_require__.n(last_);
// CONCATENATED MODULE: ./src/utils/last.js
// CONCATENATED MODULE: ./src/utils/includes.js
function includes(arrOrStr, elem) {
return arrOrStr.indexOf(elem) !== -1;
}
// CONCATENATED MODULE: ./src/utils/find.js
function find(arr, predicate, ctx) {
for (var i = 0, len = arr.length; i < len; i++) {
if (predicate.call(ctx, arr[i], i, arr)) return arr[i];
}
return undefined;
}
// CONCATENATED MODULE: ./src/utils/quickDiff.js
function quickDiff(arrA, arrB) {
if (arrA.length !== arrB.length) return true;
for (var i = 0; i < arrA.length; i++) {
if (arrA[i] !== arrB[i]) return true;
}
return false;
}
// CONCATENATED MODULE: ./src/utils/index.js
// CONCATENATED MODULE: ./src/constants.js
var NO_PARENT_NODE = null;
var UNCHECKED = 0;
var INDETERMINATE = 1;
var CHECKED = 2;
var ALL_CHILDREN = 'ALL_CHILDREN';
var ALL_DESCENDANTS = 'ALL_DESCENDANTS';
var LEAF_CHILDREN = 'LEAF_CHILDREN';
var LEAF_DESCENDANTS = 'LEAF_DESCENDANTS';
var LOAD_ROOT_OPTIONS = 'LOAD_ROOT_OPTIONS';
var LOAD_CHILDREN_OPTIONS = 'LOAD_CHILDREN_OPTIONS';
var ASYNC_SEARCH = 'ASYNC_SEARCH';
var ALL = 'ALL';
var BRANCH_PRIORITY = 'BRANCH_PRIORITY';
var LEAF_PRIORITY = 'LEAF_PRIORITY';
var ALL_WITH_INDETERMINATE = 'ALL_WITH_INDETERMINATE';
var ORDER_SELECTED = 'ORDER_SELECTED';
var LEVEL = 'LEVEL';
var INDEX = 'INDEX';
var KEY_CODES = {
BACKSPACE: 8,
ENTER: 13,
ESCAPE: 27,
END: 35,
HOME: 36,
ARROW_LEFT: 37,
ARROW_UP: 38,
ARROW_RIGHT: 39,
ARROW_DOWN: 40,
DELETE: 46
};
var INPUT_DEBOUNCE_DELAY = process.env.NODE_ENV === 'testing' ? 10 : 200;
var MIN_INPUT_WIDTH = 5;
var MENU_BUFFER = 40;
// CONCATENATED MODULE: ./src/mixins/treeselectMixin.js
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { defineProperty_default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function sortValueByIndex(a, b) {
var i = 0;
do {
if (a.level < i) return -1;
if (b.level < i) return 1;
if (a.index[i] !== b.index[i]) return a.index[i] - b.index[i];
i++;
} while (true);
}
function sortValueByLevel(a, b) {
return a.level === b.level ? sortValueByIndex(a, b) : a.level - b.level;
}
function createAsyncOptionsStates() {
return {
isLoaded: false,
isLoading: false,
loadingError: ''
};
}
function stringifyOptionPropValue(value) {
if (typeof value === 'string') return value;
if (typeof value === 'number' && !isNaN_isNaN(value)) return value + '';
return '';
}
function match(enableFuzzyMatch, needle, haystack) {
return enableFuzzyMatch ? external_fuzzysearch_default()(needle, haystack) : includes(haystack, needle);
}
function getErrorMessage(err) {
return err.message || String(err);
}
var instanceId = 0;
/* harmony default export */ var treeselectMixin = ({
provide: function provide() {
return {
instance: this
};
},
props: {
allowClearingDisabled: {
type: Boolean,
default: false
},
allowSelectingDisabledDescendants: {
type: Boolean,
default: false
},
alwaysOpen: {
type: Boolean,
default: false
},
appendToBody: {
type: Boolean,
default: false
},
async: {
type: Boolean,
default: false
},
autoFocus: {
type: Boolean,
default: false
},
autoLoadRootOptions: {
type: Boolean,
default: true
},
autoDeselectAncestors: {
type: Boolean,
default: false
},
autoDeselectDescendants: {
type: Boolean,
default: false
},
autoSelectAncestors: {
type: Boolean,
default: false
},
autoSelectDescendants: {
type: Boolean,
default: false
},
backspaceRemoves: {
type: Boolean,
default: true
},
beforeClearAll: {
type: Function,
default: constant_default()(true)
},
branchNodesFirst: {
type: Boolean,
default: false
},
cacheOptions: {
type: Boolean,
default: true
},
clearable: {
type: Boolean,
default: true
},
clearAllText: {
type: String,
default: 'Clear all'
},
clearOnSelect: {
type: Boolean,
default: false
},
clearValueText: {
type: String,
default: 'Clear value'
},
closeOnSelect: {
type: Boolean,
default: true
},
defaultExpandLevel: {
type: Number,
default: 0
},
defaultOptions: {
default: false
},
deleteRemoves: {
type: Boolean,
default: true
},
delimiter: {
type: String,
default: ','
},
flattenSearchResults: {
type: Boolean,
default: false
},
disableBranchNodes: {
type: Boolean,
default: false
},
disabled: {
type: Boolean,
default: false
},
disableFuzzyMatching: {
type: Boolean,
default: false
},
flat: {
type: Boolean,
default: false
},
instanceId: {
default: function _default() {
return "".concat(instanceId++, "$$");
},
type: [String, Number]
},
joinValues: {
type: Boolean,
default: false
},
limit: {
type: Number,
default: Infinity
},
limitText: {
type: Function,
default: function limitTextDefault(count) {
return "and ".concat(count, " more");
}
},
loadingText: {
type: String,
default: 'Loading...'
},
loadOptions: {
type: Function
},
matchKeys: {
type: Array,
default: constant_default()(['label'])
},
maxHeight: {
type: Number,
default: 300
},
multiple: {
type: Boolean,
default: false
},
name: {
type: String
},
noChildrenText: {
type: String,
default: 'No sub-options.'
},
noOptionsText: {
type: String,
default: 'No options available.'
},
noResultsText: {
type: String,
default: 'No results found...'
},
normalizer: {
type: Function,
default: identity_default.a
},
openDirection: {
type: String,
default: 'auto',
validator: function validator(value) {
var acceptableValues = ['auto', 'top', 'bottom', 'above', 'below'];
return includes(acceptableValues, value);
}
},
openOnClick: {
type: Boolean,
default: true
},
openOnFocus: {
type: Boolean,
default: false
},
options: {
type: Array
},
placeholder: {
type: String,
default: 'Select...'
},
required: {
type: Boolean,
default: false
},
retryText: {
type: String,
default: 'Retry?'
},
retryTitle: {
type: String,
default: 'Click to retry'
},
searchable: {
type: Boolean,
default: true
},
searchNested: {
type: Boolean,
default: false
},
searchPromptText: {
type: String,
default: 'Type to search...'
},
showCount: {
type: Boolean,
default: false
},
showCountOf: {
type: String,
default: ALL_CHILDREN,
validator: function validator(value) {
var acceptableValues = [ALL_CHILDREN, ALL_DESCENDANTS, LEAF_CHILDREN, LEAF_DESCENDANTS];
return includes(acceptableValues, value);
}
},
showCountOnSearch: null,
sortValueBy: {
type: String,
default: ORDER_SELECTED,
validator: function validator(value) {
var acceptableValues = [ORDER_SELECTED, LEVEL, INDEX];
return includes(acceptableValues, value);
}
},
tabIndex: {
type: Number,
default: 0
},
value: null,
valueConsistsOf: {
type: String,
default: BRANCH_PRIORITY,
validator: function validator(value) {
var acceptableValues = [ALL, BRANCH_PRIORITY, LEAF_PRIORITY, ALL_WITH_INDETERMINATE];
return includes(acceptableValues, value);
}
},
valueFormat: {
type: String,
default: 'id'
},
zIndex: {
type: [Number, String],
default: 999
}
},
data: function data() {
return {
trigger: {
isFocused: false,
searchQuery: ''
},
menu: {
isOpen: false,
current: null,
lastScrollPosition: 0,
placement: 'bottom'
},
forest: {
normalizedOptions: [],
nodeMap: createMap(),
checkedStateMap: createMap(),
selectedNodeIds: this.extractCheckedNodeIdsFromValue(),
selectedNodeMap: createMap()
},
rootOptionsStates: createAsyncOptionsStates(),
localSearch: {
active: false,
noResults: true,
countMap: createMap()
},
remoteSearch: createMap()
};
},
computed: {
selectedNodes: function selectedNodes() {
return this.forest.selectedNodeIds.map(this.getNode);
},
internalValue: function internalValue() {
var _this = this;
var internalValue;
if (this.single || this.flat || this.disableBranchNodes || this.valueConsistsOf === ALL) {
internalValue = this.forest.selectedNodeIds.slice();
} else if (this.valueConsistsOf === BRANCH_PRIORITY) {
internalValue = this.forest.selectedNodeIds.filter(function (id) {
var node = _this.getNode(id);
if (node.isRootNode) return true;
return !_this.isSelected(node.parentNode);
});
} else if (this.valueConsistsOf === LEAF_PRIORITY) {
internalValue = this.forest.selectedNodeIds.filter(function (id) {
var node = _this.getNode(id);
if (node.isLeaf) return true;
return node.children.length === 0;
});
} else if (this.valueConsistsOf === ALL_WITH_INDETERMINATE) {
var _internalValue;
var indeterminateNodeIds = [];
internalValue = this.forest.selectedNodeIds.slice();
this.selectedNodes.forEach(function (selectedNode) {
selectedNode.ancestors.forEach(function (ancestor) {
if (includes(indeterminateNodeIds, ancestor.id)) return;
if (includes(internalValue, ancestor.id)) return;
indeterminateNodeIds.push(ancestor.id);
});
});
(_internalValue = internalValue).push.apply(_internalValue, indeterminateNodeIds);
}
if (this.sortValueBy === LEVEL) {
internalValue.sort(function (a, b) {
return sortValueByLevel(_this.getNode(a), _this.getNode(b));
});
} else if (this.sortValueBy === INDEX) {
internalValue.sort(function (a, b) {
return sortValueByIndex(_this.getNode(a), _this.getNode(b));
});
}
return internalValue;
},
hasValue: function hasValue() {
return this.internalValue.length > 0;
},
single: function single() {
return !this.multiple;
},
visibleOptionIds: function visibleOptionIds() {
var _this2 = this;
var visibleOptionIds = [];
this.traverseAllNodesByIndex(function (node) {
if (!_this2.localSearch.active || _this2.shouldOptionBeIncludedInSearchResult(node)) {
visibleOptionIds.push(node.id);
}
if (node.isBranch && !_this2.shouldExpand(node)) {
return false;
}
});
return visibleOptionIds;
},
hasVisibleOptions: function hasVisibleOptions() {
return this.visibleOptionIds.length !== 0;
},
showCountOnSearchComputed: function showCountOnSearchComputed() {
return typeof this.showCountOnSearch === 'boolean' ? this.showCountOnSearch : this.showCount;
},
hasBranchNodes: function hasBranchNodes() {
return this.forest.normalizedOptions.some(function (rootNode) {
return rootNode.isBranch;
});
},
shouldFlattenOptions: function shouldFlattenOptions() {
return this.localSearch.active && this.flattenSearchResults;
}
},
watch: {
alwaysOpen: function alwaysOpen(newValue) {
if (newValue) this.openMenu();else this.closeMenu();
},
branchNodesFirst: function branchNodesFirst() {
this.initialize();
},
disabled: function disabled(newValue) {
if (newValue && this.menu.isOpen) this.closeMenu();else if (!newValue && !this.menu.isOpen && this.alwaysOpen) this.openMenu();
},
flat: function flat() {
this.initialize();
},
internalValue: function internalValue(newValue, oldValue) {
var hasChanged = quickDiff(newValue, oldValue);
if (hasChanged) this.$emit('input', this.getValue(), this.getInstanceId());
},
matchKeys: function matchKeys() {
this.initialize();
},
multiple: function multiple(newValue) {
if (newValue) this.buildForestState();
},
options: {
handler: function handler() {
if (this.async) return;
this.initialize();
this.rootOptionsStates.isLoaded = Array.isArray(this.options);
},
deep: true,
immediate: true
},
'trigger.searchQuery': function triggerSearchQuery() {
if (this.async) {
this.handleRemoteSearch();
} else {
this.handleLocalSearch();
}
this.$emit('search-change', this.trigger.searchQuery, this.getInstanceId());
},
value: function value() {
var nodeIdsFromValue = this.extractCheckedNodeIdsFromValue();
var hasChanged = quickDiff(nodeIdsFromValue, this.internalValue);
if (hasChanged) this.fixSelectedNodeIds(nodeIdsFromValue);
}
},
methods: {
verifyProps: function verifyProps() {
var _this3 = this;
warning_warning(function () {
return _this3.async ? _this3.searchable : true;
}, function () {
return 'For async search mode, the value of "searchable" prop must be true.';
});
if (this.options == null && !this.loadOptions) {
warning_warning(function () {
return false;
}, function () {
return 'Are you meant to dynamically load options? You need to use "loadOptions" prop.';
});
}
if (this.flat) {
warning_warning(function () {
return _this3.multiple;
}, function () {
return 'You are using flat mode. But you forgot to add "multiple=true"?';
});
}
if (!this.flat) {
var propNames = ['autoSelectAncestors', 'autoSelectDescendants', 'autoDeselectAncestors', 'autoDeselectDescendants'];
propNames.forEach(function (propName) {
warning_warning(function () {
return !_this3[propName];
}, function () {
return "\"".concat(propName, "\" only applies to flat mode.");
});
});
}
},
resetFlags: function resetFlags() {
this._blurOnSelect = false;
},
initialize: function initialize() {
var options = this.async ? this.getRemoteSearchEntry().options : this.options;
if (Array.isArray(options)) {
var prevNodeMap = this.forest.nodeMap;
this.forest.nodeMap = createMap();
this.keepDataOfSelectedNodes(prevNodeMap);
this.forest.normalizedOptions = this.normalize(NO_PARENT_NODE, options, prevNodeMap);
this.fixSelectedNodeIds(this.internalValue);
} else {
this.forest.normalizedOptions = [];
}
},
getInstanceId: function getInstanceId() {
return this.instanceId == null ? this.id : this.instanceId;
},
getValue: function getValue() {
var _this4 = this;
if (this.valueFormat === 'id') {
return this.multiple ? this.internalValue.slice() : this.internalValue[0];
}
var rawNodes = this.internalValue.map(function (id) {
return _this4.getNode(id).raw;
});
return this.multiple ? rawNodes : rawNodes[0];
},
getNode: function getNode(nodeId) {
warning_warning(function () {
return nodeId != null;
}, function () {
return "Invalid node id: ".concat(nodeId);
});
if (nodeId == null) return null;
return nodeId in this.forest.nodeMap ? this.forest.nodeMap[nodeId] : this.createFallbackNode(nodeId);
},
createFallbackNode: function createFallbackNode(id) {
var raw = this.extractNodeFromValue(id);
var label = this.enhancedNormalizer(raw).label || "".concat(id, " (unknown)");
var fallbackNode = {
id: id,
label: label,
ancestors: [],
parentNode: NO_PARENT_NODE,
isFallbackNode: true,
isRootNode: true,
isLeaf: true,
isBranch: false,
isDisabled: false,
isNew: false,
index: [-1],
level: 0,
raw: raw
};
return this.$set(this.forest.nodeMap, id, fallbackNode);
},
extractCheckedNodeIdsFromValue: function extractCheckedNodeIdsFromValue() {
var _this5 = this;
if (this.value == null) return [];
if (this.valueFormat === 'id') {
return this.multiple ? this.value.slice() : [this.value];
}
return (this.multiple ? this.value : [this.value]).map(function (node) {
return _this5.enhancedNormalizer(node);
}).map(function (node) {
return node.id;
});
},
extractNodeFromValue: function extractNodeFromValue(id) {
var _this6 = this;
var defaultNode = {
id: id
};
if (this.valueFormat === 'id') {
return defaultNode;
}
var valueArray = this.multiple ? Array.isArray(this.value) ? this.value : [] : this.value ? [this.value] : [];
var matched = find(valueArray, function (node) {
return node && _this6.enhancedNormalizer(node).id === id;
});
return matched || defaultNode;
},
fixSelectedNodeIds: function fixSelectedNodeIds(nodeIdListOfPrevValue) {
var _this7 = this;
var nextSelectedNodeIds = [];
if (this.single || this.flat || this.disableBranchNodes || this.valueConsistsOf === ALL) {
nextSelectedNodeIds = nodeIdListOfPrevValue;
} else if (this.valueConsistsOf === BRANCH_PRIORITY) {
nodeIdListOfPrevValue.forEach(function (nodeId) {
nextSelectedNodeIds.push(nodeId);
var node = _this7.getNode(nodeId);
if (node.isBranch) _this7.traverseDescendantsBFS(node, function (descendant) {
nextSelectedNodeIds.push(descendant.id);
});
});
} else if (this.valueConsistsOf === LEAF_PRIORITY) {
var map = createMap();
var queue = nodeIdListOfPrevValue.slice();
while (queue.length) {
var nodeId = queue.shift();
var node = this.getNode(nodeId);
nextSelectedNodeIds.push(nodeId);
if (node.isRootNode) continue;
if (!(node.parentNode.id in map)) map[node.parentNode.id] = node.parentNode.children.length;
if (--map[node.parentNode.id] === 0) queue.push(node.parentNode.id);
}
} else if (this.valueConsistsOf === ALL_WITH_INDETERMINATE) {
var _map = createMap();
var _queue = nodeIdListOfPrevValue.filter(function (nodeId) {
var node = _this7.getNode(nodeId);
return node.isLeaf || node.children.length === 0;
});
while (_queue.length) {
var _nodeId = _queue.shift();
var _node = this.getNode(_nodeId);
nextSelectedNodeIds.push(_nodeId);
if (_node.isRootNode) continue;
if (!(_node.parentNode.id in _map)) _map[_node.parentNode.id] = _node.parentNode.children.length;
if (--_map[_node.parentNode.id] === 0) _queue.push(_node.parentNode.id);
}
}
var hasChanged = quickDiff(this.forest.selectedNodeIds, nextSelectedNodeIds);
if (hasChanged) this.forest.selectedNodeIds = nextSelectedNodeIds;
this.buildForestState();
},
keepDataOfSelectedNodes: function keepDataOfSelectedNodes(prevNodeMap) {
var _this8 = this;
this.forest.selectedNodeIds.forEach(function (id) {
if (!prevNodeMap[id]) return;
var node = _objectSpread({}, prevNodeMap[id], {
isFallbackNode: true
});
_this8.$set(_this8.forest.nodeMap, id, node);
});
},
isSelected: function isSelected(node) {
return this.forest.selectedNodeMap[node.id] === true;
},
traverseDescendantsBFS: function traverseDescendantsBFS(parentNode, callback) {
if (!parentNode.isBranch) return;
var queue = parentNode.children.slice();
while (queue.length) {
var currNode = queue[0];
if (currNode.isBranch) queue.push.apply(queue, toConsumableArray_default()(currNode.children));
callback(currNode);
queue.shift();
}
},
traverseDescendantsDFS: function traverseDescendantsDFS(parentNode, callback) {
var _this9 = this;
if (!parentNode.isBranch) return;
parentNode.children.forEach(function (child) {
_this9.traverseDescendantsDFS(child, callback);
callback(child);
});
},
traverseAllNodesDFS: function traverseAllNodesDFS(callback) {
var _this10 = this;
this.forest.normalizedOptions.forEach(function (rootNode) {
_this10.traverseDescendantsDFS(rootNode, callback);
callback(rootNode);
});
},
traverseAllNodesByIndex: function traverseAllNodesByIndex(callback) {
var walk = function walk(parentNode) {
parentNode.children.forEach(function (child) {
if (callback(child) !== false && child.isBranch) {
walk(child);
}
});
};
walk({
children: this.forest.normalizedOptions
});
},
toggleClickOutsideEvent: function toggleClickOutsideEvent(enabled) {
if (enabled) {
document.addEventListener('mousedown', this.handleClickOutside, false);
} else {
document.removeEventListener('mousedown', this.handleClickOutside, false);
}
},
getValueContainer: function getValueContainer() {
return this.$refs.control.$refs['value-container'];
},
getInput: function getInput() {
return this.getValueContainer().$refs.input;
},
focusInput: function focusInput() {
this.getInput().focus();
},
blurInput: function blurInput() {
this.getInput().blur();
},
handleMouseDown: onLeftClick(function handleMouseDown(evt) {
evt.preventDefault();
evt.stopPropagation();
if (this.disabled) return;
var isClickedOnValueContainer = this.getValueContainer().$el.contains(evt.target);
if (isClickedOnValueContainer && !this.menu.isOpen && (this.openOnClick || this.trigger.isFocused)) {
this.openMenu();
}
if (this._blurOnSelect) {
this.blurInput();
} else {
this.focusInput();
}
this.resetFlags();
}),
handleClickOutside: function handleClickOutside(evt) {
if (this.$refs.wrapper && !this.$refs.wrapper.contains(evt.target)) {
this.blurInput();
this.closeMenu();
}
},
handleLocalSearch: function handleLocalSearch() {
var _this11 = this;
var searchQuery = this.trigger.searchQuery;
var done = function done() {
return _this11.resetHighlightedOptionWhenNecessary(true);
};
if (!searchQuery) {
this.localSearch.active = false;
return done();
}
this.localSearch.active = true;
this.localSearch.noResults = true;
this.traverseAllNodesDFS(function (node) {
if (node.isBranch) {
var _this11$$set;
node.isExpandedOnSearch = false;
node.showAllChildrenOnSearch = false;
node.isMatched = false;
node.hasMatchedDescendants = false;
_this11.$set(_this11.localSearch.countMap, node.id, (_this11$$set = {}, defineProperty_default()(_this11$$set, ALL_CHILDREN, 0), defineProperty_default()(_this11$$set, ALL_DESCENDANTS, 0), defineProperty_default()(_this11$$set, LEAF_CHILDREN, 0), defineProperty_default()(_this11$$set, LEAF_DESCENDANTS, 0), _this11$$set));
}
});
var lowerCasedSearchQuery = searchQuery.trim().toLocaleLowerCase();
var splitSearchQuery = lowerCasedSearchQuery.replace(/\s+/g, ' ').split(' ');
this.traverseAllNodesDFS(function (node) {
if (_this11.searchNested && splitSearchQuery.length > 1) {
node.isMatched = splitSearchQuery.every(function (filterValue) {
return match(false, filterValue, node.nestedSearchLabel);
});
} else {
node.isMatched = _this11.matchKeys.some(function (matchKey) {
return match(!_this11.disableFuzzyMatching, lowerCasedSearchQuery, node.lowerCased[matchKey]);
});
}
if (node.isMatched) {
_this11.localSearch.noResults = false;
node.ancestors.forEach(function (ancestor) {
return _this11.localSearch.countMap[ancestor.id][ALL_DESCENDANTS]++;
});
if (node.isLeaf) node.ancestors.forEach(function (ancestor) {
return _this11.localSearch.countMap[ancestor.id][LEAF_DESCENDANTS]++;
});
if (node.parentNode !== NO_PARENT_NODE) {
_this11.localSearch.countMap[node.parentNode.id][ALL_CHILDREN] += 1;
if (node.isLeaf) _this11.localSearch.countMap[node.parentNode.id][LEAF_CHILDREN] += 1;
}
}
if ((node.isMatched || node.isBranch && node.isExpandedOnSearch) && node.parentNode !== NO_PARENT_NODE) {
node.parentNode.isExpandedOnSearch = true;
node.parentNode.hasMatchedDescendants = true;
}
});
done();
},
handleRemoteSearch: function handleRemoteSearch() {
var _this12 = this;
var searchQuery = this.trigger.searchQuery;
var entry = this.getRemoteSearchEntry();
var done = function done() {
_this12.initialize();
_this12.resetHighlightedOptionWhenNecessary(true);
};
if ((searchQuery === '' || this.cacheOptions) && entry.isLoaded) {
return done();
}
this.callLoadOptionsProp({
action: ASYNC_SEARCH,
args: {
searchQuery: searchQuery
},
isPending: function isPending() {
return entry.isLoading;
},
start: function start() {
entry.isLoading = true;
entry.isLoaded = false;
entry.loadingError = '';
},
succeed: function succeed(options) {
entry.isLoaded = true;
entry.options = options;
if (_this12.trigger.searchQuery === searchQuery) done();
},
fail: function fail(err) {
entry.loadingError = getErrorMessage(err);
},
end: function end() {
entry.isLoading = false;
}
});
},
getRemoteSearchEntry: function getRemoteSearchEntry() {
var _this13 = this;
var searchQuery = this.trigger.searchQuery;
var entry = this.remoteSearch[searchQuery] || _objectSpread({}, createAsyncOptionsStates(), {
options: []
});
this.$watch(function () {
return entry.options;
}, function () {
if (_this13.trigger.searchQuery === searchQuery) _this13.initialize();
}, {
deep: true
});
if (searchQuery === '') {
if (Array.isArray(this.defaultOptions)) {
entry.options = this.defaultOptions;
entry.isLoaded = true;
return entry;
} else if (this.defaultOptions !== true) {
entry.isLoaded = true;
return entry;
}
}
if (!this.remoteSearch[searchQuery]) {
this.$set(this.remoteSearch, searchQuery, entry);
}
return entry;
},
shouldExpand: function shouldExpand(node) {
return this.localSearch.active ? node.isExpandedOnSearch : node.isExpanded;
},
shouldOptionBeIncludedInSearchResult: function shouldOptionBeIncludedInSearchResult(node) {
if (node.isMatched) return true;
if (node.isBranch && node.hasMatchedDescendants && !this.flattenSearchResults) return true;
if (!node.isRootNode && node.parentNode.showAllChildrenOnSearch) return true;
return false;
},
shouldShowOptionInMenu: function shouldShowOptionInMenu(node) {
if (this.localSearch.active && !this.shouldOptionBeIncludedInSearchResult(node)) {
return false;
}
return true;
},
getControl: function getControl() {
return this.$refs.control.$el;
},
getMenu: function getMenu() {
var ref = this.appendToBody ? this.$refs.portal.portalTarget : this;
var $menu = ref.$refs.menu.$refs.menu;
return $menu && $menu.nodeName !== '#comment' ? $menu : null;
},
setCurrentHighlightedOption: function setCurrentHighlightedOption(node) {
var _this14 = this;
var scroll = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var prev = this.menu.current;
if (prev != null && prev in this.forest.nodeMap) {
this.forest.nodeMap[prev].isHighlighted = false;
}
this.menu.current = node.id;
node.isHighlighted = true;
if (this.menu.isOpen && scroll) {
var scrollToOption = function scrollToOption() {
var $menu = _this14.getMenu();
var $option = $menu.querySelector(".vue-treeselect__option[data-id=\"".concat(node.id, "\"]"));
if ($option) scrollIntoView($menu, $option);
};
if (this.getMenu()) {
scrollToOption();
} else {
this.$nextTick(scrollToOption);
}
}
},
resetHighlightedOptionWhenNecessary: function resetHighlightedOptionWhenNecessary() {
var forceReset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var current = this.menu.current;
if (forceReset || current == null || !(current in this.forest.nodeMap) || !this.shouldShowOptionInMenu(this.getNode(current))) {
this.highlightFirstOption();
}
},
highlightFirstOption: function highlightFirstOption() {
if (!this.hasVisibleOptions) return;
var first = this.visibleOptionIds[0];
this.setCurrentHighlightedOption(this.getNode(first));
},
highlightPrevOption: function highlightPrevOption() {
if (!this.hasVisibleOptions) return;
var prev = this.visibleOptionIds.indexOf(this.menu.current) - 1;
if (prev === -1) return this.highlightLastOption();
this.setCurrentHighlightedOption(this.getNode(this.visibleOptionIds[prev]));
},
highlightNextOption: function highlightNextOption() {
if (!this.hasVisibleOptions) return;
var next = this.visibleOptionIds.indexOf(this.menu.current) + 1;
if (next === this.visibleOptionIds.length) return this.highlightFirstOption();
this.setCurrentHighlightedOption(this.getNode(this.visibleOptionIds[next]));
},
highlightLastOption: function highlightLastOption() {
if (!this.hasVisibleOptions) return;
var last = last_default()(this.visibleOptionIds);
this.setCurrentHighlightedOption(this.getNode(last));
},
resetSearchQuery: function resetSearchQuery() {
this.trigger.searchQuery = '';
},
closeMenu: function closeMenu() {
if (!this.menu.isOpen || !this.disabled && this.alwaysOpen) return;
this.saveMenuScrollPosition();
this.menu.isOpen = false;
this.toggleClickOutsideEvent(false);
this.resetSearchQuery();
this.$emit('close', this.getValue(), this.getInstanceId());
},
openMenu: function openMenu() {
if (this.disabled || this.menu.isOpen) return;
this.menu.isOpen = true;
this.$nextTick(this.resetHighlightedOptionWhenNecessary);
this.$nextTick(this.restoreMenuScrollPosition);
if (!this.options && !this.async) this.loadRootOptions();
this.toggleClickOutsideEvent(true);
this.$emit('open', this.getInstanceId());
},
toggleMenu: function toggleMenu() {
if (this.menu.isOpen) {
this.closeMenu();
} else {
this.openMenu();
}
},
toggleExpanded: function toggleExpanded(node) {
var nextState;
if (this.localSearch.active) {
nextState = node.isExpandedOnSearch = !node.isExpandedOnSearch;
if (nextState) node.showAllChildrenOnSearch = true;
} else {
nextState = node.isExpanded = !node.isExpanded;
}
if (nextState && !node.childrenStates.isLoaded) {
this.loadChildrenOptions(node);
}
},
buildForestState: function buildForestState() {
var _this15 = this;
var selectedNodeMap = createMap();
this.forest.selectedNodeIds.forEach(function (selectedNodeId) {
selectedNodeMap[selectedNodeId] = true;
});
this.forest.selectedNodeMap = selectedNodeMap;
var checkedStateMap = createMap();
if (this.multiple) {
this.traverseAllNodesByIndex(function (node) {
checkedStateMap[node.id] = UNCHECKED;
});
this.selectedNodes.forEach(function (selectedNode) {
checkedStateMap[selectedNode.id] = CHECKED;
if (!_this15.flat && !_this15.disableBranchNodes) {
selectedNode.ancestors.forEach(function (ancestorNode) {
if (!_this15.isSelected(ancestorNode)) {
checkedStateMap[ancestorNode.id] = INDETERMINATE;
}
});
}
});
}
this.forest.checkedStateMap = checkedStateMap;
},
enhancedNormalizer: function enhancedNormalizer(raw) {
return _objectSpread({}, raw, {}, this.normalizer(raw, this.getInstanceId()));
},
normalize: function normalize(parentNode, nodes, prevNodeMap) {
var _this16 = this;
var normalizedOptions = nodes.map(function (node) {
return [_this16.enhancedNormalizer(node), node];
}).map(function (_ref, index) {
var _ref2 = slicedToArray_default()(_ref, 2),
node = _ref2[0],
raw = _ref2[1];
_this16.checkDuplication(node);
_this16.verifyNodeShape(node);
var id = node.id,
label = node.label,
children = node.children,
isDefaultExpanded = node.isDefaultExpanded;
var isRootNode = parentNode === NO_PARENT_NODE;
var level = isRootNode ? 0 : parentNode.level + 1;
var isBranch = Array.isArray(children) || children === null;
var isLeaf = !isBranch;
var isDisabled = !!node.isDisabled || !_this16.flat && !isRootNode && parentNode.isDisabled;
var isNew = !!node.isNew;
var lowerCased = _this16.matchKeys.reduce(function (prev, key) {
return _objectSpread({}, prev, defineProperty_default()({}, key, stringifyOptionPropValue(node[key]).toLocaleLowerCase()));
}, {});
var nestedSearchLabel = isRootNode ? lowerCased.label : parentNode.nestedSearchLabel + ' ' + lowerCased.label;
var normalized = _this16.$set(_this16.forest.nodeMap, id, createMap());
_this16.$set(normalized, 'id', id);
_this16.$set(normalized, 'label', label);
_this16.$set(normalized, 'level', level);
_this16.$set(normalized, 'ancestors', isRootNode ? [] : [parentNode].concat(parentNode.ancestors));
_this16.$set(normalized, 'index', (isRootNode ? [] : parentNode.index).concat(index));
_this16.$set(normalized, 'parentNode', parentNode);
_this16.$set(normalized, 'lowerCased', lowerCased);
_this16.$set(normalized, 'nestedSearchLabel', nestedSearchLabel);
_this16.$set(normalized, 'isDisabled', isDisabled);
_this16.$set(normalized, 'isNew', isNew);
_this16.$set(normalized, 'isMatched', false);
_this16.$set(normalized, 'isHighlighted', false);
_this16.$set(normalized, 'isBranch', isBranch);
_this16.$set(normalized, 'isLeaf', isLeaf);