纽威
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3143 lines
108 KiB

3 years ago
  1. (function ($) {
  2. 'use strict';
  3. var DISALLOWED_ATTRIBUTES = ['sanitize', 'whiteList', 'sanitizeFn'];
  4. var uriAttrs = [
  5. 'background',
  6. 'cite',
  7. 'href',
  8. 'itemtype',
  9. 'longdesc',
  10. 'poster',
  11. 'src',
  12. 'xlink:href'
  13. ];
  14. var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i;
  15. var DefaultWhitelist = {
  16. // Global attributes allowed on any supplied element below.
  17. '*': ['class', 'dir', 'id', 'lang', 'role', 'tabindex', 'style', ARIA_ATTRIBUTE_PATTERN],
  18. a: ['target', 'href', 'title', 'rel'],
  19. area: [],
  20. b: [],
  21. br: [],
  22. col: [],
  23. code: [],
  24. div: [],
  25. em: [],
  26. hr: [],
  27. h1: [],
  28. h2: [],
  29. h3: [],
  30. h4: [],
  31. h5: [],
  32. h6: [],
  33. i: [],
  34. img: ['src', 'alt', 'title', 'width', 'height'],
  35. li: [],
  36. ol: [],
  37. p: [],
  38. pre: [],
  39. s: [],
  40. small: [],
  41. span: [],
  42. sub: [],
  43. sup: [],
  44. strong: [],
  45. u: [],
  46. ul: []
  47. }
  48. /**
  49. * A pattern that recognizes a commonly useful subset of URLs that are safe.
  50. *
  51. * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts
  52. */
  53. var SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi;
  54. /**
  55. * A pattern that matches safe data URLs. Only matches image, video and audio types.
  56. *
  57. * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts
  58. */
  59. var DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+/]+=*$/i;
  60. function allowedAttribute (attr, allowedAttributeList) {
  61. var attrName = attr.nodeName.toLowerCase()
  62. if ($.inArray(attrName, allowedAttributeList) !== -1) {
  63. if ($.inArray(attrName, uriAttrs) !== -1) {
  64. return Boolean(attr.nodeValue.match(SAFE_URL_PATTERN) || attr.nodeValue.match(DATA_URL_PATTERN))
  65. }
  66. return true
  67. }
  68. var regExp = $(allowedAttributeList).filter(function (index, value) {
  69. return value instanceof RegExp
  70. })
  71. // Check if a regular expression validates the attribute.
  72. for (var i = 0, l = regExp.length; i < l; i++) {
  73. if (attrName.match(regExp[i])) {
  74. return true
  75. }
  76. }
  77. return false
  78. }
  79. function sanitizeHtml (unsafeElements, whiteList, sanitizeFn) {
  80. if (sanitizeFn && typeof sanitizeFn === 'function') {
  81. return sanitizeFn(unsafeElements);
  82. }
  83. var whitelistKeys = Object.keys(whiteList);
  84. for (var i = 0, len = unsafeElements.length; i < len; i++) {
  85. var elements = unsafeElements[i].querySelectorAll('*');
  86. for (var j = 0, len2 = elements.length; j < len2; j++) {
  87. var el = elements[j];
  88. var elName = el.nodeName.toLowerCase();
  89. if (whitelistKeys.indexOf(elName) === -1) {
  90. el.parentNode.removeChild(el);
  91. continue;
  92. }
  93. var attributeList = [].slice.call(el.attributes);
  94. var whitelistedAttributes = [].concat(whiteList['*'] || [], whiteList[elName] || []);
  95. for (var k = 0, len3 = attributeList.length; k < len3; k++) {
  96. var attr = attributeList[k];
  97. if (!allowedAttribute(attr, whitelistedAttributes)) {
  98. el.removeAttribute(attr.nodeName);
  99. }
  100. }
  101. }
  102. }
  103. }
  104. // Polyfill for browsers with no classList support
  105. // Remove in v2
  106. if (!('classList' in document.createElement('_'))) {
  107. (function (view) {
  108. if (!('Element' in view)) return;
  109. var classListProp = 'classList',
  110. protoProp = 'prototype',
  111. elemCtrProto = view.Element[protoProp],
  112. objCtr = Object,
  113. classListGetter = function () {
  114. var $elem = $(this);
  115. return {
  116. add: function (classes) {
  117. classes = Array.prototype.slice.call(arguments).join(' ');
  118. return $elem.addClass(classes);
  119. },
  120. remove: function (classes) {
  121. classes = Array.prototype.slice.call(arguments).join(' ');
  122. return $elem.removeClass(classes);
  123. },
  124. toggle: function (classes, force) {
  125. return $elem.toggleClass(classes, force);
  126. },
  127. contains: function (classes) {
  128. return $elem.hasClass(classes);
  129. }
  130. }
  131. };
  132. if (objCtr.defineProperty) {
  133. var classListPropDesc = {
  134. get: classListGetter,
  135. enumerable: true,
  136. configurable: true
  137. };
  138. try {
  139. objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
  140. } catch (ex) { // IE 8 doesn't support enumerable:true
  141. // adding undefined to fight this issue https://github.com/eligrey/classList.js/issues/36
  142. // modernie IE8-MSW7 machine has IE8 8.0.6001.18702 and is affected
  143. if (ex.number === undefined || ex.number === -0x7FF5EC54) {
  144. classListPropDesc.enumerable = false;
  145. objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
  146. }
  147. }
  148. } else if (objCtr[protoProp].__defineGetter__) {
  149. elemCtrProto.__defineGetter__(classListProp, classListGetter);
  150. }
  151. }(window));
  152. }
  153. var testElement = document.createElement('_');
  154. testElement.classList.add('c1', 'c2');
  155. if (!testElement.classList.contains('c2')) {
  156. var _add = DOMTokenList.prototype.add,
  157. _remove = DOMTokenList.prototype.remove;
  158. DOMTokenList.prototype.add = function () {
  159. Array.prototype.forEach.call(arguments, _add.bind(this));
  160. }
  161. DOMTokenList.prototype.remove = function () {
  162. Array.prototype.forEach.call(arguments, _remove.bind(this));
  163. }
  164. }
  165. testElement.classList.toggle('c3', false);
  166. // Polyfill for IE 10 and Firefox <24, where classList.toggle does not
  167. // support the second argument.
  168. if (testElement.classList.contains('c3')) {
  169. var _toggle = DOMTokenList.prototype.toggle;
  170. DOMTokenList.prototype.toggle = function (token, force) {
  171. if (1 in arguments && !this.contains(token) === !force) {
  172. return force;
  173. } else {
  174. return _toggle.call(this, token);
  175. }
  176. };
  177. }
  178. testElement = null;
  179. // shallow array comparison
  180. function isEqual (array1, array2) {
  181. return array1.length === array2.length && array1.every(function (element, index) {
  182. return element === array2[index];
  183. });
  184. };
  185. // <editor-fold desc="Shims">
  186. if (!String.prototype.startsWith) {
  187. (function () {
  188. 'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
  189. var defineProperty = (function () {
  190. // IE 8 only supports `Object.defineProperty` on DOM elements
  191. try {
  192. var object = {};
  193. var $defineProperty = Object.defineProperty;
  194. var result = $defineProperty(object, object, object) && $defineProperty;
  195. } catch (error) {
  196. }
  197. return result;
  198. }());
  199. var toString = {}.toString;
  200. var startsWith = function (search) {
  201. if (this == null) {
  202. throw new TypeError();
  203. }
  204. var string = String(this);
  205. if (search && toString.call(search) == '[object RegExp]') {
  206. throw new TypeError();
  207. }
  208. var stringLength = string.length;
  209. var searchString = String(search);
  210. var searchLength = searchString.length;
  211. var position = arguments.length > 1 ? arguments[1] : undefined;
  212. // `ToInteger`
  213. var pos = position ? Number(position) : 0;
  214. if (pos != pos) { // better `isNaN`
  215. pos = 0;
  216. }
  217. var start = Math.min(Math.max(pos, 0), stringLength);
  218. // Avoid the `indexOf` call if no match is possible
  219. if (searchLength + start > stringLength) {
  220. return false;
  221. }
  222. var index = -1;
  223. while (++index < searchLength) {
  224. if (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {
  225. return false;
  226. }
  227. }
  228. return true;
  229. };
  230. if (defineProperty) {
  231. defineProperty(String.prototype, 'startsWith', {
  232. 'value': startsWith,
  233. 'configurable': true,
  234. 'writable': true
  235. });
  236. } else {
  237. String.prototype.startsWith = startsWith;
  238. }
  239. }());
  240. }
  241. if (!Object.keys) {
  242. Object.keys = function (
  243. o, // object
  244. k, // key
  245. r // result array
  246. ) {
  247. // initialize object and result
  248. r = [];
  249. // iterate over object keys
  250. for (k in o) {
  251. // fill result array with non-prototypical keys
  252. r.hasOwnProperty.call(o, k) && r.push(k);
  253. }
  254. // return result
  255. return r;
  256. };
  257. }
  258. if (HTMLSelectElement && !HTMLSelectElement.prototype.hasOwnProperty('selectedOptions')) {
  259. Object.defineProperty(HTMLSelectElement.prototype, 'selectedOptions', {
  260. get: function () {
  261. return this.querySelectorAll(':checked');
  262. }
  263. });
  264. }
  265. function getSelectedOptions (select, ignoreDisabled) {
  266. var selectedOptions = select.selectedOptions,
  267. options = [],
  268. opt;
  269. if (ignoreDisabled) {
  270. for (var i = 0, len = selectedOptions.length; i < len; i++) {
  271. opt = selectedOptions[i];
  272. if (!(opt.disabled || opt.parentNode.tagName === 'OPTGROUP' && opt.parentNode.disabled)) {
  273. options.push(opt);
  274. }
  275. }
  276. return options;
  277. }
  278. return selectedOptions;
  279. }
  280. // much faster than $.val()
  281. function getSelectValues (select, selectedOptions) {
  282. var value = [],
  283. options = selectedOptions || select.selectedOptions,
  284. opt;
  285. for (var i = 0, len = options.length; i < len; i++) {
  286. opt = options[i];
  287. if (!(opt.disabled || opt.parentNode.tagName === 'OPTGROUP' && opt.parentNode.disabled)) {
  288. value.push(opt.value);
  289. }
  290. }
  291. if (!select.multiple) {
  292. return !value.length ? null : value[0];
  293. }
  294. return value;
  295. }
  296. // set data-selected on select element if the value has been programmatically selected
  297. // prior to initialization of bootstrap-select
  298. // * consider removing or replacing an alternative method *
  299. var valHooks = {
  300. useDefault: false,
  301. _set: $.valHooks.select.set
  302. };
  303. $.valHooks.select.set = function (elem, value) {
  304. if (value && !valHooks.useDefault) $(elem).data('selected', true);
  305. return valHooks._set.apply(this, arguments);
  306. };
  307. var changedArguments = null;
  308. var EventIsSupported = (function () {
  309. try {
  310. new Event('change');
  311. return true;
  312. } catch (e) {
  313. return false;
  314. }
  315. })();
  316. $.fn.triggerNative = function (eventName) {
  317. var el = this[0],
  318. event;
  319. if (el.dispatchEvent) { // for modern browsers & IE9+
  320. if (EventIsSupported) {
  321. // For modern browsers
  322. event = new Event(eventName, {
  323. bubbles: true
  324. });
  325. } else {
  326. // For IE since it doesn't support Event constructor
  327. event = document.createEvent('Event');
  328. event.initEvent(eventName, true, false);
  329. }
  330. el.dispatchEvent(event);
  331. } else if (el.fireEvent) { // for IE8
  332. event = document.createEventObject();
  333. event.eventType = eventName;
  334. el.fireEvent('on' + eventName, event);
  335. } else {
  336. // fall back to jQuery.trigger
  337. this.trigger(eventName);
  338. }
  339. };
  340. // </editor-fold>
  341. function stringSearch (li, searchString, method, normalize) {
  342. var stringTypes = [
  343. 'display',
  344. 'subtext',
  345. 'tokens'
  346. ],
  347. searchSuccess = false;
  348. for (var i = 0; i < stringTypes.length; i++) {
  349. var stringType = stringTypes[i],
  350. string = li[stringType];
  351. if (string) {
  352. string = string.toString();
  353. // Strip HTML tags. This isn't perfect, but it's much faster than any other method
  354. if (stringType === 'display') {
  355. string = string.replace(/<[^>]+>/g, '');
  356. }
  357. if (normalize) string = normalizeToBase(string);
  358. string = string.toUpperCase();
  359. if (method === 'contains') {
  360. searchSuccess = string.indexOf(searchString) >= 0;
  361. } else {
  362. searchSuccess = string.startsWith(searchString);
  363. }
  364. if (searchSuccess) break;
  365. }
  366. }
  367. return searchSuccess;
  368. }
  369. function toInteger (value) {
  370. return parseInt(value, 10) || 0;
  371. }
  372. // Borrowed from Lodash (_.deburr)
  373. /** Used to map Latin Unicode letters to basic Latin letters. */
  374. var deburredLetters = {
  375. // Latin-1 Supplement block.
  376. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  377. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  378. '\xc7': 'C', '\xe7': 'c',
  379. '\xd0': 'D', '\xf0': 'd',
  380. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  381. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  382. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  383. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  384. '\xd1': 'N', '\xf1': 'n',
  385. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  386. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  387. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  388. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  389. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  390. '\xc6': 'Ae', '\xe6': 'ae',
  391. '\xde': 'Th', '\xfe': 'th',
  392. '\xdf': 'ss',
  393. // Latin Extended-A block.
  394. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  395. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  396. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  397. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  398. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  399. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  400. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  401. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  402. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  403. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  404. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  405. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  406. '\u0134': 'J', '\u0135': 'j',
  407. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  408. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  409. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  410. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  411. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  412. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  413. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  414. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  415. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  416. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  417. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  418. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  419. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  420. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  421. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  422. '\u0174': 'W', '\u0175': 'w',
  423. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  424. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  425. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  426. '\u0132': 'IJ', '\u0133': 'ij',
  427. '\u0152': 'Oe', '\u0153': 'oe',
  428. '\u0149': "'n", '\u017f': 's'
  429. };
  430. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  431. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  432. /** Used to compose unicode character classes. */
  433. var rsComboMarksRange = '\\u0300-\\u036f',
  434. reComboHalfMarksRange = '\\ufe20-\\ufe2f',
  435. rsComboSymbolsRange = '\\u20d0-\\u20ff',
  436. rsComboMarksExtendedRange = '\\u1ab0-\\u1aff',
  437. rsComboMarksSupplementRange = '\\u1dc0-\\u1dff',
  438. rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange + rsComboMarksExtendedRange + rsComboMarksSupplementRange;
  439. /** Used to compose unicode capture groups. */
  440. var rsCombo = '[' + rsComboRange + ']';
  441. /**
  442. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  443. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  444. */
  445. var reComboMark = RegExp(rsCombo, 'g');
  446. function deburrLetter (key) {
  447. return deburredLetters[key];
  448. };
  449. function normalizeToBase (string) {
  450. string = string.toString();
  451. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  452. }
  453. // List of HTML entities for escaping.
  454. var escapeMap = {
  455. '&': '&amp;',
  456. '<': '&lt;',
  457. '>': '&gt;',
  458. '"': '&quot;',
  459. "'": '&#x27;',
  460. '`': '&#x60;'
  461. };
  462. // Functions for escaping and unescaping strings to/from HTML interpolation.
  463. var createEscaper = function (map) {
  464. var escaper = function (match) {
  465. return map[match];
  466. };
  467. // Regexes for identifying a key that needs to be escaped.
  468. var source = '(?:' + Object.keys(map).join('|') + ')';
  469. var testRegexp = RegExp(source);
  470. var replaceRegexp = RegExp(source, 'g');
  471. return function (string) {
  472. string = string == null ? '' : '' + string;
  473. return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
  474. };
  475. };
  476. var htmlEscape = createEscaper(escapeMap);
  477. /**
  478. * ------------------------------------------------------------------------
  479. * Constants
  480. * ------------------------------------------------------------------------
  481. */
  482. var keyCodeMap = {
  483. 32: ' ',
  484. 48: '0',
  485. 49: '1',
  486. 50: '2',
  487. 51: '3',
  488. 52: '4',
  489. 53: '5',
  490. 54: '6',
  491. 55: '7',
  492. 56: '8',
  493. 57: '9',
  494. 59: ';',
  495. 65: 'A',
  496. 66: 'B',
  497. 67: 'C',
  498. 68: 'D',
  499. 69: 'E',
  500. 70: 'F',
  501. 71: 'G',
  502. 72: 'H',
  503. 73: 'I',
  504. 74: 'J',
  505. 75: 'K',
  506. 76: 'L',
  507. 77: 'M',
  508. 78: 'N',
  509. 79: 'O',
  510. 80: 'P',
  511. 81: 'Q',
  512. 82: 'R',
  513. 83: 'S',
  514. 84: 'T',
  515. 85: 'U',
  516. 86: 'V',
  517. 87: 'W',
  518. 88: 'X',
  519. 89: 'Y',
  520. 90: 'Z',
  521. 96: '0',
  522. 97: '1',
  523. 98: '2',
  524. 99: '3',
  525. 100: '4',
  526. 101: '5',
  527. 102: '6',
  528. 103: '7',
  529. 104: '8',
  530. 105: '9'
  531. };
  532. var keyCodes = {
  533. ESCAPE: 27, // KeyboardEvent.which value for Escape (Esc) key
  534. ENTER: 13, // KeyboardEvent.which value for Enter key
  535. SPACE: 32, // KeyboardEvent.which value for space key
  536. TAB: 9, // KeyboardEvent.which value for tab key
  537. ARROW_UP: 38, // KeyboardEvent.which value for up arrow key
  538. ARROW_DOWN: 40 // KeyboardEvent.which value for down arrow key
  539. }
  540. var version = {
  541. success: false,
  542. major: '3'
  543. };
  544. try {
  545. version.full = ($.fn.dropdown.Constructor.VERSION || '').split(' ')[0].split('.');
  546. version.major = version.full[0];
  547. version.success = true;
  548. } catch (err) {
  549. // do nothing
  550. }
  551. var selectId = 0;
  552. var EVENT_KEY = '.bs.select';
  553. var classNames = {
  554. DISABLED: 'disabled',
  555. DIVIDER: 'divider',
  556. SHOW: 'open',
  557. DROPUP: 'dropup',
  558. MENU: 'dropdown-menu',
  559. MENURIGHT: 'dropdown-menu-right',
  560. MENULEFT: 'dropdown-menu-left',
  561. // to-do: replace with more advanced template/customization options
  562. BUTTONCLASS: 'btn-default',
  563. POPOVERHEADER: 'popover-title',
  564. ICONBASE: 'glyphicon',
  565. TICKICON: 'glyphicon-ok'
  566. }
  567. var Selector = {
  568. MENU: '.' + classNames.MENU
  569. }
  570. var elementTemplates = {
  571. span: document.createElement('span'),
  572. i: document.createElement('i'),
  573. subtext: document.createElement('small'),
  574. a: document.createElement('a'),
  575. li: document.createElement('li'),
  576. whitespace: document.createTextNode('\u00A0'),
  577. fragment: document.createDocumentFragment()
  578. }
  579. elementTemplates.a.setAttribute('role', 'option');
  580. if (version.major === '4') elementTemplates.a.className = 'dropdown-item';
  581. elementTemplates.subtext.className = 'text-muted';
  582. elementTemplates.text = elementTemplates.span.cloneNode(false);
  583. elementTemplates.text.className = 'text';
  584. elementTemplates.checkMark = elementTemplates.span.cloneNode(false);
  585. var REGEXP_ARROW = new RegExp(keyCodes.ARROW_UP + '|' + keyCodes.ARROW_DOWN);
  586. var REGEXP_TAB_OR_ESCAPE = new RegExp('^' + keyCodes.TAB + '$|' + keyCodes.ESCAPE);
  587. var generateOption = {
  588. li: function (content, classes, optgroup) {
  589. var li = elementTemplates.li.cloneNode(false);
  590. if (content) {
  591. if (content.nodeType === 1 || content.nodeType === 11) {
  592. li.appendChild(content);
  593. } else {
  594. li.innerHTML = content;
  595. }
  596. }
  597. if (typeof classes !== 'undefined' && classes !== '') li.className = classes;
  598. if (typeof optgroup !== 'undefined' && optgroup !== null) li.classList.add('optgroup-' + optgroup);
  599. return li;
  600. },
  601. a: function (text, classes, inline) {
  602. var a = elementTemplates.a.cloneNode(true);
  603. if (text) {
  604. if (text.nodeType === 11) {
  605. a.appendChild(text);
  606. } else {
  607. a.insertAdjacentHTML('beforeend', text);
  608. }
  609. }
  610. if (typeof classes !== 'undefined' && classes !== '') a.classList.add.apply(a.classList, classes.split(' '));
  611. if (inline) a.setAttribute('style', inline);
  612. return a;
  613. },
  614. text: function (options, useFragment) {
  615. var textElement = elementTemplates.text.cloneNode(false),
  616. subtextElement,
  617. iconElement;
  618. if (options.content) {
  619. textElement.innerHTML = options.content;
  620. } else {
  621. textElement.textContent = options.text;
  622. if (options.icon) {
  623. var whitespace = elementTemplates.whitespace.cloneNode(false);
  624. // need to use <i> for icons in the button to prevent a breaking change
  625. // note: switch to span in next major release
  626. iconElement = (useFragment === true ? elementTemplates.i : elementTemplates.span).cloneNode(false);
  627. iconElement.className = this.options.iconBase + ' ' + options.icon;
  628. elementTemplates.fragment.appendChild(iconElement);
  629. elementTemplates.fragment.appendChild(whitespace);
  630. }
  631. if (options.subtext) {
  632. subtextElement = elementTemplates.subtext.cloneNode(false);
  633. subtextElement.textContent = options.subtext;
  634. textElement.appendChild(subtextElement);
  635. }
  636. }
  637. if (useFragment === true) {
  638. while (textElement.childNodes.length > 0) {
  639. elementTemplates.fragment.appendChild(textElement.childNodes[0]);
  640. }
  641. } else {
  642. elementTemplates.fragment.appendChild(textElement);
  643. }
  644. return elementTemplates.fragment;
  645. },
  646. label: function (options) {
  647. var textElement = elementTemplates.text.cloneNode(false),
  648. subtextElement,
  649. iconElement;
  650. textElement.innerHTML = options.display;
  651. if (options.icon) {
  652. var whitespace = elementTemplates.whitespace.cloneNode(false);
  653. iconElement = elementTemplates.span.cloneNode(false);
  654. iconElement.className = this.options.iconBase + ' ' + options.icon;
  655. elementTemplates.fragment.appendChild(iconElement);
  656. elementTemplates.fragment.appendChild(whitespace);
  657. }
  658. if (options.subtext) {
  659. subtextElement = elementTemplates.subtext.cloneNode(false);
  660. subtextElement.textContent = options.subtext;
  661. textElement.appendChild(subtextElement);
  662. }
  663. elementTemplates.fragment.appendChild(textElement);
  664. return elementTemplates.fragment;
  665. }
  666. }
  667. var Selectpicker = function (element, options) {
  668. var that = this;
  669. // bootstrap-select has been initialized - revert valHooks.select.set back to its original function
  670. if (!valHooks.useDefault) {
  671. $.valHooks.select.set = valHooks._set;
  672. valHooks.useDefault = true;
  673. }
  674. this.$element = $(element);
  675. this.$newElement = null;
  676. this.$button = null;
  677. this.$menu = null;
  678. this.options = options;
  679. this.selectpicker = {
  680. main: {},
  681. search: {},
  682. current: {}, // current changes if a search is in progress
  683. view: {},
  684. isSearching: false,
  685. keydown: {
  686. keyHistory: '',
  687. resetKeyHistory: {
  688. start: function () {
  689. return setTimeout(function () {
  690. that.selectpicker.keydown.keyHistory = '';
  691. }, 800);
  692. }
  693. }
  694. }
  695. };
  696. this.sizeInfo = {};
  697. // If we have no title yet, try to pull it from the html title attribute (jQuery doesnt' pick it up as it's not a
  698. // data-attribute)
  699. if (this.options.title === null) {
  700. this.options.title = this.$element.attr('title');
  701. }
  702. // Format window padding
  703. var winPad = this.options.windowPadding;
  704. if (typeof winPad === 'number') {
  705. this.options.windowPadding = [winPad, winPad, winPad, winPad];
  706. }
  707. // Expose public methods
  708. this.val = Selectpicker.prototype.val;
  709. this.render = Selectpicker.prototype.render;
  710. this.refresh = Selectpicker.prototype.refresh;
  711. this.setStyle = Selectpicker.prototype.setStyle;
  712. this.selectAll = Selectpicker.prototype.selectAll;
  713. this.deselectAll = Selectpicker.prototype.deselectAll;
  714. this.destroy = Selectpicker.prototype.destroy;
  715. this.remove = Selectpicker.prototype.remove;
  716. this.show = Selectpicker.prototype.show;
  717. this.hide = Selectpicker.prototype.hide;
  718. this.init();
  719. };
  720. Selectpicker.VERSION = '1.13.12';
  721. // part of this is duplicated in i18n/defaults-en_US.js. Make sure to update both.
  722. Selectpicker.DEFAULTS = {
  723. noneSelectedText: 'Nothing selected',
  724. noneResultsText: 'No results matched {0}',
  725. countSelectedText: function (numSelected, numTotal) {
  726. return (numSelected == 1) ? '{0} item selected' : '{0} items selected';
  727. },
  728. maxOptionsText: function (numAll, numGroup) {
  729. return [
  730. (numAll == 1) ? 'Limit reached ({n} item max)' : 'Limit reached ({n} items max)',
  731. (numGroup == 1) ? 'Group limit reached ({n} item max)' : 'Group limit reached ({n} items max)'
  732. ];
  733. },
  734. selectAllText: 'Select All',
  735. deselectAllText: 'Deselect All',
  736. doneButton: false,
  737. doneButtonText: 'Close',
  738. multipleSeparator: ', ',
  739. styleBase: 'btn',
  740. style: classNames.BUTTONCLASS,
  741. size: 'auto',
  742. title: null,
  743. selectedTextFormat: 'values',
  744. width: false,
  745. container: false,
  746. hideDisabled: false,
  747. showSubtext: false,
  748. showIcon: true,
  749. showContent: true,
  750. dropupAuto: true,
  751. header: false,
  752. liveSearch: false,
  753. liveSearchPlaceholder: null,
  754. liveSearchNormalize: false,
  755. liveSearchStyle: 'contains',
  756. actionsBox: false,
  757. iconBase: classNames.ICONBASE,
  758. tickIcon: classNames.TICKICON,
  759. showTick: false,
  760. template: {
  761. caret: '<span class="caret"></span>'
  762. },
  763. maxOptions: false,
  764. mobile: false,
  765. selectOnTab: false,
  766. dropdownAlignRight: false,
  767. windowPadding: 0,
  768. virtualScroll: 600,
  769. display: false,
  770. sanitize: true,
  771. sanitizeFn: null,
  772. whiteList: DefaultWhitelist
  773. };
  774. Selectpicker.prototype = {
  775. constructor: Selectpicker,
  776. init: function () {
  777. var that = this,
  778. id = this.$element.attr('id');
  779. selectId++;
  780. this.selectId = 'bs-select-' + selectId;
  781. this.$element[0].classList.add('bs-select-hidden');
  782. this.multiple = this.$element.prop('multiple');
  783. this.autofocus = this.$element.prop('autofocus');
  784. if (this.$element[0].classList.contains('show-tick')) {
  785. this.options.showTick = true;
  786. }
  787. this.$newElement = this.createDropdown();
  788. this.buildData();
  789. this.$element
  790. .after(this.$newElement)
  791. .prependTo(this.$newElement);
  792. this.$button = this.$newElement.children('button');
  793. this.$menu = this.$newElement.children(Selector.MENU);
  794. this.$menuInner = this.$menu.children('.inner');
  795. this.$searchbox = this.$menu.find('input');
  796. this.$element[0].classList.remove('bs-select-hidden');
  797. if (this.options.dropdownAlignRight === true) this.$menu[0].classList.add(classNames.MENURIGHT);
  798. if (typeof id !== 'undefined') {
  799. this.$button.attr('data-id', id);
  800. }
  801. this.checkDisabled();
  802. this.clickListener();
  803. if (this.options.liveSearch) {
  804. this.liveSearchListener();
  805. this.focusedParent = this.$searchbox[0];
  806. } else {
  807. this.focusedParent = this.$menuInner[0];
  808. }
  809. this.setStyle();
  810. this.render();
  811. this.setWidth();
  812. if (this.options.container) {
  813. this.selectPosition();
  814. } else {
  815. this.$element.on('hide' + EVENT_KEY, function () {
  816. if (that.isVirtual()) {
  817. // empty menu on close
  818. var menuInner = that.$menuInner[0],
  819. emptyMenu = menuInner.firstChild.cloneNode(false);
  820. // replace the existing UL with an empty one - this is faster than $.empty() or innerHTML = ''
  821. menuInner.replaceChild(emptyMenu, menuInner.firstChild);
  822. menuInner.scrollTop = 0;
  823. }
  824. });
  825. }
  826. this.$menu.data('this', this);
  827. this.$newElement.data('this', this);
  828. if (this.options.mobile) this.mobile();
  829. this.$newElement.on({
  830. 'hide.bs.dropdown': function (e) {
  831. that.$element.trigger('hide' + EVENT_KEY, e);
  832. },
  833. 'hidden.bs.dropdown': function (e) {
  834. that.$element.trigger('hidden' + EVENT_KEY, e);
  835. },
  836. 'show.bs.dropdown': function (e) {
  837. that.$element.trigger('show' + EVENT_KEY, e);
  838. },
  839. 'shown.bs.dropdown': function (e) {
  840. that.$element.trigger('shown' + EVENT_KEY, e);
  841. }
  842. });
  843. if (that.$element[0].hasAttribute('required')) {
  844. this.$element.on('invalid' + EVENT_KEY, function () {
  845. that.$button[0].classList.add('bs-invalid');
  846. that.$element
  847. .on('shown' + EVENT_KEY + '.invalid', function () {
  848. that.$element
  849. .val(that.$element.val()) // set the value to hide the validation message in Chrome when menu is opened
  850. .off('shown' + EVENT_KEY + '.invalid');
  851. })
  852. .on('rendered' + EVENT_KEY, function () {
  853. // if select is no longer invalid, remove the bs-invalid class
  854. if (this.validity.valid) that.$button[0].classList.remove('bs-invalid');
  855. that.$element.off('rendered' + EVENT_KEY);
  856. });
  857. that.$button.on('blur' + EVENT_KEY, function () {
  858. that.$element.trigger('focus').trigger('blur');
  859. that.$button.off('blur' + EVENT_KEY);
  860. });
  861. });
  862. }
  863. setTimeout(function () {
  864. that.buildList();
  865. that.$element.trigger('loaded' + EVENT_KEY);
  866. });
  867. },
  868. createDropdown: function () {
  869. // Options
  870. // If we are multiple or showTick option is set, then add the show-tick class
  871. var showTick = (this.multiple || this.options.showTick) ? ' show-tick' : '',
  872. multiselectable = this.multiple ? ' aria-multiselectable="true"' : '',
  873. inputGroup = '',
  874. autofocus = this.autofocus ? ' autofocus' : '';
  875. if (version.major < 4 && this.$element.parent().hasClass('input-group')) {
  876. inputGroup = ' input-group-btn';
  877. }
  878. // Elements
  879. var drop,
  880. header = '',
  881. searchbox = '',
  882. actionsbox = '',
  883. donebutton = '';
  884. if (this.options.header) {
  885. header =
  886. '<div class="' + classNames.POPOVERHEADER + '">' +
  887. '<button type="button" class="close" aria-hidden="true">&times;</button>' +
  888. this.options.header +
  889. '</div>';
  890. }
  891. if (this.options.liveSearch) {
  892. searchbox =
  893. '<div class="bs-searchbox">' +
  894. '<input type="search" class="form-control" autocomplete="off"' +
  895. (
  896. this.options.liveSearchPlaceholder === null ? ''
  897. :
  898. ' placeholder="' + htmlEscape(this.options.liveSearchPlaceholder) + '"'
  899. ) +
  900. ' role="combobox" aria-label="Search" aria-controls="' + this.selectId + '" aria-autocomplete="list">' +
  901. '</div>';
  902. }
  903. if (this.multiple && this.options.actionsBox) {
  904. actionsbox =
  905. '<div class="bs-actionsbox">' +
  906. '<div class="btn-group btn-group-sm btn-block">' +
  907. '<button type="button" class="actions-btn bs-select-all btn ' + classNames.BUTTONCLASS + '">' +
  908. this.options.selectAllText +
  909. '</button>' +
  910. '<button type="button" class="actions-btn bs-deselect-all btn ' + classNames.BUTTONCLASS + '">' +
  911. this.options.deselectAllText +
  912. '</button>' +
  913. '</div>' +
  914. '</div>';
  915. }
  916. if (this.multiple && this.options.doneButton) {
  917. donebutton =
  918. '<div class="bs-donebutton">' +
  919. '<div class="btn-group btn-block">' +
  920. '<button type="button" class="btn btn-sm ' + classNames.BUTTONCLASS + '">' +
  921. this.options.doneButtonText +
  922. '</button>' +
  923. '</div>' +
  924. '</div>';
  925. }
  926. drop =
  927. '<div class="dropdown bootstrap-select' + showTick + inputGroup + '">' +
  928. '<button type="button" class="' + this.options.styleBase + ' dropdown-toggle" ' + (this.options.display === 'static' ? 'data-display="static"' : '') + 'data-toggle="dropdown"' + autofocus + ' role="combobox" aria-owns="' + this.selectId + '" aria-haspopup="listbox" aria-expanded="false">' +
  929. '<div class="filter-option">' +
  930. '<div class="filter-option-inner">' +
  931. '<div class="filter-option-inner-inner"></div>' +
  932. '</div> ' +
  933. '</div>' +
  934. (
  935. version.major === '4' ? ''
  936. :
  937. '<span class="bs-caret">' +
  938. this.options.template.caret +
  939. '</span>'
  940. ) +
  941. '</button>' +
  942. '<div class="' + classNames.MENU + ' ' + (version.major === '4' ? '' : classNames.SHOW) + '">' +
  943. header +
  944. searchbox +
  945. actionsbox +
  946. '<div class="inner ' + classNames.SHOW + '" role="listbox" id="' + this.selectId + '" tabindex="-1" ' + multiselectable + '>' +
  947. '<ul class="' + classNames.MENU + ' inner ' + (version.major === '4' ? classNames.SHOW : '') + '" role="presentation">' +
  948. '</ul>' +
  949. '</div>' +
  950. donebutton +
  951. '</div>' +
  952. '</div>';
  953. return $(drop);
  954. },
  955. setPositionData: function () {
  956. this.selectpicker.view.canHighlight = [];
  957. this.selectpicker.view.size = 0;
  958. for (var i = 0; i < this.selectpicker.current.data.length; i++) {
  959. var li = this.selectpicker.current.data[i],
  960. canHighlight = true;
  961. if (li.type === 'divider') {
  962. canHighlight = false;
  963. li.height = this.sizeInfo.dividerHeight;
  964. } else if (li.type === 'optgroup-label') {
  965. canHighlight = false;
  966. li.height = this.sizeInfo.dropdownHeaderHeight;
  967. } else {
  968. li.height = this.sizeInfo.liHeight;
  969. }
  970. if (li.disabled) canHighlight = false;
  971. this.selectpicker.view.canHighlight.push(canHighlight);
  972. if (canHighlight) {
  973. this.selectpicker.view.size++;
  974. li.posinset = this.selectpicker.view.size;
  975. }
  976. li.position = (i === 0 ? 0 : this.selectpicker.current.data[i - 1].position) + li.height;
  977. }
  978. },
  979. isVirtual: function () {
  980. return (this.options.virtualScroll !== false) && (this.selectpicker.main.elements.length >= this.options.virtualScroll) || this.options.virtualScroll === true;
  981. },
  982. createView: function (isSearching, setSize, refresh) {
  983. var that = this,
  984. scrollTop = 0,
  985. active = [],
  986. selected,
  987. prevActive;
  988. this.selectpicker.isSearching = isSearching;
  989. this.selectpicker.current = isSearching ? this.selectpicker.search : this.selectpicker.main;
  990. this.setPositionData();
  991. if (setSize) {
  992. if (refresh) {
  993. scrollTop = this.$menuInner[0].scrollTop;
  994. } else if (!that.multiple) {
  995. var element = that.$element[0],
  996. selectedIndex = (element.options[element.selectedIndex] || {}).liIndex;
  997. if (typeof selectedIndex === 'number' && that.options.size !== false) {
  998. var selectedData = that.selectpicker.main.data[selectedIndex],
  999. position = selectedData && selectedData.position;
  1000. if (position) {
  1001. scrollTop = position - ((that.sizeInfo.menuInnerHeight + that.sizeInfo.liHeight) / 2);
  1002. }
  1003. }
  1004. }
  1005. }
  1006. scroll(scrollTop, true);
  1007. this.$menuInner.off('scroll.createView').on('scroll.createView', function (e, updateValue) {
  1008. if (!that.noScroll) scroll(this.scrollTop, updateValue);
  1009. that.noScroll = false;
  1010. });
  1011. function scroll (scrollTop, init) {
  1012. var size = that.selectpicker.current.elements.length,
  1013. chunks = [],
  1014. chunkSize,
  1015. chunkCount,
  1016. firstChunk,
  1017. lastChunk,
  1018. currentChunk,
  1019. prevPositions,
  1020. positionIsDifferent,
  1021. previousElements,
  1022. menuIsDifferent = true,
  1023. isVirtual = that.isVirtual();
  1024. that.selectpicker.view.scrollTop = scrollTop;
  1025. chunkSize = Math.ceil(that.sizeInfo.menuInnerHeight / that.sizeInfo.liHeight * 1.5); // number of options in a chunk
  1026. chunkCount = Math.round(size / chunkSize) || 1; // number of chunks
  1027. for (var i = 0; i < chunkCount; i++) {
  1028. var endOfChunk = (i + 1) * chunkSize;
  1029. if (i === chunkCount - 1) {
  1030. endOfChunk = size;
  1031. }
  1032. chunks[i] = [
  1033. (i) * chunkSize + (!i ? 0 : 1),
  1034. endOfChunk
  1035. ];
  1036. if (!size) break;
  1037. if (currentChunk === undefined && scrollTop - 1 <= that.selectpicker.current.data[endOfChunk - 1].position - that.sizeInfo.menuInnerHeight) {
  1038. currentChunk = i;
  1039. }
  1040. }
  1041. if (currentChunk === undefined) currentChunk = 0;
  1042. prevPositions = [that.selectpicker.view.position0, that.selectpicker.view.position1];
  1043. // always display previous, current, and next chunks
  1044. firstChunk = Math.max(0, currentChunk - 1);
  1045. lastChunk = Math.min(chunkCount - 1, currentChunk + 1);
  1046. that.selectpicker.view.position0 = isVirtual === false ? 0 : (Math.max(0, chunks[firstChunk][0]) || 0);
  1047. that.selectpicker.view.position1 = isVirtual === false ? size : (Math.min(size, chunks[lastChunk][1]) || 0);
  1048. positionIsDifferent = prevPositions[0] !== that.selectpicker.view.position0 || prevPositions[1] !== that.selectpicker.view.position1;
  1049. if (that.activeIndex !== undefined) {
  1050. prevActive = that.selectpicker.main.elements[that.prevActiveIndex];
  1051. active = that.selectpicker.main.elements[that.activeIndex];
  1052. selected = that.selectpicker.main.elements[that.selectedIndex];
  1053. if (init) {
  1054. if (that.activeIndex !== that.selectedIndex) {
  1055. that.defocusItem(active);
  1056. }
  1057. that.activeIndex = undefined;
  1058. }
  1059. if (that.activeIndex && that.activeIndex !== that.selectedIndex) {
  1060. that.defocusItem(selected);
  1061. }
  1062. }
  1063. if (that.prevActiveIndex !== undefined && that.prevActiveIndex !== that.activeIndex && that.prevActiveIndex !== that.selectedIndex) {
  1064. that.defocusItem(prevActive);
  1065. }
  1066. if (init || positionIsDifferent) {
  1067. previousElements = that.selectpicker.view.visibleElements ? that.selectpicker.view.visibleElements.slice() : [];
  1068. if (isVirtual === false) {
  1069. that.selectpicker.view.visibleElements = that.selectpicker.current.elements;
  1070. } else {
  1071. that.selectpicker.view.visibleElements = that.selectpicker.current.elements.slice(that.selectpicker.view.position0, that.selectpicker.view.position1);
  1072. }
  1073. that.setOptionStatus();
  1074. // if searching, check to make sure the list has actually been updated before updating DOM
  1075. // this prevents unnecessary repaints
  1076. if (isSearching || (isVirtual === false && init)) menuIsDifferent = !isEqual(previousElements, that.selectpicker.view.visibleElements);
  1077. // if virtual scroll is disabled and not searching,
  1078. // menu should never need to be updated more than once
  1079. if ((init || isVirtual === true) && menuIsDifferent) {
  1080. var menuInner = that.$menuInner[0],
  1081. menuFragment = document.createDocumentFragment(),
  1082. emptyMenu = menuInner.firstChild.cloneNode(false),
  1083. marginTop,
  1084. marginBottom,
  1085. elements = that.selectpicker.view.visibleElements,
  1086. toSanitize = [];
  1087. // replace the existing UL with an empty one - this is faster than $.empty()
  1088. menuInner.replaceChild(emptyMenu, menuInner.firstChild);
  1089. for (var i = 0, visibleElementsLen = elements.length; i < visibleElementsLen; i++) {
  1090. var element = elements[i],
  1091. elText,
  1092. elementData;
  1093. if (that.options.sanitize) {
  1094. elText = element.lastChild;
  1095. if (elText) {
  1096. elementData = that.selectpicker.current.data[i + that.selectpicker.view.position0];
  1097. if (elementData && elementData.content && !elementData.sanitized) {
  1098. toSanitize.push(elText);
  1099. elementData.sanitized = true;
  1100. }
  1101. }
  1102. }
  1103. menuFragment.appendChild(element);
  1104. }
  1105. if (that.options.sanitize && toSanitize.length) {
  1106. sanitizeHtml(toSanitize, that.options.whiteList, that.options.sanitizeFn);
  1107. }
  1108. if (isVirtual === true) {
  1109. marginTop = (that.selectpicker.view.position0 === 0 ? 0 : that.selectpicker.current.data[that.selectpicker.view.position0 - 1].position);
  1110. marginBottom = (that.selectpicker.view.position1 > size - 1 ? 0 : that.selectpicker.current.data[size - 1].position - that.selectpicker.current.data[that.selectpicker.view.position1 - 1].position);
  1111. menuInner.firstChild.style.marginTop = marginTop + 'px';
  1112. menuInner.firstChild.style.marginBottom = marginBottom + 'px';
  1113. } else {
  1114. menuInner.firstChild.style.marginTop = 0;
  1115. menuInner.firstChild.style.marginBottom = 0;
  1116. }
  1117. menuInner.firstChild.appendChild(menuFragment);
  1118. // if an option is encountered that is wider than the current menu width, update the menu width accordingly
  1119. // switch to ResizeObserver with increased browser support
  1120. if (isVirtual === true && that.sizeInfo.hasScrollBar) {
  1121. var menuInnerInnerWidth = menuInner.firstChild.offsetWidth;
  1122. if (init && menuInnerInnerWidth < that.sizeInfo.menuInnerInnerWidth && that.sizeInfo.totalMenuWidth > that.sizeInfo.selectWidth) {
  1123. menuInner.firstChild.style.minWidth = that.sizeInfo.menuInnerInnerWidth + 'px';
  1124. } else if (menuInnerInnerWidth > that.sizeInfo.menuInnerInnerWidth) {
  1125. // set to 0 to get actual width of menu
  1126. that.$menu[0].style.minWidth = 0;
  1127. var actualMenuWidth = menuInner.firstChild.offsetWidth;
  1128. if (actualMenuWidth > that.sizeInfo.menuInnerInnerWidth) {
  1129. that.sizeInfo.menuInnerInnerWidth = actualMenuWidth;
  1130. menuInner.firstChild.style.minWidth = that.sizeInfo.menuInnerInnerWidth + 'px';
  1131. }
  1132. // reset to default CSS styling
  1133. that.$menu[0].style.minWidth = '';
  1134. }
  1135. }
  1136. }
  1137. }
  1138. that.prevActiveIndex = that.activeIndex;
  1139. if (!that.options.liveSearch) {
  1140. that.$menuInner.trigger('focus');
  1141. } else if (isSearching && init) {
  1142. var index = 0,
  1143. newActive;
  1144. if (!that.selectpicker.view.canHighlight[index]) {
  1145. index = 1 + that.selectpicker.view.canHighlight.slice(1).indexOf(true);
  1146. }
  1147. newActive = that.selectpicker.view.visibleElements[index];
  1148. that.defocusItem(that.selectpicker.view.currentActive);
  1149. that.activeIndex = (that.selectpicker.current.data[index] || {}).index;
  1150. that.focusItem(newActive);
  1151. }
  1152. }
  1153. $(window)
  1154. .off('resize' + EVENT_KEY + '.' + this.selectId + '.createView')
  1155. .on('resize' + EVENT_KEY + '.' + this.selectId + '.createView', function () {
  1156. var isActive = that.$newElement.hasClass(classNames.SHOW);
  1157. if (isActive) scroll(that.$menuInner[0].scrollTop);
  1158. });
  1159. },
  1160. focusItem: function (li, liData, noStyle) {
  1161. if (li) {
  1162. liData = liData || this.selectpicker.main.data[this.activeIndex];
  1163. var a = li.firstChild;
  1164. if (a) {
  1165. a.setAttribute('aria-setsize', this.selectpicker.view.size);
  1166. a.setAttribute('aria-posinset', liData.posinset);
  1167. if (noStyle !== true) {
  1168. this.focusedParent.setAttribute('aria-activedescendant', a.id);
  1169. li.classList.add('active');
  1170. a.classList.add('active');
  1171. }
  1172. }
  1173. }
  1174. },
  1175. defocusItem: function (li) {
  1176. if (li) {
  1177. li.classList.remove('active');
  1178. if (li.firstChild) li.firstChild.classList.remove('active');
  1179. }
  1180. },
  1181. setPlaceholder: function () {
  1182. var updateIndex = false;
  1183. if (this.options.title && !this.multiple) {
  1184. if (!this.selectpicker.view.titleOption) this.selectpicker.view.titleOption = document.createElement('option');
  1185. // this option doesn't create a new <li> element, but does add a new option at the start,
  1186. // so startIndex should increase to prevent having to check every option for the bs-title-option class
  1187. updateIndex = true;
  1188. var element = this.$element[0],
  1189. isSelected = false,
  1190. titleNotAppended = !this.selectpicker.view.titleOption.parentNode;
  1191. if (titleNotAppended) {
  1192. // Use native JS to prepend option (faster)
  1193. this.selectpicker.view.titleOption.className = 'bs-title-option';
  1194. this.selectpicker.view.titleOption.value = '';
  1195. // Check if selected or data-selected attribute is already set on an option. If not, select the titleOption option.
  1196. // the selected item may have been changed by user or programmatically before the bootstrap select plugin runs,
  1197. // if so, the select will have the data-selected attribute
  1198. var $opt = $(element.options[element.selectedIndex]);
  1199. isSelected = $opt.attr('selected') === undefined && this.$element.data('selected') === undefined;
  1200. }
  1201. if (titleNotAppended || this.selectpicker.view.titleOption.index !== 0) {
  1202. element.insertBefore(this.selectpicker.view.titleOption, element.firstChild);
  1203. }
  1204. // Set selected *after* appending to select,
  1205. // otherwise the option doesn't get selected in IE
  1206. // set using selectedIndex, as setting the selected attr to true here doesn't work in IE11
  1207. if (isSelected) element.selectedIndex = 0;
  1208. }
  1209. return updateIndex;
  1210. },
  1211. buildData: function () {
  1212. var optionSelector = ':not([hidden]):not([data-hidden="true"])',
  1213. mainData = [],
  1214. optID = 0,
  1215. startIndex = this.setPlaceholder() ? 1 : 0; // append the titleOption if necessary and skip the first option in the loop
  1216. if (this.options.hideDisabled) optionSelector += ':not(:disabled)';
  1217. var selectOptions = this.$element[0].querySelectorAll('select > *' + optionSelector);
  1218. function addDivider (config) {
  1219. var previousData = mainData[mainData.length - 1];
  1220. // ensure optgroup doesn't create back-to-back dividers
  1221. if (
  1222. previousData &&
  1223. previousData.type === 'divider' &&
  1224. (previousData.optID || config.optID)
  1225. ) {
  1226. return;
  1227. }
  1228. config = config || {};
  1229. config.type = 'divider';
  1230. mainData.push(config);
  1231. }
  1232. function addOption (option, config) {
  1233. config = config || {};
  1234. config.divider = option.getAttribute('data-divider') === 'true';
  1235. if (config.divider) {
  1236. addDivider({
  1237. optID: config.optID
  1238. });
  1239. } else {
  1240. var liIndex = mainData.length,
  1241. cssText = option.style.cssText,
  1242. inlineStyle = cssText ? htmlEscape(cssText) : '',
  1243. optionClass = (option.className || '') + (config.optgroupClass || '');
  1244. if (config.optID) optionClass = 'opt ' + optionClass;
  1245. config.optionClass = optionClass.trim();
  1246. config.inlineStyle = inlineStyle;
  1247. config.text = option.textContent;
  1248. config.content = option.getAttribute('data-content');
  1249. config.tokens = option.getAttribute('data-tokens');
  1250. config.subtext = option.getAttribute('data-subtext');
  1251. config.icon = option.getAttribute('data-icon');
  1252. option.liIndex = liIndex;
  1253. config.display = config.content || config.text;
  1254. config.type = 'option';
  1255. config.index = liIndex;
  1256. config.option = option;
  1257. config.selected = !!option.selected;
  1258. config.disabled = config.disabled || !!option.disabled;
  1259. mainData.push(config);
  1260. }
  1261. }
  1262. function addOptgroup (index, selectOptions) {
  1263. var optgroup = selectOptions[index],
  1264. previous = selectOptions[index - 1],
  1265. next = selectOptions[index + 1],
  1266. options = optgroup.querySelectorAll('option' + optionSelector);
  1267. if (!options.length) return;
  1268. var config = {
  1269. display: htmlEscape(optgroup.label),
  1270. subtext: optgroup.getAttribute('data-subtext'),
  1271. icon: optgroup.getAttribute('data-icon'),
  1272. type: 'optgroup-label',
  1273. optgroupClass: ' ' + (optgroup.className || '')
  1274. },
  1275. headerIndex,
  1276. lastIndex;
  1277. optID++;
  1278. if (previous) {
  1279. addDivider({ optID: optID });
  1280. }
  1281. config.optID = optID;
  1282. mainData.push(config);
  1283. for (var j = 0, len = options.length; j < len; j++) {
  1284. var option = options[j];
  1285. if (j === 0) {
  1286. headerIndex = mainData.length - 1;
  1287. lastIndex = headerIndex + len;
  1288. }
  1289. addOption(option, {
  1290. headerIndex: headerIndex,
  1291. lastIndex: lastIndex,
  1292. optID: config.optID,
  1293. optgroupClass: config.optgroupClass,
  1294. disabled: optgroup.disabled
  1295. });
  1296. }
  1297. if (next) {
  1298. addDivider({ optID: optID });
  1299. }
  1300. }
  1301. for (var len = selectOptions.length; startIndex < len; startIndex++) {
  1302. var item = selectOptions[startIndex];
  1303. if (item.tagName !== 'OPTGROUP') {
  1304. addOption(item, {});
  1305. } else {
  1306. addOptgroup(startIndex, selectOptions);
  1307. }
  1308. }
  1309. this.selectpicker.main.data = this.selectpicker.current.data = mainData;
  1310. },
  1311. buildList: function () {
  1312. var that = this,
  1313. selectData = this.selectpicker.main.data,
  1314. mainElements = [],
  1315. widestOptionLength = 0;
  1316. if ((that.options.showTick || that.multiple) && !elementTemplates.checkMark.parentNode) {
  1317. elementTemplates.checkMark.className = this.options.iconBase + ' ' + that.options.tickIcon + ' check-mark';
  1318. elementTemplates.a.appendChild(elementTemplates.checkMark);
  1319. }
  1320. function buildElement (item) {
  1321. var liElement,
  1322. combinedLength = 0;
  1323. switch (item.type) {
  1324. case 'divider':
  1325. liElement = generateOption.li(
  1326. false,
  1327. classNames.DIVIDER,
  1328. (item.optID ? item.optID + 'div' : undefined)
  1329. );
  1330. break;
  1331. case 'option':
  1332. liElement = generateOption.li(
  1333. generateOption.a(
  1334. generateOption.text.call(that, item),
  1335. item.optionClass,
  1336. item.inlineStyle
  1337. ),
  1338. '',
  1339. item.optID
  1340. );
  1341. if (liElement.firstChild) {
  1342. liElement.firstChild.id = that.selectId + '-' + item.index;
  1343. }
  1344. break;
  1345. case 'optgroup-label':
  1346. liElement = generateOption.li(
  1347. generateOption.label.call(that, item),
  1348. 'dropdown-header' + item.optgroupClass,
  1349. item.optID
  1350. );
  1351. break;
  1352. }
  1353. mainElements.push(liElement);
  1354. // count the number of characters in the option - not perfect, but should work in most cases
  1355. if (item.display) combinedLength += item.display.length;
  1356. if (item.subtext) combinedLength += item.subtext.length;
  1357. // if there is an icon, ensure this option's width is checked
  1358. if (item.icon) combinedLength += 1;
  1359. if (combinedLength > widestOptionLength) {
  1360. widestOptionLength = combinedLength;
  1361. // guess which option is the widest
  1362. // use this when calculating menu width
  1363. // not perfect, but it's fast, and the width will be updating accordingly when scrolling
  1364. that.selectpicker.view.widestOption = mainElements[mainElements.length - 1];
  1365. }
  1366. }
  1367. for (var len = selectData.length, i = 0; i < len; i++) {
  1368. var item = selectData[i];
  1369. buildElement(item);
  1370. }
  1371. this.selectpicker.main.elements = this.selectpicker.current.elements = mainElements;
  1372. },
  1373. findLis: function () {
  1374. return this.$menuInner.find('.inner > li');
  1375. },
  1376. render: function () {
  1377. var that = this,
  1378. // ensure titleOption is appended and selected (if necessary) before getting selectedOptions
  1379. startIndex = this.setPlaceholder() ? 1 : 0,
  1380. element = this.$element[0],
  1381. selectedOptions = getSelectedOptions(element, this.options.hideDisabled),
  1382. selectedCount = selectedOptions.length,
  1383. button = this.$button[0],
  1384. buttonInner = button.querySelector('.filter-option-inner-inner'),
  1385. multipleSeparator = document.createTextNode(this.options.multipleSeparator),
  1386. titleFragment = elementTemplates.fragment.cloneNode(false),
  1387. showCount,
  1388. countMax,
  1389. hasContent = false;
  1390. button.classList.toggle('bs-placeholder', that.multiple ? !selectedCount : !getSelectValues(element, selectedOptions));
  1391. this.tabIndex();
  1392. if (this.options.selectedTextFormat === 'static') {
  1393. titleFragment = generateOption.text.call(this, { text: this.options.title }, true);
  1394. } else {
  1395. showCount = this.multiple && this.options.selectedTextFormat.indexOf('count') !== -1 && selectedCount > 1;
  1396. // determine if the number of selected options will be shown (showCount === true)
  1397. if (showCount) {
  1398. countMax = this.options.selectedTextFormat.split('>');
  1399. showCount = (countMax.length > 1 && selectedCount > countMax[1]) || (countMax.length === 1 && selectedCount >= 2);
  1400. }
  1401. // only loop through all selected options if the count won't be shown
  1402. if (showCount === false) {
  1403. for (var selectedIndex = startIndex; selectedIndex < selectedCount; selectedIndex++) {
  1404. if (selectedIndex < 50) {
  1405. var option = selectedOptions[selectedIndex],
  1406. thisData = this.selectpicker.main.data[option.liIndex],
  1407. titleOptions = {};
  1408. if (this.multiple && selectedIndex > 0) {
  1409. titleFragment.appendChild(multipleSeparator.cloneNode(false));
  1410. }
  1411. if (option.title) {
  1412. titleOptions.text = option.title;
  1413. } else if (thisData.content && that.options.showContent) {
  1414. titleOptions.content = thisData.content.toString();
  1415. hasContent = true;
  1416. } else {
  1417. if (that.options.showIcon) {
  1418. titleOptions.icon = thisData.icon;
  1419. }
  1420. if (that.options.showSubtext && !that.multiple && thisData.subtext) titleOptions.subtext = ' ' + thisData.subtext;
  1421. titleOptions.text = option.textContent.trim();
  1422. }
  1423. titleFragment.appendChild(generateOption.text.call(this, titleOptions, true));
  1424. } else {
  1425. break;
  1426. }
  1427. }
  1428. // add ellipsis
  1429. if (selectedCount > 49) {
  1430. titleFragment.appendChild(document.createTextNode('...'));
  1431. }
  1432. } else {
  1433. var optionSelector = ':not([hidden]):not([data-hidden="true"]):not([data-divider="true"])';
  1434. if (this.options.hideDisabled) optionSelector += ':not(:disabled)';
  1435. // If this is a multiselect, and selectedTextFormat is count, then show 1 of 2 selected, etc.
  1436. var totalCount = this.$element[0].querySelectorAll('select > option' + optionSelector + ', optgroup' + optionSelector + ' option' + optionSelector).length,
  1437. tr8nText = (typeof this.options.countSelectedText === 'function') ? this.options.countSelectedText(selectedCount, totalCount) : this.options.countSelectedText;
  1438. titleFragment = generateOption.text.call(this, {
  1439. text: tr8nText.replace('{0}', selectedCount.toString()).replace('{1}', totalCount.toString())
  1440. }, true);
  1441. }
  1442. }
  1443. if (this.options.title == undefined) {
  1444. // use .attr to ensure undefined is returned if title attribute is not set
  1445. this.options.title = this.$element.attr('title');
  1446. }
  1447. // If the select doesn't have a title, then use the default, or if nothing is set at all, use noneSelectedText
  1448. if (!titleFragment.childNodes.length) {
  1449. titleFragment = generateOption.text.call(this, {
  1450. text: typeof this.options.title !== 'undefined' ? this.options.title : this.options.noneSelectedText
  1451. }, true);
  1452. }
  1453. // strip all HTML tags and trim the result, then unescape any escaped tags
  1454. button.title = titleFragment.textContent.replace(/<[^>]*>?/g, '').trim();
  1455. if (this.options.sanitize && hasContent) {
  1456. sanitizeHtml([titleFragment], that.options.whiteList, that.options.sanitizeFn);
  1457. }
  1458. buttonInner.innerHTML = '';
  1459. buttonInner.appendChild(titleFragment);
  1460. if (version.major < 4 && this.$newElement[0].classList.contains('bs3-has-addon')) {
  1461. var filterExpand = button.querySelector('.filter-expand'),
  1462. clone = buttonInner.cloneNode(true);
  1463. clone.className = 'filter-expand';
  1464. if (filterExpand) {
  1465. button.replaceChild(clone, filterExpand);
  1466. } else {
  1467. button.appendChild(clone);
  1468. }
  1469. }
  1470. this.$element.trigger('rendered' + EVENT_KEY);
  1471. },
  1472. /**
  1473. * @param [style]
  1474. * @param [status]
  1475. */
  1476. setStyle: function (newStyle, status) {
  1477. var button = this.$button[0],
  1478. newElement = this.$newElement[0],
  1479. style = this.options.style.trim(),
  1480. buttonClass;
  1481. if (this.$element.attr('class')) {
  1482. this.$newElement.addClass(this.$element.attr('class').replace(/selectpicker|mobile-device|bs-select-hidden|validate\[.*\]/gi, ''));
  1483. }
  1484. if (version.major < 4) {
  1485. newElement.classList.add('bs3');
  1486. if (newElement.parentNode.classList.contains('input-group') &&
  1487. (newElement.previousElementSibling || newElement.nextElementSibling) &&
  1488. (newElement.previousElementSibling || newElement.nextElementSibling).classList.contains('input-group-addon')
  1489. ) {
  1490. newElement.classList.add('bs3-has-addon');
  1491. }
  1492. }
  1493. if (newStyle) {
  1494. buttonClass = newStyle.trim();
  1495. } else {
  1496. buttonClass = style;
  1497. }
  1498. if (status == 'add') {
  1499. if (buttonClass) button.classList.add.apply(button.classList, buttonClass.split(' '));
  1500. } else if (status == 'remove') {
  1501. if (buttonClass) button.classList.remove.apply(button.classList, buttonClass.split(' '));
  1502. } else {
  1503. if (style) button.classList.remove.apply(button.classList, style.split(' '));
  1504. if (buttonClass) button.classList.add.apply(button.classList, buttonClass.split(' '));
  1505. }
  1506. },
  1507. liHeight: function (refresh) {
  1508. if (!refresh && (this.options.size === false || Object.keys(this.sizeInfo).length)) return;
  1509. var newElement = document.createElement('div'),
  1510. menu = document.createElement('div'),
  1511. menuInner = document.createElement('div'),
  1512. menuInnerInner = document.createElement('ul'),
  1513. divider = document.createElement('li'),
  1514. dropdownHeader = document.createElement('li'),
  1515. li = document.createElement('li'),
  1516. a = document.createElement('a'),
  1517. text = document.createElement('span'),
  1518. header = this.options.header && this.$menu.find('.' + classNames.POPOVERHEADER).length > 0 ? this.$menu.find('.' + classNames.POPOVERHEADER)[0].cloneNode(true) : null,
  1519. search = this.options.liveSearch ? document.createElement('div') : null,
  1520. actions = this.options.actionsBox && this.multiple && this.$menu.find('.bs-actionsbox').length > 0 ? this.$menu.find('.bs-actionsbox')[0].cloneNode(true) : null,
  1521. doneButton = this.options.doneButton && this.multiple && this.$menu.find('.bs-donebutton').length > 0 ? this.$menu.find('.bs-donebutton')[0].cloneNode(true) : null,
  1522. firstOption = this.$element.find('option')[0];
  1523. this.sizeInfo.selectWidth = this.$newElement[0].offsetWidth;
  1524. text.className = 'text';
  1525. a.className = 'dropdown-item ' + (firstOption ? firstOption.className : '');
  1526. newElement.className = this.$menu[0].parentNode.className + ' ' + classNames.SHOW;
  1527. newElement.style.width = 0; // ensure button width doesn't affect natural width of menu when calculating
  1528. if (this.options.width === 'auto') menu.style.minWidth = 0;
  1529. menu.className = classNames.MENU + ' ' + classNames.SHOW;
  1530. menuInner.className = 'inner ' + classNames.SHOW;
  1531. menuInnerInner.className = classNames.MENU + ' inner ' + (version.major === '4' ? classNames.SHOW : '');
  1532. divider.className = classNames.DIVIDER;
  1533. dropdownHeader.className = 'dropdown-header';
  1534. text.appendChild(document.createTextNode('\u200b'));
  1535. a.appendChild(text);
  1536. li.appendChild(a);
  1537. dropdownHeader.appendChild(text.cloneNode(true));
  1538. if (this.selectpicker.view.widestOption) {
  1539. menuInnerInner.appendChild(this.selectpicker.view.widestOption.cloneNode(true));
  1540. }
  1541. menuInnerInner.appendChild(li);
  1542. menuInnerInner.appendChild(divider);
  1543. menuInnerInner.appendChild(dropdownHeader);
  1544. if (header) menu.appendChild(header);
  1545. if (search) {
  1546. var input = document.createElement('input');
  1547. search.className = 'bs-searchbox';
  1548. input.className = 'form-control';
  1549. search.appendChild(input);
  1550. menu.appendChild(search);
  1551. }
  1552. if (actions) menu.appendChild(actions);
  1553. menuInner.appendChild(menuInnerInner);
  1554. menu.appendChild(menuInner);
  1555. if (doneButton) menu.appendChild(doneButton);
  1556. newElement.appendChild(menu);
  1557. document.body.appendChild(newElement);
  1558. var liHeight = li.offsetHeight,
  1559. dropdownHeaderHeight = dropdownHeader ? dropdownHeader.offsetHeight : 0,
  1560. headerHeight = header ? header.offsetHeight : 0,
  1561. searchHeight = search ? search.offsetHeight : 0,
  1562. actionsHeight = actions ? actions.offsetHeight : 0,
  1563. doneButtonHeight = doneButton ? doneButton.offsetHeight : 0,
  1564. dividerHeight = $(divider).outerHeight(true),
  1565. // fall back to jQuery if getComputedStyle is not supported
  1566. menuStyle = window.getComputedStyle ? window.getComputedStyle(menu) : false,
  1567. menuWidth = menu.offsetWidth,
  1568. $menu = menuStyle ? null : $(menu),
  1569. menuPadding = {
  1570. vert: toInteger(menuStyle ? menuStyle.paddingTop : $menu.css('paddingTop')) +
  1571. toInteger(menuStyle ? menuStyle.paddingBottom : $menu.css('paddingBottom')) +
  1572. toInteger(menuStyle ? menuStyle.borderTopWidth : $menu.css('borderTopWidth')) +
  1573. toInteger(menuStyle ? menuStyle.borderBottomWidth : $menu.css('borderBottomWidth')),
  1574. horiz: toInteger(menuStyle ? menuStyle.paddingLeft : $menu.css('paddingLeft')) +
  1575. toInteger(menuStyle ? menuStyle.paddingRight : $menu.css('paddingRight')) +
  1576. toInteger(menuStyle ? menuStyle.borderLeftWidth : $menu.css('borderLeftWidth')) +
  1577. toInteger(menuStyle ? menuStyle.borderRightWidth : $menu.css('borderRightWidth'))
  1578. },
  1579. menuExtras = {
  1580. vert: menuPadding.vert +
  1581. toInteger(menuStyle ? menuStyle.marginTop : $menu.css('marginTop')) +
  1582. toInteger(menuStyle ? menuStyle.marginBottom : $menu.css('marginBottom')) + 2,
  1583. horiz: menuPadding.horiz +
  1584. toInteger(menuStyle ? menuStyle.marginLeft : $menu.css('marginLeft')) +
  1585. toInteger(menuStyle ? menuStyle.marginRight : $menu.css('marginRight')) + 2
  1586. },
  1587. scrollBarWidth;
  1588. menuInner.style.overflowY = 'scroll';
  1589. scrollBarWidth = menu.offsetWidth - menuWidth;
  1590. document.body.removeChild(newElement);
  1591. this.sizeInfo.liHeight = liHeight;
  1592. this.sizeInfo.dropdownHeaderHeight = dropdownHeaderHeight;
  1593. this.sizeInfo.headerHeight = headerHeight;
  1594. this.sizeInfo.searchHeight = searchHeight;
  1595. this.sizeInfo.actionsHeight = actionsHeight;
  1596. this.sizeInfo.doneButtonHeight = doneButtonHeight;
  1597. this.sizeInfo.dividerHeight = dividerHeight;
  1598. this.sizeInfo.menuPadding = menuPadding;
  1599. this.sizeInfo.menuExtras = menuExtras;
  1600. this.sizeInfo.menuWidth = menuWidth;
  1601. this.sizeInfo.menuInnerInnerWidth = menuWidth - menuPadding.horiz;
  1602. this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth;
  1603. this.sizeInfo.scrollBarWidth = scrollBarWidth;
  1604. this.sizeInfo.selectHeight = this.$newElement[0].offsetHeight;
  1605. this.setPositionData();
  1606. },
  1607. getSelectPosition: function () {
  1608. var that = this,
  1609. $window = $(window),
  1610. pos = that.$newElement.offset(),
  1611. $container = $(that.options.container),
  1612. containerPos;
  1613. if (that.options.container && $container.length && !$container.is('body')) {
  1614. containerPos = $container.offset();
  1615. containerPos.top += parseInt($container.css('borderTopWidth'));
  1616. containerPos.left += parseInt($container.css('borderLeftWidth'));
  1617. } else {
  1618. containerPos = { top: 0, left: 0 };
  1619. }
  1620. var winPad = that.options.windowPadding;
  1621. this.sizeInfo.selectOffsetTop = pos.top - containerPos.top - $window.scrollTop();
  1622. this.sizeInfo.selectOffsetBot = $window.height() - this.sizeInfo.selectOffsetTop - this.sizeInfo.selectHeight - containerPos.top - winPad[2];
  1623. this.sizeInfo.selectOffsetLeft = pos.left - containerPos.left - $window.scrollLeft();
  1624. this.sizeInfo.selectOffsetRight = $window.width() - this.sizeInfo.selectOffsetLeft - this.sizeInfo.selectWidth - containerPos.left - winPad[1];
  1625. this.sizeInfo.selectOffsetTop -= winPad[0];
  1626. this.sizeInfo.selectOffsetLeft -= winPad[3];
  1627. },
  1628. setMenuSize: function (isAuto) {
  1629. this.getSelectPosition();
  1630. var selectWidth = this.sizeInfo.selectWidth,
  1631. liHeight = this.sizeInfo.liHeight,
  1632. headerHeight = this.sizeInfo.headerHeight,
  1633. searchHeight = this.sizeInfo.searchHeight,
  1634. actionsHeight = this.sizeInfo.actionsHeight,
  1635. doneButtonHeight = this.sizeInfo.doneButtonHeight,
  1636. divHeight = this.sizeInfo.dividerHeight,
  1637. menuPadding = this.sizeInfo.menuPadding,
  1638. menuInnerHeight,
  1639. menuHeight,
  1640. divLength = 0,
  1641. minHeight,
  1642. _minHeight,
  1643. maxHeight,
  1644. menuInnerMinHeight,
  1645. estimate,
  1646. isDropup;
  1647. if (this.options.dropupAuto) {
  1648. // Get the estimated height of the menu without scrollbars.
  1649. // This is useful for smaller menus, where there might be plenty of room
  1650. // below the button without setting dropup, but we can't know
  1651. // the exact height of the menu until createView is called later
  1652. estimate = liHeight * this.selectpicker.current.elements.length + menuPadding.vert;
  1653. isDropup = this.sizeInfo.selectOffsetTop - this.sizeInfo.selectOffsetBot > this.sizeInfo.menuExtras.vert && estimate + this.sizeInfo.menuExtras.vert + 50 > this.sizeInfo.selectOffsetBot;
  1654. // ensure dropup doesn't change while searching (so menu doesn't bounce back and forth)
  1655. if (this.selectpicker.isSearching === true) {
  1656. isDropup = this.selectpicker.dropup;
  1657. }
  1658. this.$newElement.toggleClass(classNames.DROPUP, isDropup);
  1659. this.selectpicker.dropup = isDropup;
  1660. }
  1661. if (this.options.size === 'auto') {
  1662. _minHeight = this.selectpicker.current.elements.length > 3 ? this.sizeInfo.liHeight * 3 + this.sizeInfo.menuExtras.vert - 2 : 0;
  1663. menuHeight = this.sizeInfo.selectOffsetBot - this.sizeInfo.menuExtras.vert;
  1664. minHeight = _minHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight;
  1665. menuInnerMinHeight = Math.max(_minHeight - menuPadding.vert, 0);
  1666. if (this.$newElement.hasClass(classNames.DROPUP)) {
  1667. menuHeight = this.sizeInfo.selectOffsetTop - this.sizeInfo.menuExtras.vert;
  1668. }
  1669. maxHeight = menuHeight;
  1670. menuInnerHeight = menuHeight - headerHeight - searchHeight - actionsHeight - doneButtonHeight - menuPadding.vert;
  1671. } else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) {
  1672. for (var i = 0; i < this.options.size; i++) {
  1673. if (this.selectpicker.current.data[i].type === 'divider') divLength++;
  1674. }
  1675. menuHeight = liHeight * this.options.size + divLength * divHeight + menuPadding.vert;
  1676. menuInnerHeight = menuHeight - menuPadding.vert;
  1677. maxHeight = menuHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight;
  1678. minHeight = menuInnerMinHeight = '';
  1679. }
  1680. this.$menu.css({
  1681. 'max-height': maxHeight + 'px',
  1682. 'overflow': 'hidden',
  1683. 'min-height': minHeight + 'px'
  1684. });
  1685. this.$menuInner.css({
  1686. 'max-height': menuInnerHeight + 'px',
  1687. 'overflow-y': 'auto',
  1688. 'min-height': menuInnerMinHeight + 'px'
  1689. });
  1690. // ensure menuInnerHeight is always a positive number to prevent issues calculating chunkSize in createView
  1691. this.sizeInfo.menuInnerHeight = Math.max(menuInnerHeight, 1);
  1692. if (this.selectpicker.current.data.length && this.selectpicker.current.data[this.selectpicker.current.data.length - 1].position > this.sizeInfo.menuInnerHeight) {
  1693. this.sizeInfo.hasScrollBar = true;
  1694. this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth + this.sizeInfo.scrollBarWidth;
  1695. }
  1696. if (this.options.dropdownAlignRight === 'auto') {
  1697. this.$menu.toggleClass(classNames.MENURIGHT, this.sizeInfo.selectOffsetLeft > this.sizeInfo.selectOffsetRight && this.sizeInfo.selectOffsetRight < (this.sizeInfo.totalMenuWidth - selectWidth));
  1698. }
  1699. if (this.dropdown && this.dropdown._popper) this.dropdown._popper.update();
  1700. },
  1701. setSize: function (refresh) {
  1702. this.liHeight(refresh);
  1703. if (this.options.header) this.$menu.css('padding-top', 0);
  1704. if (this.options.size !== false) {
  1705. var that = this,
  1706. $window = $(window);
  1707. this.setMenuSize();
  1708. if (this.options.liveSearch) {
  1709. this.$searchbox
  1710. .off('input.setMenuSize propertychange.setMenuSize')
  1711. .on('input.setMenuSize propertychange.setMenuSize', function () {
  1712. return that.setMenuSize();
  1713. });
  1714. }
  1715. if (this.options.size === 'auto') {
  1716. $window
  1717. .off('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize')
  1718. .on('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize', function () {
  1719. return that.setMenuSize();
  1720. });
  1721. } else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) {
  1722. $window.off('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize');
  1723. }
  1724. }
  1725. this.createView(false, true, refresh);
  1726. },
  1727. setWidth: function () {
  1728. var that = this;
  1729. if (this.options.width === 'auto') {
  1730. requestAnimationFrame(function () {
  1731. that.$menu.css('min-width', '0');
  1732. that.$element.on('loaded' + EVENT_KEY, function () {
  1733. that.liHeight();
  1734. that.setMenuSize();
  1735. // Get correct width if element is hidden
  1736. var $selectClone = that.$newElement.clone().appendTo('body'),
  1737. btnWidth = $selectClone.css('width', 'auto').children('button').outerWidth();
  1738. $selectClone.remove();
  1739. // Set width to whatever's larger, button title or longest option
  1740. that.sizeInfo.selectWidth = Math.max(that.sizeInfo.totalMenuWidth, btnWidth);
  1741. that.$newElement.css('width', that.sizeInfo.selectWidth + 'px');
  1742. });
  1743. });
  1744. } else if (this.options.width === 'fit') {
  1745. // Remove inline min-width so width can be changed from 'auto'
  1746. this.$menu.css('min-width', '');
  1747. this.$newElement.css('width', '').addClass('fit-width');
  1748. } else if (this.options.width) {
  1749. // Remove inline min-width so width can be changed from 'auto'
  1750. this.$menu.css('min-width', '');
  1751. this.$newElement.css('width', this.options.width);
  1752. } else {
  1753. // Remove inline min-width/width so width can be changed
  1754. this.$menu.css('min-width', '');
  1755. this.$newElement.css('width', '');
  1756. }
  1757. // Remove fit-width class if width is changed programmatically
  1758. if (this.$newElement.hasClass('fit-width') && this.options.width !== 'fit') {
  1759. this.$newElement[0].classList.remove('fit-width');
  1760. }
  1761. },
  1762. selectPosition: function () {
  1763. this.$bsContainer = $('<div class="bs-container" />');
  1764. var that = this,
  1765. $container = $(this.options.container),
  1766. pos,
  1767. containerPos,
  1768. actualHeight,
  1769. getPlacement = function ($element) {
  1770. var containerPosition = {},
  1771. // fall back to dropdown's default display setting if display is not manually set
  1772. display = that.options.display || (
  1773. // Bootstrap 3 doesn't have $.fn.dropdown.Constructor.Default
  1774. $.fn.dropdown.Constructor.Default ? $.fn.dropdown.Constructor.Default.display
  1775. : false
  1776. );
  1777. that.$bsContainer.addClass($element.attr('class').replace(/form-control|fit-width/gi, '')).toggleClass(classNames.DROPUP, $element.hasClass(classNames.DROPUP));
  1778. pos = $element.offset();
  1779. if (!$container.is('body')) {
  1780. containerPos = $container.offset();
  1781. containerPos.top += parseInt($container.css('borderTopWidth')) - $container.scrollTop();
  1782. containerPos.left += parseInt($container.css('borderLeftWidth')) - $container.scrollLeft();
  1783. } else {
  1784. containerPos = { top: 0, left: 0 };
  1785. }
  1786. actualHeight = $element.hasClass(classNames.DROPUP) ? 0 : $element[0].offsetHeight;
  1787. // Bootstrap 4+ uses Popper for menu positioning
  1788. if (version.major < 4 || display === 'static') {
  1789. containerPosition.top = pos.top - containerPos.top + actualHeight;
  1790. containerPosition.left = pos.left - containerPos.left;
  1791. }
  1792. containerPosition.width = $element[0].offsetWidth;
  1793. that.$bsContainer.css(containerPosition);
  1794. };
  1795. this.$button.on('click.bs.dropdown.data-api', function () {
  1796. if (that.isDisabled()) {
  1797. return;
  1798. }
  1799. getPlacement(that.$newElement);
  1800. that.$bsContainer
  1801. .appendTo(that.options.container)
  1802. .toggleClass(classNames.SHOW, !that.$button.hasClass(classNames.SHOW))
  1803. .append(that.$menu);
  1804. });
  1805. $(window)
  1806. .off('resize' + EVENT_KEY + '.' + this.selectId + ' scroll' + EVENT_KEY + '.' + this.selectId)
  1807. .on('resize' + EVENT_KEY + '.' + this.selectId + ' scroll' + EVENT_KEY + '.' + this.selectId, function () {
  1808. var isActive = that.$newElement.hasClass(classNames.SHOW);
  1809. if (isActive) getPlacement(that.$newElement);
  1810. });
  1811. this.$element.on('hide' + EVENT_KEY, function () {
  1812. that.$menu.data('height', that.$menu.height());
  1813. that.$bsContainer.detach();
  1814. });
  1815. },
  1816. setOptionStatus: function (selectedOnly) {
  1817. var that = this;
  1818. that.noScroll = false;
  1819. if (that.selectpicker.view.visibleElements && that.selectpicker.view.visibleElements.length) {
  1820. for (var i = 0; i < that.selectpicker.view.visibleElements.length; i++) {
  1821. var liData = that.selectpicker.current.data[i + that.selectpicker.view.position0],
  1822. option = liData.option;
  1823. if (option) {
  1824. if (selectedOnly !== true) {
  1825. that.setDisabled(
  1826. liData.index,
  1827. liData.disabled
  1828. );
  1829. }
  1830. that.setSelected(
  1831. liData.index,
  1832. option.selected
  1833. );
  1834. }
  1835. }
  1836. }
  1837. },
  1838. /**
  1839. * @param {number} index - the index of the option that is being changed
  1840. * @param {boolean} selected - true if the option is being selected, false if being deselected
  1841. */
  1842. setSelected: function (index, selected) {
  1843. var li = this.selectpicker.main.elements[index],
  1844. liData = this.selectpicker.main.data[index],
  1845. activeIndexIsSet = this.activeIndex !== undefined,
  1846. thisIsActive = this.activeIndex === index,
  1847. prevActive,
  1848. a,
  1849. // if current option is already active
  1850. // OR
  1851. // if the current option is being selected, it's NOT multiple, and
  1852. // activeIndex is undefined:
  1853. // - when the menu is first being opened, OR
  1854. // - after a search has been performed, OR
  1855. // - when retainActive is false when selecting a new option (i.e. index of the newly selected option is not the same as the current activeIndex)
  1856. keepActive = thisIsActive || (selected && !this.multiple && !activeIndexIsSet);
  1857. liData.selected = selected;
  1858. a = li.firstChild;
  1859. if (selected) {
  1860. this.selectedIndex = index;
  1861. }
  1862. li.classList.toggle('selected', selected);
  1863. if (keepActive) {
  1864. this.focusItem(li, liData);
  1865. this.selectpicker.view.currentActive = li;
  1866. this.activeIndex = index;
  1867. } else {
  1868. this.defocusItem(li);
  1869. }
  1870. if (a) {
  1871. a.classList.toggle('selected', selected);
  1872. if (selected) {
  1873. a.setAttribute('aria-selected', true);
  1874. } else {
  1875. if (this.multiple) {
  1876. a.setAttribute('aria-selected', false);
  1877. } else {
  1878. a.removeAttribute('aria-selected');
  1879. }
  1880. }
  1881. }
  1882. if (!keepActive && !activeIndexIsSet && selected && this.prevActiveIndex !== undefined) {
  1883. prevActive = this.selectpicker.main.elements[this.prevActiveIndex];
  1884. this.defocusItem(prevActive);
  1885. }
  1886. },
  1887. /**
  1888. * @param {number} index - the index of the option that is being disabled
  1889. * @param {boolean} disabled - true if the option is being disabled, false if being enabled
  1890. */
  1891. setDisabled: function (index, disabled) {
  1892. var li = this.selectpicker.main.elements[index],
  1893. a;
  1894. this.selectpicker.main.data[index].disabled = disabled;
  1895. a = li.firstChild;
  1896. li.classList.toggle(classNames.DISABLED, disabled);
  1897. if (a) {
  1898. if (version.major === '4') a.classList.toggle(classNames.DISABLED, disabled);
  1899. if (disabled) {
  1900. a.setAttribute('aria-disabled', disabled);
  1901. a.setAttribute('tabindex', -1);
  1902. } else {
  1903. a.removeAttribute('aria-disabled');
  1904. a.setAttribute('tabindex', 0);
  1905. }
  1906. }
  1907. },
  1908. isDisabled: function () {
  1909. return this.$element[0].disabled;
  1910. },
  1911. checkDisabled: function () {
  1912. if (this.isDisabled()) {
  1913. this.$newElement[0].classList.add(classNames.DISABLED);
  1914. this.$button.addClass(classNames.DISABLED).attr('tabindex', -1).attr('aria-disabled', true);
  1915. } else {
  1916. if (this.$button[0].classList.contains(classNames.DISABLED)) {
  1917. this.$newElement[0].classList.remove(classNames.DISABLED);
  1918. this.$button.removeClass(classNames.DISABLED).attr('aria-disabled', false);
  1919. }
  1920. if (this.$button.attr('tabindex') == -1 && !this.$element.data('tabindex')) {
  1921. this.$button.removeAttr('tabindex');
  1922. }
  1923. }
  1924. },
  1925. tabIndex: function () {
  1926. if (this.$element.data('tabindex') !== this.$element.attr('tabindex') &&
  1927. (this.$element.attr('tabindex') !== -98 && this.$element.attr('tabindex') !== '-98')) {
  1928. this.$element.data('tabindex', this.$element.attr('tabindex'));
  1929. this.$button.attr('tabindex', this.$element.data('tabindex'));
  1930. }
  1931. this.$element.attr('tabindex', -98);
  1932. },
  1933. clickListener: function () {
  1934. var that = this,
  1935. $document = $(document);
  1936. $document.data('spaceSelect', false);
  1937. this.$button.on('keyup', function (e) {
  1938. if (/(32)/.test(e.keyCode.toString(10)) && $document.data('spaceSelect')) {
  1939. e.preventDefault();
  1940. $document.data('spaceSelect', false);
  1941. }
  1942. });
  1943. this.$newElement.on('show.bs.dropdown', function () {
  1944. if (version.major > 3 && !that.dropdown) {
  1945. that.dropdown = that.$button.data('bs.dropdown');
  1946. that.dropdown._menu = that.$menu[0];
  1947. }
  1948. });
  1949. this.$button.on('click.bs.dropdown.data-api', function () {
  1950. if (!that.$newElement.hasClass(classNames.SHOW)) {
  1951. that.setSize();
  1952. }
  1953. });
  1954. function setFocus () {
  1955. if (that.options.liveSearch) {
  1956. that.$searchbox.trigger('focus');
  1957. } else {
  1958. that.$menuInner.trigger('focus');
  1959. }
  1960. }
  1961. function checkPopperExists () {
  1962. if (that.dropdown && that.dropdown._popper && that.dropdown._popper.state.isCreated) {
  1963. setFocus();
  1964. } else {
  1965. requestAnimationFrame(checkPopperExists);
  1966. }
  1967. }
  1968. this.$element.on('shown' + EVENT_KEY, function () {
  1969. if (that.$menuInner[0].scrollTop !== that.selectpicker.view.scrollTop) {
  1970. that.$menuInner[0].scrollTop = that.selectpicker.view.scrollTop;
  1971. }
  1972. if (version.major > 3) {
  1973. requestAnimationFrame(checkPopperExists);
  1974. } else {
  1975. setFocus();
  1976. }
  1977. });
  1978. // ensure posinset and setsize are correct before selecting an option via a click
  1979. this.$menuInner.on('mouseenter', 'li a', function (e) {
  1980. var hoverLi = this.parentElement,
  1981. position0 = that.isVirtual() ? that.selectpicker.view.position0 : 0,
  1982. index = Array.prototype.indexOf.call(hoverLi.parentElement.children, hoverLi),
  1983. hoverData = that.selectpicker.current.data[index + position0];
  1984. that.focusItem(hoverLi, hoverData, true);
  1985. });
  1986. this.$menuInner.on('click', 'li a', function (e, retainActive) {
  1987. var $this = $(this),
  1988. element = that.$element[0],
  1989. position0 = that.isVirtual() ? that.selectpicker.view.position0 : 0,
  1990. clickedData = that.selectpicker.current.data[$this.parent().index() + position0],
  1991. clickedIndex = clickedData.index,
  1992. prevValue = getSelectValues(element),
  1993. prevIndex = element.selectedIndex,
  1994. prevOption = element.options[prevIndex],
  1995. triggerChange = true;
  1996. // Don't close on multi choice menu
  1997. if (that.multiple && that.options.maxOptions !== 1) {
  1998. e.stopPropagation();
  1999. }
  2000. e.preventDefault();
  2001. // Don't run if the select is disabled
  2002. if (!that.isDisabled() && !$this.parent().hasClass(classNames.DISABLED)) {
  2003. var option = clickedData.option,
  2004. $option = $(option),
  2005. state = option.selected,
  2006. $optgroup = $option.parent('optgroup'),
  2007. $optgroupOptions = $optgroup.find('option'),
  2008. maxOptions = that.options.maxOptions,
  2009. maxOptionsGrp = $optgroup.data('maxOptions') || false;
  2010. if (clickedIndex === that.activeIndex) retainActive = true;
  2011. if (!retainActive) {
  2012. that.prevActiveIndex = that.activeIndex;
  2013. that.activeIndex = undefined;
  2014. }
  2015. if (!that.multiple) { // Deselect all others if not multi select box
  2016. if (prevOption) prevOption.selected = false;
  2017. option.selected = true;
  2018. that.setSelected(clickedIndex, true);
  2019. } else { // Toggle the one we have chosen if we are multi select.
  2020. option.selected = !state;
  2021. that.setSelected(clickedIndex, !state);
  2022. $this.trigger('blur');
  2023. if (maxOptions !== false || maxOptionsGrp !== false) {
  2024. var maxReached = maxOptions < getSelectedOptions(element).length,
  2025. maxReachedGrp = maxOptionsGrp < $optgroup.find('option:selected').length;
  2026. if ((maxOptions && maxReached) || (maxOptionsGrp && maxReachedGrp)) {
  2027. if (maxOptions && maxOptions == 1) {
  2028. element.selectedIndex = -1;
  2029. option.selected = true;
  2030. that.setOptionStatus(true);
  2031. } else if (maxOptionsGrp && maxOptionsGrp == 1) {
  2032. for (var i = 0; i < $optgroupOptions.length; i++) {
  2033. var _option = $optgroupOptions[i];
  2034. _option.selected = false;
  2035. that.setSelected(_option.liIndex, false);
  2036. }
  2037. option.selected = true;
  2038. that.setSelected(clickedIndex, true);
  2039. } else {
  2040. var maxOptionsText = typeof that.options.maxOptionsText === 'string' ? [that.options.maxOptionsText, that.options.maxOptionsText] : that.options.maxOptionsText,
  2041. maxOptionsArr = typeof maxOptionsText === 'function' ? maxOptionsText(maxOptions, maxOptionsGrp) : maxOptionsText,
  2042. maxTxt = maxOptionsArr[0].replace('{n}', maxOptions),
  2043. maxTxtGrp = maxOptionsArr[1].replace('{n}', maxOptionsGrp),
  2044. $notify = $('<div class="notify"></div>');
  2045. // If {var} is set in array, replace it
  2046. /** @deprecated */
  2047. if (maxOptionsArr[2]) {
  2048. maxTxt = maxTxt.replace('{var}', maxOptionsArr[2][maxOptions > 1 ? 0 : 1]);
  2049. maxTxtGrp = maxTxtGrp.replace('{var}', maxOptionsArr[2][maxOptionsGrp > 1 ? 0 : 1]);
  2050. }
  2051. option.selected = false;
  2052. that.$menu.append($notify);
  2053. if (maxOptions && maxReached) {
  2054. $notify.append($('<div>' + maxTxt + '</div>'));
  2055. triggerChange = false;
  2056. that.$element.trigger('maxReached' + EVENT_KEY);
  2057. }
  2058. if (maxOptionsGrp && maxReachedGrp) {
  2059. $notify.append($('<div>' + maxTxtGrp + '</div>'));
  2060. triggerChange = false;
  2061. that.$element.trigger('maxReachedGrp' + EVENT_KEY);
  2062. }
  2063. setTimeout(function () {
  2064. that.setSelected(clickedIndex, false);
  2065. }, 10);
  2066. $notify[0].classList.add('fadeOut');
  2067. setTimeout(function () {
  2068. $notify.remove();
  2069. }, 1050);
  2070. }
  2071. }
  2072. }
  2073. }
  2074. if (!that.multiple || (that.multiple && that.options.maxOptions === 1)) {
  2075. that.$button.trigger('focus');
  2076. } else if (that.options.liveSearch) {
  2077. that.$searchbox.trigger('focus');
  2078. }
  2079. // Trigger select 'change'
  2080. if (triggerChange) {
  2081. if (that.multiple || prevIndex !== element.selectedIndex) {
  2082. // $option.prop('selected') is current option state (selected/unselected). prevValue is the value of the select prior to being changed.
  2083. changedArguments = [option.index, $option.prop('selected'), prevValue];
  2084. that.$element
  2085. .triggerNative('change');
  2086. }
  2087. }
  2088. }
  2089. });
  2090. this.$menu.on('click', 'li.' + classNames.DISABLED + ' a, .' + classNames.POPOVERHEADER + ', .' + classNames.POPOVERHEADER + ' :not(.close)', function (e) {
  2091. if (e.currentTarget == this) {
  2092. e.preventDefault();
  2093. e.stopPropagation();
  2094. if (that.options.liveSearch && !$(e.target).hasClass('close')) {
  2095. that.$searchbox.trigger('focus');
  2096. } else {
  2097. that.$button.trigger('focus');
  2098. }
  2099. }
  2100. });
  2101. this.$menuInner.on('click', '.divider, .dropdown-header', function (e) {
  2102. e.preventDefault();
  2103. e.stopPropagation();
  2104. if (that.options.liveSearch) {
  2105. that.$searchbox.trigger('focus');
  2106. } else {
  2107. that.$button.trigger('focus');
  2108. }
  2109. });
  2110. this.$menu.on('click', '.' + classNames.POPOVERHEADER + ' .close', function () {
  2111. that.$button.trigger('click');
  2112. });
  2113. this.$searchbox.on('click', function (e) {
  2114. e.stopPropagation();
  2115. });
  2116. this.$menu.on('click', '.actions-btn', function (e) {
  2117. if (that.options.liveSearch) {
  2118. that.$searchbox.trigger('focus');
  2119. } else {
  2120. that.$button.trigger('focus');
  2121. }
  2122. e.preventDefault();
  2123. e.stopPropagation();
  2124. if ($(this).hasClass('bs-select-all')) {
  2125. that.selectAll();
  2126. } else {
  2127. that.deselectAll();
  2128. }
  2129. });
  2130. this.$element
  2131. .on('change' + EVENT_KEY, function () {
  2132. that.render();
  2133. that.$element.trigger('changed' + EVENT_KEY, changedArguments);
  2134. changedArguments = null;
  2135. })
  2136. .on('focus' + EVENT_KEY, function () {
  2137. if (!that.options.mobile) that.$button.trigger('focus');
  2138. });
  2139. },
  2140. liveSearchListener: function () {
  2141. var that = this,
  2142. noResults = document.createElement('li');
  2143. this.$button.on('click.bs.dropdown.data-api', function () {
  2144. if (!!that.$searchbox.val()) {
  2145. that.$searchbox.val('');
  2146. }
  2147. });
  2148. this.$searchbox.on('click.bs.dropdown.data-api focus.bs.dropdown.data-api touchend.bs.dropdown.data-api', function (e) {
  2149. e.stopPropagation();
  2150. });
  2151. this.$searchbox.on('input propertychange', function () {
  2152. var searchValue = that.$searchbox.val();
  2153. that.selectpicker.search.elements = [];
  2154. that.selectpicker.search.data = [];
  2155. if (searchValue) {
  2156. var i,
  2157. searchMatch = [],
  2158. q = searchValue.toUpperCase(),
  2159. cache = {},
  2160. cacheArr = [],
  2161. searchStyle = that._searchStyle(),
  2162. normalizeSearch = that.options.liveSearchNormalize;
  2163. if (normalizeSearch) q = normalizeToBase(q);
  2164. for (var i = 0; i < that.selectpicker.main.data.length; i++) {
  2165. var li = that.selectpicker.main.data[i];
  2166. if (!cache[i]) {
  2167. cache[i] = stringSearch(li, q, searchStyle, normalizeSearch);
  2168. }
  2169. if (cache[i] && li.headerIndex !== undefined && cacheArr.indexOf(li.headerIndex) === -1) {
  2170. if (li.headerIndex > 0) {
  2171. cache[li.headerIndex - 1] = true;
  2172. cacheArr.push(li.headerIndex - 1);
  2173. }
  2174. cache[li.headerIndex] = true;
  2175. cacheArr.push(li.headerIndex);
  2176. cache[li.lastIndex + 1] = true;
  2177. }
  2178. if (cache[i] && li.type !== 'optgroup-label') cacheArr.push(i);
  2179. }
  2180. for (var i = 0, cacheLen = cacheArr.length; i < cacheLen; i++) {
  2181. var index = cacheArr[i],
  2182. prevIndex = cacheArr[i - 1],
  2183. li = that.selectpicker.main.data[index],
  2184. liPrev = that.selectpicker.main.data[prevIndex];
  2185. if (li.type !== 'divider' || (li.type === 'divider' && liPrev && liPrev.type !== 'divider' && cacheLen - 1 !== i)) {
  2186. that.selectpicker.search.data.push(li);
  2187. searchMatch.push(that.selectpicker.main.elements[index]);
  2188. }
  2189. }
  2190. that.activeIndex = undefined;
  2191. that.noScroll = true;
  2192. that.$menuInner.scrollTop(0);
  2193. that.selectpicker.search.elements = searchMatch;
  2194. that.createView(true);
  2195. if (!searchMatch.length) {
  2196. noResults.className = 'no-results';
  2197. noResults.innerHTML = that.options.noneResultsText.replace('{0}', '"' + htmlEscape(searchValue) + '"');
  2198. that.$menuInner[0].firstChild.appendChild(noResults);
  2199. }
  2200. } else {
  2201. that.$menuInner.scrollTop(0);
  2202. that.createView(false);
  2203. }
  2204. });
  2205. },
  2206. _searchStyle: function () {
  2207. return this.options.liveSearchStyle || 'contains';
  2208. },
  2209. val: function (value) {
  2210. var element = this.$element[0];
  2211. if (typeof value !== 'undefined') {
  2212. var prevValue = getSelectValues(element);
  2213. changedArguments = [null, null, prevValue];
  2214. this.$element
  2215. .val(value)
  2216. .trigger('changed' + EVENT_KEY, changedArguments);
  2217. if (this.$newElement.hasClass(classNames.SHOW)) {
  2218. if (this.multiple) {
  2219. this.setOptionStatus(true);
  2220. } else {
  2221. var liSelectedIndex = (element.options[element.selectedIndex] || {}).liIndex;
  2222. if (typeof liSelectedIndex === 'number') {
  2223. this.setSelected(this.selectedIndex, false);
  2224. this.setSelected(liSelectedIndex, true);
  2225. }
  2226. }
  2227. }
  2228. this.render();
  2229. changedArguments = null;
  2230. return this.$element;
  2231. } else {
  2232. return this.$element.val();
  2233. }
  2234. },
  2235. changeAll: function (status) {
  2236. if (!this.multiple) return;
  2237. if (typeof status === 'undefined') status = true;
  2238. var element = this.$element[0],
  2239. previousSelected = 0,
  2240. currentSelected = 0,
  2241. prevValue = getSelectValues(element);
  2242. element.classList.add('bs-select-hidden');
  2243. for (var i = 0, data = this.selectpicker.current.data, len = data.length; i < len; i++) {
  2244. var liData = data[i],
  2245. option = liData.option;
  2246. if (option && !liData.disabled && liData.type !== 'divider') {
  2247. if (liData.selected) previousSelected++;
  2248. option.selected = status;
  2249. if (status === true) currentSelected++;
  2250. }
  2251. }
  2252. element.classList.remove('bs-select-hidden');
  2253. if (previousSelected === currentSelected) return;
  2254. this.setOptionStatus();
  2255. changedArguments = [null, null, prevValue];
  2256. this.$element
  2257. .triggerNative('change');
  2258. },
  2259. selectAll: function () {
  2260. return this.changeAll(true);
  2261. },
  2262. deselectAll: function () {
  2263. return this.changeAll(false);
  2264. },
  2265. toggle: function (e) {
  2266. e = e || window.event;
  2267. if (e) e.stopPropagation();
  2268. this.$button.trigger('click.bs.dropdown.data-api');
  2269. },
  2270. keydown: function (e) {
  2271. var $this = $(this),
  2272. isToggle = $this.hasClass('dropdown-toggle'),
  2273. $parent = isToggle ? $this.closest('.dropdown') : $this.closest(Selector.MENU),
  2274. that = $parent.data('this'),
  2275. $items = that.findLis(),
  2276. index,
  2277. isActive,
  2278. liActive,
  2279. activeLi,
  2280. offset,
  2281. updateScroll = false,
  2282. downOnTab = e.which === keyCodes.TAB && !isToggle && !that.options.selectOnTab,
  2283. isArrowKey = REGEXP_ARROW.test(e.which) || downOnTab,
  2284. scrollTop = that.$menuInner[0].scrollTop,
  2285. isVirtual = that.isVirtual(),
  2286. position0 = isVirtual === true ? that.selectpicker.view.position0 : 0;
  2287. // do nothing if a function key is pressed
  2288. if (e.which >= 112 && e.which <= 123) return;
  2289. isActive = that.$newElement.hasClass(classNames.SHOW);
  2290. if (
  2291. !isActive &&
  2292. (
  2293. isArrowKey ||
  2294. (e.which >= 48 && e.which <= 57) ||
  2295. (e.which >= 96 && e.which <= 105) ||
  2296. (e.which >= 65 && e.which <= 90)
  2297. )
  2298. ) {
  2299. that.$button.trigger('click.bs.dropdown.data-api');
  2300. if (that.options.liveSearch) {
  2301. that.$searchbox.trigger('focus');
  2302. return;
  2303. }
  2304. }
  2305. if (e.which === keyCodes.ESCAPE && isActive) {
  2306. e.preventDefault();
  2307. that.$button.trigger('click.bs.dropdown.data-api').trigger('focus');
  2308. }
  2309. if (isArrowKey) { // if up or down
  2310. if (!$items.length) return;
  2311. liActive = that.selectpicker.main.elements[that.activeIndex];
  2312. index = liActive ? Array.prototype.indexOf.call(liActive.parentElement.children, liActive) : -1;
  2313. if (index !== -1) {
  2314. that.defocusItem(liActive);
  2315. }
  2316. if (e.which === keyCodes.ARROW_UP) { // up
  2317. if (index !== -1) index--;
  2318. if (index + position0 < 0) index += $items.length;
  2319. if (!that.selectpicker.view.canHighlight[index + position0]) {
  2320. index = that.selectpicker.view.canHighlight.slice(0, index + position0).lastIndexOf(true) - position0;
  2321. if (index === -1) index = $items.length - 1;
  2322. }
  2323. } else if (e.which === keyCodes.ARROW_DOWN || downOnTab) { // down
  2324. index++;
  2325. if (index + position0 >= that.selectpicker.view.canHighlight.length) index = 0;
  2326. if (!that.selectpicker.view.canHighlight[index + position0]) {
  2327. index = index + 1 + that.selectpicker.view.canHighlight.slice(index + position0 + 1).indexOf(true);
  2328. }
  2329. }
  2330. e.preventDefault();
  2331. var liActiveIndex = position0 + index;
  2332. if (e.which === keyCodes.ARROW_UP) { // up
  2333. // scroll to bottom and highlight last option
  2334. if (position0 === 0 && index === $items.length - 1) {
  2335. that.$menuInner[0].scrollTop = that.$menuInner[0].scrollHeight;
  2336. liActiveIndex = that.selectpicker.current.elements.length - 1;
  2337. } else {
  2338. activeLi = that.selectpicker.current.data[liActiveIndex];
  2339. offset = activeLi.position - activeLi.height;
  2340. updateScroll = offset < scrollTop;
  2341. }
  2342. } else if (e.which === keyCodes.ARROW_DOWN || downOnTab) { // down
  2343. // scroll to top and highlight first option
  2344. if (index === 0) {
  2345. that.$menuInner[0].scrollTop = 0;
  2346. liActiveIndex = 0;
  2347. } else {
  2348. activeLi = that.selectpicker.current.data[liActiveIndex];
  2349. offset = activeLi.position - that.sizeInfo.menuInnerHeight;
  2350. updateScroll = offset > scrollTop;
  2351. }
  2352. }
  2353. liActive = that.selectpicker.current.elements[liActiveIndex];
  2354. that.activeIndex = that.selectpicker.current.data[liActiveIndex].index;
  2355. that.focusItem(liActive);
  2356. that.selectpicker.view.currentActive = liActive;
  2357. if (updateScroll) that.$menuInner[0].scrollTop = offset;
  2358. if (that.options.liveSearch) {
  2359. that.$searchbox.trigger('focus');
  2360. } else {
  2361. $this.trigger('focus');
  2362. }
  2363. } else if (
  2364. (!$this.is('input') && !REGEXP_TAB_OR_ESCAPE.test(e.which)) ||
  2365. (e.which === keyCodes.SPACE && that.selectpicker.keydown.keyHistory)
  2366. ) {
  2367. var searchMatch,
  2368. matches = [],
  2369. keyHistory;
  2370. e.preventDefault();
  2371. that.selectpicker.keydown.keyHistory += keyCodeMap[e.which];
  2372. if (that.selectpicker.keydown.resetKeyHistory.cancel) clearTimeout(that.selectpicker.keydown.resetKeyHistory.cancel);
  2373. that.selectpicker.keydown.resetKeyHistory.cancel = that.selectpicker.keydown.resetKeyHistory.start();
  2374. keyHistory = that.selectpicker.keydown.keyHistory;
  2375. // if all letters are the same, set keyHistory to just the first character when searching
  2376. if (/^(.)\1+$/.test(keyHistory)) {
  2377. keyHistory = keyHistory.charAt(0);
  2378. }
  2379. // find matches
  2380. for (var i = 0; i < that.selectpicker.current.data.length; i++) {
  2381. var li = that.selectpicker.current.data[i],
  2382. hasMatch;
  2383. hasMatch = stringSearch(li, keyHistory, 'startsWith', true);
  2384. if (hasMatch && that.selectpicker.view.canHighlight[i]) {
  2385. matches.push(li.index);
  2386. }
  2387. }
  2388. if (matches.length) {
  2389. var matchIndex = 0;
  2390. $items.removeClass('active').find('a').removeClass('active');
  2391. // either only one key has been pressed or they are all the same key
  2392. if (keyHistory.length === 1) {
  2393. matchIndex = matches.indexOf(that.activeIndex);
  2394. if (matchIndex === -1 || matchIndex === matches.length - 1) {
  2395. matchIndex = 0;
  2396. } else {
  2397. matchIndex++;
  2398. }
  2399. }
  2400. searchMatch = matches[matchIndex];
  2401. activeLi = that.selectpicker.main.data[searchMatch];
  2402. if (scrollTop - activeLi.position > 0) {
  2403. offset = activeLi.position - activeLi.height;
  2404. updateScroll = true;
  2405. } else {
  2406. offset = activeLi.position - that.sizeInfo.menuInnerHeight;
  2407. // if the option is already visible at the current scroll position, just keep it the same
  2408. updateScroll = activeLi.position > scrollTop + that.sizeInfo.menuInnerHeight;
  2409. }
  2410. liActive = that.selectpicker.main.elements[searchMatch];
  2411. that.activeIndex = matches[matchIndex];
  2412. that.focusItem(liActive);
  2413. if (liActive) liActive.firstChild.focus();
  2414. if (updateScroll) that.$menuInner[0].scrollTop = offset;
  2415. $this.trigger('focus');
  2416. }
  2417. }
  2418. // Select focused option if "Enter", "Spacebar" or "Tab" (when selectOnTab is true) are pressed inside the menu.
  2419. if (
  2420. isActive &&
  2421. (
  2422. (e.which === keyCodes.SPACE && !that.selectpicker.keydown.keyHistory) ||
  2423. e.which === keyCodes.ENTER ||
  2424. (e.which === keyCodes.TAB && that.options.selectOnTab)
  2425. )
  2426. ) {
  2427. if (e.which !== keyCodes.SPACE) e.preventDefault();
  2428. if (!that.options.liveSearch || e.which !== keyCodes.SPACE) {
  2429. that.$menuInner.find('.active a').trigger('click', true); // retain active class
  2430. $this.trigger('focus');
  2431. if (!that.options.liveSearch) {
  2432. // Prevent screen from scrolling if the user hits the spacebar
  2433. e.preventDefault();
  2434. // Fixes spacebar selection of dropdown items in FF & IE
  2435. $(document).data('spaceSelect', true);
  2436. }
  2437. }
  2438. }
  2439. },
  2440. mobile: function () {
  2441. this.$element[0].classList.add('mobile-device');
  2442. },
  2443. refresh: function () {
  2444. // update options if data attributes have been changed
  2445. var config = $.extend({}, this.options, this.$element.data());
  2446. this.options = config;
  2447. this.checkDisabled();
  2448. this.setStyle();
  2449. this.render();
  2450. this.buildData();
  2451. this.buildList();
  2452. this.setWidth();
  2453. this.setSize(true);
  2454. this.$element.trigger('refreshed' + EVENT_KEY);
  2455. },
  2456. hide: function () {
  2457. this.$newElement.hide();
  2458. },
  2459. show: function () {
  2460. this.$newElement.show();
  2461. },
  2462. remove: function () {
  2463. this.$newElement.remove();
  2464. this.$element.remove();
  2465. },
  2466. destroy: function () {
  2467. this.$newElement.before(this.$element).remove();
  2468. if (this.$bsContainer) {
  2469. this.$bsContainer.remove();
  2470. } else {
  2471. this.$menu.remove();
  2472. }
  2473. this.$element
  2474. .off(EVENT_KEY)
  2475. .removeData('selectpicker')
  2476. .removeClass('bs-select-hidden selectpicker');
  2477. $(window).off(EVENT_KEY + '.' + this.selectId);
  2478. }
  2479. };
  2480. // SELECTPICKER PLUGIN DEFINITION
  2481. // ==============================
  2482. function Plugin (option) {
  2483. // get the args of the outer function..
  2484. var args = arguments;
  2485. // The arguments of the function are explicitly re-defined from the argument list, because the shift causes them
  2486. // to get lost/corrupted in android 2.3 and IE9 #715 #775
  2487. var _option = option;
  2488. [].shift.apply(args);
  2489. // if the version was not set successfully
  2490. if (!version.success) {
  2491. // try to retreive it again
  2492. try {
  2493. version.full = ($.fn.dropdown.Constructor.VERSION || '').split(' ')[0].split('.');
  2494. } catch (err) {
  2495. // fall back to use BootstrapVersion if set
  2496. if (Selectpicker.BootstrapVersion) {
  2497. version.full = Selectpicker.BootstrapVersion.split(' ')[0].split('.');
  2498. } else {
  2499. version.full = [version.major, '0', '0'];
  2500. console.warn(
  2501. 'There was an issue retrieving Bootstrap\'s version. ' +
  2502. 'Ensure Bootstrap is being loaded before bootstrap-select and there is no namespace collision. ' +
  2503. 'If loading Bootstrap asynchronously, the version may need to be manually specified via $.fn.selectpicker.Constructor.BootstrapVersion.',
  2504. err
  2505. );
  2506. }
  2507. }
  2508. version.major = version.full[0];
  2509. version.success = true;
  2510. }
  2511. if (version.major === '4') {
  2512. // some defaults need to be changed if using Bootstrap 4
  2513. // check to see if they have already been manually changed before forcing them to update
  2514. var toUpdate = [];
  2515. if (Selectpicker.DEFAULTS.style === classNames.BUTTONCLASS) toUpdate.push({ name: 'style', className: 'BUTTONCLASS' });
  2516. if (Selectpicker.DEFAULTS.iconBase === classNames.ICONBASE) toUpdate.push({ name: 'iconBase', className: 'ICONBASE' });
  2517. if (Selectpicker.DEFAULTS.tickIcon === classNames.TICKICON) toUpdate.push({ name: 'tickIcon', className: 'TICKICON' });
  2518. classNames.DIVIDER = 'dropdown-divider';
  2519. classNames.SHOW = 'show';
  2520. classNames.BUTTONCLASS = 'btn-light';
  2521. classNames.POPOVERHEADER = 'popover-header';
  2522. classNames.ICONBASE = '';
  2523. classNames.TICKICON = 'bs-ok-default';
  2524. for (var i = 0; i < toUpdate.length; i++) {
  2525. var option = toUpdate[i];
  2526. Selectpicker.DEFAULTS[option.name] = classNames[option.className];
  2527. }
  2528. }
  2529. var value;
  2530. var chain = this.each(function () {
  2531. var $this = $(this);
  2532. if ($this.is('select')) {
  2533. var data = $this.data('selectpicker'),
  2534. options = typeof _option == 'object' && _option;
  2535. if (!data) {
  2536. var dataAttributes = $this.data();
  2537. for (var dataAttr in dataAttributes) {
  2538. if (dataAttributes.hasOwnProperty(dataAttr) && $.inArray(dataAttr, DISALLOWED_ATTRIBUTES) !== -1) {
  2539. delete dataAttributes[dataAttr];
  2540. }
  2541. }
  2542. var config = $.extend({}, Selectpicker.DEFAULTS, $.fn.selectpicker.defaults || {}, dataAttributes, options);
  2543. config.template = $.extend({}, Selectpicker.DEFAULTS.template, ($.fn.selectpicker.defaults ? $.fn.selectpicker.defaults.template : {}), dataAttributes.template, options.template);
  2544. $this.data('selectpicker', (data = new Selectpicker(this, config)));
  2545. } else if (options) {
  2546. for (var i in options) {
  2547. if (options.hasOwnProperty(i)) {
  2548. data.options[i] = options[i];
  2549. }
  2550. }
  2551. }
  2552. if (typeof _option == 'string') {
  2553. if (data[_option] instanceof Function) {
  2554. value = data[_option].apply(data, args);
  2555. } else {
  2556. value = data.options[_option];
  2557. }
  2558. }
  2559. }
  2560. });
  2561. if (typeof value !== 'undefined') {
  2562. // noinspection JSUnusedAssignment
  2563. return value;
  2564. } else {
  2565. return chain;
  2566. }
  2567. }
  2568. var old = $.fn.selectpicker;
  2569. $.fn.selectpicker = Plugin;
  2570. $.fn.selectpicker.Constructor = Selectpicker;
  2571. // SELECTPICKER NO CONFLICT
  2572. // ========================
  2573. $.fn.selectpicker.noConflict = function () {
  2574. $.fn.selectpicker = old;
  2575. return this;
  2576. };
  2577. $(document)
  2578. .off('keydown.bs.dropdown.data-api', '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select .dropdown-menu')
  2579. .on('keydown' + EVENT_KEY, '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bootstrap-select .bs-searchbox input', Selectpicker.prototype.keydown)
  2580. .on('focusin.modal', '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bootstrap-select .bs-searchbox input', function (e) {
  2581. e.stopPropagation();
  2582. });
  2583. // SELECTPICKER DATA-API
  2584. // =====================
  2585. $(window).on('load' + EVENT_KEY + '.data-api', function () {
  2586. $('.selectpicker').each(function () {
  2587. var $selectpicker = $(this);
  2588. Plugin.call($selectpicker, $selectpicker.data());
  2589. })
  2590. });
  2591. })(jQuery);