cp.scripts.js 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939
  1. /*!
  2. * Bootstrap-select v1.13.9 (https://developer.snapappointments.com/bootstrap-select)
  3. *
  4. * Copyright 2012-2019 SnapAppointments, LLC
  5. * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
  6. */
  7. (function (root, factory) {
  8. if (root === undefined && window !== undefined) root = window;
  9. if (typeof define === 'function' && define.amd) {
  10. // AMD. Register as an anonymous module unless amdModuleId is set
  11. define(["jquery"], function (a0) {
  12. return (factory(a0));
  13. });
  14. } else if (typeof module === 'object' && module.exports) {
  15. // Node. Does not work with strict CommonJS, but
  16. // only CommonJS-like environments that support module.exports,
  17. // like Node.
  18. module.exports = factory(require("jquery"));
  19. } else {
  20. factory(root["jQuery"]);
  21. }
  22. }(this, function (jQuery) {
  23. (function ($) {
  24. 'use strict';
  25. var DISALLOWED_ATTRIBUTES = ['sanitize', 'whiteList', 'sanitizeFn'];
  26. var uriAttrs = [
  27. 'background',
  28. 'cite',
  29. 'href',
  30. 'itemtype',
  31. 'longdesc',
  32. 'poster',
  33. 'src',
  34. 'xlink:href'
  35. ];
  36. var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i;
  37. var DefaultWhitelist = {
  38. // Global attributes allowed on any supplied element below.
  39. '*': ['class', 'dir', 'id', 'lang', 'role', 'tabindex', 'style', ARIA_ATTRIBUTE_PATTERN],
  40. a: ['target', 'href', 'title', 'rel'],
  41. area: [],
  42. b: [],
  43. br: [],
  44. col: [],
  45. code: [],
  46. div: [],
  47. em: [],
  48. hr: [],
  49. h1: [],
  50. h2: [],
  51. h3: [],
  52. h4: [],
  53. h5: [],
  54. h6: [],
  55. i: [],
  56. img: ['src', 'alt', 'title', 'width', 'height'],
  57. li: [],
  58. ol: [],
  59. p: [],
  60. pre: [],
  61. s: [],
  62. small: [],
  63. span: [],
  64. sub: [],
  65. sup: [],
  66. strong: [],
  67. u: [],
  68. ul: []
  69. }
  70. /**
  71. * A pattern that recognizes a commonly useful subset of URLs that are safe.
  72. *
  73. * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts
  74. */
  75. var SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi;
  76. /**
  77. * A pattern that matches safe data URLs. Only matches image, video and audio types.
  78. *
  79. * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts
  80. */
  81. 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;
  82. function allowedAttribute (attr, allowedAttributeList) {
  83. var attrName = attr.nodeName.toLowerCase()
  84. if ($.inArray(attrName, allowedAttributeList) !== -1) {
  85. if ($.inArray(attrName, uriAttrs) !== -1) {
  86. return Boolean(attr.nodeValue.match(SAFE_URL_PATTERN) || attr.nodeValue.match(DATA_URL_PATTERN))
  87. }
  88. return true
  89. }
  90. var regExp = $(allowedAttributeList).filter(function (index, value) {
  91. return value instanceof RegExp
  92. })
  93. // Check if a regular expression validates the attribute.
  94. for (var i = 0, l = regExp.length; i < l; i++) {
  95. if (attrName.match(regExp[i])) {
  96. return true
  97. }
  98. }
  99. return false
  100. }
  101. function sanitizeHtml (unsafeElements, whiteList, sanitizeFn) {
  102. if (sanitizeFn && typeof sanitizeFn === 'function') {
  103. return sanitizeFn(unsafeElements);
  104. }
  105. var whitelistKeys = Object.keys(whiteList);
  106. for (var i = 0, len = unsafeElements.length; i < len; i++) {
  107. var elements = unsafeElements[i].querySelectorAll('*');
  108. for (var j = 0, len2 = elements.length; j < len2; j++) {
  109. var el = elements[j];
  110. var elName = el.nodeName.toLowerCase();
  111. if (whitelistKeys.indexOf(elName) === -1) {
  112. el.parentNode.removeChild(el);
  113. continue;
  114. }
  115. var attributeList = [].slice.call(el.attributes);
  116. var whitelistedAttributes = [].concat(whiteList['*'] || [], whiteList[elName] || []);
  117. for (var k = 0, len3 = attributeList.length; k < len3; k++) {
  118. var attr = attributeList[k];
  119. if (!allowedAttribute(attr, whitelistedAttributes)) {
  120. el.removeAttribute(attr.nodeName);
  121. }
  122. }
  123. }
  124. }
  125. }
  126. // Polyfill for browsers with no classList support
  127. // Remove in v2
  128. if (!('classList' in document.createElement('_'))) {
  129. (function (view) {
  130. if (!('Element' in view)) return;
  131. var classListProp = 'classList',
  132. protoProp = 'prototype',
  133. elemCtrProto = view.Element[protoProp],
  134. objCtr = Object,
  135. classListGetter = function () {
  136. var $elem = $(this);
  137. return {
  138. add: function (classes) {
  139. classes = Array.prototype.slice.call(arguments).join(' ');
  140. return $elem.addClass(classes);
  141. },
  142. remove: function (classes) {
  143. classes = Array.prototype.slice.call(arguments).join(' ');
  144. return $elem.removeClass(classes);
  145. },
  146. toggle: function (classes, force) {
  147. return $elem.toggleClass(classes, force);
  148. },
  149. contains: function (classes) {
  150. return $elem.hasClass(classes);
  151. }
  152. }
  153. };
  154. if (objCtr.defineProperty) {
  155. var classListPropDesc = {
  156. get: classListGetter,
  157. enumerable: true,
  158. configurable: true
  159. };
  160. try {
  161. objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
  162. } catch (ex) { // IE 8 doesn't support enumerable:true
  163. // adding undefined to fight this issue https://github.com/eligrey/classList.js/issues/36
  164. // modernie IE8-MSW7 machine has IE8 8.0.6001.18702 and is affected
  165. if (ex.number === undefined || ex.number === -0x7FF5EC54) {
  166. classListPropDesc.enumerable = false;
  167. objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
  168. }
  169. }
  170. } else if (objCtr[protoProp].__defineGetter__) {
  171. elemCtrProto.__defineGetter__(classListProp, classListGetter);
  172. }
  173. }(window));
  174. }
  175. var testElement = document.createElement('_');
  176. testElement.classList.add('c1', 'c2');
  177. if (!testElement.classList.contains('c2')) {
  178. var _add = DOMTokenList.prototype.add,
  179. _remove = DOMTokenList.prototype.remove;
  180. DOMTokenList.prototype.add = function () {
  181. Array.prototype.forEach.call(arguments, _add.bind(this));
  182. }
  183. DOMTokenList.prototype.remove = function () {
  184. Array.prototype.forEach.call(arguments, _remove.bind(this));
  185. }
  186. }
  187. testElement.classList.toggle('c3', false);
  188. // Polyfill for IE 10 and Firefox <24, where classList.toggle does not
  189. // support the second argument.
  190. if (testElement.classList.contains('c3')) {
  191. var _toggle = DOMTokenList.prototype.toggle;
  192. DOMTokenList.prototype.toggle = function (token, force) {
  193. if (1 in arguments && !this.contains(token) === !force) {
  194. return force;
  195. } else {
  196. return _toggle.call(this, token);
  197. }
  198. };
  199. }
  200. testElement = null;
  201. // shallow array comparison
  202. function isEqual (array1, array2) {
  203. return array1.length === array2.length && array1.every(function (element, index) {
  204. return element === array2[index];
  205. });
  206. };
  207. // <editor-fold desc="Shims">
  208. if (!String.prototype.startsWith) {
  209. (function () {
  210. 'use strict';
  211. var defineProperty = (function () {
  212. try {
  213. var object = {};
  214. var $defineProperty = Object.defineProperty;
  215. var result = $defineProperty(object, object, object) && $defineProperty;
  216. } catch (error) {
  217. }
  218. return result;
  219. }());
  220. var toString = {}.toString;
  221. var startsWith = function (search) {
  222. if (this == null) {
  223. throw new TypeError();
  224. }
  225. var string = String(this);
  226. if (search && toString.call(search) == '[object RegExp]') {
  227. throw new TypeError();
  228. }
  229. var stringLength = string.length;
  230. var searchString = String(search);
  231. var searchLength = searchString.length;
  232. var position = arguments.length > 1 ? arguments[1] : undefined;
  233. var pos = position ? Number(position) : 0;
  234. if (pos != pos) {
  235. pos = 0;
  236. }
  237. var start = Math.min(Math.max(pos, 0), stringLength);
  238. if (searchLength + start > stringLength) {
  239. return false;
  240. }
  241. var index = -1;
  242. while (++index < searchLength) {
  243. if (string.charCodeAt(start + index) != searchString.charCodeAt(index)) {
  244. return false;
  245. }
  246. }
  247. return true;
  248. };
  249. if (defineProperty) {
  250. defineProperty(String.prototype, 'startsWith', {
  251. 'value': startsWith,
  252. 'configurable': true,
  253. 'writable': true
  254. });
  255. } else {
  256. String.prototype.startsWith = startsWith;
  257. }
  258. }());
  259. }
  260. if (!Object.keys) {
  261. Object.keys = function (
  262. o, // object
  263. k, // key
  264. r // result array
  265. ) {
  266. // initialize object and result
  267. r = [];
  268. // iterate over object keys
  269. for (k in o) {
  270. // fill result array with non-prototypical keys
  271. r.hasOwnProperty.call(o, k) && r.push(k);
  272. }
  273. // return result
  274. return r;
  275. };
  276. }
  277. if (HTMLSelectElement && !HTMLSelectElement.prototype.hasOwnProperty('selectedOptions')) {
  278. Object.defineProperty(HTMLSelectElement.prototype, 'selectedOptions', {
  279. get: function () {
  280. return this.querySelectorAll(':checked');
  281. }
  282. });
  283. }
  284. // much faster than $.val()
  285. function getSelectValues (select) {
  286. var result = [];
  287. var options = select.selectedOptions;
  288. var opt;
  289. if (select.multiple) {
  290. for (var i = 0, len = options.length; i < len; i++) {
  291. opt = options[i];
  292. result.push(opt.value || opt.text);
  293. }
  294. } else {
  295. result = select.value;
  296. }
  297. return result;
  298. }
  299. // set data-selected on select element if the value has been programmatically selected
  300. // prior to initialization of bootstrap-select
  301. // * consider removing or replacing an alternative method *
  302. var valHooks = {
  303. useDefault: false,
  304. _set: $.valHooks.select.set
  305. };
  306. $.valHooks.select.set = function (elem, value) {
  307. if (value && !valHooks.useDefault) $(elem).data('selected', true);
  308. return valHooks._set.apply(this, arguments);
  309. };
  310. var changedArguments = null;
  311. var EventIsSupported = (function () {
  312. try {
  313. new Event('change');
  314. return true;
  315. } catch (e) {
  316. return false;
  317. }
  318. })();
  319. $.fn.triggerNative = function (eventName) {
  320. var el = this[0],
  321. event;
  322. if (el.dispatchEvent) { // for modern browsers & IE9+
  323. if (EventIsSupported) {
  324. // For modern browsers
  325. event = new Event(eventName, {
  326. bubbles: true
  327. });
  328. } else {
  329. // For IE since it doesn't support Event constructor
  330. event = document.createEvent('Event');
  331. event.initEvent(eventName, true, false);
  332. }
  333. el.dispatchEvent(event);
  334. } else if (el.fireEvent) { // for IE8
  335. event = document.createEventObject();
  336. event.eventType = eventName;
  337. el.fireEvent('on' + eventName, event);
  338. } else {
  339. // fall back to jQuery.trigger
  340. this.trigger(eventName);
  341. }
  342. };
  343. // </editor-fold>
  344. function stringSearch (li, searchString, method, normalize) {
  345. var stringTypes = [
  346. 'display',
  347. 'subtext',
  348. 'tokens'
  349. ],
  350. searchSuccess = false;
  351. for (var i = 0; i < stringTypes.length; i++) {
  352. var stringType = stringTypes[i],
  353. string = li[stringType];
  354. if (string) {
  355. string = string.toString();
  356. // Strip HTML tags. This isn't perfect, but it's much faster than any other method
  357. if (stringType === 'display') {
  358. string = string.replace(/<[^>]+>/g, '');
  359. }
  360. if (normalize) string = normalizeToBase(string);
  361. string = string.toUpperCase();
  362. if (method === 'contains') {
  363. searchSuccess = string.indexOf(searchString) >= 0;
  364. } else {
  365. searchSuccess = string.startsWith(searchString);
  366. }
  367. if (searchSuccess) break;
  368. }
  369. }
  370. return searchSuccess;
  371. }
  372. function toInteger (value) {
  373. return parseInt(value, 10) || 0;
  374. }
  375. // Borrowed from Lodash (_.deburr)
  376. /** Used to map Latin Unicode letters to basic Latin letters. */
  377. var deburredLetters = {
  378. // Latin-1 Supplement block.
  379. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  380. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  381. '\xc7': 'C', '\xe7': 'c',
  382. '\xd0': 'D', '\xf0': 'd',
  383. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  384. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  385. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  386. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  387. '\xd1': 'N', '\xf1': 'n',
  388. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  389. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  390. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  391. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  392. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  393. '\xc6': 'Ae', '\xe6': 'ae',
  394. '\xde': 'Th', '\xfe': 'th',
  395. '\xdf': 'ss',
  396. // Latin Extended-A block.
  397. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  398. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  399. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  400. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  401. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  402. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  403. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  404. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  405. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  406. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  407. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  408. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  409. '\u0134': 'J', '\u0135': 'j',
  410. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  411. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  412. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  413. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  414. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  415. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  416. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  417. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  418. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  419. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  420. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  421. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  422. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  423. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  424. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  425. '\u0174': 'W', '\u0175': 'w',
  426. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  427. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  428. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  429. '\u0132': 'IJ', '\u0133': 'ij',
  430. '\u0152': 'Oe', '\u0153': 'oe',
  431. '\u0149': "'n", '\u017f': 's'
  432. };
  433. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  434. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  435. /** Used to compose unicode character classes. */
  436. var rsComboMarksRange = '\\u0300-\\u036f',
  437. reComboHalfMarksRange = '\\ufe20-\\ufe2f',
  438. rsComboSymbolsRange = '\\u20d0-\\u20ff',
  439. rsComboMarksExtendedRange = '\\u1ab0-\\u1aff',
  440. rsComboMarksSupplementRange = '\\u1dc0-\\u1dff',
  441. rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange + rsComboMarksExtendedRange + rsComboMarksSupplementRange;
  442. /** Used to compose unicode capture groups. */
  443. var rsCombo = '[' + rsComboRange + ']';
  444. /**
  445. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  446. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  447. */
  448. var reComboMark = RegExp(rsCombo, 'g');
  449. function deburrLetter (key) {
  450. return deburredLetters[key];
  451. };
  452. function normalizeToBase (string) {
  453. string = string.toString();
  454. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  455. }
  456. // List of HTML entities for escaping.
  457. var escapeMap = {
  458. '&': '&amp;',
  459. '<': '&lt;',
  460. '>': '&gt;',
  461. '"': '&quot;',
  462. "'": '&#x27;',
  463. '`': '&#x60;'
  464. };
  465. // Functions for escaping and unescaping strings to/from HTML interpolation.
  466. var createEscaper = function (map) {
  467. var escaper = function (match) {
  468. return map[match];
  469. };
  470. // Regexes for identifying a key that needs to be escaped.
  471. var source = '(?:' + Object.keys(map).join('|') + ')';
  472. var testRegexp = RegExp(source);
  473. var replaceRegexp = RegExp(source, 'g');
  474. return function (string) {
  475. string = string == null ? '' : '' + string;
  476. return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
  477. };
  478. };
  479. var htmlEscape = createEscaper(escapeMap);
  480. /**
  481. * ------------------------------------------------------------------------
  482. * Constants
  483. * ------------------------------------------------------------------------
  484. */
  485. var keyCodeMap = {
  486. 32: ' ',
  487. 48: '0',
  488. 49: '1',
  489. 50: '2',
  490. 51: '3',
  491. 52: '4',
  492. 53: '5',
  493. 54: '6',
  494. 55: '7',
  495. 56: '8',
  496. 57: '9',
  497. 59: ';',
  498. 65: 'A',
  499. 66: 'B',
  500. 67: 'C',
  501. 68: 'D',
  502. 69: 'E',
  503. 70: 'F',
  504. 71: 'G',
  505. 72: 'H',
  506. 73: 'I',
  507. 74: 'J',
  508. 75: 'K',
  509. 76: 'L',
  510. 77: 'M',
  511. 78: 'N',
  512. 79: 'O',
  513. 80: 'P',
  514. 81: 'Q',
  515. 82: 'R',
  516. 83: 'S',
  517. 84: 'T',
  518. 85: 'U',
  519. 86: 'V',
  520. 87: 'W',
  521. 88: 'X',
  522. 89: 'Y',
  523. 90: 'Z',
  524. 96: '0',
  525. 97: '1',
  526. 98: '2',
  527. 99: '3',
  528. 100: '4',
  529. 101: '5',
  530. 102: '6',
  531. 103: '7',
  532. 104: '8',
  533. 105: '9'
  534. };
  535. var keyCodes = {
  536. ESCAPE: 27, // KeyboardEvent.which value for Escape (Esc) key
  537. ENTER: 13, // KeyboardEvent.which value for Enter key
  538. SPACE: 32, // KeyboardEvent.which value for space key
  539. TAB: 9, // KeyboardEvent.which value for tab key
  540. ARROW_UP: 38, // KeyboardEvent.which value for up arrow key
  541. ARROW_DOWN: 40 // KeyboardEvent.which value for down arrow key
  542. }
  543. var version = {
  544. success: false,
  545. major: '3'
  546. };
  547. try {
  548. version.full = ($.fn.dropdown.Constructor.VERSION || '').split(' ')[0].split('.');
  549. version.major = version.full[0];
  550. version.success = true;
  551. } catch (err) {
  552. // do nothing
  553. }
  554. var selectId = 0;
  555. var EVENT_KEY = '.bs.select';
  556. var classNames = {
  557. DISABLED: 'disabled',
  558. DIVIDER: 'divider',
  559. SHOW: 'open',
  560. DROPUP: 'dropup',
  561. MENU: 'dropdown-menu',
  562. MENURIGHT: 'dropdown-menu-right',
  563. MENULEFT: 'dropdown-menu-left',
  564. // to-do: replace with more advanced template/customization options
  565. BUTTONCLASS: 'btn-default',
  566. POPOVERHEADER: 'popover-title',
  567. ICONBASE: 'glyphicon',
  568. TICKICON: 'glyphicon-ok'
  569. }
  570. var Selector = {
  571. MENU: '.' + classNames.MENU
  572. }
  573. var elementTemplates = {
  574. span: document.createElement('span'),
  575. i: document.createElement('i'),
  576. subtext: document.createElement('small'),
  577. a: document.createElement('a'),
  578. li: document.createElement('li'),
  579. whitespace: document.createTextNode('\u00A0'),
  580. fragment: document.createDocumentFragment()
  581. }
  582. elementTemplates.a.setAttribute('role', 'option');
  583. elementTemplates.subtext.className = 'text-muted';
  584. elementTemplates.text = elementTemplates.span.cloneNode(false);
  585. elementTemplates.text.className = 'text';
  586. elementTemplates.checkMark = elementTemplates.span.cloneNode(false);
  587. var REGEXP_ARROW = new RegExp(keyCodes.ARROW_UP + '|' + keyCodes.ARROW_DOWN);
  588. var REGEXP_TAB_OR_ESCAPE = new RegExp('^' + keyCodes.TAB + '$|' + keyCodes.ESCAPE);
  589. var generateOption = {
  590. li: function (content, classes, optgroup) {
  591. var li = elementTemplates.li.cloneNode(false);
  592. if (content) {
  593. if (content.nodeType === 1 || content.nodeType === 11) {
  594. li.appendChild(content);
  595. } else {
  596. li.innerHTML = content;
  597. }
  598. }
  599. if (typeof classes !== 'undefined' && classes !== '') li.className = classes;
  600. if (typeof optgroup !== 'undefined' && optgroup !== null) li.classList.add('optgroup-' + optgroup);
  601. return li;
  602. },
  603. a: function (text, classes, inline) {
  604. var a = elementTemplates.a.cloneNode(true);
  605. if (text) {
  606. if (text.nodeType === 11) {
  607. a.appendChild(text);
  608. } else {
  609. a.insertAdjacentHTML('beforeend', text);
  610. }
  611. }
  612. if (typeof classes !== 'undefined' && classes !== '') a.className = classes;
  613. if (version.major === '4') a.classList.add('dropdown-item');
  614. if (inline) a.setAttribute('style', inline);
  615. return a;
  616. },
  617. text: function (options, useFragment) {
  618. var textElement = elementTemplates.text.cloneNode(false),
  619. subtextElement,
  620. iconElement;
  621. if (options.content) {
  622. textElement.innerHTML = options.content;
  623. } else {
  624. textElement.textContent = options.text;
  625. if (options.icon) {
  626. var whitespace = elementTemplates.whitespace.cloneNode(false);
  627. // need to use <i> for icons in the button to prevent a breaking change
  628. // note: switch to span in next major release
  629. iconElement = (useFragment === true ? elementTemplates.i : elementTemplates.span).cloneNode(false);
  630. iconElement.className = options.iconBase + ' ' + options.icon;
  631. elementTemplates.fragment.appendChild(iconElement);
  632. elementTemplates.fragment.appendChild(whitespace);
  633. }
  634. if (options.subtext) {
  635. subtextElement = elementTemplates.subtext.cloneNode(false);
  636. subtextElement.textContent = options.subtext;
  637. textElement.appendChild(subtextElement);
  638. }
  639. }
  640. if (useFragment === true) {
  641. while (textElement.childNodes.length > 0) {
  642. elementTemplates.fragment.appendChild(textElement.childNodes[0]);
  643. }
  644. } else {
  645. elementTemplates.fragment.appendChild(textElement);
  646. }
  647. return elementTemplates.fragment;
  648. },
  649. label: function (options) {
  650. var textElement = elementTemplates.text.cloneNode(false),
  651. subtextElement,
  652. iconElement;
  653. textElement.innerHTML = options.label;
  654. if (options.icon) {
  655. var whitespace = elementTemplates.whitespace.cloneNode(false);
  656. iconElement = elementTemplates.span.cloneNode(false);
  657. iconElement.className = options.iconBase + ' ' + options.icon;
  658. elementTemplates.fragment.appendChild(iconElement);
  659. elementTemplates.fragment.appendChild(whitespace);
  660. }
  661. if (options.subtext) {
  662. subtextElement = elementTemplates.subtext.cloneNode(false);
  663. subtextElement.textContent = options.subtext;
  664. textElement.appendChild(subtextElement);
  665. }
  666. elementTemplates.fragment.appendChild(textElement);
  667. return elementTemplates.fragment;
  668. }
  669. }
  670. var Selectpicker = function (element, options) {
  671. var that = this;
  672. // bootstrap-select has been initialized - revert valHooks.select.set back to its original function
  673. if (!valHooks.useDefault) {
  674. $.valHooks.select.set = valHooks._set;
  675. valHooks.useDefault = true;
  676. }
  677. this.$element = $(element);
  678. this.$newElement = null;
  679. this.$button = null;
  680. this.$menu = null;
  681. this.options = options;
  682. this.selectpicker = {
  683. main: {},
  684. current: {}, // current changes if a search is in progress
  685. search: {},
  686. view: {},
  687. keydown: {
  688. keyHistory: '',
  689. resetKeyHistory: {
  690. start: function () {
  691. return setTimeout(function () {
  692. that.selectpicker.keydown.keyHistory = '';
  693. }, 800);
  694. }
  695. }
  696. }
  697. };
  698. // 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
  699. // data-attribute)
  700. if (this.options.title === null) {
  701. this.options.title = this.$element.attr('title');
  702. }
  703. // Format window padding
  704. var winPad = this.options.windowPadding;
  705. if (typeof winPad === 'number') {
  706. this.options.windowPadding = [winPad, winPad, winPad, winPad];
  707. }
  708. // Expose public methods
  709. this.val = Selectpicker.prototype.val;
  710. this.render = Selectpicker.prototype.render;
  711. this.refresh = Selectpicker.prototype.refresh;
  712. this.setStyle = Selectpicker.prototype.setStyle;
  713. this.selectAll = Selectpicker.prototype.selectAll;
  714. this.deselectAll = Selectpicker.prototype.deselectAll;
  715. this.destroy = Selectpicker.prototype.destroy;
  716. this.remove = Selectpicker.prototype.remove;
  717. this.show = Selectpicker.prototype.show;
  718. this.hide = Selectpicker.prototype.hide;
  719. this.init();
  720. };
  721. Selectpicker.VERSION = '1.13.9';
  722. // part of this is duplicated in i18n/defaults-en_US.js. Make sure to update both.
  723. Selectpicker.DEFAULTS = {
  724. noneSelectedText: 'Nothing selected',
  725. noneResultsText: 'No results matched {0}',
  726. countSelectedText: function (numSelected, numTotal) {
  727. return (numSelected == 1) ? '{0} item selected' : '{0} items selected';
  728. },
  729. maxOptionsText: function (numAll, numGroup) {
  730. return [
  731. (numAll == 1) ? 'Limit reached ({n} item max)' : 'Limit reached ({n} items max)',
  732. (numGroup == 1) ? 'Group limit reached ({n} item max)' : 'Group limit reached ({n} items max)'
  733. ];
  734. },
  735. selectAllText: 'Select All',
  736. deselectAllText: 'Deselect All',
  737. doneButton: false,
  738. doneButtonText: 'Close',
  739. multipleSeparator: ', ',
  740. styleBase: 'btn',
  741. style: classNames.BUTTONCLASS,
  742. size: 'auto',
  743. title: null,
  744. selectedTextFormat: 'values',
  745. width: false,
  746. container: false,
  747. hideDisabled: false,
  748. showSubtext: false,
  749. showIcon: true,
  750. showContent: true,
  751. dropupAuto: true,
  752. header: false,
  753. liveSearch: false,
  754. liveSearchPlaceholder: null,
  755. liveSearchNormalize: false,
  756. liveSearchStyle: 'contains',
  757. actionsBox: false,
  758. iconBase: classNames.ICONBASE,
  759. tickIcon: classNames.TICKICON,
  760. showTick: false,
  761. template: {
  762. caret: '<span class="caret"></span>'
  763. },
  764. maxOptions: false,
  765. mobile: false,
  766. selectOnTab: false,
  767. dropdownAlignRight: false,
  768. windowPadding: 0,
  769. virtualScroll: 600,
  770. display: false,
  771. sanitize: true,
  772. sanitizeFn: null,
  773. whiteList: DefaultWhitelist
  774. };
  775. Selectpicker.prototype = {
  776. constructor: Selectpicker,
  777. init: function () {
  778. var that = this,
  779. id = this.$element.attr('id');
  780. this.selectId = selectId++;
  781. this.$element[0].classList.add('bs-select-hidden');
  782. this.multiple = this.$element.prop('multiple');
  783. this.autofocus = this.$element.prop('autofocus');
  784. this.options.showTick = this.$element[0].classList.contains('show-tick');
  785. this.$newElement = this.createDropdown();
  786. this.$element
  787. .after(this.$newElement)
  788. .prependTo(this.$newElement);
  789. this.$button = this.$newElement.children('button');
  790. this.$menu = this.$newElement.children(Selector.MENU);
  791. this.$menuInner = this.$menu.children('.inner');
  792. this.$searchbox = this.$menu.find('input');
  793. this.$element[0].classList.remove('bs-select-hidden');
  794. if (this.options.dropdownAlignRight === true) this.$menu[0].classList.add(classNames.MENURIGHT);
  795. if (typeof id !== 'undefined') {
  796. this.$button.attr('data-id', id);
  797. }
  798. this.checkDisabled();
  799. this.clickListener();
  800. if (this.options.liveSearch) this.liveSearchListener();
  801. this.setStyle();
  802. this.render();
  803. this.setWidth();
  804. if (this.options.container) {
  805. this.selectPosition();
  806. } else {
  807. this.$element.on('hide' + EVENT_KEY, function () {
  808. if (that.isVirtual()) {
  809. // empty menu on close
  810. var menuInner = that.$menuInner[0],
  811. emptyMenu = menuInner.firstChild.cloneNode(false);
  812. // replace the existing UL with an empty one - this is faster than $.empty() or innerHTML = ''
  813. menuInner.replaceChild(emptyMenu, menuInner.firstChild);
  814. menuInner.scrollTop = 0;
  815. }
  816. });
  817. }
  818. this.$menu.data('this', this);
  819. this.$newElement.data('this', this);
  820. if (this.options.mobile) this.mobile();
  821. this.$newElement.on({
  822. 'hide.bs.dropdown': function (e) {
  823. that.$menuInner.attr('aria-expanded', false);
  824. that.$element.trigger('hide' + EVENT_KEY, e);
  825. },
  826. 'hidden.bs.dropdown': function (e) {
  827. that.$element.trigger('hidden' + EVENT_KEY, e);
  828. },
  829. 'show.bs.dropdown': function (e) {
  830. that.$menuInner.attr('aria-expanded', true);
  831. that.$element.trigger('show' + EVENT_KEY, e);
  832. },
  833. 'shown.bs.dropdown': function (e) {
  834. that.$element.trigger('shown' + EVENT_KEY, e);
  835. }
  836. });
  837. if (that.$element[0].hasAttribute('required')) {
  838. this.$element.on('invalid' + EVENT_KEY, function () {
  839. that.$button[0].classList.add('bs-invalid');
  840. that.$element
  841. .on('shown' + EVENT_KEY + '.invalid', function () {
  842. that.$element
  843. .val(that.$element.val()) // set the value to hide the validation message in Chrome when menu is opened
  844. .off('shown' + EVENT_KEY + '.invalid');
  845. })
  846. .on('rendered' + EVENT_KEY, function () {
  847. // if select is no longer invalid, remove the bs-invalid class
  848. if (this.validity.valid) that.$button[0].classList.remove('bs-invalid');
  849. that.$element.off('rendered' + EVENT_KEY);
  850. });
  851. that.$button.on('blur' + EVENT_KEY, function () {
  852. that.$element.trigger('focus').trigger('blur');
  853. that.$button.off('blur' + EVENT_KEY);
  854. });
  855. });
  856. }
  857. setTimeout(function () {
  858. that.createLi();
  859. that.$element.trigger('loaded' + EVENT_KEY);
  860. });
  861. },
  862. createDropdown: function () {
  863. // Options
  864. // If we are multiple or showTick option is set, then add the show-tick class
  865. var showTick = (this.multiple || this.options.showTick) ? ' show-tick' : '',
  866. inputGroup = '',
  867. autofocus = this.autofocus ? ' autofocus' : '';
  868. if (version.major < 4 && this.$element.parent().hasClass('input-group')) {
  869. inputGroup = ' input-group-btn';
  870. }
  871. // Elements
  872. var drop,
  873. header = '',
  874. searchbox = '',
  875. actionsbox = '',
  876. donebutton = '';
  877. if (this.options.header) {
  878. header =
  879. '<div class="' + classNames.POPOVERHEADER + '">' +
  880. '<button type="button" class="close" aria-hidden="true">&times;</button>' +
  881. this.options.header +
  882. '</div>';
  883. }
  884. if (this.options.liveSearch) {
  885. searchbox =
  886. '<div class="bs-searchbox">' +
  887. '<input type="text" class="form-control" autocomplete="off"' +
  888. (
  889. this.options.liveSearchPlaceholder === null ? ''
  890. :
  891. ' placeholder="' + htmlEscape(this.options.liveSearchPlaceholder) + '"'
  892. ) +
  893. ' role="textbox" aria-label="Search">' +
  894. '</div>';
  895. }
  896. if (this.multiple && this.options.actionsBox) {
  897. actionsbox =
  898. '<div class="bs-actionsbox">' +
  899. '<div class="btn-group btn-group-sm btn-block">' +
  900. '<button type="button" class="actions-btn bs-select-all btn ' + classNames.BUTTONCLASS + '">' +
  901. this.options.selectAllText +
  902. '</button>' +
  903. '<button type="button" class="actions-btn bs-deselect-all btn ' + classNames.BUTTONCLASS + '">' +
  904. this.options.deselectAllText +
  905. '</button>' +
  906. '</div>' +
  907. '</div>';
  908. }
  909. if (this.multiple && this.options.doneButton) {
  910. donebutton =
  911. '<div class="bs-donebutton">' +
  912. '<div class="btn-group btn-block">' +
  913. '<button type="button" class="btn btn-sm ' + classNames.BUTTONCLASS + '">' +
  914. this.options.doneButtonText +
  915. '</button>' +
  916. '</div>' +
  917. '</div>';
  918. }
  919. drop =
  920. '<div class="dropdown bootstrap-select' + showTick + inputGroup + '">' +
  921. '<button type="button" class="' + this.options.styleBase + ' dropdown-toggle" ' + (this.options.display === 'static' ? 'data-display="static"' : '') + 'data-toggle="dropdown"' + autofocus + ' role="button">' +
  922. '<div class="filter-option">' +
  923. '<div class="filter-option-inner">' +
  924. '<div class="filter-option-inner-inner"></div>' +
  925. '</div> ' +
  926. '</div>' +
  927. (
  928. version.major === '4' ? ''
  929. :
  930. '<span class="bs-caret">' +
  931. this.options.template.caret +
  932. '</span>'
  933. ) +
  934. '</button>' +
  935. '<div class="' + classNames.MENU + ' ' + (version.major === '4' ? '' : classNames.SHOW) + '" role="combobox">' +
  936. header +
  937. searchbox +
  938. actionsbox +
  939. '<div class="inner ' + classNames.SHOW + '" role="listbox" aria-expanded="false" tabindex="-1">' +
  940. '<ul class="' + classNames.MENU + ' inner ' + (version.major === '4' ? classNames.SHOW : '') + '">' +
  941. '</ul>' +
  942. '</div>' +
  943. donebutton +
  944. '</div>' +
  945. '</div>';
  946. return $(drop);
  947. },
  948. setPositionData: function () {
  949. this.selectpicker.view.canHighlight = [];
  950. for (var i = 0; i < this.selectpicker.current.data.length; i++) {
  951. var li = this.selectpicker.current.data[i],
  952. canHighlight = true;
  953. if (li.type === 'divider') {
  954. canHighlight = false;
  955. li.height = this.sizeInfo.dividerHeight;
  956. } else if (li.type === 'optgroup-label') {
  957. canHighlight = false;
  958. li.height = this.sizeInfo.dropdownHeaderHeight;
  959. } else {
  960. li.height = this.sizeInfo.liHeight;
  961. }
  962. if (li.disabled) canHighlight = false;
  963. this.selectpicker.view.canHighlight.push(canHighlight);
  964. li.position = (i === 0 ? 0 : this.selectpicker.current.data[i - 1].position) + li.height;
  965. }
  966. },
  967. isVirtual: function () {
  968. return (this.options.virtualScroll !== false) && (this.selectpicker.main.elements.length >= this.options.virtualScroll) || this.options.virtualScroll === true;
  969. },
  970. createView: function (isSearching, scrollTop) {
  971. scrollTop = scrollTop || 0;
  972. var that = this;
  973. this.selectpicker.current = isSearching ? this.selectpicker.search : this.selectpicker.main;
  974. var active = [];
  975. var selected;
  976. var prevActive;
  977. this.setPositionData();
  978. scroll(scrollTop, true);
  979. this.$menuInner.off('scroll.createView').on('scroll.createView', function (e, updateValue) {
  980. if (!that.noScroll) scroll(this.scrollTop, updateValue);
  981. that.noScroll = false;
  982. });
  983. function scroll (scrollTop, init) {
  984. var size = that.selectpicker.current.elements.length,
  985. chunks = [],
  986. chunkSize,
  987. chunkCount,
  988. firstChunk,
  989. lastChunk,
  990. currentChunk,
  991. prevPositions,
  992. positionIsDifferent,
  993. previousElements,
  994. menuIsDifferent = true,
  995. isVirtual = that.isVirtual();
  996. that.selectpicker.view.scrollTop = scrollTop;
  997. if (isVirtual === true) {
  998. // if an option that is encountered that is wider than the current menu width, update the menu width accordingly
  999. if (that.sizeInfo.hasScrollBar && that.$menu[0].offsetWidth > that.sizeInfo.totalMenuWidth) {
  1000. that.sizeInfo.menuWidth = that.$menu[0].offsetWidth;
  1001. that.sizeInfo.totalMenuWidth = that.sizeInfo.menuWidth + that.sizeInfo.scrollBarWidth;
  1002. that.$menu.css('min-width', that.sizeInfo.menuWidth);
  1003. }
  1004. }
  1005. chunkSize = Math.ceil(that.sizeInfo.menuInnerHeight / that.sizeInfo.liHeight * 1.5); // number of options in a chunk
  1006. chunkCount = Math.round(size / chunkSize) || 1; // number of chunks
  1007. for (var i = 0; i < chunkCount; i++) {
  1008. var endOfChunk = (i + 1) * chunkSize;
  1009. if (i === chunkCount - 1) {
  1010. endOfChunk = size;
  1011. }
  1012. chunks[i] = [
  1013. (i) * chunkSize + (!i ? 0 : 1),
  1014. endOfChunk
  1015. ];
  1016. if (!size) break;
  1017. if (currentChunk === undefined && scrollTop <= that.selectpicker.current.data[endOfChunk - 1].position - that.sizeInfo.menuInnerHeight) {
  1018. currentChunk = i;
  1019. }
  1020. }
  1021. if (currentChunk === undefined) currentChunk = 0;
  1022. prevPositions = [that.selectpicker.view.position0, that.selectpicker.view.position1];
  1023. // always display previous, current, and next chunks
  1024. firstChunk = Math.max(0, currentChunk - 1);
  1025. lastChunk = Math.min(chunkCount - 1, currentChunk + 1);
  1026. that.selectpicker.view.position0 = isVirtual === false ? 0 : (Math.max(0, chunks[firstChunk][0]) || 0);
  1027. that.selectpicker.view.position1 = isVirtual === false ? size : (Math.min(size, chunks[lastChunk][1]) || 0);
  1028. positionIsDifferent = prevPositions[0] !== that.selectpicker.view.position0 || prevPositions[1] !== that.selectpicker.view.position1;
  1029. if (that.activeIndex !== undefined) {
  1030. prevActive = that.selectpicker.main.elements[that.prevActiveIndex];
  1031. active = that.selectpicker.main.elements[that.activeIndex];
  1032. selected = that.selectpicker.main.elements[that.selectedIndex];
  1033. if (init) {
  1034. if (that.activeIndex !== that.selectedIndex && active && active.length) {
  1035. active.classList.remove('active');
  1036. if (active.firstChild) active.firstChild.classList.remove('active');
  1037. }
  1038. that.activeIndex = undefined;
  1039. }
  1040. if (that.activeIndex && that.activeIndex !== that.selectedIndex && selected && selected.length) {
  1041. selected.classList.remove('active');
  1042. if (selected.firstChild) selected.firstChild.classList.remove('active');
  1043. }
  1044. }
  1045. if (that.prevActiveIndex !== undefined && that.prevActiveIndex !== that.activeIndex && that.prevActiveIndex !== that.selectedIndex && prevActive && prevActive.length) {
  1046. prevActive.classList.remove('active');
  1047. if (prevActive.firstChild) prevActive.firstChild.classList.remove('active');
  1048. }
  1049. if (init || positionIsDifferent) {
  1050. previousElements = that.selectpicker.view.visibleElements ? that.selectpicker.view.visibleElements.slice() : [];
  1051. if (isVirtual === false) {
  1052. that.selectpicker.view.visibleElements = that.selectpicker.current.elements;
  1053. } else {
  1054. that.selectpicker.view.visibleElements = that.selectpicker.current.elements.slice(that.selectpicker.view.position0, that.selectpicker.view.position1);
  1055. }
  1056. that.setOptionStatus();
  1057. // if searching, check to make sure the list has actually been updated before updating DOM
  1058. // this prevents unnecessary repaints
  1059. if (isSearching || (isVirtual === false && init)) menuIsDifferent = !isEqual(previousElements, that.selectpicker.view.visibleElements);
  1060. // if virtual scroll is disabled and not searching,
  1061. // menu should never need to be updated more than once
  1062. if ((init || isVirtual === true) && menuIsDifferent) {
  1063. var menuInner = that.$menuInner[0],
  1064. menuFragment = document.createDocumentFragment(),
  1065. emptyMenu = menuInner.firstChild.cloneNode(false),
  1066. marginTop,
  1067. marginBottom,
  1068. elements = that.selectpicker.view.visibleElements,
  1069. toSanitize = [];
  1070. // replace the existing UL with an empty one - this is faster than $.empty()
  1071. menuInner.replaceChild(emptyMenu, menuInner.firstChild);
  1072. for (var i = 0, visibleElementsLen = elements.length; i < visibleElementsLen; i++) {
  1073. var element = elements[i],
  1074. elText,
  1075. elementData;
  1076. if (that.options.sanitize) {
  1077. elText = element.lastChild;
  1078. if (elText) {
  1079. elementData = that.selectpicker.current.data[i + that.selectpicker.view.position0];
  1080. if (elementData && elementData.content && !elementData.sanitized) {
  1081. toSanitize.push(elText);
  1082. elementData.sanitized = true;
  1083. }
  1084. }
  1085. }
  1086. menuFragment.appendChild(element);
  1087. }
  1088. if (that.options.sanitize && toSanitize.length) {
  1089. sanitizeHtml(toSanitize, that.options.whiteList, that.options.sanitizeFn);
  1090. }
  1091. if (isVirtual === true) {
  1092. marginTop = (that.selectpicker.view.position0 === 0 ? 0 : that.selectpicker.current.data[that.selectpicker.view.position0 - 1].position);
  1093. 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);
  1094. menuInner.firstChild.style.marginTop = marginTop + 'px';
  1095. menuInner.firstChild.style.marginBottom = marginBottom + 'px';
  1096. }
  1097. menuInner.firstChild.appendChild(menuFragment);
  1098. }
  1099. }
  1100. that.prevActiveIndex = that.activeIndex;
  1101. if (!that.options.liveSearch) {
  1102. that.$menuInner.trigger('focus');
  1103. } else if (isSearching && init) {
  1104. var index = 0,
  1105. newActive;
  1106. if (!that.selectpicker.view.canHighlight[index]) {
  1107. index = 1 + that.selectpicker.view.canHighlight.slice(1).indexOf(true);
  1108. }
  1109. newActive = that.selectpicker.view.visibleElements[index];
  1110. if (that.selectpicker.view.currentActive) {
  1111. that.selectpicker.view.currentActive.classList.remove('active');
  1112. if (that.selectpicker.view.currentActive.firstChild) that.selectpicker.view.currentActive.firstChild.classList.remove('active');
  1113. }
  1114. if (newActive) {
  1115. newActive.classList.add('active');
  1116. if (newActive.firstChild) newActive.firstChild.classList.add('active');
  1117. }
  1118. that.activeIndex = (that.selectpicker.current.data[index] || {}).index;
  1119. }
  1120. }
  1121. $(window)
  1122. .off('resize' + EVENT_KEY + '.' + this.selectId + '.createView')
  1123. .on('resize' + EVENT_KEY + '.' + this.selectId + '.createView', function () {
  1124. var isActive = that.$newElement.hasClass(classNames.SHOW);
  1125. if (isActive) scroll(that.$menuInner[0].scrollTop);
  1126. });
  1127. },
  1128. setPlaceholder: function () {
  1129. var updateIndex = false;
  1130. if (this.options.title && !this.multiple) {
  1131. if (!this.selectpicker.view.titleOption) this.selectpicker.view.titleOption = document.createElement('option');
  1132. // this option doesn't create a new <li> element, but does add a new option at the start,
  1133. // so startIndex should increase to prevent having to check every option for the bs-title-option class
  1134. updateIndex = true;
  1135. var element = this.$element[0],
  1136. isSelected = false,
  1137. titleNotAppended = !this.selectpicker.view.titleOption.parentNode;
  1138. if (titleNotAppended) {
  1139. // Use native JS to prepend option (faster)
  1140. this.selectpicker.view.titleOption.className = 'bs-title-option';
  1141. this.selectpicker.view.titleOption.value = '';
  1142. // Check if selected or data-selected attribute is already set on an option. If not, select the titleOption option.
  1143. // the selected item may have been changed by user or programmatically before the bootstrap select plugin runs,
  1144. // if so, the select will have the data-selected attribute
  1145. var $opt = $(element.options[element.selectedIndex]);
  1146. isSelected = $opt.attr('selected') === undefined && this.$element.data('selected') === undefined;
  1147. }
  1148. if (titleNotAppended || this.selectpicker.view.titleOption.index !== 0) {
  1149. element.insertBefore(this.selectpicker.view.titleOption, element.firstChild);
  1150. }
  1151. // Set selected *after* appending to select,
  1152. // otherwise the option doesn't get selected in IE
  1153. // set using selectedIndex, as setting the selected attr to true here doesn't work in IE11
  1154. if (isSelected) element.selectedIndex = 0;
  1155. }
  1156. return updateIndex;
  1157. },
  1158. createLi: function () {
  1159. var that = this,
  1160. iconBase = this.options.iconBase,
  1161. optionSelector = ':not([hidden]):not([data-hidden="true"])',
  1162. mainElements = [],
  1163. mainData = [],
  1164. widestOptionLength = 0,
  1165. optID = 0,
  1166. startIndex = this.setPlaceholder() ? 1 : 0; // append the titleOption if necessary and skip the first option in the loop
  1167. if (this.options.hideDisabled) optionSelector += ':not(:disabled)';
  1168. if ((that.options.showTick || that.multiple) && !elementTemplates.checkMark.parentNode) {
  1169. elementTemplates.checkMark.className = iconBase + ' ' + that.options.tickIcon + ' check-mark';
  1170. elementTemplates.a.appendChild(elementTemplates.checkMark);
  1171. }
  1172. var selectOptions = this.$element[0].querySelectorAll('select > *' + optionSelector);
  1173. function addDivider (config) {
  1174. var previousData = mainData[mainData.length - 1];
  1175. // ensure optgroup doesn't create back-to-back dividers
  1176. if (
  1177. previousData &&
  1178. previousData.type === 'divider' &&
  1179. (previousData.optID || config.optID)
  1180. ) {
  1181. return;
  1182. }
  1183. config = config || {};
  1184. config.type = 'divider';
  1185. mainElements.push(
  1186. generateOption.li(
  1187. false,
  1188. classNames.DIVIDER,
  1189. (config.optID ? config.optID + 'div' : undefined)
  1190. )
  1191. );
  1192. mainData.push(config);
  1193. }
  1194. function addOption (option, config) {
  1195. config = config || {};
  1196. config.divider = option.getAttribute('data-divider') === 'true';
  1197. if (config.divider) {
  1198. addDivider({
  1199. optID: config.optID
  1200. });
  1201. } else {
  1202. var liIndex = mainData.length,
  1203. cssText = option.style.cssText,
  1204. inlineStyle = cssText ? htmlEscape(cssText) : '',
  1205. optionClass = (option.className || '') + (config.optgroupClass || '');
  1206. if (config.optID) optionClass = 'opt ' + optionClass;
  1207. config.text = option.textContent;
  1208. config.content = option.getAttribute('data-content');
  1209. config.tokens = option.getAttribute('data-tokens');
  1210. config.subtext = option.getAttribute('data-subtext');
  1211. config.icon = option.getAttribute('data-icon');
  1212. config.iconBase = iconBase;
  1213. var textElement = generateOption.text(config);
  1214. mainElements.push(
  1215. generateOption.li(
  1216. generateOption.a(
  1217. textElement,
  1218. optionClass,
  1219. inlineStyle
  1220. ),
  1221. '',
  1222. config.optID
  1223. )
  1224. );
  1225. option.liIndex = liIndex;
  1226. config.display = config.content || config.text;
  1227. config.type = 'option';
  1228. config.index = liIndex;
  1229. config.option = option;
  1230. config.disabled = config.disabled || option.disabled;
  1231. mainData.push(config);
  1232. var combinedLength = 0;
  1233. // count the number of characters in the option - not perfect, but should work in most cases
  1234. if (config.display) combinedLength += config.display.length;
  1235. if (config.subtext) combinedLength += config.subtext.length;
  1236. // if there is an icon, ensure this option's width is checked
  1237. if (config.icon) combinedLength += 1;
  1238. if (combinedLength > widestOptionLength) {
  1239. widestOptionLength = combinedLength;
  1240. // guess which option is the widest
  1241. // use this when calculating menu width
  1242. // not perfect, but it's fast, and the width will be updating accordingly when scrolling
  1243. that.selectpicker.view.widestOption = mainElements[mainElements.length - 1];
  1244. }
  1245. }
  1246. }
  1247. function addOptgroup (index, selectOptions) {
  1248. var optgroup = selectOptions[index],
  1249. previous = selectOptions[index - 1],
  1250. next = selectOptions[index + 1],
  1251. options = optgroup.querySelectorAll('option' + optionSelector);
  1252. if (!options.length) return;
  1253. var config = {
  1254. label: htmlEscape(optgroup.label),
  1255. subtext: optgroup.getAttribute('data-subtext'),
  1256. icon: optgroup.getAttribute('data-icon'),
  1257. iconBase: iconBase
  1258. },
  1259. optgroupClass = ' ' + (optgroup.className || ''),
  1260. headerIndex,
  1261. lastIndex;
  1262. optID++;
  1263. if (previous) {
  1264. addDivider({ optID: optID });
  1265. }
  1266. var labelElement = generateOption.label(config);
  1267. mainElements.push(
  1268. generateOption.li(labelElement, 'dropdown-header' + optgroupClass, optID)
  1269. );
  1270. mainData.push({
  1271. display: config.label,
  1272. subtext: config.subtext,
  1273. type: 'optgroup-label',
  1274. optID: optID
  1275. });
  1276. for (var j = 0, len = options.length; j < len; j++) {
  1277. var option = options[j];
  1278. if (j === 0) {
  1279. headerIndex = mainData.length - 1;
  1280. lastIndex = headerIndex + len;
  1281. }
  1282. addOption(option, {
  1283. headerIndex: headerIndex,
  1284. lastIndex: lastIndex,
  1285. optID: optID,
  1286. optgroupClass: optgroupClass,
  1287. disabled: optgroup.disabled
  1288. });
  1289. }
  1290. if (next) {
  1291. addDivider({ optID: optID });
  1292. }
  1293. }
  1294. for (var len = selectOptions.length; startIndex < len; startIndex++) {
  1295. var item = selectOptions[startIndex];
  1296. if (item.tagName !== 'OPTGROUP') {
  1297. addOption(item, {});
  1298. } else {
  1299. addOptgroup(startIndex, selectOptions);
  1300. }
  1301. }
  1302. this.selectpicker.main.elements = mainElements;
  1303. this.selectpicker.main.data = mainData;
  1304. this.selectpicker.current = this.selectpicker.main;
  1305. },
  1306. findLis: function () {
  1307. return this.$menuInner.find('.inner > li');
  1308. },
  1309. render: function () {
  1310. // ensure titleOption is appended and selected (if necessary) before getting selectedOptions
  1311. this.setPlaceholder();
  1312. var that = this,
  1313. selectedOptions = this.$element[0].selectedOptions,
  1314. selectedCount = selectedOptions.length,
  1315. button = this.$button[0],
  1316. buttonInner = button.querySelector('.filter-option-inner-inner'),
  1317. multipleSeparator = document.createTextNode(this.options.multipleSeparator),
  1318. titleFragment = elementTemplates.fragment.cloneNode(false),
  1319. showCount,
  1320. countMax,
  1321. hasContent = false;
  1322. this.togglePlaceholder();
  1323. this.tabIndex();
  1324. if (this.options.selectedTextFormat === 'static') {
  1325. titleFragment = generateOption.text({ text: this.options.title }, true);
  1326. } else {
  1327. showCount = this.multiple && this.options.selectedTextFormat.indexOf('count') !== -1 && selectedCount > 1;
  1328. // determine if the number of selected options will be shown (showCount === true)
  1329. if (showCount) {
  1330. countMax = this.options.selectedTextFormat.split('>');
  1331. showCount = (countMax.length > 1 && selectedCount > countMax[1]) || (countMax.length === 1 && selectedCount >= 2);
  1332. }
  1333. // only loop through all selected options if the count won't be shown
  1334. if (showCount === false) {
  1335. for (var selectedIndex = 0; selectedIndex < selectedCount; selectedIndex++) {
  1336. if (selectedIndex < 50) {
  1337. var option = selectedOptions[selectedIndex],
  1338. titleOptions = {},
  1339. thisData = {
  1340. content: option.getAttribute('data-content'),
  1341. subtext: option.getAttribute('data-subtext'),
  1342. icon: option.getAttribute('data-icon')
  1343. };
  1344. if (this.multiple && selectedIndex > 0) {
  1345. titleFragment.appendChild(multipleSeparator.cloneNode(false));
  1346. }
  1347. if (option.title) {
  1348. titleOptions.text = option.title;
  1349. } else if (thisData.content && that.options.showContent) {
  1350. titleOptions.content = thisData.content.toString();
  1351. hasContent = true;
  1352. } else {
  1353. if (that.options.showIcon) {
  1354. titleOptions.icon = thisData.icon;
  1355. titleOptions.iconBase = this.options.iconBase;
  1356. }
  1357. if (that.options.showSubtext && !that.multiple && thisData.subtext) titleOptions.subtext = ' ' + thisData.subtext;
  1358. titleOptions.text = option.textContent.trim();
  1359. }
  1360. titleFragment.appendChild(generateOption.text(titleOptions, true));
  1361. } else {
  1362. break;
  1363. }
  1364. }
  1365. // add ellipsis
  1366. if (selectedCount > 49) {
  1367. titleFragment.appendChild(document.createTextNode('...'));
  1368. }
  1369. } else {
  1370. var optionSelector = ':not([hidden]):not([data-hidden="true"]):not([data-divider="true"])';
  1371. if (this.options.hideDisabled) optionSelector += ':not(:disabled)';
  1372. // If this is a multiselect, and selectedTextFormat is count, then show 1 of 2 selected, etc.
  1373. var totalCount = this.$element[0].querySelectorAll('select > option' + optionSelector + ', optgroup' + optionSelector + ' option' + optionSelector).length,
  1374. tr8nText = (typeof this.options.countSelectedText === 'function') ? this.options.countSelectedText(selectedCount, totalCount) : this.options.countSelectedText;
  1375. titleFragment = generateOption.text({
  1376. text: tr8nText.replace('{0}', selectedCount.toString()).replace('{1}', totalCount.toString())
  1377. }, true);
  1378. }
  1379. }
  1380. if (this.options.title == undefined) {
  1381. // use .attr to ensure undefined is returned if title attribute is not set
  1382. this.options.title = this.$element.attr('title');
  1383. }
  1384. // If the select doesn't have a title, then use the default, or if nothing is set at all, use noneSelectedText
  1385. if (!titleFragment.childNodes.length) {
  1386. titleFragment = generateOption.text({
  1387. text: typeof this.options.title !== 'undefined' ? this.options.title : this.options.noneSelectedText
  1388. }, true);
  1389. }
  1390. // strip all HTML tags and trim the result, then unescape any escaped tags
  1391. button.title = titleFragment.textContent.replace(/<[^>]*>?/g, '').trim();
  1392. if (this.options.sanitize && hasContent) {
  1393. sanitizeHtml([titleFragment], that.options.whiteList, that.options.sanitizeFn);
  1394. }
  1395. buttonInner.innerHTML = '';
  1396. buttonInner.appendChild(titleFragment);
  1397. if (version.major < 4 && this.$newElement[0].classList.contains('bs3-has-addon')) {
  1398. var filterExpand = button.querySelector('.filter-expand'),
  1399. clone = buttonInner.cloneNode(true);
  1400. clone.className = 'filter-expand';
  1401. if (filterExpand) {
  1402. button.replaceChild(clone, filterExpand);
  1403. } else {
  1404. button.appendChild(clone);
  1405. }
  1406. }
  1407. this.$element.trigger('rendered' + EVENT_KEY);
  1408. },
  1409. /**
  1410. * @param [style]
  1411. * @param [status]
  1412. */
  1413. setStyle: function (newStyle, status) {
  1414. var button = this.$button[0],
  1415. newElement = this.$newElement[0],
  1416. style = this.options.style.trim(),
  1417. buttonClass;
  1418. if (this.$element.attr('class')) {
  1419. this.$newElement.addClass(this.$element.attr('class').replace(/selectpicker|mobile-device|bs-select-hidden|validate\[.*\]/gi, ''));
  1420. }
  1421. if (version.major < 4) {
  1422. newElement.classList.add('bs3');
  1423. if (newElement.parentNode.classList.contains('input-group') &&
  1424. (newElement.previousElementSibling || newElement.nextElementSibling) &&
  1425. (newElement.previousElementSibling || newElement.nextElementSibling).classList.contains('input-group-addon')
  1426. ) {
  1427. newElement.classList.add('bs3-has-addon');
  1428. }
  1429. }
  1430. if (newStyle) {
  1431. buttonClass = newStyle.trim();
  1432. } else {
  1433. buttonClass = style;
  1434. }
  1435. if (status == 'add') {
  1436. if (buttonClass) button.classList.add.apply(button.classList, buttonClass.split(' '));
  1437. } else if (status == 'remove') {
  1438. if (buttonClass) button.classList.remove.apply(button.classList, buttonClass.split(' '));
  1439. } else {
  1440. if (style) button.classList.remove.apply(button.classList, style.split(' '));
  1441. if (buttonClass) button.classList.add.apply(button.classList, buttonClass.split(' '));
  1442. }
  1443. },
  1444. liHeight: function (refresh) {
  1445. if (!refresh && (this.options.size === false || this.sizeInfo)) return;
  1446. if (!this.sizeInfo) this.sizeInfo = {};
  1447. var newElement = document.createElement('div'),
  1448. menu = document.createElement('div'),
  1449. menuInner = document.createElement('div'),
  1450. menuInnerInner = document.createElement('ul'),
  1451. divider = document.createElement('li'),
  1452. dropdownHeader = document.createElement('li'),
  1453. li = document.createElement('li'),
  1454. a = document.createElement('a'),
  1455. text = document.createElement('span'),
  1456. header = this.options.header && this.$menu.find('.' + classNames.POPOVERHEADER).length > 0 ? this.$menu.find('.' + classNames.POPOVERHEADER)[0].cloneNode(true) : null,
  1457. search = this.options.liveSearch ? document.createElement('div') : null,
  1458. actions = this.options.actionsBox && this.multiple && this.$menu.find('.bs-actionsbox').length > 0 ? this.$menu.find('.bs-actionsbox')[0].cloneNode(true) : null,
  1459. doneButton = this.options.doneButton && this.multiple && this.$menu.find('.bs-donebutton').length > 0 ? this.$menu.find('.bs-donebutton')[0].cloneNode(true) : null,
  1460. firstOption = this.$element.find('option')[0];
  1461. this.sizeInfo.selectWidth = this.$newElement[0].offsetWidth;
  1462. text.className = 'text';
  1463. a.className = 'dropdown-item ' + (firstOption ? firstOption.className : '');
  1464. newElement.className = this.$menu[0].parentNode.className + ' ' + classNames.SHOW;
  1465. newElement.style.width = this.sizeInfo.selectWidth + 'px';
  1466. if (this.options.width === 'auto') menu.style.minWidth = 0;
  1467. menu.className = classNames.MENU + ' ' + classNames.SHOW;
  1468. menuInner.className = 'inner ' + classNames.SHOW;
  1469. menuInnerInner.className = classNames.MENU + ' inner ' + (version.major === '4' ? classNames.SHOW : '');
  1470. divider.className = classNames.DIVIDER;
  1471. dropdownHeader.className = 'dropdown-header';
  1472. text.appendChild(document.createTextNode('\u200b'));
  1473. a.appendChild(text);
  1474. li.appendChild(a);
  1475. dropdownHeader.appendChild(text.cloneNode(true));
  1476. if (this.selectpicker.view.widestOption) {
  1477. menuInnerInner.appendChild(this.selectpicker.view.widestOption.cloneNode(true));
  1478. }
  1479. menuInnerInner.appendChild(li);
  1480. menuInnerInner.appendChild(divider);
  1481. menuInnerInner.appendChild(dropdownHeader);
  1482. if (header) menu.appendChild(header);
  1483. if (search) {
  1484. var input = document.createElement('input');
  1485. search.className = 'bs-searchbox';
  1486. input.className = 'form-control';
  1487. search.appendChild(input);
  1488. menu.appendChild(search);
  1489. }
  1490. if (actions) menu.appendChild(actions);
  1491. menuInner.appendChild(menuInnerInner);
  1492. menu.appendChild(menuInner);
  1493. if (doneButton) menu.appendChild(doneButton);
  1494. newElement.appendChild(menu);
  1495. document.body.appendChild(newElement);
  1496. var liHeight = li.offsetHeight,
  1497. dropdownHeaderHeight = dropdownHeader ? dropdownHeader.offsetHeight : 0,
  1498. headerHeight = header ? header.offsetHeight : 0,
  1499. searchHeight = search ? search.offsetHeight : 0,
  1500. actionsHeight = actions ? actions.offsetHeight : 0,
  1501. doneButtonHeight = doneButton ? doneButton.offsetHeight : 0,
  1502. dividerHeight = $(divider).outerHeight(true),
  1503. // fall back to jQuery if getComputedStyle is not supported
  1504. menuStyle = window.getComputedStyle ? window.getComputedStyle(menu) : false,
  1505. menuWidth = menu.offsetWidth,
  1506. $menu = menuStyle ? null : $(menu),
  1507. menuPadding = {
  1508. vert: toInteger(menuStyle ? menuStyle.paddingTop : $menu.css('paddingTop')) +
  1509. toInteger(menuStyle ? menuStyle.paddingBottom : $menu.css('paddingBottom')) +
  1510. toInteger(menuStyle ? menuStyle.borderTopWidth : $menu.css('borderTopWidth')) +
  1511. toInteger(menuStyle ? menuStyle.borderBottomWidth : $menu.css('borderBottomWidth')),
  1512. horiz: toInteger(menuStyle ? menuStyle.paddingLeft : $menu.css('paddingLeft')) +
  1513. toInteger(menuStyle ? menuStyle.paddingRight : $menu.css('paddingRight')) +
  1514. toInteger(menuStyle ? menuStyle.borderLeftWidth : $menu.css('borderLeftWidth')) +
  1515. toInteger(menuStyle ? menuStyle.borderRightWidth : $menu.css('borderRightWidth'))
  1516. },
  1517. menuExtras = {
  1518. vert: menuPadding.vert +
  1519. toInteger(menuStyle ? menuStyle.marginTop : $menu.css('marginTop')) +
  1520. toInteger(menuStyle ? menuStyle.marginBottom : $menu.css('marginBottom')) + 2,
  1521. horiz: menuPadding.horiz +
  1522. toInteger(menuStyle ? menuStyle.marginLeft : $menu.css('marginLeft')) +
  1523. toInteger(menuStyle ? menuStyle.marginRight : $menu.css('marginRight')) + 2
  1524. },
  1525. scrollBarWidth;
  1526. menuInner.style.overflowY = 'scroll';
  1527. scrollBarWidth = menu.offsetWidth - menuWidth;
  1528. document.body.removeChild(newElement);
  1529. this.sizeInfo.liHeight = liHeight;
  1530. this.sizeInfo.dropdownHeaderHeight = dropdownHeaderHeight;
  1531. this.sizeInfo.headerHeight = headerHeight;
  1532. this.sizeInfo.searchHeight = searchHeight;
  1533. this.sizeInfo.actionsHeight = actionsHeight;
  1534. this.sizeInfo.doneButtonHeight = doneButtonHeight;
  1535. this.sizeInfo.dividerHeight = dividerHeight;
  1536. this.sizeInfo.menuPadding = menuPadding;
  1537. this.sizeInfo.menuExtras = menuExtras;
  1538. this.sizeInfo.menuWidth = menuWidth;
  1539. this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth;
  1540. this.sizeInfo.scrollBarWidth = scrollBarWidth;
  1541. this.sizeInfo.selectHeight = this.$newElement[0].offsetHeight;
  1542. this.setPositionData();
  1543. },
  1544. getSelectPosition: function () {
  1545. var that = this,
  1546. $window = $(window),
  1547. pos = that.$newElement.offset(),
  1548. $container = $(that.options.container),
  1549. containerPos;
  1550. if (that.options.container && $container.length && !$container.is('body')) {
  1551. containerPos = $container.offset();
  1552. containerPos.top += parseInt($container.css('borderTopWidth'));
  1553. containerPos.left += parseInt($container.css('borderLeftWidth'));
  1554. } else {
  1555. containerPos = { top: 0, left: 0 };
  1556. }
  1557. var winPad = that.options.windowPadding;
  1558. this.sizeInfo.selectOffsetTop = pos.top - containerPos.top - $window.scrollTop();
  1559. this.sizeInfo.selectOffsetBot = $window.height() - this.sizeInfo.selectOffsetTop - this.sizeInfo.selectHeight - containerPos.top - winPad[2];
  1560. this.sizeInfo.selectOffsetLeft = pos.left - containerPos.left - $window.scrollLeft();
  1561. this.sizeInfo.selectOffsetRight = $window.width() - this.sizeInfo.selectOffsetLeft - this.sizeInfo.selectWidth - containerPos.left - winPad[1];
  1562. this.sizeInfo.selectOffsetTop -= winPad[0];
  1563. this.sizeInfo.selectOffsetLeft -= winPad[3];
  1564. },
  1565. setMenuSize: function (isAuto) {
  1566. this.getSelectPosition();
  1567. var selectWidth = this.sizeInfo.selectWidth,
  1568. liHeight = this.sizeInfo.liHeight,
  1569. headerHeight = this.sizeInfo.headerHeight,
  1570. searchHeight = this.sizeInfo.searchHeight,
  1571. actionsHeight = this.sizeInfo.actionsHeight,
  1572. doneButtonHeight = this.sizeInfo.doneButtonHeight,
  1573. divHeight = this.sizeInfo.dividerHeight,
  1574. menuPadding = this.sizeInfo.menuPadding,
  1575. menuInnerHeight,
  1576. menuHeight,
  1577. divLength = 0,
  1578. minHeight,
  1579. _minHeight,
  1580. maxHeight,
  1581. menuInnerMinHeight,
  1582. estimate;
  1583. if (this.options.dropupAuto) {
  1584. // Get the estimated height of the menu without scrollbars.
  1585. // This is useful for smaller menus, where there might be plenty of room
  1586. // below the button without setting dropup, but we can't know
  1587. // the exact height of the menu until createView is called later
  1588. estimate = liHeight * this.selectpicker.current.elements.length + menuPadding.vert;
  1589. this.$newElement.toggleClass(classNames.DROPUP, this.sizeInfo.selectOffsetTop - this.sizeInfo.selectOffsetBot > this.sizeInfo.menuExtras.vert && estimate + this.sizeInfo.menuExtras.vert + 50 > this.sizeInfo.selectOffsetBot);
  1590. }
  1591. if (this.options.size === 'auto') {
  1592. _minHeight = this.selectpicker.current.elements.length > 3 ? this.sizeInfo.liHeight * 3 + this.sizeInfo.menuExtras.vert - 2 : 0;
  1593. menuHeight = this.sizeInfo.selectOffsetBot - this.sizeInfo.menuExtras.vert;
  1594. minHeight = _minHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight;
  1595. menuInnerMinHeight = Math.max(_minHeight - menuPadding.vert, 0);
  1596. if (this.$newElement.hasClass(classNames.DROPUP)) {
  1597. menuHeight = this.sizeInfo.selectOffsetTop - this.sizeInfo.menuExtras.vert;
  1598. }
  1599. maxHeight = menuHeight;
  1600. menuInnerHeight = menuHeight - headerHeight - searchHeight - actionsHeight - doneButtonHeight - menuPadding.vert;
  1601. } else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) {
  1602. for (var i = 0; i < this.options.size; i++) {
  1603. if (this.selectpicker.current.data[i].type === 'divider') divLength++;
  1604. }
  1605. menuHeight = liHeight * this.options.size + divLength * divHeight + menuPadding.vert;
  1606. menuInnerHeight = menuHeight - menuPadding.vert;
  1607. maxHeight = menuHeight + headerHeight + searchHeight + actionsHeight + doneButtonHeight;
  1608. minHeight = menuInnerMinHeight = '';
  1609. }
  1610. if (this.options.dropdownAlignRight === 'auto') {
  1611. this.$menu.toggleClass(classNames.MENURIGHT, this.sizeInfo.selectOffsetLeft > this.sizeInfo.selectOffsetRight && this.sizeInfo.selectOffsetRight < (this.sizeInfo.totalMenuWidth - selectWidth));
  1612. }
  1613. this.$menu.css({
  1614. 'max-height': maxHeight + 'px',
  1615. 'overflow': 'hidden',
  1616. 'min-height': minHeight + 'px'
  1617. });
  1618. this.$menuInner.css({
  1619. 'max-height': menuInnerHeight + 'px',
  1620. 'overflow-y': 'auto',
  1621. 'min-height': menuInnerMinHeight + 'px'
  1622. });
  1623. // ensure menuInnerHeight is always a positive number to prevent issues calculating chunkSize in createView
  1624. this.sizeInfo.menuInnerHeight = Math.max(menuInnerHeight, 1);
  1625. if (this.selectpicker.current.data.length && this.selectpicker.current.data[this.selectpicker.current.data.length - 1].position > this.sizeInfo.menuInnerHeight) {
  1626. this.sizeInfo.hasScrollBar = true;
  1627. this.sizeInfo.totalMenuWidth = this.sizeInfo.menuWidth + this.sizeInfo.scrollBarWidth;
  1628. this.$menu.css('min-width', this.sizeInfo.totalMenuWidth);
  1629. }
  1630. if (this.dropdown && this.dropdown._popper) this.dropdown._popper.update();
  1631. },
  1632. setSize: function (refresh) {
  1633. this.liHeight(refresh);
  1634. if (this.options.header) this.$menu.css('padding-top', 0);
  1635. if (this.options.size === false) return;
  1636. var that = this,
  1637. $window = $(window),
  1638. selectedIndex,
  1639. offset = 0;
  1640. this.setMenuSize();
  1641. if (this.options.liveSearch) {
  1642. this.$searchbox
  1643. .off('input.setMenuSize propertychange.setMenuSize')
  1644. .on('input.setMenuSize propertychange.setMenuSize', function () {
  1645. return that.setMenuSize();
  1646. });
  1647. }
  1648. if (this.options.size === 'auto') {
  1649. $window
  1650. .off('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize')
  1651. .on('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize', function () {
  1652. return that.setMenuSize();
  1653. });
  1654. } else if (this.options.size && this.options.size != 'auto' && this.selectpicker.current.elements.length > this.options.size) {
  1655. $window.off('resize' + EVENT_KEY + '.' + this.selectId + '.setMenuSize' + ' scroll' + EVENT_KEY + '.' + this.selectId + '.setMenuSize');
  1656. }
  1657. if (refresh) {
  1658. offset = this.$menuInner[0].scrollTop;
  1659. } else if (!that.multiple) {
  1660. var element = that.$element[0];
  1661. selectedIndex = (element.options[element.selectedIndex] || {}).liIndex;
  1662. if (typeof selectedIndex === 'number' && that.options.size !== false) {
  1663. offset = that.sizeInfo.liHeight * selectedIndex;
  1664. offset = offset - (that.sizeInfo.menuInnerHeight / 2) + (that.sizeInfo.liHeight / 2);
  1665. }
  1666. }
  1667. that.createView(false, offset);
  1668. },
  1669. setWidth: function () {
  1670. var that = this;
  1671. if (this.options.width === 'auto') {
  1672. requestAnimationFrame(function () {
  1673. that.$menu.css('min-width', '0');
  1674. that.$element.on('loaded' + EVENT_KEY, function () {
  1675. that.liHeight();
  1676. that.setMenuSize();
  1677. // Get correct width if element is hidden
  1678. var $selectClone = that.$newElement.clone().appendTo('body'),
  1679. btnWidth = $selectClone.css('width', 'auto').children('button').outerWidth();
  1680. $selectClone.remove();
  1681. // Set width to whatever's larger, button title or longest option
  1682. that.sizeInfo.selectWidth = Math.max(that.sizeInfo.totalMenuWidth, btnWidth);
  1683. that.$newElement.css('width', that.sizeInfo.selectWidth + 'px');
  1684. });
  1685. });
  1686. } else if (this.options.width === 'fit') {
  1687. // Remove inline min-width so width can be changed from 'auto'
  1688. this.$menu.css('min-width', '');
  1689. this.$newElement.css('width', '').addClass('fit-width');
  1690. } else if (this.options.width) {
  1691. // Remove inline min-width so width can be changed from 'auto'
  1692. this.$menu.css('min-width', '');
  1693. this.$newElement.css('width', this.options.width);
  1694. } else {
  1695. // Remove inline min-width/width so width can be changed
  1696. this.$menu.css('min-width', '');
  1697. this.$newElement.css('width', '');
  1698. }
  1699. // Remove fit-width class if width is changed programmatically
  1700. if (this.$newElement.hasClass('fit-width') && this.options.width !== 'fit') {
  1701. this.$newElement[0].classList.remove('fit-width');
  1702. }
  1703. },
  1704. selectPosition: function () {
  1705. this.$bsContainer = $('<div class="bs-container" />');
  1706. var that = this,
  1707. $container = $(this.options.container),
  1708. pos,
  1709. containerPos,
  1710. actualHeight,
  1711. getPlacement = function ($element) {
  1712. var containerPosition = {},
  1713. // fall back to dropdown's default display setting if display is not manually set
  1714. display = that.options.display || (
  1715. // Bootstrap 3 doesn't have $.fn.dropdown.Constructor.Default
  1716. $.fn.dropdown.Constructor.Default ? $.fn.dropdown.Constructor.Default.display
  1717. : false
  1718. );
  1719. that.$bsContainer.addClass($element.attr('class').replace(/form-control|fit-width/gi, '')).toggleClass(classNames.DROPUP, $element.hasClass(classNames.DROPUP));
  1720. pos = $element.offset();
  1721. if (!$container.is('body')) {
  1722. containerPos = $container.offset();
  1723. containerPos.top += parseInt($container.css('borderTopWidth')) - $container.scrollTop();
  1724. containerPos.left += parseInt($container.css('borderLeftWidth')) - $container.scrollLeft();
  1725. } else {
  1726. containerPos = { top: 0, left: 0 };
  1727. }
  1728. actualHeight = $element.hasClass(classNames.DROPUP) ? 0 : $element[0].offsetHeight;
  1729. // Bootstrap 4+ uses Popper for menu positioning
  1730. if (version.major < 4 || display === 'static') {
  1731. containerPosition.top = pos.top - containerPos.top + actualHeight;
  1732. containerPosition.left = pos.left - containerPos.left;
  1733. }
  1734. containerPosition.width = $element[0].offsetWidth;
  1735. that.$bsContainer.css(containerPosition);
  1736. };
  1737. this.$button.on('click.bs.dropdown.data-api', function () {
  1738. if (that.isDisabled()) {
  1739. return;
  1740. }
  1741. getPlacement(that.$newElement);
  1742. that.$bsContainer
  1743. .appendTo(that.options.container)
  1744. .toggleClass(classNames.SHOW, !that.$button.hasClass(classNames.SHOW))
  1745. .append(that.$menu);
  1746. });
  1747. $(window)
  1748. .off('resize' + EVENT_KEY + '.' + this.selectId + ' scroll' + EVENT_KEY + '.' + this.selectId)
  1749. .on('resize' + EVENT_KEY + '.' + this.selectId + ' scroll' + EVENT_KEY + '.' + this.selectId, function () {
  1750. var isActive = that.$newElement.hasClass(classNames.SHOW);
  1751. if (isActive) getPlacement(that.$newElement);
  1752. });
  1753. this.$element.on('hide' + EVENT_KEY, function () {
  1754. that.$menu.data('height', that.$menu.height());
  1755. that.$bsContainer.detach();
  1756. });
  1757. },
  1758. setOptionStatus: function () {
  1759. var that = this;
  1760. that.noScroll = false;
  1761. if (that.selectpicker.view.visibleElements && that.selectpicker.view.visibleElements.length) {
  1762. for (var i = 0; i < that.selectpicker.view.visibleElements.length; i++) {
  1763. var liData = that.selectpicker.current.data[i + that.selectpicker.view.position0],
  1764. option = liData.option;
  1765. if (option) {
  1766. that.setDisabled(
  1767. liData.index,
  1768. liData.disabled
  1769. );
  1770. that.setSelected(
  1771. liData.index,
  1772. option.selected
  1773. );
  1774. }
  1775. }
  1776. }
  1777. },
  1778. /**
  1779. * @param {number} index - the index of the option that is being changed
  1780. * @param {boolean} selected - true if the option is being selected, false if being deselected
  1781. */
  1782. setSelected: function (index, selected) {
  1783. var li = this.selectpicker.main.elements[index],
  1784. liData = this.selectpicker.main.data[index],
  1785. activeIndexIsSet = this.activeIndex !== undefined,
  1786. thisIsActive = this.activeIndex === index,
  1787. prevActive,
  1788. a,
  1789. // if current option is already active
  1790. // OR
  1791. // if the current option is being selected, it's NOT multiple, and
  1792. // activeIndex is undefined:
  1793. // - when the menu is first being opened, OR
  1794. // - after a search has been performed, OR
  1795. // - 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)
  1796. keepActive = thisIsActive || (selected && !this.multiple && !activeIndexIsSet);
  1797. liData.selected = selected;
  1798. a = li.firstChild;
  1799. if (selected) {
  1800. this.selectedIndex = index;
  1801. }
  1802. li.classList.toggle('selected', selected);
  1803. li.classList.toggle('active', keepActive);
  1804. if (keepActive) {
  1805. this.selectpicker.view.currentActive = li;
  1806. this.activeIndex = index;
  1807. }
  1808. if (a) {
  1809. a.classList.toggle('selected', selected);
  1810. a.classList.toggle('active', keepActive);
  1811. a.setAttribute('aria-selected', selected);
  1812. }
  1813. if (!keepActive) {
  1814. if (!activeIndexIsSet && selected && this.prevActiveIndex !== undefined) {
  1815. prevActive = this.selectpicker.main.elements[this.prevActiveIndex];
  1816. prevActive.classList.remove('active');
  1817. if (prevActive.firstChild) {
  1818. prevActive.firstChild.classList.remove('active');
  1819. }
  1820. }
  1821. }
  1822. },
  1823. /**
  1824. * @param {number} index - the index of the option that is being disabled
  1825. * @param {boolean} disabled - true if the option is being disabled, false if being enabled
  1826. */
  1827. setDisabled: function (index, disabled) {
  1828. var li = this.selectpicker.main.elements[index],
  1829. a;
  1830. this.selectpicker.main.data[index].disabled = disabled;
  1831. a = li.firstChild;
  1832. li.classList.toggle(classNames.DISABLED, disabled);
  1833. if (a) {
  1834. if (version.major === '4') a.classList.toggle(classNames.DISABLED, disabled);
  1835. a.setAttribute('aria-disabled', disabled);
  1836. if (disabled) {
  1837. a.setAttribute('tabindex', -1);
  1838. } else {
  1839. a.setAttribute('tabindex', 0);
  1840. }
  1841. }
  1842. },
  1843. isDisabled: function () {
  1844. return this.$element[0].disabled;
  1845. },
  1846. checkDisabled: function () {
  1847. var that = this;
  1848. if (this.isDisabled()) {
  1849. this.$newElement[0].classList.add(classNames.DISABLED);
  1850. this.$button.addClass(classNames.DISABLED).attr('tabindex', -1).attr('aria-disabled', true);
  1851. } else {
  1852. if (this.$button[0].classList.contains(classNames.DISABLED)) {
  1853. this.$newElement[0].classList.remove(classNames.DISABLED);
  1854. this.$button.removeClass(classNames.DISABLED).attr('aria-disabled', false);
  1855. }
  1856. if (this.$button.attr('tabindex') == -1 && !this.$element.data('tabindex')) {
  1857. this.$button.removeAttr('tabindex');
  1858. }
  1859. }
  1860. this.$button.on('click', function () {
  1861. return !that.isDisabled();
  1862. });
  1863. },
  1864. togglePlaceholder: function () {
  1865. // much faster than calling $.val()
  1866. var element = this.$element[0],
  1867. selectedIndex = element.selectedIndex,
  1868. nothingSelected = selectedIndex === -1;
  1869. if (!nothingSelected && !element.options[selectedIndex].value) nothingSelected = true;
  1870. this.$button.toggleClass('bs-placeholder', nothingSelected);
  1871. },
  1872. tabIndex: function () {
  1873. if (this.$element.data('tabindex') !== this.$element.attr('tabindex') &&
  1874. (this.$element.attr('tabindex') !== -98 && this.$element.attr('tabindex') !== '-98')) {
  1875. this.$element.data('tabindex', this.$element.attr('tabindex'));
  1876. this.$button.attr('tabindex', this.$element.data('tabindex'));
  1877. }
  1878. this.$element.attr('tabindex', -98);
  1879. },
  1880. clickListener: function () {
  1881. var that = this,
  1882. $document = $(document);
  1883. $document.data('spaceSelect', false);
  1884. this.$button.on('keyup', function (e) {
  1885. if (/(32)/.test(e.keyCode.toString(10)) && $document.data('spaceSelect')) {
  1886. e.preventDefault();
  1887. $document.data('spaceSelect', false);
  1888. }
  1889. });
  1890. this.$newElement.on('show.bs.dropdown', function () {
  1891. if (version.major > 3 && !that.dropdown) {
  1892. that.dropdown = that.$button.data('bs.dropdown');
  1893. that.dropdown._menu = that.$menu[0];
  1894. }
  1895. });
  1896. this.$button.on('click.bs.dropdown.data-api', function () {
  1897. if (!that.$newElement.hasClass(classNames.SHOW)) {
  1898. that.setSize();
  1899. }
  1900. });
  1901. function setFocus () {
  1902. if (that.options.liveSearch) {
  1903. that.$searchbox.trigger('focus');
  1904. } else {
  1905. that.$menuInner.trigger('focus');
  1906. }
  1907. }
  1908. function checkPopperExists () {
  1909. if (that.dropdown && that.dropdown._popper && that.dropdown._popper.state.isCreated) {
  1910. setFocus();
  1911. } else {
  1912. requestAnimationFrame(checkPopperExists);
  1913. }
  1914. }
  1915. this.$element.on('shown' + EVENT_KEY, function () {
  1916. if (that.$menuInner[0].scrollTop !== that.selectpicker.view.scrollTop) {
  1917. that.$menuInner[0].scrollTop = that.selectpicker.view.scrollTop;
  1918. }
  1919. if (version.major > 3) {
  1920. requestAnimationFrame(checkPopperExists);
  1921. } else {
  1922. setFocus();
  1923. }
  1924. });
  1925. this.$menuInner.on('click', 'li a', function (e, retainActive) {
  1926. var $this = $(this),
  1927. position0 = that.isVirtual() ? that.selectpicker.view.position0 : 0,
  1928. clickedData = that.selectpicker.current.data[$this.parent().index() + position0],
  1929. clickedIndex = clickedData.index,
  1930. prevValue = getSelectValues(that.$element[0]),
  1931. prevIndex = that.$element.prop('selectedIndex'),
  1932. triggerChange = true;
  1933. // Don't close on multi choice menu
  1934. if (that.multiple && that.options.maxOptions !== 1) {
  1935. e.stopPropagation();
  1936. }
  1937. e.preventDefault();
  1938. // Don't run if the select is disabled
  1939. if (!that.isDisabled() && !$this.parent().hasClass(classNames.DISABLED)) {
  1940. var $options = that.$element.find('option'),
  1941. option = clickedData.option,
  1942. $option = $(option),
  1943. state = option.selected,
  1944. $optgroup = $option.parent('optgroup'),
  1945. $optgroupOptions = $optgroup.find('option'),
  1946. maxOptions = that.options.maxOptions,
  1947. maxOptionsGrp = $optgroup.data('maxOptions') || false;
  1948. if (clickedIndex === that.activeIndex) retainActive = true;
  1949. if (!retainActive) {
  1950. that.prevActiveIndex = that.activeIndex;
  1951. that.activeIndex = undefined;
  1952. }
  1953. if (!that.multiple) { // Deselect all others if not multi select box
  1954. $options.prop('selected', false);
  1955. option.selected = true;
  1956. that.setSelected(clickedIndex, true);
  1957. } else { // Toggle the one we have chosen if we are multi select.
  1958. option.selected = !state;
  1959. that.setSelected(clickedIndex, !state);
  1960. $this.trigger('blur');
  1961. if (maxOptions !== false || maxOptionsGrp !== false) {
  1962. var maxReached = maxOptions < $options.filter(':selected').length,
  1963. maxReachedGrp = maxOptionsGrp < $optgroup.find('option:selected').length;
  1964. if ((maxOptions && maxReached) || (maxOptionsGrp && maxReachedGrp)) {
  1965. if (maxOptions && maxOptions == 1) {
  1966. $options.prop('selected', false);
  1967. $option.prop('selected', true);
  1968. for (var i = 0; i < $options.length; i++) {
  1969. that.setSelected(i, false);
  1970. }
  1971. that.setSelected(clickedIndex, true);
  1972. } else if (maxOptionsGrp && maxOptionsGrp == 1) {
  1973. $optgroup.find('option:selected').prop('selected', false);
  1974. $option.prop('selected', true);
  1975. for (var i = 0; i < $optgroupOptions.length; i++) {
  1976. var option = $optgroupOptions[i];
  1977. that.setSelected($options.index(option), false);
  1978. }
  1979. that.setSelected(clickedIndex, true);
  1980. } else {
  1981. var maxOptionsText = typeof that.options.maxOptionsText === 'string' ? [that.options.maxOptionsText, that.options.maxOptionsText] : that.options.maxOptionsText,
  1982. maxOptionsArr = typeof maxOptionsText === 'function' ? maxOptionsText(maxOptions, maxOptionsGrp) : maxOptionsText,
  1983. maxTxt = maxOptionsArr[0].replace('{n}', maxOptions),
  1984. maxTxtGrp = maxOptionsArr[1].replace('{n}', maxOptionsGrp),
  1985. $notify = $('<div class="notify"></div>');
  1986. // If {var} is set in array, replace it
  1987. /** @deprecated */
  1988. if (maxOptionsArr[2]) {
  1989. maxTxt = maxTxt.replace('{var}', maxOptionsArr[2][maxOptions > 1 ? 0 : 1]);
  1990. maxTxtGrp = maxTxtGrp.replace('{var}', maxOptionsArr[2][maxOptionsGrp > 1 ? 0 : 1]);
  1991. }
  1992. $option.prop('selected', false);
  1993. that.$menu.append($notify);
  1994. if (maxOptions && maxReached) {
  1995. $notify.append($('<div>' + maxTxt + '</div>'));
  1996. triggerChange = false;
  1997. that.$element.trigger('maxReached' + EVENT_KEY);
  1998. }
  1999. if (maxOptionsGrp && maxReachedGrp) {
  2000. $notify.append($('<div>' + maxTxtGrp + '</div>'));
  2001. triggerChange = false;
  2002. that.$element.trigger('maxReachedGrp' + EVENT_KEY);
  2003. }
  2004. setTimeout(function () {
  2005. that.setSelected(clickedIndex, false);
  2006. }, 10);
  2007. $notify.delay(750).fadeOut(300, function () {
  2008. $(this).remove();
  2009. });
  2010. }
  2011. }
  2012. }
  2013. }
  2014. if (!that.multiple || (that.multiple && that.options.maxOptions === 1)) {
  2015. that.$button.trigger('focus');
  2016. } else if (that.options.liveSearch) {
  2017. that.$searchbox.trigger('focus');
  2018. }
  2019. // Trigger select 'change'
  2020. if (triggerChange) {
  2021. if ((prevValue != getSelectValues(that.$element[0]) && that.multiple) || (prevIndex != that.$element.prop('selectedIndex') && !that.multiple)) {
  2022. // $option.prop('selected') is current option state (selected/unselected). prevValue is the value of the select prior to being changed.
  2023. changedArguments = [option.index, $option.prop('selected'), prevValue];
  2024. that.$element
  2025. .triggerNative('change');
  2026. }
  2027. }
  2028. }
  2029. });
  2030. this.$menu.on('click', 'li.' + classNames.DISABLED + ' a, .' + classNames.POPOVERHEADER + ', .' + classNames.POPOVERHEADER + ' :not(.close)', function (e) {
  2031. if (e.currentTarget == this) {
  2032. e.preventDefault();
  2033. e.stopPropagation();
  2034. if (that.options.liveSearch && !$(e.target).hasClass('close')) {
  2035. that.$searchbox.trigger('focus');
  2036. } else {
  2037. that.$button.trigger('focus');
  2038. }
  2039. }
  2040. });
  2041. this.$menuInner.on('click', '.divider, .dropdown-header', function (e) {
  2042. e.preventDefault();
  2043. e.stopPropagation();
  2044. if (that.options.liveSearch) {
  2045. that.$searchbox.trigger('focus');
  2046. } else {
  2047. that.$button.trigger('focus');
  2048. }
  2049. });
  2050. this.$menu.on('click', '.' + classNames.POPOVERHEADER + ' .close', function () {
  2051. that.$button.trigger('click');
  2052. });
  2053. this.$searchbox.on('click', function (e) {
  2054. e.stopPropagation();
  2055. });
  2056. this.$menu.on('click', '.actions-btn', function (e) {
  2057. if (that.options.liveSearch) {
  2058. that.$searchbox.trigger('focus');
  2059. } else {
  2060. that.$button.trigger('focus');
  2061. }
  2062. e.preventDefault();
  2063. e.stopPropagation();
  2064. if ($(this).hasClass('bs-select-all')) {
  2065. that.selectAll();
  2066. } else {
  2067. that.deselectAll();
  2068. }
  2069. });
  2070. this.$element
  2071. .on('change' + EVENT_KEY, function () {
  2072. that.render();
  2073. that.$element.trigger('changed' + EVENT_KEY, changedArguments);
  2074. changedArguments = null;
  2075. })
  2076. .on('focus' + EVENT_KEY, function () {
  2077. if (!that.options.mobile) that.$button.trigger('focus');
  2078. });
  2079. },
  2080. liveSearchListener: function () {
  2081. var that = this,
  2082. noResults = document.createElement('li');
  2083. this.$button.on('click.bs.dropdown.data-api', function () {
  2084. if (!!that.$searchbox.val()) {
  2085. that.$searchbox.val('');
  2086. }
  2087. });
  2088. this.$searchbox.on('click.bs.dropdown.data-api focus.bs.dropdown.data-api touchend.bs.dropdown.data-api', function (e) {
  2089. e.stopPropagation();
  2090. });
  2091. this.$searchbox.on('input propertychange', function () {
  2092. var searchValue = that.$searchbox.val();
  2093. that.selectpicker.search.elements = [];
  2094. that.selectpicker.search.data = [];
  2095. if (searchValue) {
  2096. var i,
  2097. searchMatch = [],
  2098. q = searchValue.toUpperCase(),
  2099. cache = {},
  2100. cacheArr = [],
  2101. searchStyle = that._searchStyle(),
  2102. normalizeSearch = that.options.liveSearchNormalize;
  2103. if (normalizeSearch) q = normalizeToBase(q);
  2104. that._$lisSelected = that.$menuInner.find('.selected');
  2105. for (var i = 0; i < that.selectpicker.main.data.length; i++) {
  2106. var li = that.selectpicker.main.data[i];
  2107. if (!cache[i]) {
  2108. cache[i] = stringSearch(li, q, searchStyle, normalizeSearch);
  2109. }
  2110. if (cache[i] && li.headerIndex !== undefined && cacheArr.indexOf(li.headerIndex) === -1) {
  2111. if (li.headerIndex > 0) {
  2112. cache[li.headerIndex - 1] = true;
  2113. cacheArr.push(li.headerIndex - 1);
  2114. }
  2115. cache[li.headerIndex] = true;
  2116. cacheArr.push(li.headerIndex);
  2117. cache[li.lastIndex + 1] = true;
  2118. }
  2119. if (cache[i] && li.type !== 'optgroup-label') cacheArr.push(i);
  2120. }
  2121. for (var i = 0, cacheLen = cacheArr.length; i < cacheLen; i++) {
  2122. var index = cacheArr[i],
  2123. prevIndex = cacheArr[i - 1],
  2124. li = that.selectpicker.main.data[index],
  2125. liPrev = that.selectpicker.main.data[prevIndex];
  2126. if (li.type !== 'divider' || (li.type === 'divider' && liPrev && liPrev.type !== 'divider' && cacheLen - 1 !== i)) {
  2127. that.selectpicker.search.data.push(li);
  2128. searchMatch.push(that.selectpicker.main.elements[index]);
  2129. }
  2130. }
  2131. that.activeIndex = undefined;
  2132. that.noScroll = true;
  2133. that.$menuInner.scrollTop(0);
  2134. that.selectpicker.search.elements = searchMatch;
  2135. that.createView(true);
  2136. if (!searchMatch.length) {
  2137. noResults.className = 'no-results';
  2138. noResults.innerHTML = that.options.noneResultsText.replace('{0}', '"' + htmlEscape(searchValue) + '"');
  2139. that.$menuInner[0].firstChild.appendChild(noResults);
  2140. }
  2141. } else {
  2142. that.$menuInner.scrollTop(0);
  2143. that.createView(false);
  2144. }
  2145. });
  2146. },
  2147. _searchStyle: function () {
  2148. return this.options.liveSearchStyle || 'contains';
  2149. },
  2150. val: function (value) {
  2151. if (typeof value !== 'undefined') {
  2152. var prevValue = getSelectValues(this.$element[0]);
  2153. changedArguments = [null, null, prevValue];
  2154. this.$element
  2155. .val(value)
  2156. .trigger('changed' + EVENT_KEY, changedArguments);
  2157. this.render();
  2158. changedArguments = null;
  2159. return this.$element;
  2160. } else {
  2161. return this.$element.val();
  2162. }
  2163. },
  2164. changeAll: function (status) {
  2165. if (!this.multiple) return;
  2166. if (typeof status === 'undefined') status = true;
  2167. var element = this.$element[0],
  2168. previousSelected = 0,
  2169. currentSelected = 0,
  2170. prevValue = getSelectValues(element);
  2171. element.classList.add('bs-select-hidden');
  2172. for (var i = 0, len = this.selectpicker.current.elements.length; i < len; i++) {
  2173. var liData = this.selectpicker.current.data[i],
  2174. option = liData.option;
  2175. if (option && !liData.disabled && liData.type !== 'divider') {
  2176. if (liData.selected) previousSelected++;
  2177. option.selected = status;
  2178. if (status) currentSelected++;
  2179. }
  2180. }
  2181. element.classList.remove('bs-select-hidden');
  2182. if (previousSelected === currentSelected) return;
  2183. this.setOptionStatus();
  2184. this.togglePlaceholder();
  2185. changedArguments = [null, null, prevValue];
  2186. this.$element
  2187. .triggerNative('change');
  2188. },
  2189. selectAll: function () {
  2190. return this.changeAll(true);
  2191. },
  2192. deselectAll: function () {
  2193. return this.changeAll(false);
  2194. },
  2195. toggle: function (e) {
  2196. e = e || window.event;
  2197. if (e) e.stopPropagation();
  2198. this.$button.trigger('click.bs.dropdown.data-api');
  2199. },
  2200. keydown: function (e) {
  2201. var $this = $(this),
  2202. isToggle = $this.hasClass('dropdown-toggle'),
  2203. $parent = isToggle ? $this.closest('.dropdown') : $this.closest(Selector.MENU),
  2204. that = $parent.data('this'),
  2205. $items = that.findLis(),
  2206. index,
  2207. isActive,
  2208. liActive,
  2209. activeLi,
  2210. offset,
  2211. updateScroll = false,
  2212. downOnTab = e.which === keyCodes.TAB && !isToggle && !that.options.selectOnTab,
  2213. isArrowKey = REGEXP_ARROW.test(e.which) || downOnTab,
  2214. scrollTop = that.$menuInner[0].scrollTop,
  2215. isVirtual = that.isVirtual(),
  2216. position0 = isVirtual === true ? that.selectpicker.view.position0 : 0;
  2217. isActive = that.$newElement.hasClass(classNames.SHOW);
  2218. if (
  2219. !isActive &&
  2220. (
  2221. isArrowKey ||
  2222. (e.which >= 48 && e.which <= 57) ||
  2223. (e.which >= 96 && e.which <= 105) ||
  2224. (e.which >= 65 && e.which <= 90)
  2225. )
  2226. ) {
  2227. that.$button.trigger('click.bs.dropdown.data-api');
  2228. if (that.options.liveSearch) {
  2229. that.$searchbox.trigger('focus');
  2230. return;
  2231. }
  2232. }
  2233. if (e.which === keyCodes.ESCAPE && isActive) {
  2234. e.preventDefault();
  2235. that.$button.trigger('click.bs.dropdown.data-api').trigger('focus');
  2236. }
  2237. if (isArrowKey) { // if up or down
  2238. if (!$items.length) return;
  2239. // $items.index/.filter is too slow with a large list and no virtual scroll
  2240. index = isVirtual === true ? $items.index($items.filter('.active')) : that.activeIndex;
  2241. if (index === undefined) index = -1;
  2242. if (index !== -1) {
  2243. liActive = that.selectpicker.current.elements[index + position0];
  2244. liActive.classList.remove('active');
  2245. if (liActive.firstChild) liActive.firstChild.classList.remove('active');
  2246. }
  2247. if (e.which === keyCodes.ARROW_UP) { // up
  2248. if (index !== -1) index--;
  2249. if (index + position0 < 0) index += $items.length;
  2250. if (!that.selectpicker.view.canHighlight[index + position0]) {
  2251. index = that.selectpicker.view.canHighlight.slice(0, index + position0).lastIndexOf(true) - position0;
  2252. if (index === -1) index = $items.length - 1;
  2253. }
  2254. } else if (e.which === keyCodes.ARROW_DOWN || downOnTab) { // down
  2255. index++;
  2256. if (index + position0 >= that.selectpicker.view.canHighlight.length) index = 0;
  2257. if (!that.selectpicker.view.canHighlight[index + position0]) {
  2258. index = index + 1 + that.selectpicker.view.canHighlight.slice(index + position0 + 1).indexOf(true);
  2259. }
  2260. }
  2261. e.preventDefault();
  2262. var liActiveIndex = position0 + index;
  2263. if (e.which === keyCodes.ARROW_UP) { // up
  2264. // scroll to bottom and highlight last option
  2265. if (position0 === 0 && index === $items.length - 1) {
  2266. that.$menuInner[0].scrollTop = that.$menuInner[0].scrollHeight;
  2267. liActiveIndex = that.selectpicker.current.elements.length - 1;
  2268. } else {
  2269. activeLi = that.selectpicker.current.data[liActiveIndex];
  2270. offset = activeLi.position - activeLi.height;
  2271. updateScroll = offset < scrollTop;
  2272. }
  2273. } else if (e.which === keyCodes.ARROW_DOWN || downOnTab) { // down
  2274. // scroll to top and highlight first option
  2275. if (index === 0) {
  2276. that.$menuInner[0].scrollTop = 0;
  2277. liActiveIndex = 0;
  2278. } else {
  2279. activeLi = that.selectpicker.current.data[liActiveIndex];
  2280. offset = activeLi.position - that.sizeInfo.menuInnerHeight;
  2281. updateScroll = offset > scrollTop;
  2282. }
  2283. }
  2284. liActive = that.selectpicker.current.elements[liActiveIndex];
  2285. if (liActive) {
  2286. liActive.classList.add('active');
  2287. if (liActive.firstChild) liActive.firstChild.classList.add('active');
  2288. }
  2289. that.activeIndex = that.selectpicker.current.data[liActiveIndex].index;
  2290. that.selectpicker.view.currentActive = liActive;
  2291. if (updateScroll) that.$menuInner[0].scrollTop = offset;
  2292. if (that.options.liveSearch) {
  2293. that.$searchbox.trigger('focus');
  2294. } else {
  2295. $this.trigger('focus');
  2296. }
  2297. } else if (
  2298. (!$this.is('input') && !REGEXP_TAB_OR_ESCAPE.test(e.which)) ||
  2299. (e.which === keyCodes.SPACE && that.selectpicker.keydown.keyHistory)
  2300. ) {
  2301. var searchMatch,
  2302. matches = [],
  2303. keyHistory;
  2304. e.preventDefault();
  2305. that.selectpicker.keydown.keyHistory += keyCodeMap[e.which];
  2306. if (that.selectpicker.keydown.resetKeyHistory.cancel) clearTimeout(that.selectpicker.keydown.resetKeyHistory.cancel);
  2307. that.selectpicker.keydown.resetKeyHistory.cancel = that.selectpicker.keydown.resetKeyHistory.start();
  2308. keyHistory = that.selectpicker.keydown.keyHistory;
  2309. // if all letters are the same, set keyHistory to just the first character when searching
  2310. if (/^(.)\1+$/.test(keyHistory)) {
  2311. keyHistory = keyHistory.charAt(0);
  2312. }
  2313. // find matches
  2314. for (var i = 0; i < that.selectpicker.current.data.length; i++) {
  2315. var li = that.selectpicker.current.data[i],
  2316. hasMatch;
  2317. hasMatch = stringSearch(li, keyHistory, 'startsWith', true);
  2318. if (hasMatch && that.selectpicker.view.canHighlight[i]) {
  2319. matches.push(li.index);
  2320. }
  2321. }
  2322. if (matches.length) {
  2323. var matchIndex = 0;
  2324. $items.removeClass('active').find('a').removeClass('active');
  2325. // either only one key has been pressed or they are all the same key
  2326. if (keyHistory.length === 1) {
  2327. matchIndex = matches.indexOf(that.activeIndex);
  2328. if (matchIndex === -1 || matchIndex === matches.length - 1) {
  2329. matchIndex = 0;
  2330. } else {
  2331. matchIndex++;
  2332. }
  2333. }
  2334. searchMatch = matches[matchIndex];
  2335. activeLi = that.selectpicker.main.data[searchMatch];
  2336. if (scrollTop - activeLi.position > 0) {
  2337. offset = activeLi.position - activeLi.height;
  2338. updateScroll = true;
  2339. } else {
  2340. offset = activeLi.position - that.sizeInfo.menuInnerHeight;
  2341. // if the option is already visible at the current scroll position, just keep it the same
  2342. updateScroll = activeLi.position > scrollTop + that.sizeInfo.menuInnerHeight;
  2343. }
  2344. liActive = that.selectpicker.main.elements[searchMatch];
  2345. liActive.classList.add('active');
  2346. if (liActive.firstChild) liActive.firstChild.classList.add('active');
  2347. that.activeIndex = matches[matchIndex];
  2348. liActive.firstChild.focus();
  2349. if (updateScroll) that.$menuInner[0].scrollTop = offset;
  2350. $this.trigger('focus');
  2351. }
  2352. }
  2353. // Select focused option if "Enter", "Spacebar" or "Tab" (when selectOnTab is true) are pressed inside the menu.
  2354. if (
  2355. isActive &&
  2356. (
  2357. (e.which === keyCodes.SPACE && !that.selectpicker.keydown.keyHistory) ||
  2358. e.which === keyCodes.ENTER ||
  2359. (e.which === keyCodes.TAB && that.options.selectOnTab)
  2360. )
  2361. ) {
  2362. if (e.which !== keyCodes.SPACE) e.preventDefault();
  2363. if (!that.options.liveSearch || e.which !== keyCodes.SPACE) {
  2364. that.$menuInner.find('.active a').trigger('click', true); // retain active class
  2365. $this.trigger('focus');
  2366. if (!that.options.liveSearch) {
  2367. // Prevent screen from scrolling if the user hits the spacebar
  2368. e.preventDefault();
  2369. // Fixes spacebar selection of dropdown items in FF & IE
  2370. $(document).data('spaceSelect', true);
  2371. }
  2372. }
  2373. }
  2374. },
  2375. mobile: function () {
  2376. this.$element[0].classList.add('mobile-device');
  2377. },
  2378. refresh: function () {
  2379. // update options if data attributes have been changed
  2380. var config = $.extend({}, this.options, this.$element.data());
  2381. this.options = config;
  2382. this.checkDisabled();
  2383. this.setStyle();
  2384. this.render();
  2385. this.createLi();
  2386. this.setWidth();
  2387. this.setSize(true);
  2388. this.$element.trigger('refreshed' + EVENT_KEY);
  2389. },
  2390. hide: function () {
  2391. this.$newElement.hide();
  2392. },
  2393. show: function () {
  2394. this.$newElement.show();
  2395. },
  2396. remove: function () {
  2397. this.$newElement.remove();
  2398. this.$element.remove();
  2399. },
  2400. destroy: function () {
  2401. this.$newElement.before(this.$element).remove();
  2402. if (this.$bsContainer) {
  2403. this.$bsContainer.remove();
  2404. } else {
  2405. this.$menu.remove();
  2406. }
  2407. this.$element
  2408. .off(EVENT_KEY)
  2409. .removeData('selectpicker')
  2410. .removeClass('bs-select-hidden selectpicker');
  2411. $(window).off(EVENT_KEY + '.' + this.selectId);
  2412. }
  2413. };
  2414. // SELECTPICKER PLUGIN DEFINITION
  2415. // ==============================
  2416. function Plugin (option) {
  2417. // get the args of the outer function..
  2418. var args = arguments;
  2419. // The arguments of the function are explicitly re-defined from the argument list, because the shift causes them
  2420. // to get lost/corrupted in android 2.3 and IE9 #715 #775
  2421. var _option = option;
  2422. [].shift.apply(args);
  2423. // if the version was not set successfully
  2424. if (!version.success) {
  2425. // try to retreive it again
  2426. try {
  2427. version.full = ($.fn.dropdown.Constructor.VERSION || '').split(' ')[0].split('.');
  2428. } catch (err) {
  2429. // fall back to use BootstrapVersion if set
  2430. if (Selectpicker.BootstrapVersion) {
  2431. version.full = Selectpicker.BootstrapVersion.split(' ')[0].split('.');
  2432. } else {
  2433. version.full = [version.major, '0', '0'];
  2434. console.warn(
  2435. 'There was an issue retrieving Bootstrap\'s version. ' +
  2436. 'Ensure Bootstrap is being loaded before bootstrap-select and there is no namespace collision. ' +
  2437. 'If loading Bootstrap asynchronously, the version may need to be manually specified via $.fn.selectpicker.Constructor.BootstrapVersion.',
  2438. err
  2439. );
  2440. }
  2441. }
  2442. version.major = version.full[0];
  2443. version.success = true;
  2444. }
  2445. if (version.major === '4') {
  2446. // some defaults need to be changed if using Bootstrap 4
  2447. // check to see if they have already been manually changed before forcing them to update
  2448. var toUpdate = [];
  2449. if (Selectpicker.DEFAULTS.style === classNames.BUTTONCLASS) toUpdate.push({ name: 'style', className: 'BUTTONCLASS' });
  2450. if (Selectpicker.DEFAULTS.iconBase === classNames.ICONBASE) toUpdate.push({ name: 'iconBase', className: 'ICONBASE' });
  2451. if (Selectpicker.DEFAULTS.tickIcon === classNames.TICKICON) toUpdate.push({ name: 'tickIcon', className: 'TICKICON' });
  2452. classNames.DIVIDER = 'dropdown-divider';
  2453. classNames.SHOW = 'show';
  2454. classNames.BUTTONCLASS = 'btn-light';
  2455. classNames.POPOVERHEADER = 'popover-header';
  2456. classNames.ICONBASE = '';
  2457. classNames.TICKICON = 'bs-ok-default';
  2458. for (var i = 0; i < toUpdate.length; i++) {
  2459. var option = toUpdate[i];
  2460. Selectpicker.DEFAULTS[option.name] = classNames[option.className];
  2461. }
  2462. }
  2463. var value;
  2464. var chain = this.each(function () {
  2465. var $this = $(this);
  2466. if ($this.is('select')) {
  2467. var data = $this.data('selectpicker'),
  2468. options = typeof _option == 'object' && _option;
  2469. if (!data) {
  2470. var dataAttributes = $this.data();
  2471. for (var dataAttr in dataAttributes) {
  2472. if (dataAttributes.hasOwnProperty(dataAttr) && $.inArray(dataAttr, DISALLOWED_ATTRIBUTES) !== -1) {
  2473. delete dataAttributes[dataAttr];
  2474. }
  2475. }
  2476. var config = $.extend({}, Selectpicker.DEFAULTS, $.fn.selectpicker.defaults || {}, dataAttributes, options);
  2477. config.template = $.extend({}, Selectpicker.DEFAULTS.template, ($.fn.selectpicker.defaults ? $.fn.selectpicker.defaults.template : {}), dataAttributes.template, options.template);
  2478. $this.data('selectpicker', (data = new Selectpicker(this, config)));
  2479. } else if (options) {
  2480. for (var i in options) {
  2481. if (options.hasOwnProperty(i)) {
  2482. data.options[i] = options[i];
  2483. }
  2484. }
  2485. }
  2486. if (typeof _option == 'string') {
  2487. if (data[_option] instanceof Function) {
  2488. value = data[_option].apply(data, args);
  2489. } else {
  2490. value = data.options[_option];
  2491. }
  2492. }
  2493. }
  2494. });
  2495. if (typeof value !== 'undefined') {
  2496. // noinspection JSUnusedAssignment
  2497. return value;
  2498. } else {
  2499. return chain;
  2500. }
  2501. }
  2502. var old = $.fn.selectpicker;
  2503. $.fn.selectpicker = Plugin;
  2504. $.fn.selectpicker.Constructor = Selectpicker;
  2505. // SELECTPICKER NO CONFLICT
  2506. // ========================
  2507. $.fn.selectpicker.noConflict = function () {
  2508. $.fn.selectpicker = old;
  2509. return this;
  2510. };
  2511. $(document)
  2512. .off('keydown.bs.dropdown.data-api')
  2513. .on('keydown' + EVENT_KEY, '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bootstrap-select .bs-searchbox input', Selectpicker.prototype.keydown)
  2514. .on('focusin.modal', '.bootstrap-select [data-toggle="dropdown"], .bootstrap-select [role="listbox"], .bootstrap-select .bs-searchbox input', function (e) {
  2515. e.stopPropagation();
  2516. });
  2517. // SELECTPICKER DATA-API
  2518. // =====================
  2519. $(window).on('load' + EVENT_KEY + '.data-api', function () {
  2520. $('.selectpicker').each(function () {
  2521. var $selectpicker = $(this);
  2522. Plugin.call($selectpicker, $selectpicker.data());
  2523. })
  2524. });
  2525. })(jQuery);
  2526. }));
  2527. /******************************************************************************/
  2528. // https://github.com/jackmoore/autosize
  2529. (function (global, factory) {
  2530. if (typeof define === "function" && define.amd) {
  2531. define(['module', 'exports'], factory);
  2532. } else if (typeof exports !== "undefined") {
  2533. factory(module, exports);
  2534. } else {
  2535. var mod = {
  2536. exports: {}
  2537. };
  2538. factory(mod, mod.exports);
  2539. global.autosize = mod.exports;
  2540. }
  2541. })(this, function (module, exports) {
  2542. 'use strict';
  2543. var map = typeof Map === "function" ? new Map() : function () {
  2544. var keys = [];
  2545. var values = [];
  2546. return {
  2547. has: function has(key) {
  2548. return keys.indexOf(key) > -1;
  2549. },
  2550. get: function get(key) {
  2551. return values[keys.indexOf(key)];
  2552. },
  2553. set: function set(key, value) {
  2554. if (keys.indexOf(key) === -1) {
  2555. keys.push(key);
  2556. values.push(value);
  2557. }
  2558. },
  2559. delete: function _delete(key) {
  2560. var index = keys.indexOf(key);
  2561. if (index > -1) {
  2562. keys.splice(index, 1);
  2563. values.splice(index, 1);
  2564. }
  2565. }
  2566. };
  2567. }();
  2568. var createEvent = function createEvent(name) {
  2569. return new Event(name, { bubbles: true });
  2570. };
  2571. try {
  2572. new Event('test');
  2573. } catch (e) {
  2574. // IE does not support 'new Event()'
  2575. createEvent = function createEvent(name) {
  2576. var evt = document.createEvent('Event');
  2577. evt.initEvent(name, true, false);
  2578. return evt;
  2579. };
  2580. }
  2581. function assign(ta) {
  2582. if (!ta || !ta.nodeName || ta.nodeName !== 'TEXTAREA' || map.has(ta)) return;
  2583. var heightOffset = null;
  2584. var clientWidth = null;
  2585. var cachedHeight = null;
  2586. function init() {
  2587. var style = window.getComputedStyle(ta, null);
  2588. if (style.resize === 'vertical') {
  2589. ta.style.resize = 'none';
  2590. } else if (style.resize === 'both') {
  2591. ta.style.resize = 'horizontal';
  2592. }
  2593. if (style.boxSizing === 'content-box') {
  2594. heightOffset = -(parseFloat(style.paddingTop) + parseFloat(style.paddingBottom));
  2595. } else {
  2596. heightOffset = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
  2597. }
  2598. // Fix when a textarea is not on document body and heightOffset is Not a Number
  2599. if (isNaN(heightOffset)) {
  2600. heightOffset = 0;
  2601. }
  2602. update();
  2603. }
  2604. function changeOverflow(value) {
  2605. {
  2606. // Chrome/Safari-specific fix:
  2607. // When the textarea y-overflow is hidden, Chrome/Safari do not reflow the text to account for the space
  2608. // made available by removing the scrollbar. The following forces the necessary text reflow.
  2609. var width = ta.style.width;
  2610. ta.style.width = '0px';
  2611. // Force reflow:
  2612. /* jshint ignore:start */
  2613. ta.offsetWidth;
  2614. /* jshint ignore:end */
  2615. ta.style.width = width;
  2616. }
  2617. ta.style.overflowY = value;
  2618. }
  2619. function getParentOverflows(el) {
  2620. var arr = [];
  2621. while (el && el.parentNode && el.parentNode instanceof Element) {
  2622. if (el.parentNode.scrollTop) {
  2623. arr.push({
  2624. node: el.parentNode,
  2625. scrollTop: el.parentNode.scrollTop
  2626. });
  2627. }
  2628. el = el.parentNode;
  2629. }
  2630. return arr;
  2631. }
  2632. function resize() {
  2633. if (ta.scrollHeight === 0) {
  2634. // If the scrollHeight is 0, then the element probably has display:none or is detached from the DOM.
  2635. return;
  2636. }
  2637. var overflows = getParentOverflows(ta);
  2638. var docTop = document.documentElement && document.documentElement.scrollTop; // Needed for Mobile IE (ticket #240)
  2639. ta.style.height = '';
  2640. ta.style.height = ta.scrollHeight + heightOffset + 'px';
  2641. // used to check if an update is actually necessary on window.resize
  2642. clientWidth = ta.clientWidth;
  2643. // prevents scroll-position jumping
  2644. overflows.forEach(function (el) {
  2645. el.node.scrollTop = el.scrollTop;
  2646. });
  2647. if (docTop) {
  2648. document.documentElement.scrollTop = docTop;
  2649. }
  2650. }
  2651. function update() {
  2652. resize();
  2653. var styleHeight = Math.round(parseFloat(ta.style.height));
  2654. var computed = window.getComputedStyle(ta, null);
  2655. // Using offsetHeight as a replacement for computed.height in IE, because IE does not account use of border-box
  2656. var actualHeight = computed.boxSizing === 'content-box' ? Math.round(parseFloat(computed.height)) : ta.offsetHeight;
  2657. // The actual height not matching the style height (set via the resize method) indicates that
  2658. // the max-height has been exceeded, in which case the overflow should be allowed.
  2659. if (actualHeight < styleHeight) {
  2660. if (computed.overflowY === 'hidden') {
  2661. changeOverflow('scroll');
  2662. resize();
  2663. actualHeight = computed.boxSizing === 'content-box' ? Math.round(parseFloat(window.getComputedStyle(ta, null).height)) : ta.offsetHeight;
  2664. }
  2665. } else {
  2666. // Normally keep overflow set to hidden, to avoid flash of scrollbar as the textarea expands.
  2667. if (computed.overflowY !== 'hidden') {
  2668. changeOverflow('hidden');
  2669. resize();
  2670. actualHeight = computed.boxSizing === 'content-box' ? Math.round(parseFloat(window.getComputedStyle(ta, null).height)) : ta.offsetHeight;
  2671. }
  2672. }
  2673. if (cachedHeight !== actualHeight) {
  2674. cachedHeight = actualHeight;
  2675. var evt = createEvent('autosize:resized');
  2676. try {
  2677. ta.dispatchEvent(evt);
  2678. } catch (err) {
  2679. // Firefox will throw an error on dispatchEvent for a detached element
  2680. // https://bugzilla.mozilla.org/show_bug.cgi?id=889376
  2681. }
  2682. }
  2683. }
  2684. var pageResize = function pageResize() {
  2685. if (ta.clientWidth !== clientWidth) {
  2686. update();
  2687. }
  2688. };
  2689. var destroy = function (style) {
  2690. window.removeEventListener('resize', pageResize, false);
  2691. ta.removeEventListener('input', update, false);
  2692. ta.removeEventListener('keyup', update, false);
  2693. ta.removeEventListener('autosize:destroy', destroy, false);
  2694. ta.removeEventListener('autosize:update', update, false);
  2695. Object.keys(style).forEach(function (key) {
  2696. ta.style[key] = style[key];
  2697. });
  2698. map.delete(ta);
  2699. }.bind(ta, {
  2700. height: ta.style.height,
  2701. resize: ta.style.resize,
  2702. overflowY: ta.style.overflowY,
  2703. overflowX: ta.style.overflowX,
  2704. wordWrap: ta.style.wordWrap
  2705. });
  2706. ta.addEventListener('autosize:destroy', destroy, false);
  2707. // IE9 does not fire onpropertychange or oninput for deletions,
  2708. // so binding to onkeyup to catch most of those events.
  2709. // There is no way that I know of to detect something like 'cut' in IE9.
  2710. if ('onpropertychange' in ta && 'oninput' in ta) {
  2711. ta.addEventListener('keyup', update, false);
  2712. }
  2713. window.addEventListener('resize', pageResize, false);
  2714. ta.addEventListener('input', update, false);
  2715. ta.addEventListener('autosize:update', update, false);
  2716. ta.style.overflowX = 'hidden';
  2717. ta.style.wordWrap = 'break-word';
  2718. map.set(ta, {
  2719. destroy: destroy,
  2720. update: update
  2721. });
  2722. init();
  2723. }
  2724. function destroy(ta) {
  2725. var methods = map.get(ta);
  2726. if (methods) {
  2727. methods.destroy();
  2728. }
  2729. }
  2730. function update(ta) {
  2731. var methods = map.get(ta);
  2732. if (methods) {
  2733. methods.update();
  2734. }
  2735. }
  2736. var autosize = null;
  2737. // Do nothing in Node.js environment and IE8 (or lower)
  2738. if (typeof window === 'undefined' || typeof window.getComputedStyle !== 'function') {
  2739. autosize = function autosize(el) {
  2740. return el;
  2741. };
  2742. autosize.destroy = function (el) {
  2743. return el;
  2744. };
  2745. autosize.update = function (el) {
  2746. return el;
  2747. };
  2748. } else {
  2749. autosize = function autosize(el, options) {
  2750. if (el) {
  2751. Array.prototype.forEach.call(el.length ? el : [el], function (x) {
  2752. return assign(x, options);
  2753. });
  2754. }
  2755. return el;
  2756. };
  2757. autosize.destroy = function (el) {
  2758. if (el) {
  2759. Array.prototype.forEach.call(el.length ? el : [el], destroy);
  2760. }
  2761. return el;
  2762. };
  2763. autosize.update = function (el) {
  2764. if (el) {
  2765. Array.prototype.forEach.call(el.length ? el : [el], update);
  2766. }
  2767. return el;
  2768. };
  2769. }
  2770. exports.default = autosize;
  2771. module.exports = exports['default'];
  2772. });
  2773. /******************************************************************************/
  2774. (function(window, $) {
  2775. var fave = function(window, $) {
  2776. // Private
  2777. var FormDataWasChanged = false;
  2778. function IsDebugMode() {
  2779. return window.fave_debug && window.fave_debug === true;
  2780. };
  2781. function GetModalAlertTmpl(title, message, error) {
  2782. return '<div class="alert alert-' + (!error?'success':'danger') + ' alert-dismissible fade show" role="alert"><strong>' + title + '</strong> ' + message + '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>';
  2783. };
  2784. function ShowSystemMsg(title, message, error) {
  2785. var modal_alert_place = $('.modal.show .sys-messages');
  2786. if(!modal_alert_place.length) {
  2787. modal_alert_place = $('form.alert-here .sys-messages');
  2788. }
  2789. if(modal_alert_place.length) {
  2790. modal_alert_place.html(GetModalAlertTmpl(title, message, error));
  2791. } else {
  2792. ShowSystemMsgModal(title, message, error);
  2793. }
  2794. };
  2795. function ShowSystemMsgModal(title, message, error) {
  2796. $('#sys-modal-system-message-placeholder').html('');
  2797. var html = '<div class="modal fade" id="sys-modal-system-message" tabindex="-1" role="dialog" aria-labelledby="sysModalSystemMessageLabel" aria-hidden="true"> \
  2798. <div class="modal-dialog modal-dialog-centered" role="document"> \
  2799. <div class="modal-content"> \
  2800. <input type="hidden" name="action" value="index-user-update-profile"> \
  2801. <div class="modal-header"> \
  2802. <h5 class="modal-title" id="sysModalSystemMessageLabel">' + title + '</h5> \
  2803. <button type="button" class="close" data-dismiss="modal" aria-label="Close"> \
  2804. <span aria-hidden="true">&times;</span> \
  2805. </button> \
  2806. </div> \
  2807. <div class="modal-body text-left">' + message + '</div> \
  2808. <div class="modal-footer"> \
  2809. <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> \
  2810. </div> \
  2811. </div> \
  2812. </div> \
  2813. </div>';
  2814. $('#sys-modal-system-message-placeholder').html(html);
  2815. $('#sys-modal-system-message').modal({
  2816. backdrop: 'static',
  2817. keyboard: true,
  2818. show: false,
  2819. });
  2820. $('#sys-modal-system-message').on('hidden.bs.modal', function(e) {
  2821. $('#sys-modal-system-message-placeholder').html('');
  2822. });
  2823. $('#sys-modal-system-message').modal('show');
  2824. };
  2825. function AjaxEval(data) {
  2826. try {
  2827. eval(data);
  2828. } catch(e) {
  2829. if(e instanceof SyntaxError) {
  2830. console.log(data);
  2831. console.log('Error: JavaScript code eval error', e.message);
  2832. }
  2833. }
  2834. };
  2835. function AjaxDone(data) {
  2836. AjaxEval(data);
  2837. };
  2838. function AjaxFail(data, status, error) {
  2839. if(status.toLowerCase() === "error" && error.toLowerCase() === "not found") {
  2840. AjaxEval(data);
  2841. } else {
  2842. console.log('Error: data sending error, page will be reloaded', data, status, error);
  2843. setTimeout(function() {
  2844. window.location.reload(false);
  2845. }, 1000);
  2846. }
  2847. };
  2848. function FormToAjax(form) {
  2849. form.submit(function(e) {
  2850. if(form.hasClass('loading')) {
  2851. e.preventDefault();
  2852. return;
  2853. }
  2854. // Block send button
  2855. form.addClass('loading').addClass('alert-here');
  2856. var button = form.find('button[type=submit]');
  2857. button.addClass('progress-bar-striped')
  2858. .addClass('progress-bar-animated');
  2859. // Another button
  2860. if(button.attr('data-target') != '') {
  2861. $('#' + button.attr('data-target')).addClass('progress-bar-striped')
  2862. .addClass('progress-bar-animated');
  2863. }
  2864. // Clear form messages
  2865. form.find('.sys-messages').html('');
  2866. $.ajax({
  2867. type: "POST",
  2868. url: form.attr('action'),
  2869. data: form.serialize()
  2870. }).done(function(data) {
  2871. FormDataWasChanged = false;
  2872. if(IsDebugMode()) console.log('done', data);
  2873. AjaxDone(data)
  2874. }).fail(function(xhr, status, error) {
  2875. if(IsDebugMode()) console.log('fail', xhr, status, error);
  2876. AjaxFail(xhr.responseText, status, error);
  2877. }).always(function() {
  2878. // Add delay for one second
  2879. setTimeout(function() {
  2880. form.removeClass('loading').removeClass('alert-here');
  2881. button.removeClass('progress-bar-striped')
  2882. .removeClass('progress-bar-animated');
  2883. // Another button
  2884. if(button.attr('data-target') != '') {
  2885. $('#' + button.attr('data-target'))
  2886. .removeClass('progress-bar-striped')
  2887. .removeClass('progress-bar-animated');
  2888. }
  2889. }, 100);
  2890. });
  2891. // Prevent submit action
  2892. e.preventDefault();
  2893. });
  2894. // Bind to another button
  2895. var button = form.find('button[type=submit]');
  2896. if(button.attr('data-target') != '') {
  2897. $('#' + button.attr('data-target')).click(function() {
  2898. button.click();
  2899. });
  2900. }
  2901. // Mark body if any data in form was changed
  2902. if(form.hasClass('prev-data-lost')) {
  2903. form.find('input, textarea, select').on('input', function() {
  2904. if(!FormDataWasChanged) {
  2905. if(!$(this).hasClass('ignore-lost-data')) {
  2906. FormDataWasChanged = true;
  2907. }
  2908. }
  2909. });
  2910. }
  2911. };
  2912. function PreventDataLost() {
  2913. if(!FormDataWasChanged) {
  2914. FormDataWasChanged = true;
  2915. }
  2916. };
  2917. function HtmlDecode(value) {
  2918. var doc = new DOMParser().parseFromString(value, "text/html");
  2919. return doc.documentElement.textContent;
  2920. };
  2921. function HtmlFixEditorHtml(value) {
  2922. newValue = value;
  2923. newValue = newValue.replace(/&nbsp;/gi, '');
  2924. return newValue;
  2925. };
  2926. function AllFormsToAjax() {
  2927. $('form').each(function() {
  2928. FormToAjax($(this));
  2929. });
  2930. };
  2931. function BindWindowBeforeUnload() {
  2932. // Prevent page reload if data was changed
  2933. $(window).bind('beforeunload', function(){
  2934. if(FormDataWasChanged) {
  2935. return 'Some data was changed and not saved. Are you sure want to leave page?';
  2936. }
  2937. });
  2938. };
  2939. function MakeTextAreasAutoSized() {
  2940. autosize($('textarea.autosize'));
  2941. };
  2942. function MakeTextAreasWysiwyg() {
  2943. $('textarea.wysiwyg').each(function() {
  2944. var area = $(this)[0];
  2945. var area_id = area.id;
  2946. var area_name = area.name;
  2947. var area_html = area.innerHTML;
  2948. // Wrap editro by additional DIV and remove target textarea
  2949. $(area).wrap('<div id="' + area_id + '_wysiwyg" class="form-control wysiwyg" style="height:auto;padding:0px"></div>').remove();
  2950. var wysiwyg = document.getElementById(area_id + '_wysiwyg');
  2951. wysiwyg.id = area_id;
  2952. // Create and init editor
  2953. var editor = window.pell.init({
  2954. element: wysiwyg,
  2955. onChange: function(html) {
  2956. area.innerHTML = HtmlFixEditorHtml(html);
  2957. $(area).val(HtmlFixEditorHtml(html));
  2958. if(!FormDataWasChanged) {
  2959. FormDataWasChanged = true;
  2960. }
  2961. },
  2962. defaultParagraphSeparator: 'p',
  2963. styleWithCSS: false,
  2964. actions: [
  2965. 'paragraph',
  2966. 'heading1',
  2967. 'heading2',
  2968. 'bold',
  2969. 'italic',
  2970. 'underline',
  2971. 'strikethrough',
  2972. 'ulist',
  2973. 'olist',
  2974. 'link',
  2975. {
  2976. name: 'htmlcode',
  2977. icon: 'HTML',
  2978. title: 'HTML Source',
  2979. result: function(edt, ctn, btn) {
  2980. var jedt = $(edt);
  2981. var jctn = $(ctn);
  2982. var jbtn = $(btn);
  2983. if(!jbtn.hasClass('pell-button-html-pressed')) {
  2984. jbtn.addClass('pell-button-html-pressed');
  2985. jedt.addClass('pell-html-mode');
  2986. jedt.find('.pell-actionbar .pell-button').prop('disabled', true);
  2987. jbtn.prop('disabled', false);
  2988. setTimeout(function() {
  2989. jedt.find('textarea.form-control').focus();
  2990. }, 0);
  2991. } else {
  2992. jbtn.removeClass('pell-button-html-pressed');
  2993. jedt.removeClass('pell-html-mode');
  2994. jedt.find('.pell-actionbar .pell-button').prop('disabled', false);
  2995. var srcValue = jedt.find('textarea.form-control').val();
  2996. ctn.innerHTML = HtmlFixEditorHtml(srcValue);
  2997. $(ctn).val(HtmlFixEditorHtml(srcValue));
  2998. setTimeout(function() {
  2999. jctn.focus();
  3000. }, 0);
  3001. }
  3002. },
  3003. },
  3004. ],
  3005. classes: {
  3006. actionbar: 'pell-actionbar',
  3007. button: 'pell-button',
  3008. content: 'pell-content',
  3009. selected: 'pell-button-selected'
  3010. }
  3011. });
  3012. editor.onfocusin = function() {
  3013. $(wysiwyg).addClass('focused');
  3014. };
  3015. editor.onfocusout = function() {
  3016. $(wysiwyg).find('.pell-actionbar button.pell-button-selected').removeClass('pell-button-selected');
  3017. $(wysiwyg).removeClass('focused');
  3018. };
  3019. // Re-add textarea
  3020. $(wysiwyg).append('<textarea class="form-control" id="' + area_id + '_wysiwyg' + '" name="' + area_name + '" style="display:none"></textarea>');
  3021. area = document.getElementById(area_id + '_wysiwyg');
  3022. // Prevent data lost if HTML was changed
  3023. $(area).on('input', function() {
  3024. if(!FormDataWasChanged) {
  3025. FormDataWasChanged = true;
  3026. }
  3027. });
  3028. // Copy HTML to textarea and editor
  3029. area.innerHTML = HtmlFixEditorHtml(HtmlDecode(area_html));
  3030. $(area).val(HtmlFixEditorHtml(HtmlDecode(area_html)));
  3031. editor.content.innerHTML = HtmlFixEditorHtml(HtmlDecode(area_html));
  3032. });
  3033. };
  3034. function MakeTextAreasTmplEditor() {
  3035. $('textarea.tmpl-editor').each(function() {
  3036. var targetTextArea = $(this)[0];
  3037. var targetFileExt = $(this).data('emode');
  3038. var targetEditorMode = 'text/html';
  3039. if(targetFileExt == 'js') {
  3040. targetEditorMode = 'javascript';
  3041. } else if(targetFileExt == 'css') {
  3042. targetEditorMode = 'css';
  3043. }
  3044. CodeMirror.fromTextArea(targetTextArea, {
  3045. lineNumbers: true,
  3046. lineWrapping: true,
  3047. viewportMargin: Infinity,
  3048. mode: targetEditorMode,
  3049. }).on('change', function(editor){
  3050. targetTextArea.value = editor.getValue();
  3051. });
  3052. });
  3053. };
  3054. function MakeTextAreasNotReactOnTab() {
  3055. $('textarea.use-tab-key').each(function() {
  3056. $(this).keydown(function(e) {
  3057. if(e.keyCode === 9) {
  3058. var start = this.selectionStart;
  3059. var end = this.selectionEnd;
  3060. var $this = $(this);
  3061. var value = $this.val();
  3062. $this.val(value.substring(0, start) + "\t" + value.substring(end));
  3063. this.selectionStart = this.selectionEnd = start + 1;
  3064. e.preventDefault();
  3065. if(!FormDataWasChanged) {
  3066. FormDataWasChanged = true;
  3067. }
  3068. }
  3069. });
  3070. });
  3071. };
  3072. function Initialize() {
  3073. // Check if jQuery was loaded
  3074. if(typeof $ == 'function') {
  3075. AllFormsToAjax();
  3076. BindWindowBeforeUnload();
  3077. MakeTextAreasAutoSized();
  3078. MakeTextAreasWysiwyg();
  3079. MakeTextAreasTmplEditor();
  3080. MakeTextAreasNotReactOnTab();
  3081. } else {
  3082. console.log('Error: jQuery is not loaded!');
  3083. }
  3084. };
  3085. // Initialize
  3086. if(window.addEventListener) {
  3087. // W3C standard
  3088. window.addEventListener('load', Initialize, false);
  3089. } else if(window.attachEvent) {
  3090. // Microsoft
  3091. window.attachEvent('onload', Initialize);
  3092. };
  3093. // Public
  3094. return {
  3095. ShowMsgSuccess: function(title, message) {
  3096. ShowSystemMsg(title, message, false);
  3097. },
  3098. ShowMsgError: function(title, message) {
  3099. ShowSystemMsg(title, message, true);
  3100. },
  3101. FormDataWasChanged: function() {
  3102. PreventDataLost();
  3103. },
  3104. ModalUserProfile: function() {
  3105. var html = '<div class="modal fade" id="sys-modal-user-settings" tabindex="-1" role="dialog" aria-labelledby="sysModalUserSettingsLabel" aria-hidden="true"> \
  3106. <div class="modal-dialog modal-dialog-centered" role="document"> \
  3107. <div class="modal-content"> \
  3108. <form class="form-user-settings" action="/cp/" method="post" autocomplete="off"> \
  3109. <input type="hidden" name="action" value="index-user-update-profile"> \
  3110. <div class="modal-header"> \
  3111. <h5 class="modal-title" id="sysModalUserSettingsLabel">My profile</h5> \
  3112. <button type="button" class="close" data-dismiss="modal" aria-label="Close"> \
  3113. <span aria-hidden="true">&times;</span> \
  3114. </button> \
  3115. </div> \
  3116. <div class="modal-body text-left"> \
  3117. <div class="form-group"> \
  3118. <label for="first_name">First name</label> \
  3119. <input type="text" class="form-control" id="first_name" name="first_name" value="' + window.CurrentUserProfileData.first_name + '" placeholder="User first name" autocomplete="off"> \
  3120. </div> \
  3121. <div class="form-group"> \
  3122. <label for="last_name">Last name</label> \
  3123. <input type="text" class="form-control" id="last_name" name="last_name" value="' + window.CurrentUserProfileData.last_name + '" placeholder="User last name" autocomplete="off"> \
  3124. </div> \
  3125. <div class="form-group"> \
  3126. <label for="email">Email</label> \
  3127. <input type="email" class="form-control" id="email" name="email" value="' + window.CurrentUserProfileData.email + '" placeholder="User email" autocomplete="off" required> \
  3128. </div> \
  3129. <div class="form-group"> \
  3130. <label for="password">New password</label> \
  3131. <input type="password" class="form-control" id="password" aria-describedby="passwordHelp" name="password" value="" placeholder="User new password" autocomplete="off"> \
  3132. <small id="passwordHelp" class="form-text text-muted">Leave this field empty if you don\'t want change your password</small> \
  3133. </div> \
  3134. <div class="sys-messages"></div> \
  3135. </div> \
  3136. <div class="modal-footer"> \
  3137. <button type="submit" class="btn btn-primary">Save</button> \
  3138. <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> \
  3139. </div> \
  3140. </form> \
  3141. </div> \
  3142. </div> \
  3143. </div>';
  3144. $('#sys-modal-user-settings-placeholder').html(html);
  3145. $("#sys-modal-user-settings").modal({
  3146. backdrop: 'static',
  3147. keyboard: false,
  3148. show: false,
  3149. });
  3150. $('#sys-modal-user-settings').on('hidden.bs.modal', function(e) {
  3151. $('#sys-modal-user-settings-placeholder').html('');
  3152. });
  3153. FormToAjax($('#sys-modal-user-settings form'));
  3154. $("#sys-modal-user-settings").modal('show');
  3155. },
  3156. ShopProductsAdd: function() {
  3157. var selText = $('#lbl_attributes option:selected').text();
  3158. var selValue = $('#lbl_attributes').val();
  3159. if(selValue == '0') { return; }
  3160. $('#lbl_attributes')[0].selectedIndex = 0;
  3161. $('#lbl_attributes').selectpicker('refresh');
  3162. if($('#prod_attr_' + selValue).length > 0) { return; }
  3163. $('#list').append('<div class="form-group" id="prod_attr_' + selValue + '"><div><b>' + selText + '</b></div><div class="position-relative"><select class="form-control" name="value.' + selValue + '" autocomplete="off" required disabled><option value="0">Loading values...</option></select><button type="button" class="btn btn-danger btn-dynamic-remove" onclick="fave.ShopProductsRemove(this);" disabled>&times;</button></div></div>');
  3164. PreventDataLost();
  3165. $.ajax({
  3166. type: 'POST',
  3167. url: '/cp/',
  3168. data: {
  3169. action: 'shop-get-attribute-values',
  3170. id: selValue
  3171. }
  3172. }).done(function(data) {
  3173. try {
  3174. eval(data);
  3175. } catch(e) {
  3176. if(e instanceof SyntaxError) {
  3177. console.log(data);
  3178. console.log('Error: JavaScript code eval error', e.message);
  3179. }
  3180. }
  3181. }).fail(function(xhr, status, error) {
  3182. $('#prod_attr_' + selValue).remove();
  3183. try {
  3184. eval(xhr.responseText);
  3185. } catch(e) {
  3186. if(e instanceof SyntaxError) {
  3187. console.log(xhr.responseText);
  3188. console.log('Error: JavaScript code eval error', e.message);
  3189. }
  3190. }
  3191. });
  3192. },
  3193. ShopProductsRemove: function(button) {
  3194. $(button).parent().parent().remove();
  3195. PreventDataLost();
  3196. },
  3197. ShopAttributesAdd: function() {
  3198. $('#list').append('<div class="form-group position-relative"><input class="form-control" type="text" name="value.0" value="" placeholder="" autocomplete="off" required><button type="button" class="btn btn-danger btn-dynamic-remove" onclick="fave.ShopAttributesRemove(this);">&times;</button></div>');
  3199. PreventDataLost();
  3200. setTimeout(function() {
  3201. $('#list input').last().focus();
  3202. }, 100);
  3203. },
  3204. ShopAttributesRemove: function(button) {
  3205. $(button).parent().remove();
  3206. PreventDataLost();
  3207. },
  3208. ShopProductsUploadImage: function(action_name, product_id, input_id) {
  3209. var fd = new FormData();
  3210. fd.append('action', action_name);
  3211. fd.append('id', product_id);
  3212. fd.append('file', $('#' + input_id)[0].files[0]);
  3213. $.ajax({
  3214. url: '/cp/',
  3215. method: 'POST',
  3216. type: 'POST',
  3217. data: fd,
  3218. contentType: false,
  3219. processData: false
  3220. }).done(function(data) {
  3221. try {
  3222. eval(data);
  3223. } catch(e) {
  3224. if(e instanceof SyntaxError) {
  3225. console.log(data);
  3226. console.log('Error: JavaScript code eval error', e.message);
  3227. }
  3228. }
  3229. }).fail(function(xhr, status, error) {
  3230. try {
  3231. eval(xhr.responseText);
  3232. } catch(e) {
  3233. if(e instanceof SyntaxError) {
  3234. console.log(xhr.responseText);
  3235. console.log('Error: JavaScript code eval error', e.message);
  3236. }
  3237. }
  3238. });
  3239. },
  3240. ShopProductsDeleteImage: function(button, product_id, filename) {
  3241. $.ajax({
  3242. type: "POST",
  3243. url: '/cp/',
  3244. data: {
  3245. action: 'shop-upload-delete',
  3246. id: product_id,
  3247. file: filename,
  3248. }
  3249. }).done(function(data) {
  3250. if(IsDebugMode()) console.log('done', data);
  3251. AjaxDone(data);
  3252. }).fail(function(xhr, status, error) {
  3253. if(IsDebugMode()) console.log('fail', xhr, status, error);
  3254. AjaxFail(xhr.responseText, status, error);
  3255. });
  3256. },
  3257. ActionLogout: function(message) {
  3258. if(confirm(message)) {
  3259. $.ajax({
  3260. type: "POST",
  3261. url: '/cp/',
  3262. data: {
  3263. action: 'index-user-logout',
  3264. }
  3265. }).done(function(data) {
  3266. if(IsDebugMode()) console.log('done', data);
  3267. AjaxDone(data);
  3268. }).fail(function(xhr, status, error) {
  3269. if(IsDebugMode()) console.log('fail', xhr, status, error);
  3270. AjaxFail(xhr.responseText, status, error);
  3271. });
  3272. }
  3273. },
  3274. ActionDataTableDelete: function(object, action, id, message) {
  3275. if(confirm(message)) {
  3276. $.ajax({
  3277. type: "POST",
  3278. url: '/cp/',
  3279. data: {
  3280. action: action,
  3281. id: id,
  3282. }
  3283. }).done(function(data) {
  3284. if(IsDebugMode()) console.log('done', data);
  3285. AjaxDone(data);
  3286. }).fail(function(xhr, status, error) {
  3287. if(IsDebugMode()) console.log('fail', xhr, status, error);
  3288. AjaxFail(xhr.responseText, status, error);
  3289. });
  3290. }
  3291. },
  3292. ActionRestoreThemeFile: function(action_name, file_name, message) {
  3293. if(confirm(message)) {
  3294. $.ajax({
  3295. type: "POST",
  3296. url: '/cp/',
  3297. data: {
  3298. action: action_name,
  3299. file: file_name,
  3300. }
  3301. }).done(function(data) {
  3302. if(IsDebugMode()) console.log('done', data);
  3303. AjaxDone(data);
  3304. }).fail(function(xhr, status, error) {
  3305. if(IsDebugMode()) console.log('fail', xhr, status, error);
  3306. AjaxFail(xhr.responseText, status, error);
  3307. });
  3308. }
  3309. return false;
  3310. },
  3311. };
  3312. }(window, $);
  3313. // Make it public
  3314. window.fave = fave;
  3315. }(window, jQuery));