select2.js 143 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596
  1. /*
  2. Copyright 2012 Igor Vaynberg
  3. Version: @@ver@@ Timestamp: @@timestamp@@
  4. This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
  5. General Public License version 2 (the "GPL License"). You may choose either license to govern your
  6. use of this software only upon the condition that you accept all of the terms of either the Apache
  7. License or the GPL License.
  8. You may obtain a copy of the Apache License and the GPL License at:
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. http://www.gnu.org/licenses/gpl-2.0.html
  11. Unless required by applicable law or agreed to in writing, software distributed under the
  12. Apache License or the GPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  13. CONDITIONS OF ANY KIND, either express or implied. See the Apache License and the GPL License for
  14. the specific language governing permissions and limitations under the Apache License and the GPL License.
  15. */
  16. (function ($) {
  17. if(typeof $.fn.each2 == "undefined") {
  18. $.extend($.fn, {
  19. /*
  20. * 4-10 times faster .each replacement
  21. * use it carefully, as it overrides jQuery context of element on each iteration
  22. */
  23. each2 : function (c) {
  24. var j = $([0]), i = -1, l = this.length;
  25. while (
  26. ++i < l
  27. && (j.context = j[0] = this[i])
  28. && c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object
  29. );
  30. return this;
  31. }
  32. });
  33. }
  34. })(jQuery);
  35. (function ($, undefined) {
  36. "use strict";
  37. /*global document, window, jQuery, console */
  38. if (window.Select2 !== undefined) {
  39. return;
  40. }
  41. var KEY, AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer,
  42. lastMousePosition={x:0,y:0}, $document, scrollBarDimensions,
  43. KEY = {
  44. TAB: 9,
  45. ENTER: 13,
  46. ESC: 27,
  47. SPACE: 32,
  48. LEFT: 37,
  49. UP: 38,
  50. RIGHT: 39,
  51. DOWN: 40,
  52. SHIFT: 16,
  53. CTRL: 17,
  54. ALT: 18,
  55. PAGE_UP: 33,
  56. PAGE_DOWN: 34,
  57. HOME: 36,
  58. END: 35,
  59. BACKSPACE: 8,
  60. DELETE: 46,
  61. isArrow: function (k) {
  62. k = k.which ? k.which : k;
  63. switch (k) {
  64. case KEY.LEFT:
  65. case KEY.RIGHT:
  66. case KEY.UP:
  67. case KEY.DOWN:
  68. return true;
  69. }
  70. return false;
  71. },
  72. isControl: function (e) {
  73. var k = e.which;
  74. switch (k) {
  75. case KEY.SHIFT:
  76. case KEY.CTRL:
  77. case KEY.ALT:
  78. return true;
  79. }
  80. if (e.metaKey) return true;
  81. return false;
  82. },
  83. isFunctionKey: function (k) {
  84. k = k.which ? k.which : k;
  85. return k >= 112 && k <= 123;
  86. }
  87. },
  88. MEASURE_SCROLLBAR_TEMPLATE = "<div class='select2-measure-scrollbar'></div>",
  89. DIACRITICS = {
  90. "\u24B6":"A","\uFF21":"A","\u00C0":"A","\u00C1":"A","\u00C2":"A","\u1EA6":"A","\u1EA4":"A","\u1EAA":"A",
  91. "\u1EA8":"A","\u00C3":"A","\u0100":"A","\u0102":"A","\u1EB0":"A","\u1EAE":"A","\u1EB4":"A","\u1EB2":"A",
  92. "\u0226":"A","\u01E0":"A","\u00C4":"A","\u01DE":"A","\u1EA2":"A","\u00C5":"A","\u01FA":"A","\u01CD":"A",
  93. "\u0200":"A","\u0202":"A","\u1EA0":"A","\u1EAC":"A","\u1EB6":"A","\u1E00":"A","\u0104":"A","\u023A":"A",
  94. "\u2C6F":"A",
  95. "\uA732":"AA","\u00C6":"AE","\u01FC":"AE","\u01E2":"AE","\uA734":"AO","\uA736":"AU","\uA738":"AV","\uA73A":"AV",
  96. "\uA73C":"AY",
  97. "\u24B7":"B","\uFF22":"B","\u1E02":"B","\u1E04":"B","\u1E06":"B","\u0243":"B","\u0182":"B","\u0181":"B",
  98. "\u24B8":"C",
  99. "\uFF23":"C","\u0106":"C","\u0108":"C","\u010A":"C","\u010C":"C","\u00C7":"C","\u1E08":"C","\u0187":"C",
  100. "\u023B":"C","\uA73E":"C",
  101. "\u24B9":"D","\uFF24":"D","\u1E0A":"D","\u010E":"D","\u1E0C":"D","\u1E10":"D","\u1E12":"D","\u1E0E":"D",
  102. "\u0110":"D","\u018B":"D","\u018A":"D","\u0189":"D","\uA779":"D",
  103. "\u01F1":"DZ","\u01C4":"DZ","\u01F2":"Dz","\u01C5":"Dz",
  104. "\u24BA":"E","\uFF25":"E","\u00C8":"E","\u00C9":"E","\u00CA":"E","\u1EC0":"E","\u1EBE":"E","\u1EC4":"E",
  105. "\u1EC2":"E","\u1EBC":"E","\u0112":"E","\u1E14":"E","\u1E16":"E","\u0114":"E","\u0116":"E","\u00CB":"E",
  106. "\u1EBA":"E","\u011A":"E","\u0204":"E","\u0206":"E","\u1EB8":"E","\u1EC6":"E","\u0228":"E","\u1E1C":"E",
  107. "\u0118":"E","\u1E18":"E","\u1E1A":"E","\u0190":"E","\u018E":"E",
  108. "\u24BB":"F","\uFF26":"F","\u1E1E":"F","\u0191":"F","\uA77B":"F",
  109. "\u24BC":"G","\uFF27":"G","\u01F4":"G","\u011C":"G","\u1E20":"G","\u011E":"G","\u0120":"G","\u01E6":"G",
  110. "\u0122":"G","\u01E4":"G","\u0193":"G","\uA7A0":"G","\uA77D":"G","\uA77E":"G",
  111. "\u24BD":"H","\uFF28":"H","\u0124":"H","\u1E22":"H","\u1E26":"H","\u021E":"H","\u1E24":"H","\u1E28":"H",
  112. "\u1E2A":"H","\u0126":"H","\u2C67":"H","\u2C75":"H","\uA78D":"H",
  113. "\u24BE":"I","\uFF29":"I","\u00CC":"I","\u00CD":"I","\u00CE":"I","\u0128":"I","\u012A":"I","\u012C":"I",
  114. "\u0130":"I","\u00CF":"I","\u1E2E":"I","\u1EC8":"I","\u01CF":"I","\u0208":"I","\u020A":"I","\u1ECA":"I",
  115. "\u012E":"I","\u1E2C":"I","\u0197":"I",
  116. "\u24BF":"J","\uFF2A":"J","\u0134":"J","\u0248":"J",
  117. "\u24C0":"K","\uFF2B":"K","\u1E30":"K","\u01E8":"K","\u1E32":"K","\u0136":"K","\u1E34":"K","\u0198":"K",
  118. "\u2C69":"K","\uA740":"K","\uA742":"K","\uA744":"K","\uA7A2":"K",
  119. "\u24C1":"L","\uFF2C":"L","\u013F":"L","\u0139":"L","\u013D":"L","\u1E36":"L","\u1E38":"L","\u013B":"L",
  120. "\u1E3C":"L","\u1E3A":"L","\u0141":"L","\u023D":"L","\u2C62":"L","\u2C60":"L","\uA748":"L","\uA746":"L",
  121. "\uA780":"L",
  122. "\u01C7":"LJ","\u01C8":"Lj",
  123. "\u24C2":"M","\uFF2D":"M","\u1E3E":"M","\u1E40":"M","\u1E42":"M","\u2C6E":"M","\u019C":"M",
  124. "\u24C3":"N","\uFF2E":"N","\u01F8":"N","\u0143":"N","\u00D1":"N","\u1E44":"N","\u0147":"N","\u1E46":"N",
  125. "\u0145":"N","\u1E4A":"N","\u1E48":"N","\u0220":"N","\u019D":"N","\uA790":"N","\uA7A4":"N",
  126. "\u01CA":"NJ","\u01CB":"Nj",
  127. "\u24C4":"O","\uFF2F":"O","\u00D2":"O","\u00D3":"O","\u00D4":"O","\u1ED2":"O","\u1ED0":"O","\u1ED6":"O",
  128. "\u1ED4":"O","\u00D5":"O","\u1E4C":"O","\u022C":"O","\u1E4E":"O","\u014C":"O","\u1E50":"O","\u1E52":"O",
  129. "\u014E":"O","\u022E":"O","\u0230":"O","\u00D6":"O","\u022A":"O","\u1ECE":"O","\u0150":"O","\u01D1":"O",
  130. "\u020C":"O","\u020E":"O","\u01A0":"O","\u1EDC":"O","\u1EDA":"O","\u1EE0":"O","\u1EDE":"O","\u1EE2":"O",
  131. "\u1ECC":"O","\u1ED8":"O","\u01EA":"O","\u01EC":"O","\u00D8":"O","\u01FE":"O","\u0186":"O","\u019F":"O",
  132. "\uA74A":"O","\uA74C":"O","\u01A2":"OI","\uA74E":"OO","\u0222":"OU",
  133. "\u24C5":"P","\uFF30":"P","\u1E54":"P","\u1E56":"P","\u01A4":"P","\u2C63":"P","\uA750":"P","\uA752":"P",
  134. "\uA754":"P",
  135. "\u24C6":"Q","\uFF31":"Q","\uA756":"Q","\uA758":"Q","\u024A":"Q",
  136. "\u24C7":"R","\uFF32":"R","\u0154":"R","\u1E58":"R","\u0158":"R","\u0210":"R","\u0212":"R","\u1E5A":"R",
  137. "\u1E5C":"R","\u0156":"R","\u1E5E":"R","\u024C":"R","\u2C64":"R","\uA75A":"R","\uA7A6":"R","\uA782":"R",
  138. "\u24C8":"S","\uFF33":"S","\u1E9E":"S","\u015A":"S","\u1E64":"S","\u015C":"S","\u1E60":"S","\u0160":"S",
  139. "\u1E66":"S","\u1E62":"S","\u1E68":"S","\u0218":"S","\u015E":"S","\u2C7E":"S","\uA7A8":"S","\uA784":"S",
  140. "\u24C9":"T","\uFF34":"T","\u1E6A":"T","\u0164":"T","\u1E6C":"T","\u021A":"T","\u0162":"T","\u1E70":"T",
  141. "\u1E6E":"T","\u0166":"T","\u01AC":"T","\u01AE":"T","\u023E":"T","\uA786":"T","\uA728":"TZ",
  142. "\u24CA":"U","\uFF35":"U","\u00D9":"U","\u00DA":"U","\u00DB":"U","\u0168":"U","\u1E78":"U","\u016A":"U",
  143. "\u1E7A":"U","\u016C":"U","\u00DC":"U","\u01DB":"U","\u01D7":"U","\u01D5":"U","\u01D9":"U","\u1EE6":"U",
  144. "\u016E":"U","\u0170":"U","\u01D3":"U","\u0214":"U","\u0216":"U","\u01AF":"U","\u1EEA":"U","\u1EE8":"U",
  145. "\u1EEE":"U","\u1EEC":"U","\u1EF0":"U","\u1EE4":"U","\u1E72":"U","\u0172":"U","\u1E76":"U","\u1E74":"U",
  146. "\u0244":"U",
  147. "\u24CB":"V","\uFF36":"V","\u1E7C":"V","\u1E7E":"V","\u01B2":"V","\uA75E":"V","\u0245":"V","\uA760":"VY",
  148. "\u24CC":"W","\uFF37":"W","\u1E80":"W","\u1E82":"W","\u0174":"W","\u1E86":"W","\u1E84":"W","\u1E88":"W",
  149. "\u2C72":"W",
  150. "\u24CD":"X","\uFF38":"X","\u1E8A":"X","\u1E8C":"X",
  151. "\u24CE":"Y","\uFF39":"Y","\u1EF2":"Y","\u00DD":"Y","\u0176":"Y","\u1EF8":"Y","\u0232":"Y","\u1E8E":"Y",
  152. "\u0178":"Y","\u1EF6":"Y","\u1EF4":"Y","\u01B3":"Y","\u024E":"Y","\u1EFE":"Y",
  153. "\u24CF":"Z","\uFF3A":"Z","\u0179":"Z","\u1E90":"Z","\u017B":"Z","\u017D":"Z","\u1E92":"Z","\u1E94":"Z",
  154. "\u01B5":"Z","\u0224":"Z","\u2C7F":"Z","\u2C6B":"Z","\uA762":"Z",
  155. "\u24D0":"a","\uFF41":"a","\u1E9A":"a","\u00E0":"a","\u00E1":"a","\u00E2":"a","\u1EA7":"a","\u1EA5":"a",
  156. "\u1EAB":"a","\u1EA9":"a","\u00E3":"a","\u0101":"a","\u0103":"a","\u1EB1":"a","\u1EAF":"a","\u1EB5":"a",
  157. "\u1EB3":"a","\u0227":"a","\u01E1":"a","\u00E4":"a","\u01DF":"a","\u1EA3":"a","\u00E5":"a","\u01FB":"a",
  158. "\u01CE":"a","\u0201":"a","\u0203":"a","\u1EA1":"a","\u1EAD":"a","\u1EB7":"a","\u1E01":"a","\u0105":"a",
  159. "\u2C65":"a","\u0250":"a",
  160. "\uA733":"aa","\u00E6":"ae","\u01FD":"ae","\u01E3":"ae","\uA735":"ao","\uA737":"au","\uA739":"av","\uA73B":"av",
  161. "\uA73D":"ay",
  162. "\u24D1":"b","\uFF42":"b","\u1E03":"b","\u1E05":"b","\u1E07":"b","\u0180":"b","\u0183":"b","\u0253":"b",
  163. "\u24D2":"c","\uFF43":"c","\u0107":"c","\u0109":"c","\u010B":"c","\u010D":"c","\u00E7":"c","\u1E09":"c",
  164. "\u0188":"c","\u023C":"c","\uA73F":"c","\u2184":"c",
  165. "\u24D3":"d","\uFF44":"d","\u1E0B":"d","\u010F":"d","\u1E0D":"d","\u1E11":"d","\u1E13":"d","\u1E0F":"d",
  166. "\u0111":"d","\u018C":"d","\u0256":"d","\u0257":"d","\uA77A":"d","\u01F3":"dz","\u01C6":"dz",
  167. "\u24D4":"e","\uFF45":"e","\u00E8":"e","\u00E9":"e","\u00EA":"e","\u1EC1":"e","\u1EBF":"e","\u1EC5":"e",
  168. "\u1EC3":"e","\u1EBD":"e","\u0113":"e","\u1E15":"e","\u1E17":"e","\u0115":"e","\u0117":"e","\u00EB":"e",
  169. "\u1EBB":"e","\u011B":"e","\u0205":"e","\u0207":"e","\u1EB9":"e","\u1EC7":"e","\u0229":"e","\u1E1D":"e",
  170. "\u0119":"e","\u1E19":"e","\u1E1B":"e","\u0247":"e","\u025B":"e","\u01DD":"e",
  171. "\u24D5":"f","\uFF46":"f","\u1E1F":"f","\u0192":"f","\uA77C":"f",
  172. "\u24D6":"g","\uFF47":"g","\u01F5":"g","\u011D":"g","\u1E21":"g","\u011F":"g","\u0121":"g","\u01E7":"g",
  173. "\u0123":"g","\u01E5":"g","\u0260":"g","\uA7A1":"g","\u1D79":"g","\uA77F":"g",
  174. "\u24D7":"h","\uFF48":"h","\u0125":"h","\u1E23":"h","\u1E27":"h","\u021F":"h","\u1E25":"h","\u1E29":"h",
  175. "\u1E2B":"h","\u1E96":"h","\u0127":"h","\u2C68":"h","\u2C76":"h","\u0265":"h","\u0195":"hv",
  176. "\u24D8":"i","\uFF49":"i","\u00EC":"i","\u00ED":"i","\u00EE":"i","\u0129":"i","\u012B":"i","\u012D":"i",
  177. "\u00EF":"i","\u1E2F":"i","\u1EC9":"i","\u01D0":"i","\u0209":"i","\u020B":"i","\u1ECB":"i","\u012F":"i",
  178. "\u1E2D":"i","\u0268":"i","\u0131":"i",
  179. "\u24D9":"j","\uFF4A":"j","\u0135":"j","\u01F0":"j","\u0249":"j",
  180. "\u24DA":"k","\uFF4B":"k","\u1E31":"k","\u01E9":"k","\u1E33":"k","\u0137":"k","\u1E35":"k","\u0199":"k",
  181. "\u2C6A":"k","\uA741":"k","\uA743":"k","\uA745":"k","\uA7A3":"k",
  182. "\u24DB":"l","\uFF4C":"l","\u0140":"l","\u013A":"l","\u013E":"l","\u1E37":"l","\u1E39":"l","\u013C":"l",
  183. "\u1E3D":"l","\u1E3B":"l","\u017F":"l","\u0142":"l","\u019A":"l","\u026B":"l","\u2C61":"l","\uA749":"l",
  184. "\uA781":"l","\uA747":"l","\u01C9":"lj",
  185. "\u24DC":"m","\uFF4D":"m","\u1E3F":"m","\u1E41":"m","\u1E43":"m","\u0271":"m","\u026F":"m",
  186. "\u24DD":"n","\uFF4E":"n","\u01F9":"n","\u0144":"n","\u00F1":"n","\u1E45":"n","\u0148":"n","\u1E47":"n",
  187. "\u0146":"n","\u1E4B":"n","\u1E49":"n","\u019E":"n","\u0272":"n","\u0149":"n","\uA791":"n","\uA7A5":"n",
  188. "\u01CC":"nj",
  189. "\u24DE":"o","\uFF4F":"o","\u00F2":"o","\u00F3":"o","\u00F4":"o","\u1ED3":"o","\u1ED1":"o","\u1ED7":"o",
  190. "\u1ED5":"o","\u00F5":"o","\u1E4D":"o","\u022D":"o","\u1E4F":"o","\u014D":"o","\u1E51":"o","\u1E53":"o",
  191. "\u014F":"o","\u022F":"o","\u0231":"o","\u00F6":"o","\u022B":"o","\u1ECF":"o","\u0151":"o","\u01D2":"o",
  192. "\u020D":"o","\u020F":"o","\u01A1":"o","\u1EDD":"o","\u1EDB":"o","\u1EE1":"o","\u1EDF":"o","\u1EE3":"o",
  193. "\u1ECD":"o","\u1ED9":"o","\u01EB":"o","\u01ED":"o","\u00F8":"o","\u01FF":"o","\u0254":"o","\uA74B":"o",
  194. "\uA74D":"o","\u0275":"o","\u01A3":"oi","\u0223":"ou","\uA74F":"oo",
  195. "\u24DF":"p","\uFF50":"p","\u1E55":"p","\u1E57":"p","\u01A5":"p","\u1D7D":"p","\uA751":"p","\uA753":"p",
  196. "\uA755":"p",
  197. "\u24E0":"q","\uFF51":"q","\u024B":"q","\uA757":"q","\uA759":"q",
  198. "\u24E1":"r","\uFF52":"r","\u0155":"r","\u1E59":"r","\u0159":"r","\u0211":"r","\u0213":"r","\u1E5B":"r",
  199. "\u1E5D":"r","\u0157":"r","\u1E5F":"r","\u024D":"r","\u027D":"r","\uA75B":"r","\uA7A7":"r","\uA783":"r",
  200. "\u24E2":"s","\uFF53":"s","\u00DF":"s","\u015B":"s","\u1E65":"s","\u015D":"s","\u1E61":"s","\u0161":"s",
  201. "\u1E67":"s","\u1E63":"s","\u1E69":"s","\u0219":"s","\u015F":"s","\u023F":"s","\uA7A9":"s","\uA785":"s",
  202. "\u1E9B":"s",
  203. "\u24E3":"t","\uFF54":"t","\u1E6B":"t","\u1E97":"t","\u0165":"t","\u1E6D":"t","\u021B":"t","\u0163":"t",
  204. "\u1E71":"t","\u1E6F":"t","\u0167":"t","\u01AD":"t","\u0288":"t","\u2C66":"t","\uA787":"t","\uA729":"tz",
  205. "\u24E4":"u","\uFF55":"u","\u00F9":"u","\u00FA":"u","\u00FB":"u","\u0169":"u","\u1E79":"u","\u016B":"u",
  206. "\u1E7B":"u","\u016D":"u","\u00FC":"u","\u01DC":"u","\u01D8":"u","\u01D6":"u","\u01DA":"u","\u1EE7":"u",
  207. "\u016F":"u","\u0171":"u","\u01D4":"u","\u0215":"u","\u0217":"u","\u01B0":"u","\u1EEB":"u","\u1EE9":"u",
  208. "\u1EEF":"u","\u1EED":"u","\u1EF1":"u","\u1EE5":"u","\u1E73":"u","\u0173":"u","\u1E77":"u","\u1E75":"u",
  209. "\u0289":"u",
  210. "\u24E5":"v","\uFF56":"v","\u1E7D":"v","\u1E7F":"v","\u028B":"v","\uA75F":"v","\u028C":"v","\uA761":"vy",
  211. "\u24E6":"w","\uFF57":"w","\u1E81":"w","\u1E83":"w","\u0175":"w","\u1E87":"w","\u1E85":"w","\u1E98":"w",
  212. "\u1E89":"w","\u2C73":"w",
  213. "\u24E7":"x","\uFF58":"x","\u1E8B":"x","\u1E8D":"x","\u24E8":"y","\uFF59":"y","\u1EF3":"y","\u00FD":"y",
  214. "\u0177":"y","\u1EF9":"y","\u0233":"y","\u1E8F":"y","\u00FF":"y","\u1EF7":"y","\u1E99":"y","\u1EF5":"y",
  215. "\u01B4":"y","\u024F":"y","\u1EFF":"y","\u24E9":"z","\uFF5A":"z","\u017A":"z","\u1E91":"z","\u017C":"z",
  216. "\u017E":"z","\u1E93":"z","\u1E95":"z","\u01B6":"z","\u0225":"z","\u0240":"z","\u2C6C":"z","\uA763":"z",
  217. "\u0386":"\u0391","\u0388":"\u0395","\u0389":"\u0397","\u038A":"\u0399",
  218. "\u03AA":"\u0399","\u038C":"\u039F","\u038E":"\u03A5","\u03AB":"\u03A5",
  219. "\u038F":"\u03A9","\u03AC":"\u03B1","\u03AD":"\u03B5","\u03AE":"\u03B7",
  220. "\u03AF":"\u03B9","\u03CA":"\u03B9","\u0390":"\u03B9","\u03CC":"\u03BF",
  221. "\u03CD":"\u03C5","\u03CB":"\u03C5","\u03B0":"\u03C5","\u03C9":"\u03C9",
  222. "\u03C2":"\u03C3"}
  223. $document = $(document);
  224. nextUid=(function() { var counter=1; return function() { return counter++; }; }());
  225. function reinsertElement(element) {
  226. var placeholder = $(document.createTextNode(''));
  227. element.before(placeholder);
  228. placeholder.before(element);
  229. placeholder.remove();
  230. }
  231. function stripDiacritics(str) {
  232. // Used 'uni range + named function' from http://jsperf.com/diacritics/18
  233. function match(a) {
  234. return DIACRITICS[a] || a;
  235. }
  236. return str.replace(/[^\u0000-\u007E]/g, match);
  237. }
  238. function indexOf(value, array) {
  239. var i = 0, l = array.length;
  240. for (; i < l; i = i + 1) {
  241. if (equal(value, array[i])) return i;
  242. }
  243. return -1;
  244. }
  245. function measureScrollbar () {
  246. var $template = $( MEASURE_SCROLLBAR_TEMPLATE );
  247. $template.appendTo('body');
  248. var dim = {
  249. width: $template.width() - $template[0].clientWidth,
  250. height: $template.height() - $template[0].clientHeight
  251. };
  252. $template.remove();
  253. return dim;
  254. }
  255. /**
  256. * Compares equality of a and b
  257. * @param a
  258. * @param b
  259. */
  260. function equal(a, b) {
  261. if (a === b) return true;
  262. if (a === undefined || b === undefined) return false;
  263. if (a === null || b === null) return false;
  264. // Check whether 'a' or 'b' is a string (primitive or object).
  265. // The concatenation of an empty string (+'') converts its argument to a string's primitive.
  266. if (a.constructor === String) return a+'' === b+''; // a+'' - in case 'a' is a String object
  267. if (b.constructor === String) return b+'' === a+''; // b+'' - in case 'b' is a String object
  268. return false;
  269. }
  270. /**
  271. * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
  272. * strings
  273. * @param string
  274. * @param separator
  275. */
  276. function splitVal(string, separator) {
  277. var val, i, l;
  278. if (string === null || string.length < 1) return [];
  279. val = string.split(separator);
  280. for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
  281. return val;
  282. }
  283. function getSideBorderPadding(element) {
  284. return element.outerWidth(false) - element.width();
  285. }
  286. function installKeyUpChangeEvent(element) {
  287. var key="keyup-change-value";
  288. element.on("keydown", function () {
  289. if ($.data(element, key) === undefined) {
  290. $.data(element, key, element.val());
  291. }
  292. });
  293. element.on("keyup", function () {
  294. var val= $.data(element, key);
  295. if (val !== undefined && element.val() !== val) {
  296. $.removeData(element, key);
  297. element.trigger("keyup-change");
  298. }
  299. });
  300. }
  301. $document.on("mousemove", function (e) {
  302. lastMousePosition.x = e.pageX;
  303. lastMousePosition.y = e.pageY;
  304. });
  305. /**
  306. * filters mouse events so an event is fired only if the mouse moved.
  307. *
  308. * filters out mouse events that occur when mouse is stationary but
  309. * the elements under the pointer are scrolled.
  310. */
  311. function installFilteredMouseMove(element) {
  312. element.on("mousemove", function (e) {
  313. var lastpos = lastMousePosition;
  314. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  315. $(e.target).trigger("mousemove-filtered", e);
  316. }
  317. });
  318. }
  319. /**
  320. * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
  321. * within the last quietMillis milliseconds.
  322. *
  323. * @param quietMillis number of milliseconds to wait before invoking fn
  324. * @param fn function to be debounced
  325. * @param ctx object to be used as this reference within fn
  326. * @return debounced version of fn
  327. */
  328. function debounce(quietMillis, fn, ctx) {
  329. ctx = ctx || undefined;
  330. var timeout;
  331. return function () {
  332. var args = arguments;
  333. window.clearTimeout(timeout);
  334. timeout = window.setTimeout(function() {
  335. fn.apply(ctx, args);
  336. }, quietMillis);
  337. };
  338. }
  339. function installDebouncedScroll(threshold, element) {
  340. var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
  341. element.on("scroll", function (e) {
  342. if (indexOf(e.target, element.get()) >= 0) notify(e);
  343. });
  344. }
  345. function focus($el) {
  346. if ($el[0] === document.activeElement) return;
  347. /* set the focus in a 0 timeout - that way the focus is set after the processing
  348. of the current event has finished - which seems like the only reliable way
  349. to set focus */
  350. window.setTimeout(function() {
  351. var el=$el[0], pos=$el.val().length, range;
  352. $el.focus();
  353. /* make sure el received focus so we do not error out when trying to manipulate the caret.
  354. sometimes modals or others listeners may steal it after its set */
  355. var isVisible = (el.offsetWidth > 0 || el.offsetHeight > 0);
  356. if (isVisible && el === document.activeElement) {
  357. /* after the focus is set move the caret to the end, necessary when we val()
  358. just before setting focus */
  359. if(el.setSelectionRange)
  360. {
  361. el.setSelectionRange(pos, pos);
  362. }
  363. else if (el.createTextRange) {
  364. range = el.createTextRange();
  365. range.collapse(false);
  366. range.select();
  367. }
  368. }
  369. }, 0);
  370. }
  371. function getCursorInfo(el) {
  372. el = $(el)[0];
  373. var offset = 0;
  374. var length = 0;
  375. if ('selectionStart' in el) {
  376. offset = el.selectionStart;
  377. length = el.selectionEnd - offset;
  378. } else if ('selection' in document) {
  379. el.focus();
  380. var sel = document.selection.createRange();
  381. length = document.selection.createRange().text.length;
  382. sel.moveStart('character', -el.value.length);
  383. offset = sel.text.length - length;
  384. }
  385. return { offset: offset, length: length };
  386. }
  387. function killEvent(event) {
  388. event.preventDefault();
  389. event.stopPropagation();
  390. }
  391. function killEventImmediately(event) {
  392. event.preventDefault();
  393. event.stopImmediatePropagation();
  394. }
  395. function measureTextWidth(e) {
  396. if (!sizer){
  397. var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
  398. sizer = $(document.createElement("div")).css({
  399. position: "absolute",
  400. left: "-10000px",
  401. top: "-10000px",
  402. display: "none",
  403. fontSize: style.fontSize,
  404. fontFamily: style.fontFamily,
  405. fontStyle: style.fontStyle,
  406. fontWeight: style.fontWeight,
  407. letterSpacing: style.letterSpacing,
  408. textTransform: style.textTransform,
  409. whiteSpace: "nowrap"
  410. });
  411. sizer.attr("class","select2-sizer");
  412. $("body").append(sizer);
  413. }
  414. sizer.text(e.val());
  415. return sizer.width();
  416. }
  417. function syncCssClasses(dest, src, adapter) {
  418. var classes, replacements = [], adapted;
  419. classes = dest.attr("class");
  420. if (classes) {
  421. classes = '' + classes; // for IE which returns object
  422. $(classes.split(" ")).each2(function() {
  423. if (this.indexOf("select2-") === 0) {
  424. replacements.push(this);
  425. }
  426. });
  427. }
  428. classes = src.attr("class");
  429. if (classes) {
  430. classes = '' + classes; // for IE which returns object
  431. $(classes.split(" ")).each2(function() {
  432. if (this.indexOf("select2-") !== 0) {
  433. adapted = adapter(this);
  434. if (adapted) {
  435. replacements.push(adapted);
  436. }
  437. }
  438. });
  439. }
  440. dest.attr("class", replacements.join(" "));
  441. }
  442. function markMatch(text, term, markup, escapeMarkup) {
  443. var match=stripDiacritics(text.toUpperCase()).indexOf(stripDiacritics(term.toUpperCase())),
  444. tl=term.length;
  445. if (match<0) {
  446. markup.push(escapeMarkup(text));
  447. return;
  448. }
  449. markup.push(escapeMarkup(text.substring(0, match)));
  450. markup.push("<span class='select2-match'>");
  451. markup.push(escapeMarkup(text.substring(match, match + tl)));
  452. markup.push("</span>");
  453. markup.push(escapeMarkup(text.substring(match + tl, text.length)));
  454. }
  455. function defaultEscapeMarkup(markup) {
  456. var replace_map = {
  457. '\\': '&#92;',
  458. '&': '&amp;',
  459. '<': '&lt;',
  460. '>': '&gt;',
  461. '"': '&quot;',
  462. "'": '&#39;',
  463. "/": '&#47;'
  464. };
  465. return String(markup).replace(/[&<>"'\/\\]/g, function (match) {
  466. return replace_map[match];
  467. });
  468. }
  469. /**
  470. * Produces an ajax-based query function
  471. *
  472. * @param options object containing configuration parameters
  473. * @param options.params parameter map for the transport ajax call, can contain such options as cache, jsonpCallback, etc. see $.ajax
  474. * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
  475. * @param options.url url for the data
  476. * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
  477. * @param options.dataType request data type: ajax, jsonp, other datatypes supported by jQuery's $.ajax function or the transport function if specified
  478. * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
  479. * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
  480. * The expected format is an object containing the following keys:
  481. * results array of objects that will be used as choices
  482. * more (optional) boolean indicating whether there are more results available
  483. * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
  484. */
  485. function ajax(options) {
  486. var timeout, // current scheduled but not yet executed request
  487. handler = null,
  488. quietMillis = options.quietMillis || 100,
  489. ajaxUrl = options.url,
  490. self = this;
  491. return function (query) {
  492. window.clearTimeout(timeout);
  493. timeout = window.setTimeout(function () {
  494. var data = options.data, // ajax data function
  495. url = ajaxUrl, // ajax url string or function
  496. transport = options.transport || $.fn.select2.ajaxDefaults.transport,
  497. // deprecated - to be removed in 4.0 - use params instead
  498. deprecated = {
  499. type: options.type || 'GET', // set type of request (GET or POST)
  500. cache: options.cache || false,
  501. jsonpCallback: options.jsonpCallback||undefined,
  502. dataType: options.dataType||"json"
  503. },
  504. params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated);
  505. data = data ? data.call(self, query.term, query.page, query.context) : null;
  506. url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
  507. if (handler && typeof handler.abort === "function") { handler.abort(); }
  508. if (options.params) {
  509. if ($.isFunction(options.params)) {
  510. $.extend(params, options.params.call(self));
  511. } else {
  512. $.extend(params, options.params);
  513. }
  514. }
  515. $.extend(params, {
  516. url: url,
  517. dataType: options.dataType,
  518. data: data,
  519. success: function (data) {
  520. // TODO - replace query.page with query so users have access to term, page, etc.
  521. var results = options.results(data, query.page);
  522. query.callback(results);
  523. }
  524. });
  525. handler = transport.call(self, params);
  526. }, quietMillis);
  527. };
  528. }
  529. /**
  530. * Produces a query function that works with a local array
  531. *
  532. * @param options object containing configuration parameters. The options parameter can either be an array or an
  533. * object.
  534. *
  535. * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
  536. *
  537. * If the object form is used it is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
  538. * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
  539. * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
  540. * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
  541. * the text.
  542. */
  543. function local(options) {
  544. var data = options, // data elements
  545. dataText,
  546. tmp,
  547. text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  548. if ($.isArray(data)) {
  549. tmp = data;
  550. data = { results: tmp };
  551. }
  552. if ($.isFunction(data) === false) {
  553. tmp = data;
  554. data = function() { return tmp; };
  555. }
  556. var dataItem = data();
  557. if (dataItem.text) {
  558. text = dataItem.text;
  559. // if text is not a function we assume it to be a key name
  560. if (!$.isFunction(text)) {
  561. dataText = dataItem.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available
  562. text = function (item) { return item[dataText]; };
  563. }
  564. }
  565. return function (query) {
  566. var t = query.term, filtered = { results: [] }, process;
  567. if (t === "") {
  568. query.callback(data());
  569. return;
  570. }
  571. process = function(datum, collection) {
  572. var group, attr;
  573. datum = datum[0];
  574. if (datum.children) {
  575. group = {};
  576. for (attr in datum) {
  577. if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
  578. }
  579. group.children=[];
  580. $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
  581. if (group.children.length || query.matcher(t, text(group), datum)) {
  582. collection.push(group);
  583. }
  584. } else {
  585. if (query.matcher(t, text(datum), datum)) {
  586. collection.push(datum);
  587. }
  588. }
  589. };
  590. $(data().results).each2(function(i, datum) { process(datum, filtered.results); });
  591. query.callback(filtered);
  592. };
  593. }
  594. // TODO javadoc
  595. function tags(data) {
  596. var isFunc = $.isFunction(data);
  597. return function (query) {
  598. var t = query.term, filtered = {results: []};
  599. var result = isFunc ? data(query) : data;
  600. if ($.isArray(result)) {
  601. $(result).each(function () {
  602. var isObject = this.text !== undefined,
  603. text = isObject ? this.text : this;
  604. if (t === "" || query.matcher(t, text)) {
  605. filtered.results.push(isObject ? this : {id: this, text: this});
  606. }
  607. });
  608. query.callback(filtered);
  609. }
  610. };
  611. }
  612. /**
  613. * Checks if the formatter function should be used.
  614. *
  615. * Throws an error if it is not a function. Returns true if it should be used,
  616. * false if no formatting should be performed.
  617. *
  618. * @param formatter
  619. */
  620. function checkFormatter(formatter, formatterName) {
  621. if ($.isFunction(formatter)) return true;
  622. if (!formatter) return false;
  623. if (typeof(formatter) === 'string') return true;
  624. throw new Error(formatterName +" must be a string, function, or falsy value");
  625. }
  626. /**
  627. * Returns a given value
  628. * If given a function, returns its output
  629. *
  630. * @param val string|function
  631. * @param context value of "this" to be passed to function
  632. * @returns {*}
  633. */
  634. function evaluate(val, context) {
  635. if ($.isFunction(val)) {
  636. var args = Array.prototype.slice.call(arguments, 2);
  637. return val.apply(context, args);
  638. }
  639. return val;
  640. }
  641. function countResults(results) {
  642. var count = 0;
  643. $.each(results, function(i, item) {
  644. if (item.children) {
  645. count += countResults(item.children);
  646. } else {
  647. count++;
  648. }
  649. });
  650. return count;
  651. }
  652. /**
  653. * Default tokenizer. This function uses breaks the input on substring match of any string from the
  654. * opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those
  655. * two options have to be defined in order for the tokenizer to work.
  656. *
  657. * @param input text user has typed so far or pasted into the search field
  658. * @param selection currently selected choices
  659. * @param selectCallback function(choice) callback tho add the choice to selection
  660. * @param opts select2's opts
  661. * @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value
  662. */
  663. function defaultTokenizer(input, selection, selectCallback, opts) {
  664. var original = input, // store the original so we can compare and know if we need to tell the search to update its text
  665. dupe = false, // check for whether a token we extracted represents a duplicate selected choice
  666. token, // token
  667. index, // position at which the separator was found
  668. i, l, // looping variables
  669. separator; // the matched separator
  670. if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined;
  671. while (true) {
  672. index = -1;
  673. for (i = 0, l = opts.tokenSeparators.length; i < l; i++) {
  674. separator = opts.tokenSeparators[i];
  675. index = input.indexOf(separator);
  676. if (index >= 0) break;
  677. }
  678. if (index < 0) break; // did not find any token separator in the input string, bail
  679. token = input.substring(0, index);
  680. input = input.substring(index + separator.length);
  681. if (token.length > 0) {
  682. token = opts.createSearchChoice.call(this, token, selection);
  683. if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) {
  684. dupe = false;
  685. for (i = 0, l = selection.length; i < l; i++) {
  686. if (equal(opts.id(token), opts.id(selection[i]))) {
  687. dupe = true; break;
  688. }
  689. }
  690. if (!dupe) selectCallback(token);
  691. }
  692. }
  693. }
  694. if (original!==input) return input;
  695. }
  696. function cleanupJQueryElements() {
  697. var self = this;
  698. Array.prototype.forEach.call(arguments, function (element) {
  699. self[element].remove();
  700. self[element] = null;
  701. });
  702. }
  703. /**
  704. * Creates a new class
  705. *
  706. * @param superClass
  707. * @param methods
  708. */
  709. function clazz(SuperClass, methods) {
  710. var constructor = function () {};
  711. constructor.prototype = new SuperClass;
  712. constructor.prototype.constructor = constructor;
  713. constructor.prototype.parent = SuperClass.prototype;
  714. constructor.prototype = $.extend(constructor.prototype, methods);
  715. return constructor;
  716. }
  717. AbstractSelect2 = clazz(Object, {
  718. // abstract
  719. bind: function (func) {
  720. var self = this;
  721. return function () {
  722. func.apply(self, arguments);
  723. };
  724. },
  725. // abstract
  726. init: function (opts) {
  727. var results, search, resultsSelector = ".select2-results";
  728. // prepare options
  729. this.opts = opts = this.prepareOpts(opts);
  730. this.id=opts.id;
  731. // destroy if called on an existing component
  732. if (opts.element.data("select2") !== undefined &&
  733. opts.element.data("select2") !== null) {
  734. opts.element.data("select2").destroy();
  735. }
  736. this.container = this.createContainer();
  737. this.liveRegion = $("<span>", {
  738. role: "status",
  739. "aria-live": "polite"
  740. })
  741. .addClass("select2-hidden-accessible")
  742. .appendTo(document.body);
  743. this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid());
  744. this.containerEventName= this.containerId
  745. .replace(/([.])/g, '_')
  746. .replace(/([;&,\-\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
  747. this.container.attr("id", this.containerId);
  748. this.container.attr("title", opts.element.attr("title"));
  749. this.body = $("body");
  750. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  751. this.container.attr("style", opts.element.attr("style"));
  752. this.container.css(evaluate(opts.containerCss, this.opts.element));
  753. this.container.addClass(evaluate(opts.containerCssClass, this.opts.element));
  754. this.elementTabIndex = this.opts.element.attr("tabindex");
  755. // swap container for the element
  756. this.opts.element
  757. .data("select2", this)
  758. .attr("tabindex", "-1")
  759. .before(this.container)
  760. .on("click.select2", killEvent); // do not leak click events
  761. this.container.data("select2", this);
  762. this.dropdown = this.container.find(".select2-drop");
  763. syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
  764. this.dropdown.addClass(evaluate(opts.dropdownCssClass, this.opts.element));
  765. this.dropdown.data("select2", this);
  766. this.dropdown.on("click", killEvent);
  767. this.results = results = this.container.find(resultsSelector);
  768. this.search = search = this.container.find("input.select2-input");
  769. this.queryCount = 0;
  770. this.resultsPage = 0;
  771. this.context = null;
  772. // initialize the container
  773. this.initContainer();
  774. this.container.on("click", killEvent);
  775. installFilteredMouseMove(this.results);
  776. this.dropdown.on("mousemove-filtered", resultsSelector, this.bind(this.highlightUnderEvent));
  777. this.dropdown.on("touchstart touchmove touchend", resultsSelector, this.bind(function (event) {
  778. this._touchEvent = true;
  779. this.highlightUnderEvent(event);
  780. }));
  781. this.dropdown.on("touchmove", resultsSelector, this.bind(this.touchMoved));
  782. this.dropdown.on("touchstart touchend", resultsSelector, this.bind(this.clearTouchMoved));
  783. // Waiting for a click event on touch devices to select option and hide dropdown
  784. // otherwise click will be triggered on an underlying element
  785. this.dropdown.on('click', this.bind(function (event) {
  786. if (this._touchEvent) {
  787. this._touchEvent = false;
  788. this.selectHighlighted();
  789. }
  790. }));
  791. installDebouncedScroll(80, this.results);
  792. this.dropdown.on("scroll-debounced", resultsSelector, this.bind(this.loadMoreIfNeeded));
  793. // do not propagate change event from the search field out of the component
  794. $(this.container).on("change", ".select2-input", function(e) {e.stopPropagation();});
  795. $(this.dropdown).on("change", ".select2-input", function(e) {e.stopPropagation();});
  796. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  797. if ($.fn.mousewheel) {
  798. results.mousewheel(function (e, delta, deltaX, deltaY) {
  799. var top = results.scrollTop();
  800. if (deltaY > 0 && top - deltaY <= 0) {
  801. results.scrollTop(0);
  802. killEvent(e);
  803. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  804. results.scrollTop(results.get(0).scrollHeight - results.height());
  805. killEvent(e);
  806. }
  807. });
  808. }
  809. installKeyUpChangeEvent(search);
  810. search.on("keyup-change input paste", this.bind(this.updateResults));
  811. search.on("focus", function () { search.addClass("select2-focused"); });
  812. search.on("blur", function () { search.removeClass("select2-focused");});
  813. this.dropdown.on("mouseup", resultsSelector, this.bind(function (e) {
  814. if ($(e.target).closest(".select2-result-selectable").length > 0) {
  815. this.highlightUnderEvent(e);
  816. this.selectHighlighted(e);
  817. }
  818. }));
  819. // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
  820. // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
  821. // dom it will trigger the popup close, which is not what we want
  822. // focusin can cause focus wars between modals and select2 since the dropdown is outside the modal.
  823. this.dropdown.on("click mouseup mousedown touchstart touchend focusin", function (e) { e.stopPropagation(); });
  824. this.nextSearchTerm = undefined;
  825. if ($.isFunction(this.opts.initSelection)) {
  826. // initialize selection based on the current value of the source element
  827. this.initSelection();
  828. // if the user has provided a function that can set selection based on the value of the source element
  829. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  830. this.monitorSource();
  831. }
  832. if (opts.maximumInputLength !== null) {
  833. this.search.attr("maxlength", opts.maximumInputLength);
  834. }
  835. var disabled = opts.element.prop("disabled");
  836. if (disabled === undefined) disabled = false;
  837. this.enable(!disabled);
  838. var readonly = opts.element.prop("readonly");
  839. if (readonly === undefined) readonly = false;
  840. this.readonly(readonly);
  841. // Calculate size of scrollbar
  842. scrollBarDimensions = scrollBarDimensions || measureScrollbar();
  843. this.autofocus = opts.element.prop("autofocus");
  844. opts.element.prop("autofocus", false);
  845. if (this.autofocus) this.focus();
  846. this.search.attr("placeholder", opts.searchInputPlaceholder);
  847. },
  848. // abstract
  849. destroy: function () {
  850. var element=this.opts.element, select2 = element.data("select2");
  851. this.close();
  852. if (element.length && element[0].detachEvent) {
  853. element.each(function () {
  854. this.detachEvent("onpropertychange", this._sync);
  855. });
  856. }
  857. if (this.propertyObserver) {
  858. this.propertyObserver.disconnect();
  859. this.propertyObserver = null;
  860. }
  861. this._sync = null;
  862. if (select2 !== undefined) {
  863. select2.container.remove();
  864. select2.liveRegion.remove();
  865. select2.dropdown.remove();
  866. element
  867. .removeClass("select2-offscreen")
  868. .removeData("select2")
  869. .off(".select2")
  870. .prop("autofocus", this.autofocus || false);
  871. if (this.elementTabIndex) {
  872. element.attr({tabindex: this.elementTabIndex});
  873. } else {
  874. element.removeAttr("tabindex");
  875. }
  876. element.show();
  877. }
  878. cleanupJQueryElements.call(this,
  879. "container",
  880. "liveRegion",
  881. "dropdown",
  882. "results",
  883. "search"
  884. );
  885. },
  886. // abstract
  887. optionToData: function(element) {
  888. if (element.is("option")) {
  889. return {
  890. id:element.prop("value"),
  891. text:element.text(),
  892. element: element.get(),
  893. css: element.attr("class"),
  894. disabled: element.prop("disabled"),
  895. locked: equal(element.attr("locked"), "locked") || equal(element.data("locked"), true)
  896. };
  897. } else if (element.is("optgroup")) {
  898. return {
  899. text:element.attr("label"),
  900. children:[],
  901. element: element.get(),
  902. css: element.attr("class")
  903. };
  904. }
  905. },
  906. // abstract
  907. prepareOpts: function (opts) {
  908. var element, select, idKey, ajaxUrl, self = this;
  909. element = opts.element;
  910. if (element.get(0).tagName.toLowerCase() === "select") {
  911. this.select = select = opts.element;
  912. }
  913. if (select) {
  914. // these options are not allowed when attached to a select because they are picked up off the element itself
  915. $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
  916. if (this in opts) {
  917. throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
  918. }
  919. });
  920. }
  921. opts = $.extend({}, {
  922. populateResults: function(container, results, query) {
  923. var populate, id=this.opts.id, liveRegion=this.liveRegion;
  924. populate=function(results, container, depth) {
  925. var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted;
  926. results = opts.sortResults(results, container, query);
  927. for (i = 0, l = results.length; i < l; i = i + 1) {
  928. result=results[i];
  929. disabled = (result.disabled === true);
  930. selectable = (!disabled) && (id(result) !== undefined);
  931. compound=result.children && result.children.length > 0;
  932. node=$("<li></li>");
  933. node.addClass("select2-results-dept-"+depth);
  934. node.addClass("select2-result");
  935. node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
  936. if (disabled) { node.addClass("select2-disabled"); }
  937. if (compound) { node.addClass("select2-result-with-children"); }
  938. node.addClass(self.opts.formatResultCssClass(result));
  939. node.attr("role", "presentation");
  940. label=$(document.createElement("div"));
  941. label.addClass("select2-result-label");
  942. label.attr("id", "select2-result-label-" + nextUid());
  943. label.attr("role", "option");
  944. formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup);
  945. if (formatted!==undefined) {
  946. label.html(formatted);
  947. node.append(label);
  948. }
  949. if (compound) {
  950. innerContainer=$("<ul></ul>");
  951. innerContainer.addClass("select2-result-sub");
  952. populate(result.children, innerContainer, depth+1);
  953. node.append(innerContainer);
  954. }
  955. node.data("select2-data", result);
  956. container.append(node);
  957. }
  958. liveRegion.text(opts.formatMatches(results.length));
  959. };
  960. populate(results, container, 0);
  961. }
  962. }, $.fn.select2.defaults, opts);
  963. if (typeof(opts.id) !== "function") {
  964. idKey = opts.id;
  965. opts.id = function (e) { return e[idKey]; };
  966. }
  967. if ($.isArray(opts.element.data("select2Tags"))) {
  968. if ("tags" in opts) {
  969. throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id");
  970. }
  971. opts.tags=opts.element.data("select2Tags");
  972. }
  973. if (select) {
  974. opts.query = this.bind(function (query) {
  975. var data = { results: [], more: false },
  976. term = query.term,
  977. children, placeholderOption, process;
  978. process=function(element, collection) {
  979. var group;
  980. if (element.is("option")) {
  981. if (query.matcher(term, element.text(), element)) {
  982. collection.push(self.optionToData(element));
  983. }
  984. } else if (element.is("optgroup")) {
  985. group=self.optionToData(element);
  986. element.children().each2(function(i, elm) { process(elm, group.children); });
  987. if (group.children.length>0) {
  988. collection.push(group);
  989. }
  990. }
  991. };
  992. children=element.children();
  993. // ignore the placeholder option if there is one
  994. if (this.getPlaceholder() !== undefined && children.length > 0) {
  995. placeholderOption = this.getPlaceholderOption();
  996. if (placeholderOption) {
  997. children=children.not(placeholderOption);
  998. }
  999. }
  1000. children.each2(function(i, elm) { process(elm, data.results); });
  1001. query.callback(data);
  1002. });
  1003. // this is needed because inside val() we construct choices from options and there id is hardcoded
  1004. opts.id=function(e) { return e.id; };
  1005. } else {
  1006. if (!("query" in opts)) {
  1007. if ("ajax" in opts) {
  1008. ajaxUrl = opts.element.data("ajax-url");
  1009. if (ajaxUrl && ajaxUrl.length > 0) {
  1010. opts.ajax.url = ajaxUrl;
  1011. }
  1012. opts.query = ajax.call(opts.element, opts.ajax);
  1013. } else if ("data" in opts) {
  1014. opts.query = local(opts.data);
  1015. } else if ("tags" in opts) {
  1016. opts.query = tags(opts.tags);
  1017. if (opts.createSearchChoice === undefined) {
  1018. opts.createSearchChoice = function (term) { return {id: $.trim(term), text: $.trim(term)}; };
  1019. }
  1020. if (opts.initSelection === undefined) {
  1021. opts.initSelection = function (element, callback) {
  1022. var data = [];
  1023. $(splitVal(element.val(), opts.separator)).each(function () {
  1024. var obj = { id: this, text: this },
  1025. tags = opts.tags;
  1026. if ($.isFunction(tags)) tags=tags();
  1027. $(tags).each(function() { if (equal(this.id, obj.id)) { obj = this; return false; } });
  1028. data.push(obj);
  1029. });
  1030. callback(data);
  1031. };
  1032. }
  1033. }
  1034. }
  1035. }
  1036. if (typeof(opts.query) !== "function") {
  1037. throw "query function not defined for Select2 " + opts.element.attr("id");
  1038. }
  1039. if (opts.createSearchChoicePosition === 'top') {
  1040. opts.createSearchChoicePosition = function(list, item) { list.unshift(item); };
  1041. }
  1042. else if (opts.createSearchChoicePosition === 'bottom') {
  1043. opts.createSearchChoicePosition = function(list, item) { list.push(item); };
  1044. }
  1045. else if (typeof(opts.createSearchChoicePosition) !== "function") {
  1046. throw "invalid createSearchChoicePosition option must be 'top', 'bottom' or a custom function";
  1047. }
  1048. return opts;
  1049. },
  1050. /**
  1051. * Monitor the original element for changes and update select2 accordingly
  1052. */
  1053. // abstract
  1054. monitorSource: function () {
  1055. var el = this.opts.element, observer, self = this;
  1056. el.on("change.select2", this.bind(function (e) {
  1057. if (this.opts.element.data("select2-change-triggered") !== true) {
  1058. this.initSelection();
  1059. }
  1060. }));
  1061. this._sync = this.bind(function () {
  1062. // sync enabled state
  1063. var disabled = el.prop("disabled");
  1064. if (disabled === undefined) disabled = false;
  1065. this.enable(!disabled);
  1066. var readonly = el.prop("readonly");
  1067. if (readonly === undefined) readonly = false;
  1068. this.readonly(readonly);
  1069. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  1070. this.container.addClass(evaluate(this.opts.containerCssClass, this.opts.element));
  1071. syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
  1072. this.dropdown.addClass(evaluate(this.opts.dropdownCssClass, this.opts.element));
  1073. });
  1074. // IE8-10 (IE9/10 won't fire propertyChange via attachEventListener)
  1075. if (el.length && el[0].attachEvent) {
  1076. el.each(function() {
  1077. this.attachEvent("onpropertychange", self._sync);
  1078. });
  1079. }
  1080. // safari, chrome, firefox, IE11
  1081. observer = window.MutationObserver || window.WebKitMutationObserver|| window.MozMutationObserver;
  1082. if (observer !== undefined) {
  1083. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  1084. this.propertyObserver = new observer(function (mutations) {
  1085. mutations.forEach(self._sync);
  1086. });
  1087. this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false });
  1088. }
  1089. },
  1090. // abstract
  1091. triggerSelect: function(data) {
  1092. var evt = $.Event("select2-selecting", { val: this.id(data), object: data });
  1093. this.opts.element.trigger(evt);
  1094. return !evt.isDefaultPrevented();
  1095. },
  1096. /**
  1097. * Triggers the change event on the source element
  1098. */
  1099. // abstract
  1100. triggerChange: function (details) {
  1101. details = details || {};
  1102. details= $.extend({}, details, { type: "change", val: this.val() });
  1103. // prevents recursive triggering
  1104. this.opts.element.data("select2-change-triggered", true);
  1105. this.opts.element.trigger(details);
  1106. this.opts.element.data("select2-change-triggered", false);
  1107. // some validation frameworks ignore the change event and listen instead to keyup, click for selects
  1108. // so here we trigger the click event manually
  1109. this.opts.element.click();
  1110. // ValidationEngine ignores the change event and listens instead to blur
  1111. // so here we trigger the blur event manually if so desired
  1112. if (this.opts.blurOnChange)
  1113. this.opts.element.blur();
  1114. },
  1115. //abstract
  1116. isInterfaceEnabled: function()
  1117. {
  1118. return this.enabledInterface === true;
  1119. },
  1120. // abstract
  1121. enableInterface: function() {
  1122. var enabled = this._enabled && !this._readonly,
  1123. disabled = !enabled;
  1124. if (enabled === this.enabledInterface) return false;
  1125. this.container.toggleClass("select2-container-disabled", disabled);
  1126. this.close();
  1127. this.enabledInterface = enabled;
  1128. return true;
  1129. },
  1130. // abstract
  1131. enable: function(enabled) {
  1132. if (enabled === undefined) enabled = true;
  1133. if (this._enabled === enabled) return;
  1134. this._enabled = enabled;
  1135. this.opts.element.prop("disabled", !enabled);
  1136. this.enableInterface();
  1137. },
  1138. // abstract
  1139. disable: function() {
  1140. this.enable(false);
  1141. },
  1142. // abstract
  1143. readonly: function(enabled) {
  1144. if (enabled === undefined) enabled = false;
  1145. if (this._readonly === enabled) return;
  1146. this._readonly = enabled;
  1147. this.opts.element.prop("readonly", enabled);
  1148. this.enableInterface();
  1149. },
  1150. // abstract
  1151. opened: function () {
  1152. return this.container.hasClass("select2-dropdown-open");
  1153. },
  1154. // abstract
  1155. positionDropdown: function() {
  1156. var $dropdown = this.dropdown,
  1157. offset = this.container.offset(),
  1158. height = this.container.outerHeight(false),
  1159. width = this.container.outerWidth(false),
  1160. dropHeight = $dropdown.outerHeight(false),
  1161. $window = $(window),
  1162. windowWidth = $window.width(),
  1163. windowHeight = $window.height(),
  1164. viewPortRight = $window.scrollLeft() + windowWidth,
  1165. viewportBottom = $window.scrollTop() + windowHeight,
  1166. dropTop = offset.top + height,
  1167. dropLeft = offset.left,
  1168. enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
  1169. enoughRoomAbove = (offset.top - dropHeight) >= $window.scrollTop(),
  1170. dropWidth = $dropdown.outerWidth(false),
  1171. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight,
  1172. aboveNow = $dropdown.hasClass("select2-drop-above"),
  1173. bodyOffset,
  1174. above,
  1175. changeDirection,
  1176. css,
  1177. resultsListNode;
  1178. // always prefer the current above/below alignment, unless there is not enough room
  1179. if (aboveNow) {
  1180. above = true;
  1181. if (!enoughRoomAbove && enoughRoomBelow) {
  1182. changeDirection = true;
  1183. above = false;
  1184. }
  1185. } else {
  1186. above = false;
  1187. if (!enoughRoomBelow && enoughRoomAbove) {
  1188. changeDirection = true;
  1189. above = true;
  1190. }
  1191. }
  1192. //if we are changing direction we need to get positions when dropdown is hidden;
  1193. if (changeDirection) {
  1194. $dropdown.hide();
  1195. offset = this.container.offset();
  1196. height = this.container.outerHeight(false);
  1197. width = this.container.outerWidth(false);
  1198. dropHeight = $dropdown.outerHeight(false);
  1199. viewPortRight = $window.scrollLeft() + windowWidth;
  1200. viewportBottom = $window.scrollTop() + windowHeight;
  1201. dropTop = offset.top + height;
  1202. dropLeft = offset.left;
  1203. dropWidth = $dropdown.outerWidth(false);
  1204. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
  1205. $dropdown.show();
  1206. // fix so the cursor does not move to the left within the search-textbox in IE
  1207. this.focusSearch();
  1208. }
  1209. if (this.opts.dropdownAutoWidth) {
  1210. resultsListNode = $('.select2-results', $dropdown)[0];
  1211. $dropdown.addClass('select2-drop-auto-width');
  1212. $dropdown.css('width', '');
  1213. // Add scrollbar width to dropdown if vertical scrollbar is present
  1214. dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width);
  1215. dropWidth > width ? width = dropWidth : dropWidth = width;
  1216. dropHeight = $dropdown.outerHeight(false);
  1217. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
  1218. }
  1219. else {
  1220. this.container.removeClass('select2-drop-auto-width');
  1221. }
  1222. //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
  1223. //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body.scrollTop(), "enough?", enoughRoomAbove);
  1224. // fix positioning when body has an offset and is not position: static
  1225. if (this.body.css('position') !== 'static') {
  1226. bodyOffset = this.body.offset();
  1227. dropTop -= bodyOffset.top;
  1228. dropLeft -= bodyOffset.left;
  1229. }
  1230. if (!enoughRoomOnRight) {
  1231. dropLeft = offset.left + this.container.outerWidth(false) - dropWidth;
  1232. }
  1233. css = {
  1234. left: dropLeft,
  1235. width: width
  1236. };
  1237. if (above) {
  1238. css.top = offset.top - dropHeight;
  1239. css.bottom = 'auto';
  1240. this.container.addClass("select2-drop-above");
  1241. $dropdown.addClass("select2-drop-above");
  1242. }
  1243. else {
  1244. css.top = dropTop;
  1245. css.bottom = 'auto';
  1246. this.container.removeClass("select2-drop-above");
  1247. $dropdown.removeClass("select2-drop-above");
  1248. }
  1249. css = $.extend(css, evaluate(this.opts.dropdownCss, this.opts.element));
  1250. $dropdown.css(css);
  1251. },
  1252. // abstract
  1253. shouldOpen: function() {
  1254. var event;
  1255. if (this.opened()) return false;
  1256. if (this._enabled === false || this._readonly === true) return false;
  1257. event = $.Event("select2-opening");
  1258. this.opts.element.trigger(event);
  1259. return !event.isDefaultPrevented();
  1260. },
  1261. // abstract
  1262. clearDropdownAlignmentPreference: function() {
  1263. // clear the classes used to figure out the preference of where the dropdown should be opened
  1264. this.container.removeClass("select2-drop-above");
  1265. this.dropdown.removeClass("select2-drop-above");
  1266. },
  1267. /**
  1268. * Opens the dropdown
  1269. *
  1270. * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
  1271. * the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
  1272. */
  1273. // abstract
  1274. open: function () {
  1275. if (!this.shouldOpen()) return false;
  1276. this.opening();
  1277. return true;
  1278. },
  1279. /**
  1280. * Performs the opening of the dropdown
  1281. */
  1282. // abstract
  1283. opening: function() {
  1284. var cid = this.containerEventName,
  1285. scroll = "scroll." + cid,
  1286. resize = "resize."+cid,
  1287. orient = "orientationchange."+cid,
  1288. mask;
  1289. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  1290. this.clearDropdownAlignmentPreference();
  1291. if(this.dropdown[0] !== this.body.children().last()[0]) {
  1292. this.dropdown.detach().appendTo(this.body);
  1293. }
  1294. // create the dropdown mask if doesn't already exist
  1295. mask = $("#select2-drop-mask");
  1296. if (mask.length == 0) {
  1297. mask = $(document.createElement("div"));
  1298. mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
  1299. mask.hide();
  1300. mask.appendTo(this.body);
  1301. mask.on("mousedown touchstart click", function (e) {
  1302. // Prevent IE from generating a click event on the body
  1303. reinsertElement(mask);
  1304. var dropdown = $("#select2-drop"), self;
  1305. if (dropdown.length > 0) {
  1306. self=dropdown.data("select2");
  1307. if (self.opts.selectOnBlur) {
  1308. self.selectHighlighted({noFocus: true});
  1309. }
  1310. self.close();
  1311. e.preventDefault();
  1312. e.stopPropagation();
  1313. }
  1314. });
  1315. }
  1316. // ensure the mask is always right before the dropdown
  1317. if (this.dropdown.prev()[0] !== mask[0]) {
  1318. this.dropdown.before(mask);
  1319. }
  1320. // move the global id to the correct dropdown
  1321. $("#select2-drop").removeAttr("id");
  1322. this.dropdown.attr("id", "select2-drop");
  1323. // show the elements
  1324. mask.show();
  1325. this.positionDropdown();
  1326. this.dropdown.show();
  1327. this.positionDropdown();
  1328. this.dropdown.addClass("select2-drop-active");
  1329. // attach listeners to events that can change the position of the container and thus require
  1330. // the position of the dropdown to be updated as well so it does not come unglued from the container
  1331. var that = this;
  1332. this.container.parents().add(window).each(function () {
  1333. $(this).on(resize+" "+scroll+" "+orient, function (e) {
  1334. if (that.opened()) that.positionDropdown();
  1335. });
  1336. });
  1337. },
  1338. // abstract
  1339. close: function () {
  1340. if (!this.opened()) return;
  1341. var cid = this.containerEventName,
  1342. scroll = "scroll." + cid,
  1343. resize = "resize."+cid,
  1344. orient = "orientationchange."+cid;
  1345. // unbind event listeners
  1346. this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); });
  1347. this.clearDropdownAlignmentPreference();
  1348. $("#select2-drop-mask").hide();
  1349. this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id
  1350. this.dropdown.hide();
  1351. this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active");
  1352. this.results.empty();
  1353. this.clearSearch();
  1354. this.search.removeClass("select2-active");
  1355. this.opts.element.trigger($.Event("select2-close"));
  1356. },
  1357. /**
  1358. * Opens control, sets input value, and updates results.
  1359. */
  1360. // abstract
  1361. externalSearch: function (term) {
  1362. this.open();
  1363. this.search.val(term);
  1364. this.updateResults(false);
  1365. },
  1366. // abstract
  1367. clearSearch: function () {
  1368. },
  1369. //abstract
  1370. getMaximumSelectionSize: function() {
  1371. return evaluate(this.opts.maximumSelectionSize, this.opts.element);
  1372. },
  1373. // abstract
  1374. ensureHighlightVisible: function () {
  1375. var results = this.results, children, index, child, hb, rb, y, more;
  1376. index = this.highlight();
  1377. if (index < 0) return;
  1378. if (index == 0) {
  1379. // if the first element is highlighted scroll all the way to the top,
  1380. // that way any unselectable headers above it will also be scrolled
  1381. // into view
  1382. results.scrollTop(0);
  1383. return;
  1384. }
  1385. children = this.findHighlightableChoices().find('.select2-result-label');
  1386. child = $(children[index]);
  1387. hb = child.offset().top + child.outerHeight(true);
  1388. // if this is the last child lets also make sure select2-more-results is visible
  1389. if (index === children.length - 1) {
  1390. more = results.find("li.select2-more-results");
  1391. if (more.length > 0) {
  1392. hb = more.offset().top + more.outerHeight(true);
  1393. }
  1394. }
  1395. rb = results.offset().top + results.outerHeight(true);
  1396. if (hb > rb) {
  1397. results.scrollTop(results.scrollTop() + (hb - rb));
  1398. }
  1399. y = child.offset().top - results.offset().top;
  1400. // make sure the top of the element is visible
  1401. if (y < 0 && child.css('display') != 'none' ) {
  1402. results.scrollTop(results.scrollTop() + y); // y is negative
  1403. }
  1404. },
  1405. // abstract
  1406. findHighlightableChoices: function() {
  1407. return this.results.find(".select2-result-selectable:not(.select2-disabled):not(.select2-selected)");
  1408. },
  1409. // abstract
  1410. moveHighlight: function (delta) {
  1411. var choices = this.findHighlightableChoices(),
  1412. index = this.highlight();
  1413. while (index > -1 && index < choices.length) {
  1414. index += delta;
  1415. var choice = $(choices[index]);
  1416. if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) {
  1417. this.highlight(index);
  1418. break;
  1419. }
  1420. }
  1421. },
  1422. // abstract
  1423. highlight: function (index) {
  1424. var choices = this.findHighlightableChoices(),
  1425. choice,
  1426. data;
  1427. if (arguments.length === 0) {
  1428. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  1429. }
  1430. if (index >= choices.length) index = choices.length - 1;
  1431. if (index < 0) index = 0;
  1432. this.removeHighlight();
  1433. choice = $(choices[index]);
  1434. choice.addClass("select2-highlighted");
  1435. // ensure assistive technology can determine the active choice
  1436. this.search.attr("aria-activedescendant", choice.find(".select2-result-label").attr("id"));
  1437. this.ensureHighlightVisible();
  1438. this.liveRegion.text(choice.text());
  1439. data = choice.data("select2-data");
  1440. if (data) {
  1441. this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data });
  1442. }
  1443. },
  1444. removeHighlight: function() {
  1445. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  1446. },
  1447. touchMoved: function() {
  1448. this._touchMoved = true;
  1449. },
  1450. clearTouchMoved: function() {
  1451. this._touchMoved = false;
  1452. },
  1453. // abstract
  1454. countSelectableResults: function() {
  1455. return this.findHighlightableChoices().length;
  1456. },
  1457. // abstract
  1458. highlightUnderEvent: function (event) {
  1459. var el = $(event.target).closest(".select2-result-selectable");
  1460. if (el.length > 0 && !el.is(".select2-highlighted")) {
  1461. var choices = this.findHighlightableChoices();
  1462. this.highlight(choices.index(el));
  1463. } else if (el.length == 0) {
  1464. // if we are over an unselectable item remove all highlights
  1465. this.removeHighlight();
  1466. }
  1467. },
  1468. // abstract
  1469. loadMoreIfNeeded: function () {
  1470. var results = this.results,
  1471. more = results.find("li.select2-more-results"),
  1472. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  1473. page = this.resultsPage + 1,
  1474. self=this,
  1475. term=this.search.val(),
  1476. context=this.context;
  1477. if (more.length === 0) return;
  1478. below = more.offset().top - results.offset().top - results.height();
  1479. if (below <= this.opts.loadMorePadding) {
  1480. more.addClass("select2-active");
  1481. this.opts.query({
  1482. element: this.opts.element,
  1483. term: term,
  1484. page: page,
  1485. context: context,
  1486. matcher: this.opts.matcher,
  1487. callback: this.bind(function (data) {
  1488. // ignore a response if the select2 has been closed before it was received
  1489. if (!self.opened()) return;
  1490. self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
  1491. self.postprocessResults(data, false, false);
  1492. if (data.more===true) {
  1493. more.detach().appendTo(results).text(evaluate(self.opts.formatLoadMore, self.opts.element, page+1));
  1494. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1495. } else {
  1496. more.remove();
  1497. }
  1498. self.positionDropdown();
  1499. self.resultsPage = page;
  1500. self.context = data.context;
  1501. this.opts.element.trigger({ type: "select2-loaded", items: data });
  1502. })});
  1503. }
  1504. },
  1505. /**
  1506. * Default tokenizer function which does nothing
  1507. */
  1508. tokenize: function() {
  1509. },
  1510. /**
  1511. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  1512. */
  1513. // abstract
  1514. updateResults: function (initial) {
  1515. var search = this.search,
  1516. results = this.results,
  1517. opts = this.opts,
  1518. data,
  1519. self = this,
  1520. input,
  1521. term = search.val(),
  1522. lastTerm = $.data(this.container, "select2-last-term"),
  1523. // sequence number used to drop out-of-order responses
  1524. queryNumber;
  1525. // prevent duplicate queries against the same term
  1526. if (initial !== true && lastTerm && equal(term, lastTerm)) return;
  1527. $.data(this.container, "select2-last-term", term);
  1528. // if the search is currently hidden we do not alter the results
  1529. if (initial !== true && (this.showSearchInput === false || !this.opened())) {
  1530. return;
  1531. }
  1532. function postRender() {
  1533. search.removeClass("select2-active");
  1534. self.positionDropdown();
  1535. if (results.find('.select2-no-results,.select2-selection-limit,.select2-searching').length) {
  1536. self.liveRegion.text(results.text());
  1537. }
  1538. else {
  1539. self.liveRegion.text(self.opts.formatMatches(results.find('.select2-result-selectable').length));
  1540. }
  1541. }
  1542. function render(html) {
  1543. results.html(html);
  1544. postRender();
  1545. }
  1546. queryNumber = ++this.queryCount;
  1547. var maxSelSize = this.getMaximumSelectionSize();
  1548. if (maxSelSize >=1) {
  1549. data = this.data();
  1550. if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
  1551. render("<li class='select2-selection-limit'>" + evaluate(opts.formatSelectionTooBig, opts.element, maxSelSize) + "</li>");
  1552. return;
  1553. }
  1554. }
  1555. if (search.val().length < opts.minimumInputLength) {
  1556. if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
  1557. render("<li class='select2-no-results'>" + evaluate(opts.formatInputTooShort, opts.element, search.val(), opts.minimumInputLength) + "</li>");
  1558. } else {
  1559. render("");
  1560. }
  1561. if (initial && this.showSearch) this.showSearch(true);
  1562. return;
  1563. }
  1564. if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) {
  1565. if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) {
  1566. render("<li class='select2-no-results'>" + evaluate(opts.formatInputTooLong, opts.element, search.val(), opts.maximumInputLength) + "</li>");
  1567. } else {
  1568. render("");
  1569. }
  1570. return;
  1571. }
  1572. if (opts.formatSearching && this.findHighlightableChoices().length === 0) {
  1573. render("<li class='select2-searching'>" + evaluate(opts.formatSearching, opts.element) + "</li>");
  1574. }
  1575. search.addClass("select2-active");
  1576. this.removeHighlight();
  1577. // give the tokenizer a chance to pre-process the input
  1578. input = this.tokenize();
  1579. if (input != undefined && input != null) {
  1580. search.val(input);
  1581. }
  1582. this.resultsPage = 1;
  1583. opts.query({
  1584. element: opts.element,
  1585. term: search.val(),
  1586. page: this.resultsPage,
  1587. context: null,
  1588. matcher: opts.matcher,
  1589. callback: this.bind(function (data) {
  1590. var def; // default choice
  1591. // ignore old responses
  1592. if (queryNumber != this.queryCount) {
  1593. return;
  1594. }
  1595. // ignore a response if the select2 has been closed before it was received
  1596. if (!this.opened()) {
  1597. this.search.removeClass("select2-active");
  1598. return;
  1599. }
  1600. // save context, if any
  1601. this.context = (data.context===undefined) ? null : data.context;
  1602. // create a default choice and prepend it to the list
  1603. if (this.opts.createSearchChoice && search.val() !== "") {
  1604. def = this.opts.createSearchChoice.call(self, search.val(), data.results);
  1605. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  1606. if ($(data.results).filter(
  1607. function () {
  1608. return equal(self.id(this), self.id(def));
  1609. }).length === 0) {
  1610. this.opts.createSearchChoicePosition(data.results, def);
  1611. }
  1612. }
  1613. }
  1614. if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
  1615. render("<li class='select2-no-results'>" + evaluate(opts.formatNoMatches, opts.element, search.val()) + "</li>");
  1616. return;
  1617. }
  1618. results.empty();
  1619. self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  1620. if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
  1621. results.append("<li class='select2-more-results'>" + opts.escapeMarkup(evaluate(opts.formatLoadMore, opts.element, this.resultsPage)) + "</li>");
  1622. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1623. }
  1624. this.postprocessResults(data, initial);
  1625. postRender();
  1626. this.opts.element.trigger({ type: "select2-loaded", items: data });
  1627. })});
  1628. },
  1629. // abstract
  1630. cancel: function () {
  1631. this.close();
  1632. },
  1633. // abstract
  1634. blur: function () {
  1635. // if selectOnBlur == true, select the currently highlighted option
  1636. if (this.opts.selectOnBlur)
  1637. this.selectHighlighted({noFocus: true});
  1638. this.close();
  1639. this.container.removeClass("select2-container-active");
  1640. // synonymous to .is(':focus'), which is available in jquery >= 1.6
  1641. if (this.search[0] === document.activeElement) { this.search.blur(); }
  1642. this.clearSearch();
  1643. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1644. },
  1645. // abstract
  1646. focusSearch: function () {
  1647. focus(this.search);
  1648. },
  1649. // abstract
  1650. selectHighlighted: function (options) {
  1651. if (this._touchMoved) {
  1652. this.clearTouchMoved();
  1653. return;
  1654. }
  1655. var index=this.highlight(),
  1656. highlighted=this.results.find(".select2-highlighted"),
  1657. data = highlighted.closest('.select2-result').data("select2-data");
  1658. if (data) {
  1659. this.highlight(index);
  1660. this.onSelect(data, options);
  1661. } else if (options && options.noFocus) {
  1662. this.close();
  1663. }
  1664. },
  1665. // abstract
  1666. getPlaceholder: function () {
  1667. var placeholderOption;
  1668. return this.opts.element.attr("placeholder") ||
  1669. this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
  1670. this.opts.element.data("placeholder") ||
  1671. this.opts.placeholder ||
  1672. ((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined);
  1673. },
  1674. // abstract
  1675. getPlaceholderOption: function() {
  1676. if (this.select) {
  1677. var firstOption = this.select.children('option').first();
  1678. if (this.opts.placeholderOption !== undefined ) {
  1679. //Determine the placeholder option based on the specified placeholderOption setting
  1680. return (this.opts.placeholderOption === "first" && firstOption) ||
  1681. (typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select));
  1682. } else if ($.trim(firstOption.text()) === "" && firstOption.val() === "") {
  1683. //No explicit placeholder option specified, use the first if it's blank
  1684. return firstOption;
  1685. }
  1686. }
  1687. },
  1688. /**
  1689. * Get the desired width for the container element. This is
  1690. * derived first from option `width` passed to select2, then
  1691. * the inline 'style' on the original element, and finally
  1692. * falls back to the jQuery calculated element width.
  1693. */
  1694. // abstract
  1695. initContainerWidth: function () {
  1696. function resolveContainerWidth() {
  1697. var style, attrs, matches, i, l, attr;
  1698. if (this.opts.width === "off") {
  1699. return null;
  1700. } else if (this.opts.width === "element"){
  1701. return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px';
  1702. } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
  1703. // check if there is inline style on the element that contains width
  1704. style = this.opts.element.attr('style');
  1705. if (style !== undefined) {
  1706. attrs = style.split(';');
  1707. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  1708. attr = attrs[i].replace(/\s/g, '');
  1709. matches = attr.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i);
  1710. if (matches !== null && matches.length >= 1)
  1711. return matches[1];
  1712. }
  1713. }
  1714. if (this.opts.width === "resolve") {
  1715. // next check if css('width') can resolve a width that is percent based, this is sometimes possible
  1716. // when attached to input type=hidden or elements hidden via css
  1717. style = this.opts.element.css('width');
  1718. if (style.indexOf("%") > 0) return style;
  1719. // finally, fallback on the calculated width of the element
  1720. return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px');
  1721. }
  1722. return null;
  1723. } else if ($.isFunction(this.opts.width)) {
  1724. return this.opts.width();
  1725. } else {
  1726. return this.opts.width;
  1727. }
  1728. };
  1729. var width = resolveContainerWidth.call(this);
  1730. if (width !== null) {
  1731. this.container.css("width", width);
  1732. }
  1733. }
  1734. });
  1735. SingleSelect2 = clazz(AbstractSelect2, {
  1736. // single
  1737. createContainer: function () {
  1738. var container = $(document.createElement("div")).attr({
  1739. "class": "select2-container"
  1740. }).html([
  1741. "<a href='javascript:void(0)' class='select2-choice' tabindex='-1'>",
  1742. " <span class='select2-chosen'>&#160;</span><abbr class='select2-search-choice-close'></abbr>",
  1743. " <span class='select2-arrow' role='presentation'><b role='presentation'></b></span>",
  1744. "</a>",
  1745. "<label for='' class='select2-offscreen'></label>",
  1746. "<input class='select2-focusser select2-offscreen' type='text' aria-haspopup='true' role='button' />",
  1747. "<div class='select2-drop select2-display-none'>",
  1748. " <div class='select2-search'>",
  1749. " <label for='' class='select2-offscreen'></label>",
  1750. " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input' role='combobox' aria-expanded='true'",
  1751. " aria-autocomplete='list' />",
  1752. " </div>",
  1753. " <ul class='select2-results' role='listbox'>",
  1754. " </ul>",
  1755. "</div>"].join(""));
  1756. return container;
  1757. },
  1758. // single
  1759. enableInterface: function() {
  1760. if (this.parent.enableInterface.apply(this, arguments)) {
  1761. this.focusser.prop("disabled", !this.isInterfaceEnabled());
  1762. }
  1763. },
  1764. // single
  1765. opening: function () {
  1766. var el, range, len;
  1767. if (this.opts.minimumResultsForSearch >= 0) {
  1768. this.showSearch(true);
  1769. }
  1770. this.parent.opening.apply(this, arguments);
  1771. if (this.showSearchInput !== false) {
  1772. // IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range
  1773. // all other browsers handle this just fine
  1774. this.search.val(this.focusser.val());
  1775. }
  1776. if (this.opts.shouldFocusInput(this)) {
  1777. this.search.focus();
  1778. // move the cursor to the end after focussing, otherwise it will be at the beginning and
  1779. // new text will appear *before* focusser.val()
  1780. el = this.search.get(0);
  1781. if (el.createTextRange) {
  1782. range = el.createTextRange();
  1783. range.collapse(false);
  1784. range.select();
  1785. } else if (el.setSelectionRange) {
  1786. len = this.search.val().length;
  1787. el.setSelectionRange(len, len);
  1788. }
  1789. }
  1790. // initializes search's value with nextSearchTerm (if defined by user)
  1791. // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
  1792. if(this.search.val() === "") {
  1793. if(this.nextSearchTerm != undefined){
  1794. this.search.val(this.nextSearchTerm);
  1795. this.search.select();
  1796. }
  1797. }
  1798. this.focusser.prop("disabled", true).val("");
  1799. this.updateResults(true);
  1800. this.opts.element.trigger($.Event("select2-open"));
  1801. },
  1802. // single
  1803. close: function () {
  1804. if (!this.opened()) return;
  1805. this.parent.close.apply(this, arguments);
  1806. this.focusser.prop("disabled", false);
  1807. if (this.opts.shouldFocusInput(this)) {
  1808. this.focusser.focus();
  1809. }
  1810. },
  1811. // single
  1812. focus: function () {
  1813. if (this.opened()) {
  1814. this.close();
  1815. } else {
  1816. this.focusser.prop("disabled", false);
  1817. if (this.opts.shouldFocusInput(this)) {
  1818. this.focusser.focus();
  1819. }
  1820. }
  1821. },
  1822. // single
  1823. isFocused: function () {
  1824. return this.container.hasClass("select2-container-active");
  1825. },
  1826. // single
  1827. cancel: function () {
  1828. this.parent.cancel.apply(this, arguments);
  1829. this.focusser.prop("disabled", false);
  1830. if (this.opts.shouldFocusInput(this)) {
  1831. this.focusser.focus();
  1832. }
  1833. },
  1834. // single
  1835. destroy: function() {
  1836. $("label[for='" + this.focusser.attr('id') + "']")
  1837. .attr('for', this.opts.element.attr("id"));
  1838. this.parent.destroy.apply(this, arguments);
  1839. cleanupJQueryElements.call(this,
  1840. "selection",
  1841. "focusser"
  1842. );
  1843. },
  1844. // single
  1845. initContainer: function () {
  1846. var selection,
  1847. container = this.container,
  1848. dropdown = this.dropdown,
  1849. idSuffix = nextUid(),
  1850. elementLabel;
  1851. if (this.opts.minimumResultsForSearch < 0) {
  1852. this.showSearch(false);
  1853. } else {
  1854. this.showSearch(true);
  1855. }
  1856. this.selection = selection = container.find(".select2-choice");
  1857. this.focusser = container.find(".select2-focusser");
  1858. // add aria associations
  1859. selection.find(".select2-chosen").attr("id", "select2-chosen-"+idSuffix);
  1860. this.focusser.attr("aria-labelledby", "select2-chosen-"+idSuffix);
  1861. this.results.attr("id", "select2-results-"+idSuffix);
  1862. this.search.attr("aria-owns", "select2-results-"+idSuffix);
  1863. // rewrite labels from original element to focusser
  1864. this.focusser.attr("id", "s2id_autogen"+idSuffix);
  1865. elementLabel = $("label[for='" + this.opts.element.attr("id") + "']");
  1866. this.focusser.prev()
  1867. .text(elementLabel.text())
  1868. .attr('for', this.focusser.attr('id'));
  1869. // Ensure the original element retains an accessible name
  1870. var originalTitle = this.opts.element.attr("title");
  1871. this.opts.element.attr("title", (originalTitle || elementLabel.text()));
  1872. this.focusser.attr("tabindex", this.elementTabIndex);
  1873. // write label for search field using the label from the focusser element
  1874. this.search.attr("id", this.focusser.attr('id') + '_search');
  1875. this.search.prev()
  1876. .text($("label[for='" + this.focusser.attr('id') + "']").text())
  1877. .attr('for', this.search.attr('id'));
  1878. this.search.on("keydown", this.bind(function (e) {
  1879. if (!this.isInterfaceEnabled()) return;
  1880. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1881. // prevent the page from scrolling
  1882. killEvent(e);
  1883. return;
  1884. }
  1885. switch (e.which) {
  1886. case KEY.UP:
  1887. case KEY.DOWN:
  1888. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1889. killEvent(e);
  1890. return;
  1891. case KEY.ENTER:
  1892. this.selectHighlighted();
  1893. killEvent(e);
  1894. return;
  1895. case KEY.TAB:
  1896. this.selectHighlighted({noFocus: true});
  1897. return;
  1898. case KEY.ESC:
  1899. this.cancel(e);
  1900. killEvent(e);
  1901. return;
  1902. }
  1903. }));
  1904. this.search.on("blur", this.bind(function(e) {
  1905. // a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown.
  1906. // without this the search field loses focus which is annoying
  1907. if (document.activeElement === this.body.get(0)) {
  1908. window.setTimeout(this.bind(function() {
  1909. if (this.opened()) {
  1910. this.search.focus();
  1911. }
  1912. }), 0);
  1913. }
  1914. }));
  1915. this.focusser.on("keydown", this.bind(function (e) {
  1916. if (!this.isInterfaceEnabled()) return;
  1917. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  1918. return;
  1919. }
  1920. if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
  1921. killEvent(e);
  1922. return;
  1923. }
  1924. if (e.which == KEY.DOWN || e.which == KEY.UP
  1925. || (e.which == KEY.ENTER && this.opts.openOnEnter)) {
  1926. if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return;
  1927. this.open();
  1928. killEvent(e);
  1929. return;
  1930. }
  1931. if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) {
  1932. if (this.opts.allowClear) {
  1933. this.clear();
  1934. }
  1935. killEvent(e);
  1936. return;
  1937. }
  1938. }));
  1939. installKeyUpChangeEvent(this.focusser);
  1940. this.focusser.on("keyup-change input", this.bind(function(e) {
  1941. if (this.opts.minimumResultsForSearch >= 0) {
  1942. e.stopPropagation();
  1943. if (this.opened()) return;
  1944. this.open();
  1945. }
  1946. }));
  1947. selection.on("mousedown touchstart", "abbr", this.bind(function (e) {
  1948. if (!this.isInterfaceEnabled()) return;
  1949. this.clear();
  1950. killEventImmediately(e);
  1951. this.close();
  1952. this.selection.focus();
  1953. }));
  1954. selection.on("mousedown touchstart", this.bind(function (e) {
  1955. // Prevent IE from generating a click event on the body
  1956. reinsertElement(selection);
  1957. if (!this.container.hasClass("select2-container-active")) {
  1958. this.opts.element.trigger($.Event("select2-focus"));
  1959. }
  1960. if (this.opened()) {
  1961. this.close();
  1962. } else if (this.isInterfaceEnabled()) {
  1963. this.open();
  1964. }
  1965. killEvent(e);
  1966. }));
  1967. dropdown.on("mousedown touchstart", this.bind(function() {
  1968. if (this.opts.shouldFocusInput(this)) {
  1969. this.search.focus();
  1970. }
  1971. }));
  1972. selection.on("focus", this.bind(function(e) {
  1973. killEvent(e);
  1974. }));
  1975. this.focusser.on("focus", this.bind(function(){
  1976. if (!this.container.hasClass("select2-container-active")) {
  1977. this.opts.element.trigger($.Event("select2-focus"));
  1978. }
  1979. this.container.addClass("select2-container-active");
  1980. })).on("blur", this.bind(function() {
  1981. if (!this.opened()) {
  1982. this.container.removeClass("select2-container-active");
  1983. this.opts.element.trigger($.Event("select2-blur"));
  1984. }
  1985. }));
  1986. this.search.on("focus", this.bind(function(){
  1987. if (!this.container.hasClass("select2-container-active")) {
  1988. this.opts.element.trigger($.Event("select2-focus"));
  1989. }
  1990. this.container.addClass("select2-container-active");
  1991. }));
  1992. this.initContainerWidth();
  1993. this.opts.element.addClass("select2-offscreen");
  1994. this.setPlaceholder();
  1995. },
  1996. // single
  1997. clear: function(triggerChange) {
  1998. var data=this.selection.data("select2-data");
  1999. if (data) { // guard against queued quick consecutive clicks
  2000. var evt = $.Event("select2-clearing");
  2001. this.opts.element.trigger(evt);
  2002. if (evt.isDefaultPrevented()) {
  2003. return;
  2004. }
  2005. var placeholderOption = this.getPlaceholderOption();
  2006. this.opts.element.val(placeholderOption ? placeholderOption.val() : "");
  2007. this.selection.find(".select2-chosen").empty();
  2008. this.selection.removeData("select2-data");
  2009. this.setPlaceholder();
  2010. if (triggerChange !== false){
  2011. this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
  2012. this.triggerChange({removed:data});
  2013. }
  2014. }
  2015. },
  2016. /**
  2017. * Sets selection based on source element's value
  2018. */
  2019. // single
  2020. initSelection: function () {
  2021. var selected;
  2022. if (this.isPlaceholderOptionSelected()) {
  2023. this.updateSelection(null);
  2024. this.close();
  2025. this.setPlaceholder();
  2026. } else {
  2027. var self = this;
  2028. this.opts.initSelection.call(null, this.opts.element, function(selected){
  2029. if (selected !== undefined && selected !== null) {
  2030. self.updateSelection(selected);
  2031. self.close();
  2032. self.setPlaceholder();
  2033. self.nextSearchTerm = self.opts.nextSearchTerm(selected, self.search.val());
  2034. }
  2035. });
  2036. }
  2037. },
  2038. isPlaceholderOptionSelected: function() {
  2039. var placeholderOption;
  2040. if (this.getPlaceholder() === undefined) return false; // no placeholder specified so no option should be considered
  2041. return ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.prop("selected"))
  2042. || (this.opts.element.val() === "")
  2043. || (this.opts.element.val() === undefined)
  2044. || (this.opts.element.val() === null);
  2045. },
  2046. // single
  2047. prepareOpts: function () {
  2048. var opts = this.parent.prepareOpts.apply(this, arguments),
  2049. self=this;
  2050. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  2051. // install the selection initializer
  2052. opts.initSelection = function (element, callback) {
  2053. var selected = element.find("option").filter(function() { return this.selected && !this.disabled });
  2054. // a single select box always has a value, no need to null check 'selected'
  2055. callback(self.optionToData(selected));
  2056. };
  2057. } else if ("data" in opts) {
  2058. // install default initSelection when applied to hidden input and data is local
  2059. opts.initSelection = opts.initSelection || function (element, callback) {
  2060. var id = element.val();
  2061. //search in data by id, storing the actual matching item
  2062. var match = null;
  2063. opts.query({
  2064. matcher: function(term, text, el){
  2065. var is_match = equal(id, opts.id(el));
  2066. if (is_match) {
  2067. match = el;
  2068. }
  2069. return is_match;
  2070. },
  2071. callback: !$.isFunction(callback) ? $.noop : function() {
  2072. callback(match);
  2073. }
  2074. });
  2075. };
  2076. }
  2077. return opts;
  2078. },
  2079. // single
  2080. getPlaceholder: function() {
  2081. // if a placeholder is specified on a single select without a valid placeholder option ignore it
  2082. if (this.select) {
  2083. if (this.getPlaceholderOption() === undefined) {
  2084. return undefined;
  2085. }
  2086. }
  2087. return this.parent.getPlaceholder.apply(this, arguments);
  2088. },
  2089. // single
  2090. setPlaceholder: function () {
  2091. var placeholder = this.getPlaceholder();
  2092. if (this.isPlaceholderOptionSelected() && placeholder !== undefined) {
  2093. // check for a placeholder option if attached to a select
  2094. if (this.select && this.getPlaceholderOption() === undefined) return;
  2095. this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder));
  2096. this.selection.addClass("select2-default");
  2097. this.container.removeClass("select2-allowclear");
  2098. }
  2099. },
  2100. // single
  2101. postprocessResults: function (data, initial, noHighlightUpdate) {
  2102. var selected = 0, self = this, showSearchInput = true;
  2103. // find the selected element in the result list
  2104. this.findHighlightableChoices().each2(function (i, elm) {
  2105. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  2106. selected = i;
  2107. return false;
  2108. }
  2109. });
  2110. // and highlight it
  2111. if (noHighlightUpdate !== false) {
  2112. if (initial === true && selected >= 0) {
  2113. this.highlight(selected);
  2114. } else {
  2115. this.highlight(0);
  2116. }
  2117. }
  2118. // hide the search box if this is the first we got the results and there are enough of them for search
  2119. if (initial === true) {
  2120. var min = this.opts.minimumResultsForSearch;
  2121. if (min >= 0) {
  2122. this.showSearch(countResults(data.results) >= min);
  2123. }
  2124. }
  2125. },
  2126. // single
  2127. showSearch: function(showSearchInput) {
  2128. if (this.showSearchInput === showSearchInput) return;
  2129. this.showSearchInput = showSearchInput;
  2130. this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput);
  2131. this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput);
  2132. //add "select2-with-searchbox" to the container if search box is shown
  2133. $(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput);
  2134. },
  2135. // single
  2136. onSelect: function (data, options) {
  2137. if (!this.triggerSelect(data)) { return; }
  2138. var old = this.opts.element.val(),
  2139. oldData = this.data();
  2140. this.opts.element.val(this.id(data));
  2141. this.updateSelection(data);
  2142. this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data });
  2143. this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val());
  2144. this.close();
  2145. if ((!options || !options.noFocus) && this.opts.shouldFocusInput(this)) {
  2146. this.focusser.focus();
  2147. }
  2148. if (!equal(old, this.id(data))) {
  2149. this.triggerChange({ added: data, removed: oldData });
  2150. }
  2151. },
  2152. // single
  2153. updateSelection: function (data) {
  2154. var container=this.selection.find(".select2-chosen"), formatted, cssClass;
  2155. this.selection.data("select2-data", data);
  2156. container.empty();
  2157. if (data !== null) {
  2158. formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup);
  2159. }
  2160. if (formatted !== undefined) {
  2161. container.append(formatted);
  2162. }
  2163. cssClass=this.opts.formatSelectionCssClass(data, container);
  2164. if (cssClass !== undefined) {
  2165. container.addClass(cssClass);
  2166. }
  2167. this.selection.removeClass("select2-default");
  2168. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  2169. this.container.addClass("select2-allowclear");
  2170. }
  2171. },
  2172. // single
  2173. val: function () {
  2174. var val,
  2175. triggerChange = false,
  2176. data = null,
  2177. self = this,
  2178. oldData = this.data();
  2179. if (arguments.length === 0) {
  2180. return this.opts.element.val();
  2181. }
  2182. val = arguments[0];
  2183. if (arguments.length > 1) {
  2184. triggerChange = arguments[1];
  2185. }
  2186. if (this.select) {
  2187. this.select
  2188. .val(val)
  2189. .find("option").filter(function() { return this.selected }).each2(function (i, elm) {
  2190. data = self.optionToData(elm);
  2191. return false;
  2192. });
  2193. this.updateSelection(data);
  2194. this.setPlaceholder();
  2195. if (triggerChange) {
  2196. this.triggerChange({added: data, removed:oldData});
  2197. }
  2198. } else {
  2199. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  2200. if (!val && val !== 0) {
  2201. this.clear(triggerChange);
  2202. return;
  2203. }
  2204. if (this.opts.initSelection === undefined) {
  2205. throw new Error("cannot call val() if initSelection() is not defined");
  2206. }
  2207. this.opts.element.val(val);
  2208. this.opts.initSelection(this.opts.element, function(data){
  2209. self.opts.element.val(!data ? "" : self.id(data));
  2210. self.updateSelection(data);
  2211. self.setPlaceholder();
  2212. if (triggerChange) {
  2213. self.triggerChange({added: data, removed:oldData});
  2214. }
  2215. });
  2216. }
  2217. },
  2218. // single
  2219. clearSearch: function () {
  2220. this.search.val("");
  2221. this.focusser.val("");
  2222. },
  2223. // single
  2224. data: function(value) {
  2225. var data,
  2226. triggerChange = false;
  2227. if (arguments.length === 0) {
  2228. data = this.selection.data("select2-data");
  2229. if (data == undefined) data = null;
  2230. return data;
  2231. } else {
  2232. if (arguments.length > 1) {
  2233. triggerChange = arguments[1];
  2234. }
  2235. if (!value) {
  2236. this.clear(triggerChange);
  2237. } else {
  2238. data = this.data();
  2239. this.opts.element.val(!value ? "" : this.id(value));
  2240. this.updateSelection(value);
  2241. if (triggerChange) {
  2242. this.triggerChange({added: value, removed:data});
  2243. }
  2244. }
  2245. }
  2246. }
  2247. });
  2248. MultiSelect2 = clazz(AbstractSelect2, {
  2249. // multi
  2250. createContainer: function () {
  2251. var container = $(document.createElement("div")).attr({
  2252. "class": "select2-container select2-container-multi"
  2253. }).html([
  2254. "<ul class='select2-choices'>",
  2255. " <li class='select2-search-field'>",
  2256. " <label for='' class='select2-offscreen'></label>",
  2257. " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'>",
  2258. " </li>",
  2259. "</ul>",
  2260. "<div class='select2-drop select2-drop-multi select2-display-none'>",
  2261. " <ul class='select2-results'>",
  2262. " </ul>",
  2263. "</div>"].join(""));
  2264. return container;
  2265. },
  2266. // multi
  2267. prepareOpts: function () {
  2268. var opts = this.parent.prepareOpts.apply(this, arguments),
  2269. self=this;
  2270. // TODO validate placeholder is a string if specified
  2271. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  2272. // install the selection initializer
  2273. opts.initSelection = function (element, callback) {
  2274. var data = [];
  2275. element.find("option").filter(function() { return this.selected && !this.disabled }).each2(function (i, elm) {
  2276. data.push(self.optionToData(elm));
  2277. });
  2278. callback(data);
  2279. };
  2280. } else if ("data" in opts) {
  2281. // install default initSelection when applied to hidden input and data is local
  2282. opts.initSelection = opts.initSelection || function (element, callback) {
  2283. var ids = splitVal(element.val(), opts.separator);
  2284. //search in data by array of ids, storing matching items in a list
  2285. var matches = [];
  2286. opts.query({
  2287. matcher: function(term, text, el){
  2288. var is_match = $.grep(ids, function(id) {
  2289. return equal(id, opts.id(el));
  2290. }).length;
  2291. if (is_match) {
  2292. matches.push(el);
  2293. }
  2294. return is_match;
  2295. },
  2296. callback: !$.isFunction(callback) ? $.noop : function() {
  2297. // reorder matches based on the order they appear in the ids array because right now
  2298. // they are in the order in which they appear in data array
  2299. var ordered = [];
  2300. for (var i = 0; i < ids.length; i++) {
  2301. var id = ids[i];
  2302. for (var j = 0; j < matches.length; j++) {
  2303. var match = matches[j];
  2304. if (equal(id, opts.id(match))) {
  2305. ordered.push(match);
  2306. matches.splice(j, 1);
  2307. break;
  2308. }
  2309. }
  2310. }
  2311. callback(ordered);
  2312. }
  2313. });
  2314. };
  2315. }
  2316. return opts;
  2317. },
  2318. // multi
  2319. selectChoice: function (choice) {
  2320. var selected = this.container.find(".select2-search-choice-focus");
  2321. if (selected.length && choice && choice[0] == selected[0]) {
  2322. } else {
  2323. if (selected.length) {
  2324. this.opts.element.trigger("choice-deselected", selected);
  2325. }
  2326. selected.removeClass("select2-search-choice-focus");
  2327. if (choice && choice.length) {
  2328. this.close();
  2329. choice.addClass("select2-search-choice-focus");
  2330. this.opts.element.trigger("choice-selected", choice);
  2331. }
  2332. }
  2333. },
  2334. // multi
  2335. destroy: function() {
  2336. $("label[for='" + this.search.attr('id') + "']")
  2337. .attr('for', this.opts.element.attr("id"));
  2338. this.parent.destroy.apply(this, arguments);
  2339. cleanupJQueryElements.call(this,
  2340. "searchContainer",
  2341. "selection"
  2342. );
  2343. },
  2344. // multi
  2345. initContainer: function () {
  2346. var selector = ".select2-choices", selection;
  2347. this.searchContainer = this.container.find(".select2-search-field");
  2348. this.selection = selection = this.container.find(selector);
  2349. var _this = this;
  2350. this.selection.on("click", ".select2-search-choice:not(.select2-locked)", function (e) {
  2351. //killEvent(e);
  2352. _this.search[0].focus();
  2353. _this.selectChoice($(this));
  2354. });
  2355. // rewrite labels from original element to focusser
  2356. this.search.attr("id", "s2id_autogen"+nextUid());
  2357. this.search.prev()
  2358. .text($("label[for='" + this.opts.element.attr("id") + "']").text())
  2359. .attr('for', this.search.attr('id'));
  2360. this.search.on("input paste", this.bind(function() {
  2361. if (this.search.attr('placeholder') && this.search.val().length == 0) return;
  2362. if (!this.isInterfaceEnabled()) return;
  2363. if (!this.opened()) {
  2364. this.open();
  2365. }
  2366. }));
  2367. this.search.attr("tabindex", this.elementTabIndex);
  2368. this.keydowns = 0;
  2369. this.search.on("keydown", this.bind(function (e) {
  2370. if (!this.isInterfaceEnabled()) return;
  2371. ++this.keydowns;
  2372. var selected = selection.find(".select2-search-choice-focus");
  2373. var prev = selected.prev(".select2-search-choice:not(.select2-locked)");
  2374. var next = selected.next(".select2-search-choice:not(.select2-locked)");
  2375. var pos = getCursorInfo(this.search);
  2376. if (selected.length &&
  2377. (e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) {
  2378. var selectedChoice = selected;
  2379. if (e.which == KEY.LEFT && prev.length) {
  2380. selectedChoice = prev;
  2381. }
  2382. else if (e.which == KEY.RIGHT) {
  2383. selectedChoice = next.length ? next : null;
  2384. }
  2385. else if (e.which === KEY.BACKSPACE) {
  2386. if (this.unselect(selected.first())) {
  2387. this.search.width(10);
  2388. selectedChoice = prev.length ? prev : next;
  2389. }
  2390. } else if (e.which == KEY.DELETE) {
  2391. if (this.unselect(selected.first())) {
  2392. this.search.width(10);
  2393. selectedChoice = next.length ? next : null;
  2394. }
  2395. } else if (e.which == KEY.ENTER) {
  2396. selectedChoice = null;
  2397. }
  2398. this.selectChoice(selectedChoice);
  2399. killEvent(e);
  2400. if (!selectedChoice || !selectedChoice.length) {
  2401. this.open();
  2402. }
  2403. return;
  2404. } else if (((e.which === KEY.BACKSPACE && this.keydowns == 1)
  2405. || e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) {
  2406. this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last());
  2407. killEvent(e);
  2408. return;
  2409. } else {
  2410. this.selectChoice(null);
  2411. }
  2412. if (this.opened()) {
  2413. switch (e.which) {
  2414. case KEY.UP:
  2415. case KEY.DOWN:
  2416. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  2417. killEvent(e);
  2418. return;
  2419. case KEY.ENTER:
  2420. this.selectHighlighted();
  2421. killEvent(e);
  2422. return;
  2423. case KEY.TAB:
  2424. this.selectHighlighted({noFocus:true});
  2425. this.close();
  2426. return;
  2427. case KEY.ESC:
  2428. this.cancel(e);
  2429. killEvent(e);
  2430. return;
  2431. }
  2432. }
  2433. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
  2434. || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  2435. return;
  2436. }
  2437. if (e.which === KEY.ENTER) {
  2438. if (this.opts.openOnEnter === false) {
  2439. return;
  2440. } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
  2441. return;
  2442. }
  2443. }
  2444. this.open();
  2445. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  2446. // prevent the page from scrolling
  2447. killEvent(e);
  2448. }
  2449. if (e.which === KEY.ENTER) {
  2450. // prevent form from being submitted
  2451. killEvent(e);
  2452. }
  2453. }));
  2454. this.search.on("keyup", this.bind(function (e) {
  2455. this.keydowns = 0;
  2456. this.resizeSearch();
  2457. })
  2458. );
  2459. this.search.on("blur", this.bind(function(e) {
  2460. this.container.removeClass("select2-container-active");
  2461. this.search.removeClass("select2-focused");
  2462. this.selectChoice(null);
  2463. if (!this.opened()) this.clearSearch();
  2464. e.stopImmediatePropagation();
  2465. this.opts.element.trigger($.Event("select2-blur"));
  2466. }));
  2467. this.container.on("click", selector, this.bind(function (e) {
  2468. if (!this.isInterfaceEnabled()) return;
  2469. if ($(e.target).closest(".select2-search-choice").length > 0) {
  2470. // clicked inside a select2 search choice, do not open
  2471. return;
  2472. }
  2473. this.selectChoice(null);
  2474. this.clearPlaceholder();
  2475. if (!this.container.hasClass("select2-container-active")) {
  2476. this.opts.element.trigger($.Event("select2-focus"));
  2477. }
  2478. this.open();
  2479. this.focusSearch();
  2480. e.preventDefault();
  2481. }));
  2482. this.container.on("focus", selector, this.bind(function () {
  2483. if (!this.isInterfaceEnabled()) return;
  2484. if (!this.container.hasClass("select2-container-active")) {
  2485. this.opts.element.trigger($.Event("select2-focus"));
  2486. }
  2487. this.container.addClass("select2-container-active");
  2488. this.dropdown.addClass("select2-drop-active");
  2489. this.clearPlaceholder();
  2490. }));
  2491. this.initContainerWidth();
  2492. this.opts.element.addClass("select2-offscreen");
  2493. // set the placeholder if necessary
  2494. this.clearSearch();
  2495. },
  2496. // multi
  2497. enableInterface: function() {
  2498. if (this.parent.enableInterface.apply(this, arguments)) {
  2499. this.search.prop("disabled", !this.isInterfaceEnabled());
  2500. }
  2501. },
  2502. // multi
  2503. initSelection: function () {
  2504. var data;
  2505. if (this.opts.element.val() === "" && this.opts.element.text() === "") {
  2506. this.updateSelection([]);
  2507. this.close();
  2508. // set the placeholder if necessary
  2509. this.clearSearch();
  2510. }
  2511. if (this.select || this.opts.element.val() !== "") {
  2512. var self = this;
  2513. this.opts.initSelection.call(null, this.opts.element, function(data){
  2514. if (data !== undefined && data !== null) {
  2515. self.updateSelection(data);
  2516. self.close();
  2517. // set the placeholder if necessary
  2518. self.clearSearch();
  2519. }
  2520. });
  2521. }
  2522. },
  2523. // multi
  2524. clearSearch: function () {
  2525. var placeholder = this.getPlaceholder(),
  2526. maxWidth = this.getMaxSearchWidth();
  2527. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  2528. this.search.val(placeholder).addClass("select2-default");
  2529. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  2530. // we could call this.resizeSearch(), but we do not because that requires a sizer and we do not want to create one so early because of a firefox bug, see #944
  2531. this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width"));
  2532. } else {
  2533. this.search.val("").width(10);
  2534. }
  2535. },
  2536. // multi
  2537. clearPlaceholder: function () {
  2538. if (this.search.hasClass("select2-default")) {
  2539. this.search.val("").removeClass("select2-default");
  2540. }
  2541. },
  2542. // multi
  2543. opening: function () {
  2544. this.clearPlaceholder(); // should be done before super so placeholder is not used to search
  2545. this.resizeSearch();
  2546. this.parent.opening.apply(this, arguments);
  2547. this.focusSearch();
  2548. // initializes search's value with nextSearchTerm (if defined by user)
  2549. // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
  2550. if(this.search.val() === "") {
  2551. if(this.nextSearchTerm != undefined){
  2552. this.search.val(this.nextSearchTerm);
  2553. this.search.select();
  2554. }
  2555. }
  2556. this.updateResults(true);
  2557. if (this.opts.shouldFocusInput(this)) {
  2558. this.search.focus();
  2559. }
  2560. this.opts.element.trigger($.Event("select2-open"));
  2561. },
  2562. // multi
  2563. close: function () {
  2564. if (!this.opened()) return;
  2565. this.parent.close.apply(this, arguments);
  2566. },
  2567. // multi
  2568. focus: function () {
  2569. this.close();
  2570. this.search.focus();
  2571. },
  2572. // multi
  2573. isFocused: function () {
  2574. return this.search.hasClass("select2-focused");
  2575. },
  2576. // multi
  2577. updateSelection: function (data) {
  2578. var ids = [], filtered = [], self = this;
  2579. // filter out duplicates
  2580. $(data).each(function () {
  2581. if (indexOf(self.id(this), ids) < 0) {
  2582. ids.push(self.id(this));
  2583. filtered.push(this);
  2584. }
  2585. });
  2586. data = filtered;
  2587. this.selection.find(".select2-search-choice").remove();
  2588. $(data).each(function () {
  2589. self.addSelectedChoice(this);
  2590. });
  2591. self.postprocessResults();
  2592. },
  2593. // multi
  2594. tokenize: function() {
  2595. var input = this.search.val();
  2596. input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts);
  2597. if (input != null && input != undefined) {
  2598. this.search.val(input);
  2599. if (input.length > 0) {
  2600. this.open();
  2601. }
  2602. }
  2603. },
  2604. // multi
  2605. onSelect: function (data, options) {
  2606. if (!this.triggerSelect(data)) { return; }
  2607. this.addSelectedChoice(data);
  2608. this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
  2609. // keep track of the search's value before it gets cleared
  2610. this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val());
  2611. this.clearSearch();
  2612. this.updateResults();
  2613. if (this.select || !this.opts.closeOnSelect) this.postprocessResults(data, false, this.opts.closeOnSelect===true);
  2614. if (this.opts.closeOnSelect) {
  2615. this.close();
  2616. this.search.width(10);
  2617. } else {
  2618. if (this.countSelectableResults()>0) {
  2619. this.search.width(10);
  2620. this.resizeSearch();
  2621. if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) {
  2622. // if we reached max selection size repaint the results so choices
  2623. // are replaced with the max selection reached message
  2624. this.updateResults(true);
  2625. } else {
  2626. // initializes search's value with nextSearchTerm and update search result
  2627. if(this.nextSearchTerm != undefined){
  2628. this.search.val(this.nextSearchTerm);
  2629. this.updateResults();
  2630. this.search.select();
  2631. }
  2632. }
  2633. this.positionDropdown();
  2634. } else {
  2635. // if nothing left to select close
  2636. this.close();
  2637. this.search.width(10);
  2638. }
  2639. }
  2640. // since its not possible to select an element that has already been
  2641. // added we do not need to check if this is a new element before firing change
  2642. this.triggerChange({ added: data });
  2643. if (!options || !options.noFocus)
  2644. this.focusSearch();
  2645. },
  2646. // multi
  2647. cancel: function () {
  2648. this.close();
  2649. this.focusSearch();
  2650. },
  2651. addSelectedChoice: function (data) {
  2652. var enableChoice = !data.locked,
  2653. enabledItem = $(
  2654. "<li class='select2-search-choice'>" +
  2655. " <div></div>" +
  2656. " <a href='#' class='select2-search-choice-close' tabindex='-1'></a>" +
  2657. "</li>"),
  2658. disabledItem = $(
  2659. "<li class='select2-search-choice select2-locked'>" +
  2660. "<div></div>" +
  2661. "</li>");
  2662. var choice = enableChoice ? enabledItem : disabledItem,
  2663. id = this.id(data),
  2664. val = this.getVal(),
  2665. formatted,
  2666. cssClass;
  2667. formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup);
  2668. if (formatted != undefined) {
  2669. choice.find("div").replaceWith("<div>"+formatted+"</div>");
  2670. }
  2671. cssClass=this.opts.formatSelectionCssClass(data, choice.find("div"));
  2672. if (cssClass != undefined) {
  2673. choice.addClass(cssClass);
  2674. }
  2675. if(enableChoice){
  2676. choice.find(".select2-search-choice-close")
  2677. .on("mousedown", killEvent)
  2678. .on("click dblclick", this.bind(function (e) {
  2679. if (!this.isInterfaceEnabled()) return;
  2680. this.unselect($(e.target));
  2681. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  2682. killEvent(e);
  2683. this.close();
  2684. this.focusSearch();
  2685. })).on("focus", this.bind(function () {
  2686. if (!this.isInterfaceEnabled()) return;
  2687. this.container.addClass("select2-container-active");
  2688. this.dropdown.addClass("select2-drop-active");
  2689. }));
  2690. }
  2691. choice.data("select2-data", data);
  2692. choice.insertBefore(this.searchContainer);
  2693. val.push(id);
  2694. this.setVal(val);
  2695. },
  2696. // multi
  2697. unselect: function (selected) {
  2698. var val = this.getVal(),
  2699. data,
  2700. index;
  2701. selected = selected.closest(".select2-search-choice");
  2702. if (selected.length === 0) {
  2703. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  2704. }
  2705. data = selected.data("select2-data");
  2706. if (!data) {
  2707. // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued
  2708. // and invoked on an element already removed
  2709. return;
  2710. }
  2711. var evt = $.Event("select2-removing");
  2712. evt.val = this.id(data);
  2713. evt.choice = data;
  2714. this.opts.element.trigger(evt);
  2715. if (evt.isDefaultPrevented()) {
  2716. return false;
  2717. }
  2718. while((index = indexOf(this.id(data), val)) >= 0) {
  2719. val.splice(index, 1);
  2720. this.setVal(val);
  2721. if (this.select) this.postprocessResults();
  2722. }
  2723. selected.remove();
  2724. this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
  2725. this.triggerChange({ removed: data });
  2726. return true;
  2727. },
  2728. // multi
  2729. postprocessResults: function (data, initial, noHighlightUpdate) {
  2730. var val = this.getVal(),
  2731. choices = this.results.find(".select2-result"),
  2732. compound = this.results.find(".select2-result-with-children"),
  2733. self = this;
  2734. choices.each2(function (i, choice) {
  2735. var id = self.id(choice.data("select2-data"));
  2736. if (indexOf(id, val) >= 0) {
  2737. choice.addClass("select2-selected");
  2738. // mark all children of the selected parent as selected
  2739. choice.find(".select2-result-selectable").addClass("select2-selected");
  2740. }
  2741. });
  2742. compound.each2(function(i, choice) {
  2743. // hide an optgroup if it doesn't have any selectable children
  2744. if (!choice.is('.select2-result-selectable')
  2745. && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) {
  2746. choice.addClass("select2-selected");
  2747. }
  2748. });
  2749. if (this.highlight() == -1 && noHighlightUpdate !== false){
  2750. self.highlight(0);
  2751. }
  2752. //If all results are chosen render formatNoMatches
  2753. if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){
  2754. if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) {
  2755. if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) {
  2756. this.results.append("<li class='select2-no-results'>" + evaluate(self.opts.formatNoMatches, self.opts.element, self.search.val()) + "</li>");
  2757. }
  2758. }
  2759. }
  2760. },
  2761. // multi
  2762. getMaxSearchWidth: function() {
  2763. return this.selection.width() - getSideBorderPadding(this.search);
  2764. },
  2765. // multi
  2766. resizeSearch: function () {
  2767. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  2768. sideBorderPadding = getSideBorderPadding(this.search);
  2769. minimumWidth = measureTextWidth(this.search) + 10;
  2770. left = this.search.offset().left;
  2771. maxWidth = this.selection.width();
  2772. containerLeft = this.selection.offset().left;
  2773. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  2774. if (searchWidth < minimumWidth) {
  2775. searchWidth = maxWidth - sideBorderPadding;
  2776. }
  2777. if (searchWidth < 40) {
  2778. searchWidth = maxWidth - sideBorderPadding;
  2779. }
  2780. if (searchWidth <= 0) {
  2781. searchWidth = minimumWidth;
  2782. }
  2783. this.search.width(Math.floor(searchWidth));
  2784. },
  2785. // multi
  2786. getVal: function () {
  2787. var val;
  2788. if (this.select) {
  2789. val = this.select.val();
  2790. return val === null ? [] : val;
  2791. } else {
  2792. val = this.opts.element.val();
  2793. return splitVal(val, this.opts.separator);
  2794. }
  2795. },
  2796. // multi
  2797. setVal: function (val) {
  2798. var unique;
  2799. if (this.select) {
  2800. this.select.val(val);
  2801. } else {
  2802. unique = [];
  2803. // filter out duplicates
  2804. $(val).each(function () {
  2805. if (indexOf(this, unique) < 0) unique.push(this);
  2806. });
  2807. this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
  2808. }
  2809. },
  2810. // multi
  2811. buildChangeDetails: function (old, current) {
  2812. var current = current.slice(0),
  2813. old = old.slice(0);
  2814. // remove intersection from each array
  2815. for (var i = 0; i < current.length; i++) {
  2816. for (var j = 0; j < old.length; j++) {
  2817. if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) {
  2818. current.splice(i, 1);
  2819. if(i>0){
  2820. i--;
  2821. }
  2822. old.splice(j, 1);
  2823. j--;
  2824. }
  2825. }
  2826. }
  2827. return {added: current, removed: old};
  2828. },
  2829. // multi
  2830. val: function (val, triggerChange) {
  2831. var oldData, self=this;
  2832. if (arguments.length === 0) {
  2833. return this.getVal();
  2834. }
  2835. oldData=this.data();
  2836. if (!oldData.length) oldData=[];
  2837. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  2838. if (!val && val !== 0) {
  2839. this.opts.element.val("");
  2840. this.updateSelection([]);
  2841. this.clearSearch();
  2842. if (triggerChange) {
  2843. this.triggerChange({added: this.data(), removed: oldData});
  2844. }
  2845. return;
  2846. }
  2847. // val is a list of ids
  2848. this.setVal(val);
  2849. if (this.select) {
  2850. this.opts.initSelection(this.select, this.bind(this.updateSelection));
  2851. if (triggerChange) {
  2852. this.triggerChange(this.buildChangeDetails(oldData, this.data()));
  2853. }
  2854. } else {
  2855. if (this.opts.initSelection === undefined) {
  2856. throw new Error("val() cannot be called if initSelection() is not defined");
  2857. }
  2858. this.opts.initSelection(this.opts.element, function(data){
  2859. var ids=$.map(data, self.id);
  2860. self.setVal(ids);
  2861. self.updateSelection(data);
  2862. self.clearSearch();
  2863. if (triggerChange) {
  2864. self.triggerChange(self.buildChangeDetails(oldData, self.data()));
  2865. }
  2866. });
  2867. }
  2868. this.clearSearch();
  2869. },
  2870. // multi
  2871. onSortStart: function() {
  2872. if (this.select) {
  2873. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  2874. }
  2875. // collapse search field into 0 width so its container can be collapsed as well
  2876. this.search.width(0);
  2877. // hide the container
  2878. this.searchContainer.hide();
  2879. },
  2880. // multi
  2881. onSortEnd:function() {
  2882. var val=[], self=this;
  2883. // show search and move it to the end of the list
  2884. this.searchContainer.show();
  2885. // make sure the search container is the last item in the list
  2886. this.searchContainer.appendTo(this.searchContainer.parent());
  2887. // since we collapsed the width in dragStarted, we resize it here
  2888. this.resizeSearch();
  2889. // update selection
  2890. this.selection.find(".select2-search-choice").each(function() {
  2891. val.push(self.opts.id($(this).data("select2-data")));
  2892. });
  2893. this.setVal(val);
  2894. this.triggerChange();
  2895. },
  2896. // multi
  2897. data: function(values, triggerChange) {
  2898. var self=this, ids, old;
  2899. if (arguments.length === 0) {
  2900. return this.selection
  2901. .children(".select2-search-choice")
  2902. .map(function() { return $(this).data("select2-data"); })
  2903. .get();
  2904. } else {
  2905. old = this.data();
  2906. if (!values) { values = []; }
  2907. ids = $.map(values, function(e) { return self.opts.id(e); });
  2908. this.setVal(ids);
  2909. this.updateSelection(values);
  2910. this.clearSearch();
  2911. if (triggerChange) {
  2912. this.triggerChange(this.buildChangeDetails(old, this.data()));
  2913. }
  2914. }
  2915. }
  2916. });
  2917. $.fn.select2 = function () {
  2918. var args = Array.prototype.slice.call(arguments, 0),
  2919. opts,
  2920. select2,
  2921. method, value, multiple,
  2922. allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "disable", "readonly", "positionDropdown", "data", "search"],
  2923. valueMethods = ["opened", "isFocused", "container", "dropdown"],
  2924. propertyMethods = ["val", "data"],
  2925. methodsMap = { search: "externalSearch" };
  2926. this.each(function () {
  2927. if (args.length === 0 || typeof(args[0]) === "object") {
  2928. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  2929. opts.element = $(this);
  2930. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  2931. multiple = opts.element.prop("multiple");
  2932. } else {
  2933. multiple = opts.multiple || false;
  2934. if ("tags" in opts) {opts.multiple = multiple = true;}
  2935. }
  2936. select2 = multiple ? new window.Select2["class"].multi() : new window.Select2["class"].single();
  2937. select2.init(opts);
  2938. } else if (typeof(args[0]) === "string") {
  2939. if (indexOf(args[0], allowedMethods) < 0) {
  2940. throw "Unknown method: " + args[0];
  2941. }
  2942. value = undefined;
  2943. select2 = $(this).data("select2");
  2944. if (select2 === undefined) return;
  2945. method=args[0];
  2946. if (method === "container") {
  2947. value = select2.container;
  2948. } else if (method === "dropdown") {
  2949. value = select2.dropdown;
  2950. } else {
  2951. if (methodsMap[method]) method = methodsMap[method];
  2952. value = select2[method].apply(select2, args.slice(1));
  2953. }
  2954. if (indexOf(args[0], valueMethods) >= 0
  2955. || (indexOf(args[0], propertyMethods) >= 0 && args.length == 1)) {
  2956. return false; // abort the iteration, ready to return first matched value
  2957. }
  2958. } else {
  2959. throw "Invalid arguments to select2 plugin: " + args;
  2960. }
  2961. });
  2962. return (value === undefined) ? this : value;
  2963. };
  2964. // plugin defaults, accessible to users
  2965. $.fn.select2.defaults = {
  2966. width: "copy",
  2967. loadMorePadding: 0,
  2968. closeOnSelect: true,
  2969. openOnEnter: true,
  2970. containerCss: {},
  2971. dropdownCss: {},
  2972. containerCssClass: "",
  2973. dropdownCssClass: "",
  2974. formatResult: function(result, container, query, escapeMarkup) {
  2975. var markup=[];
  2976. markMatch(result.text, query.term, markup, escapeMarkup);
  2977. return markup.join("");
  2978. },
  2979. formatSelection: function (data, container, escapeMarkup) {
  2980. return data ? escapeMarkup(data.text) : undefined;
  2981. },
  2982. sortResults: function (results, container, query) {
  2983. return results;
  2984. },
  2985. formatResultCssClass: function(data) {return data.css;},
  2986. formatSelectionCssClass: function(data, container) {return undefined;},
  2987. formatMatches: function (matches) { return matches + " results are available, use up and down arrow keys to navigate."; },
  2988. formatNoMatches: function () { return "No matches found"; },
  2989. formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " or more character" + (n == 1? "" : "s"); },
  2990. formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1? "" : "s"); },
  2991. formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
  2992. formatLoadMore: function (pageNumber) { return "Loading more results…"; },
  2993. formatSearching: function () { return "Searching…"; },
  2994. minimumResultsForSearch: 0,
  2995. minimumInputLength: 0,
  2996. maximumInputLength: null,
  2997. maximumSelectionSize: 0,
  2998. id: function (e) { return e == undefined ? null : e.id; },
  2999. matcher: function(term, text) {
  3000. return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0;
  3001. },
  3002. separator: ",",
  3003. tokenSeparators: [],
  3004. tokenizer: defaultTokenizer,
  3005. escapeMarkup: defaultEscapeMarkup,
  3006. blurOnChange: false,
  3007. selectOnBlur: false,
  3008. adaptContainerCssClass: function(c) { return c; },
  3009. adaptDropdownCssClass: function(c) { return null; },
  3010. nextSearchTerm: function(selectedObject, currentSearchTerm) { return undefined; },
  3011. searchInputPlaceholder: '',
  3012. createSearchChoicePosition: 'top',
  3013. shouldFocusInput: function (instance) {
  3014. // Attempt to detect touch devices
  3015. var supportsTouchEvents = (('ontouchstart' in window) ||
  3016. (navigator.msMaxTouchPoints > 0));
  3017. // Only devices which support touch events should be special cased
  3018. if (!supportsTouchEvents) {
  3019. return true;
  3020. }
  3021. // Never focus the input if search is disabled
  3022. if (instance.opts.minimumResultsForSearch < 0) {
  3023. return false;
  3024. }
  3025. return true;
  3026. }
  3027. };
  3028. $.fn.select2.ajaxDefaults = {
  3029. transport: $.ajax,
  3030. params: {
  3031. type: "GET",
  3032. cache: false,
  3033. dataType: "json"
  3034. }
  3035. };
  3036. // exports
  3037. window.Select2 = {
  3038. query: {
  3039. ajax: ajax,
  3040. local: local,
  3041. tags: tags
  3042. }, util: {
  3043. debounce: debounce,
  3044. markMatch: markMatch,
  3045. escapeMarkup: defaultEscapeMarkup,
  3046. stripDiacritics: stripDiacritics
  3047. }, "class": {
  3048. "abstract": AbstractSelect2,
  3049. "single": SingleSelect2,
  3050. "multi": MultiSelect2
  3051. }
  3052. };
  3053. }(jQuery));