select2.js 144 KB

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