ckt的看板部分
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.

3033 lines
105 KiB

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