select2.js 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426
  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"};
  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. $document.on("mousemove", function (e) {
  169. lastMousePosition.x = e.pageX;
  170. lastMousePosition.y = e.pageY;
  171. });
  172. /**
  173. * filters mouse events so an event is fired only if the mouse moved.
  174. *
  175. * filters out mouse events that occur when mouse is stationary but
  176. * the elements under the pointer are scrolled.
  177. */
  178. function installFilteredMouseMove(element) {
  179. element.on("mousemove", function (e) {
  180. var lastpos = lastMousePosition;
  181. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  182. $(e.target).trigger("mousemove-filtered", e);
  183. }
  184. });
  185. }
  186. /**
  187. * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
  188. * within the last quietMillis milliseconds.
  189. *
  190. * @param quietMillis number of milliseconds to wait before invoking fn
  191. * @param fn function to be debounced
  192. * @param ctx object to be used as this reference within fn
  193. * @return debounced version of fn
  194. */
  195. function debounce(quietMillis, fn, ctx) {
  196. ctx = ctx || undefined;
  197. var timeout;
  198. return function () {
  199. var args = arguments;
  200. window.clearTimeout(timeout);
  201. timeout = window.setTimeout(function() {
  202. fn.apply(ctx, args);
  203. }, quietMillis);
  204. };
  205. }
  206. /**
  207. * A simple implementation of a thunk
  208. * @param formula function used to lazily initialize the thunk
  209. * @return {Function}
  210. */
  211. function thunk(formula) {
  212. var evaluated = false,
  213. value;
  214. return function() {
  215. if (evaluated === false) { value = formula(); evaluated = true; }
  216. return value;
  217. };
  218. };
  219. function installDebouncedScroll(threshold, element) {
  220. var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
  221. element.on("scroll", function (e) {
  222. if (indexOf(e.target, element.get()) >= 0) notify(e);
  223. });
  224. }
  225. function focus($el) {
  226. if ($el[0] === document.activeElement) return;
  227. /* set the focus in a 0 timeout - that way the focus is set after the processing
  228. of the current event has finished - which seems like the only reliable way
  229. to set focus */
  230. window.setTimeout(function() {
  231. var el=$el[0], pos=$el.val().length, range;
  232. $el.focus();
  233. /* make sure el received focus so we do not error out when trying to manipulate the caret.
  234. sometimes modals or others listeners may steal it after its set */
  235. var isVisible = (el.offsetWidth > 0 || el.offsetHeight > 0);
  236. if (isVisible && el === document.activeElement) {
  237. /* after the focus is set move the caret to the end, necessary when we val()
  238. just before setting focus */
  239. if(el.setSelectionRange)
  240. {
  241. el.setSelectionRange(pos, pos);
  242. }
  243. else if (el.createTextRange) {
  244. range = el.createTextRange();
  245. range.collapse(false);
  246. range.select();
  247. }
  248. }
  249. }, 0);
  250. }
  251. function getCursorInfo(el) {
  252. el = $(el)[0];
  253. var offset = 0;
  254. var length = 0;
  255. if ('selectionStart' in el) {
  256. offset = el.selectionStart;
  257. length = el.selectionEnd - offset;
  258. } else if ('selection' in document) {
  259. el.focus();
  260. var sel = document.selection.createRange();
  261. length = document.selection.createRange().text.length;
  262. sel.moveStart('character', -el.value.length);
  263. offset = sel.text.length - length;
  264. }
  265. return { offset: offset, length: length };
  266. }
  267. function killEvent(event) {
  268. event.preventDefault();
  269. event.stopPropagation();
  270. }
  271. function killEventImmediately(event) {
  272. event.preventDefault();
  273. event.stopImmediatePropagation();
  274. }
  275. function measureTextWidth(e) {
  276. if (!sizer){
  277. var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
  278. sizer = $(document.createElement("div")).css({
  279. position: "absolute",
  280. left: "-10000px",
  281. top: "-10000px",
  282. display: "none",
  283. fontSize: style.fontSize,
  284. fontFamily: style.fontFamily,
  285. fontStyle: style.fontStyle,
  286. fontWeight: style.fontWeight,
  287. letterSpacing: style.letterSpacing,
  288. textTransform: style.textTransform,
  289. whiteSpace: "nowrap"
  290. });
  291. sizer.attr("class","select2-sizer");
  292. $("body").append(sizer);
  293. }
  294. sizer.text(e.val());
  295. return sizer.width();
  296. }
  297. function syncCssClasses(dest, src, adapter) {
  298. var classes, replacements = [], adapted;
  299. classes = dest.attr("class");
  300. if (classes) {
  301. classes = '' + classes; // for IE which returns object
  302. $(classes.split(" ")).each2(function() {
  303. if (this.indexOf("select2-") === 0) {
  304. replacements.push(this);
  305. }
  306. });
  307. }
  308. classes = src.attr("class");
  309. if (classes) {
  310. classes = '' + classes; // for IE which returns object
  311. $(classes.split(" ")).each2(function() {
  312. if (this.indexOf("select2-") !== 0) {
  313. adapted = adapter(this);
  314. if (adapted) {
  315. replacements.push(adapted);
  316. }
  317. }
  318. });
  319. }
  320. dest.attr("class", replacements.join(" "));
  321. }
  322. function markMatch(text, term, markup, escapeMarkup) {
  323. var match=stripDiacritics(text.toUpperCase()).indexOf(stripDiacritics(term.toUpperCase())),
  324. tl=term.length;
  325. if (match<0) {
  326. markup.push(escapeMarkup(text));
  327. return;
  328. }
  329. markup.push(escapeMarkup(text.substring(0, match)));
  330. markup.push("<span class='select2-match'>");
  331. markup.push(escapeMarkup(text.substring(match, match + tl)));
  332. markup.push("</span>");
  333. markup.push(escapeMarkup(text.substring(match + tl, text.length)));
  334. }
  335. function defaultEscapeMarkup(markup) {
  336. var replace_map = {
  337. '\\': '&#92;',
  338. '&': '&amp;',
  339. '<': '&lt;',
  340. '>': '&gt;',
  341. '"': '&quot;',
  342. "'": '&#39;',
  343. "/": '&#47;'
  344. };
  345. return String(markup).replace(/[&<>"'\/\\]/g, function (match) {
  346. return replace_map[match];
  347. });
  348. }
  349. /**
  350. * Produces an ajax-based query function
  351. *
  352. * @param options object containing configuration parameters
  353. * @param options.params parameter map for the transport ajax call, can contain such options as cache, jsonpCallback, etc. see $.ajax
  354. * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
  355. * @param options.url url for the data
  356. * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
  357. * @param options.dataType request data type: ajax, jsonp, other datatypes supported by jQuery's $.ajax function or the transport function if specified
  358. * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
  359. * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
  360. * The expected format is an object containing the following keys:
  361. * results array of objects that will be used as choices
  362. * more (optional) boolean indicating whether there are more results available
  363. * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
  364. */
  365. function ajax(options) {
  366. var timeout, // current scheduled but not yet executed request
  367. handler = null,
  368. quietMillis = options.quietMillis || 100,
  369. ajaxUrl = options.url,
  370. self = this;
  371. return function (query) {
  372. window.clearTimeout(timeout);
  373. timeout = window.setTimeout(function () {
  374. var data = options.data, // ajax data function
  375. url = ajaxUrl, // ajax url string or function
  376. transport = options.transport || $.fn.select2.ajaxDefaults.transport,
  377. // deprecated - to be removed in 4.0 - use params instead
  378. deprecated = {
  379. type: options.type || 'GET', // set type of request (GET or POST)
  380. cache: options.cache || false,
  381. jsonpCallback: options.jsonpCallback||undefined,
  382. dataType: options.dataType||"json"
  383. },
  384. params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated);
  385. data = data ? data.call(self, query.term, query.page, query.context) : null;
  386. url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
  387. if (handler && typeof handler.abort === "function") { handler.abort(); }
  388. if (options.params) {
  389. if ($.isFunction(options.params)) {
  390. $.extend(params, options.params.call(self));
  391. } else {
  392. $.extend(params, options.params);
  393. }
  394. }
  395. $.extend(params, {
  396. url: url,
  397. dataType: options.dataType,
  398. data: data,
  399. success: function (data) {
  400. // TODO - replace query.page with query so users have access to term, page, etc.
  401. var results = options.results(data, query.page);
  402. query.callback(results);
  403. }
  404. });
  405. handler = transport.call(self, params);
  406. }, quietMillis);
  407. };
  408. }
  409. /**
  410. * Produces a query function that works with a local array
  411. *
  412. * @param options object containing configuration parameters. The options parameter can either be an array or an
  413. * object.
  414. *
  415. * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
  416. *
  417. * If the object form is used it is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
  418. * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
  419. * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
  420. * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
  421. * the text.
  422. */
  423. function local(options) {
  424. var data = options, // data elements
  425. dataText,
  426. tmp,
  427. text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  428. if ($.isArray(data)) {
  429. tmp = data;
  430. data = { results: tmp };
  431. }
  432. if ($.isFunction(data) === false) {
  433. tmp = data;
  434. data = function() { return tmp; };
  435. }
  436. var dataItem = data();
  437. if (dataItem.text) {
  438. text = dataItem.text;
  439. // if text is not a function we assume it to be a key name
  440. if (!$.isFunction(text)) {
  441. 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
  442. text = function (item) { return item[dataText]; };
  443. }
  444. }
  445. return function (query) {
  446. var t = query.term, filtered = { results: [] }, process;
  447. if (t === "") {
  448. query.callback(data());
  449. return;
  450. }
  451. process = function(datum, collection) {
  452. var group, attr;
  453. datum = datum[0];
  454. if (datum.children) {
  455. group = {};
  456. for (attr in datum) {
  457. if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
  458. }
  459. group.children=[];
  460. $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
  461. if (group.children.length || query.matcher(t, text(group), datum)) {
  462. collection.push(group);
  463. }
  464. } else {
  465. if (query.matcher(t, text(datum), datum)) {
  466. collection.push(datum);
  467. }
  468. }
  469. };
  470. $(data().results).each2(function(i, datum) { process(datum, filtered.results); });
  471. query.callback(filtered);
  472. };
  473. }
  474. // TODO javadoc
  475. function tags(data) {
  476. var isFunc = $.isFunction(data);
  477. return function (query) {
  478. var t = query.term, filtered = {results: []};
  479. var result = $(isFunc ? data(query) : data);
  480. if ($.isArray(result)) {
  481. $(isFunc ? data() : data).each(function () {
  482. var isObject = this.text !== undefined,
  483. text = isObject ? this.text : this;
  484. if (t === "" || query.matcher(t, text)) {
  485. filtered.results.push(isObject ? this : {id: this, text: this});
  486. }
  487. });
  488. query.callback(filtered);
  489. }
  490. };
  491. }
  492. /**
  493. * Checks if the formatter function should be used.
  494. *
  495. * Throws an error if it is not a function. Returns true if it should be used,
  496. * false if no formatting should be performed.
  497. *
  498. * @param formatter
  499. */
  500. function checkFormatter(formatter, formatterName) {
  501. if ($.isFunction(formatter)) return true;
  502. if (!formatter) return false;
  503. if (typeof(formatter) === 'string') return true;
  504. throw new Error(formatterName +" must be a string, function, or falsy value");
  505. }
  506. function evaluate(val) {
  507. if ($.isFunction(val)) {
  508. var args = Array.prototype.slice.call(arguments, 1);
  509. return val.apply(null, args);
  510. }
  511. return val;
  512. }
  513. function countResults(results) {
  514. var count = 0;
  515. $.each(results, function(i, item) {
  516. if (item.children) {
  517. count += countResults(item.children);
  518. } else {
  519. count++;
  520. }
  521. });
  522. return count;
  523. }
  524. /**
  525. * Default tokenizer. This function uses breaks the input on substring match of any string from the
  526. * opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those
  527. * two options have to be defined in order for the tokenizer to work.
  528. *
  529. * @param input text user has typed so far or pasted into the search field
  530. * @param selection currently selected choices
  531. * @param selectCallback function(choice) callback tho add the choice to selection
  532. * @param opts select2's opts
  533. * @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value
  534. */
  535. function defaultTokenizer(input, selection, selectCallback, opts) {
  536. var original = input, // store the original so we can compare and know if we need to tell the search to update its text
  537. dupe = false, // check for whether a token we extracted represents a duplicate selected choice
  538. token, // token
  539. index, // position at which the separator was found
  540. i, l, // looping variables
  541. separator; // the matched separator
  542. if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined;
  543. while (true) {
  544. index = -1;
  545. for (i = 0, l = opts.tokenSeparators.length; i < l; i++) {
  546. separator = opts.tokenSeparators[i];
  547. index = input.indexOf(separator);
  548. if (index >= 0) break;
  549. }
  550. if (index < 0) break; // did not find any token separator in the input string, bail
  551. token = input.substring(0, index);
  552. input = input.substring(index + separator.length);
  553. if (token.length > 0) {
  554. token = opts.createSearchChoice.call(this, token, selection);
  555. if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) {
  556. dupe = false;
  557. for (i = 0, l = selection.length; i < l; i++) {
  558. if (equal(opts.id(token), opts.id(selection[i]))) {
  559. dupe = true; break;
  560. }
  561. }
  562. if (!dupe) selectCallback(token);
  563. }
  564. }
  565. }
  566. if (original!==input) return input;
  567. }
  568. /**
  569. * Creates a new class
  570. *
  571. * @param superClass
  572. * @param methods
  573. */
  574. function clazz(SuperClass, methods) {
  575. var constructor = function () {};
  576. constructor.prototype = new SuperClass;
  577. constructor.prototype.constructor = constructor;
  578. constructor.prototype.parent = SuperClass.prototype;
  579. constructor.prototype = $.extend(constructor.prototype, methods);
  580. return constructor;
  581. }
  582. AbstractSelect2 = clazz(Object, {
  583. // abstract
  584. bind: function (func) {
  585. var self = this;
  586. return function () {
  587. func.apply(self, arguments);
  588. };
  589. },
  590. // abstract
  591. init: function (opts) {
  592. var results, search, resultsSelector = ".select2-results";
  593. // prepare options
  594. this.opts = opts = this.prepareOpts(opts);
  595. this.id=opts.id;
  596. // destroy if called on an existing component
  597. if (opts.element.data("select2") !== undefined &&
  598. opts.element.data("select2") !== null) {
  599. opts.element.data("select2").destroy();
  600. }
  601. this.container = this.createContainer();
  602. this.liveRegion = $("<span>", {
  603. role: "status",
  604. "aria-live": "polite"
  605. })
  606. .addClass("select2-hidden-accessible")
  607. .appendTo(document.body);
  608. this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid()).replace(/([;&,\-\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
  609. this.containerSelector="#"+this.containerId;
  610. this.container.attr("id", this.containerId);
  611. this.container.attr("title", opts.element.attr("title"));
  612. // cache the body so future lookups are cheap
  613. this.body = thunk(function() { return opts.element.closest("body"); });
  614. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  615. this.container.attr("style", opts.element.attr("style"));
  616. this.container.css(evaluate(opts.containerCss));
  617. this.container.addClass(evaluate(opts.containerCssClass));
  618. this.elementTabIndex = this.opts.element.attr("tabindex");
  619. // swap container for the element
  620. this.opts.element
  621. .data("select2", this)
  622. .attr("tabindex", "-1")
  623. .before(this.container)
  624. .on("click.select2", killEvent); // do not leak click events
  625. this.container.data("select2", this);
  626. this.dropdown = this.container.find(".select2-drop");
  627. syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
  628. this.dropdown.addClass(evaluate(opts.dropdownCssClass));
  629. this.dropdown.data("select2", this);
  630. this.dropdown.on("click", killEvent);
  631. this.results = results = this.container.find(resultsSelector);
  632. this.search = search = this.container.find("input.select2-input");
  633. this.queryCount = 0;
  634. this.resultsPage = 0;
  635. this.context = null;
  636. // initialize the container
  637. this.initContainer();
  638. this.container.on("click", killEvent);
  639. installFilteredMouseMove(this.results);
  640. this.dropdown.on("mousemove-filtered", resultsSelector, this.bind(this.highlightUnderEvent));
  641. this.dropdown.on("touchstart touchmove touchend", resultsSelector, this.bind(function (event) {
  642. this._touchEvent = true;
  643. this.highlightUnderEvent(event);
  644. }));
  645. this.dropdown.on("touchmove", resultsSelector, this.bind(this.touchMoved));
  646. this.dropdown.on("touchstart touchend", resultsSelector, this.bind(this.clearTouchMoved));
  647. // Waiting for a click event on touch devices to select option and hide dropdown
  648. // otherwise click will be triggered on an underlying element
  649. this.dropdown.on('click', this.bind(function (event) {
  650. if (this._touchEvent) {
  651. this._touchEvent = false;
  652. this.selectHighlighted();
  653. }
  654. }));
  655. installDebouncedScroll(80, this.results);
  656. this.dropdown.on("scroll-debounced", resultsSelector, this.bind(this.loadMoreIfNeeded));
  657. // do not propagate change event from the search field out of the component
  658. $(this.container).on("change", ".select2-input", function(e) {e.stopPropagation();});
  659. $(this.dropdown).on("change", ".select2-input", function(e) {e.stopPropagation();});
  660. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  661. if ($.fn.mousewheel) {
  662. results.mousewheel(function (e, delta, deltaX, deltaY) {
  663. var top = results.scrollTop();
  664. if (deltaY > 0 && top - deltaY <= 0) {
  665. results.scrollTop(0);
  666. killEvent(e);
  667. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  668. results.scrollTop(results.get(0).scrollHeight - results.height());
  669. killEvent(e);
  670. }
  671. });
  672. }
  673. installKeyUpChangeEvent(search);
  674. search.on("keyup-change input paste", this.bind(this.updateResults));
  675. search.on("focus", function () { search.addClass("select2-focused"); });
  676. search.on("blur", function () { search.removeClass("select2-focused");});
  677. this.dropdown.on("mouseup", resultsSelector, this.bind(function (e) {
  678. if ($(e.target).closest(".select2-result-selectable").length > 0) {
  679. this.highlightUnderEvent(e);
  680. this.selectHighlighted(e);
  681. }
  682. }));
  683. // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
  684. // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
  685. // dom it will trigger the popup close, which is not what we want
  686. // focusin can cause focus wars between modals and select2 since the dropdown is outside the modal.
  687. this.dropdown.on("click mouseup mousedown touchstart touchend focusin", function (e) { e.stopPropagation(); });
  688. this.nextSearchTerm = undefined;
  689. if ($.isFunction(this.opts.initSelection)) {
  690. // initialize selection based on the current value of the source element
  691. this.initSelection();
  692. // if the user has provided a function that can set selection based on the value of the source element
  693. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  694. this.monitorSource();
  695. }
  696. if (opts.maximumInputLength !== null) {
  697. this.search.attr("maxlength", opts.maximumInputLength);
  698. }
  699. var disabled = opts.element.prop("disabled");
  700. if (disabled === undefined) disabled = false;
  701. this.enable(!disabled);
  702. var readonly = opts.element.prop("readonly");
  703. if (readonly === undefined) readonly = false;
  704. this.readonly(readonly);
  705. // Calculate size of scrollbar
  706. scrollBarDimensions = scrollBarDimensions || measureScrollbar();
  707. this.autofocus = opts.element.prop("autofocus");
  708. opts.element.prop("autofocus", false);
  709. if (this.autofocus) this.focus();
  710. this.search.attr("placeholder", opts.searchInputPlaceholder);
  711. },
  712. // abstract
  713. destroy: function () {
  714. var element=this.opts.element, select2 = element.data("select2");
  715. this.close();
  716. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  717. if (select2 !== undefined) {
  718. select2.container.remove();
  719. select2.liveRegion.remove();
  720. select2.dropdown.remove();
  721. element
  722. .removeClass("select2-offscreen")
  723. .removeData("select2")
  724. .off(".select2")
  725. .prop("autofocus", this.autofocus || false);
  726. if (this.elementTabIndex) {
  727. element.attr({tabindex: this.elementTabIndex});
  728. } else {
  729. element.removeAttr("tabindex");
  730. }
  731. element.show();
  732. }
  733. },
  734. // abstract
  735. optionToData: function(element) {
  736. if (element.is("option")) {
  737. return {
  738. id:element.prop("value"),
  739. text:element.text(),
  740. element: element.get(),
  741. css: element.attr("class"),
  742. disabled: element.prop("disabled"),
  743. locked: equal(element.attr("locked"), "locked") || equal(element.data("locked"), true)
  744. };
  745. } else if (element.is("optgroup")) {
  746. return {
  747. text:element.attr("label"),
  748. children:[],
  749. element: element.get(),
  750. css: element.attr("class")
  751. };
  752. }
  753. },
  754. // abstract
  755. prepareOpts: function (opts) {
  756. var element, select, idKey, ajaxUrl, self = this;
  757. element = opts.element;
  758. if (element.get(0).tagName.toLowerCase() === "select") {
  759. this.select = select = opts.element;
  760. }
  761. if (select) {
  762. // these options are not allowed when attached to a select because they are picked up off the element itself
  763. $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
  764. if (this in opts) {
  765. throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
  766. }
  767. });
  768. }
  769. opts = $.extend({}, {
  770. populateResults: function(container, results, query) {
  771. var populate, id=this.opts.id, liveRegion=this.liveRegion;
  772. populate=function(results, container, depth) {
  773. var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted;
  774. results = opts.sortResults(results, container, query);
  775. for (i = 0, l = results.length; i < l; i = i + 1) {
  776. result=results[i];
  777. disabled = (result.disabled === true);
  778. selectable = (!disabled) && (id(result) !== undefined);
  779. compound=result.children && result.children.length > 0;
  780. node=$("<li></li>");
  781. node.addClass("select2-results-dept-"+depth);
  782. node.addClass("select2-result");
  783. node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
  784. if (disabled) { node.addClass("select2-disabled"); }
  785. if (compound) { node.addClass("select2-result-with-children"); }
  786. node.addClass(self.opts.formatResultCssClass(result));
  787. node.attr("role", "presentation");
  788. label=$(document.createElement("div"));
  789. label.addClass("select2-result-label");
  790. label.attr("id", "select2-result-label-" + nextUid());
  791. label.attr("role", "option");
  792. formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup);
  793. if (formatted!==undefined) {
  794. label.html(formatted);
  795. node.append(label);
  796. }
  797. if (compound) {
  798. innerContainer=$("<ul></ul>");
  799. innerContainer.addClass("select2-result-sub");
  800. populate(result.children, innerContainer, depth+1);
  801. node.append(innerContainer);
  802. }
  803. node.data("select2-data", result);
  804. container.append(node);
  805. }
  806. liveRegion.text(opts.formatMatches(results.length));
  807. };
  808. populate(results, container, 0);
  809. }
  810. }, $.fn.select2.defaults, opts);
  811. if (typeof(opts.id) !== "function") {
  812. idKey = opts.id;
  813. opts.id = function (e) { return e[idKey]; };
  814. }
  815. if ($.isArray(opts.element.data("select2Tags"))) {
  816. if ("tags" in opts) {
  817. throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id");
  818. }
  819. opts.tags=opts.element.data("select2Tags");
  820. }
  821. if (select) {
  822. opts.query = this.bind(function (query) {
  823. var data = { results: [], more: false },
  824. term = query.term,
  825. children, placeholderOption, process;
  826. process=function(element, collection) {
  827. var group;
  828. if (element.is("option")) {
  829. if (query.matcher(term, element.text(), element)) {
  830. collection.push(self.optionToData(element));
  831. }
  832. } else if (element.is("optgroup")) {
  833. group=self.optionToData(element);
  834. element.children().each2(function(i, elm) { process(elm, group.children); });
  835. if (group.children.length>0) {
  836. collection.push(group);
  837. }
  838. }
  839. };
  840. children=element.children();
  841. // ignore the placeholder option if there is one
  842. if (this.getPlaceholder() !== undefined && children.length > 0) {
  843. placeholderOption = this.getPlaceholderOption();
  844. if (placeholderOption) {
  845. children=children.not(placeholderOption);
  846. }
  847. }
  848. children.each2(function(i, elm) { process(elm, data.results); });
  849. query.callback(data);
  850. });
  851. // this is needed because inside val() we construct choices from options and there id is hardcoded
  852. opts.id=function(e) { return e.id; };
  853. } else {
  854. if (!("query" in opts)) {
  855. if ("ajax" in opts) {
  856. ajaxUrl = opts.element.data("ajax-url");
  857. if (ajaxUrl && ajaxUrl.length > 0) {
  858. opts.ajax.url = ajaxUrl;
  859. }
  860. opts.query = ajax.call(opts.element, opts.ajax);
  861. } else if ("data" in opts) {
  862. opts.query = local(opts.data);
  863. } else if ("tags" in opts) {
  864. opts.query = tags(opts.tags);
  865. if (opts.createSearchChoice === undefined) {
  866. opts.createSearchChoice = function (term) { return {id: $.trim(term), text: $.trim(term)}; };
  867. }
  868. if (opts.initSelection === undefined) {
  869. opts.initSelection = function (element, callback) {
  870. var data = [];
  871. $(splitVal(element.val(), opts.separator)).each(function () {
  872. var obj = { id: this, text: this },
  873. tags = opts.tags;
  874. if ($.isFunction(tags)) tags=tags();
  875. $(tags).each(function() { if (equal(this.id, obj.id)) { obj = this; return false; } });
  876. data.push(obj);
  877. });
  878. callback(data);
  879. };
  880. }
  881. }
  882. }
  883. }
  884. if (typeof(opts.query) !== "function") {
  885. throw "query function not defined for Select2 " + opts.element.attr("id");
  886. }
  887. if (opts.createSearchChoicePosition === 'top') {
  888. opts.createSearchChoicePosition = function(list, item) { list.unshift(item); };
  889. }
  890. else if (opts.createSearchChoicePosition === 'bottom') {
  891. opts.createSearchChoicePosition = function(list, item) { list.push(item); };
  892. }
  893. else if (typeof(opts.createSearchChoicePosition) !== "function") {
  894. throw "invalid createSearchChoicePosition option must be 'top', 'bottom' or a custom function";
  895. }
  896. return opts;
  897. },
  898. /**
  899. * Monitor the original element for changes and update select2 accordingly
  900. */
  901. // abstract
  902. monitorSource: function () {
  903. var el = this.opts.element, sync, observer;
  904. el.on("change.select2", this.bind(function (e) {
  905. if (this.opts.element.data("select2-change-triggered") !== true) {
  906. this.initSelection();
  907. }
  908. }));
  909. sync = this.bind(function () {
  910. // sync enabled state
  911. var disabled = el.prop("disabled");
  912. if (disabled === undefined) disabled = false;
  913. this.enable(!disabled);
  914. var readonly = el.prop("readonly");
  915. if (readonly === undefined) readonly = false;
  916. this.readonly(readonly);
  917. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  918. this.container.addClass(evaluate(this.opts.containerCssClass));
  919. syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
  920. this.dropdown.addClass(evaluate(this.opts.dropdownCssClass));
  921. });
  922. // IE8-10 (IE9/10 won't fire propertyChange via attachEventListener)
  923. if (el.length && el[0].attachEvent) {
  924. el.each(function() {
  925. this.attachEvent("onpropertychange", sync);
  926. });
  927. }
  928. // hold onto a reference of the callback to work around a chromium bug
  929. if (this.mutationCallback === undefined) {
  930. this.mutationCallback = function (mutations) {
  931. mutations.forEach(sync);
  932. }
  933. }
  934. // safari, chrome, firefox, IE11
  935. observer = window.MutationObserver || window.WebKitMutationObserver|| window.MozMutationObserver;
  936. if (observer !== undefined) {
  937. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  938. this.propertyObserver = new observer(this.mutationCallback);
  939. this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false });
  940. }
  941. },
  942. // abstract
  943. triggerSelect: function(data) {
  944. var evt = $.Event("select2-selecting", { val: this.id(data), object: data });
  945. this.opts.element.trigger(evt);
  946. return !evt.isDefaultPrevented();
  947. },
  948. /**
  949. * Triggers the change event on the source element
  950. */
  951. // abstract
  952. triggerChange: function (details) {
  953. details = details || {};
  954. details= $.extend({}, details, { type: "change", val: this.val() });
  955. // prevents recursive triggering
  956. this.opts.element.data("select2-change-triggered", true);
  957. this.opts.element.trigger(details);
  958. this.opts.element.data("select2-change-triggered", false);
  959. // some validation frameworks ignore the change event and listen instead to keyup, click for selects
  960. // so here we trigger the click event manually
  961. this.opts.element.click();
  962. // ValidationEngine ignores the change event and listens instead to blur
  963. // so here we trigger the blur event manually if so desired
  964. if (this.opts.blurOnChange)
  965. this.opts.element.blur();
  966. },
  967. //abstract
  968. isInterfaceEnabled: function()
  969. {
  970. return this.enabledInterface === true;
  971. },
  972. // abstract
  973. enableInterface: function() {
  974. var enabled = this._enabled && !this._readonly,
  975. disabled = !enabled;
  976. if (enabled === this.enabledInterface) return false;
  977. this.container.toggleClass("select2-container-disabled", disabled);
  978. this.close();
  979. this.enabledInterface = enabled;
  980. return true;
  981. },
  982. // abstract
  983. enable: function(enabled) {
  984. if (enabled === undefined) enabled = true;
  985. if (this._enabled === enabled) return;
  986. this._enabled = enabled;
  987. this.opts.element.prop("disabled", !enabled);
  988. this.enableInterface();
  989. },
  990. // abstract
  991. disable: function() {
  992. this.enable(false);
  993. },
  994. // abstract
  995. readonly: function(enabled) {
  996. if (enabled === undefined) enabled = false;
  997. if (this._readonly === enabled) return;
  998. this._readonly = enabled;
  999. this.opts.element.prop("readonly", enabled);
  1000. this.enableInterface();
  1001. },
  1002. // abstract
  1003. opened: function () {
  1004. return this.container.hasClass("select2-dropdown-open");
  1005. },
  1006. // abstract
  1007. positionDropdown: function() {
  1008. var $dropdown = this.dropdown,
  1009. offset = this.container.offset(),
  1010. height = this.container.outerHeight(false),
  1011. width = this.container.outerWidth(false),
  1012. dropHeight = $dropdown.outerHeight(false),
  1013. $window = $(window),
  1014. windowWidth = $window.width(),
  1015. windowHeight = $window.height(),
  1016. viewPortRight = $window.scrollLeft() + windowWidth,
  1017. viewportBottom = $window.scrollTop() + windowHeight,
  1018. dropTop = offset.top + height,
  1019. dropLeft = offset.left,
  1020. enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
  1021. enoughRoomAbove = (offset.top - dropHeight) >= $window.scrollTop(),
  1022. dropWidth = $dropdown.outerWidth(false),
  1023. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight,
  1024. aboveNow = $dropdown.hasClass("select2-drop-above"),
  1025. bodyOffset,
  1026. above,
  1027. changeDirection,
  1028. css,
  1029. resultsListNode;
  1030. // always prefer the current above/below alignment, unless there is not enough room
  1031. if (aboveNow) {
  1032. above = true;
  1033. if (!enoughRoomAbove && enoughRoomBelow) {
  1034. changeDirection = true;
  1035. above = false;
  1036. }
  1037. } else {
  1038. above = false;
  1039. if (!enoughRoomBelow && enoughRoomAbove) {
  1040. changeDirection = true;
  1041. above = true;
  1042. }
  1043. }
  1044. //if we are changing direction we need to get positions when dropdown is hidden;
  1045. if (changeDirection) {
  1046. $dropdown.hide();
  1047. offset = this.container.offset();
  1048. height = this.container.outerHeight(false);
  1049. width = this.container.outerWidth(false);
  1050. dropHeight = $dropdown.outerHeight(false);
  1051. viewPortRight = $window.scrollLeft() + windowWidth;
  1052. viewportBottom = $window.scrollTop() + windowHeight;
  1053. dropTop = offset.top + height;
  1054. dropLeft = offset.left;
  1055. dropWidth = $dropdown.outerWidth(false);
  1056. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
  1057. $dropdown.show();
  1058. // fix so the cursor does not move to the left within the search-textbox in IE
  1059. this.focusSearch();
  1060. }
  1061. if (this.opts.dropdownAutoWidth) {
  1062. resultsListNode = $('.select2-results', $dropdown)[0];
  1063. $dropdown.addClass('select2-drop-auto-width');
  1064. $dropdown.css('width', '');
  1065. // Add scrollbar width to dropdown if vertical scrollbar is present
  1066. dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width);
  1067. dropWidth > width ? width = dropWidth : dropWidth = width;
  1068. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
  1069. }
  1070. else {
  1071. this.container.removeClass('select2-drop-auto-width');
  1072. }
  1073. //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
  1074. //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove);
  1075. // fix positioning when body has an offset and is not position: static
  1076. if (this.body().css('position') !== 'static') {
  1077. bodyOffset = this.body().offset();
  1078. dropTop -= bodyOffset.top;
  1079. dropLeft -= bodyOffset.left;
  1080. }
  1081. if (!enoughRoomOnRight) {
  1082. dropLeft = offset.left + this.container.outerWidth(false) - dropWidth;
  1083. }
  1084. css = {
  1085. left: dropLeft,
  1086. width: width
  1087. };
  1088. if (above) {
  1089. css.top = offset.top - dropHeight;
  1090. css.bottom = 'auto';
  1091. this.container.addClass("select2-drop-above");
  1092. $dropdown.addClass("select2-drop-above");
  1093. }
  1094. else {
  1095. css.top = dropTop;
  1096. css.bottom = 'auto';
  1097. this.container.removeClass("select2-drop-above");
  1098. $dropdown.removeClass("select2-drop-above");
  1099. }
  1100. css = $.extend(css, evaluate(this.opts.dropdownCss));
  1101. $dropdown.css(css);
  1102. },
  1103. // abstract
  1104. shouldOpen: function() {
  1105. var event;
  1106. if (this.opened()) return false;
  1107. if (this._enabled === false || this._readonly === true) return false;
  1108. event = $.Event("select2-opening");
  1109. this.opts.element.trigger(event);
  1110. return !event.isDefaultPrevented();
  1111. },
  1112. // abstract
  1113. clearDropdownAlignmentPreference: function() {
  1114. // clear the classes used to figure out the preference of where the dropdown should be opened
  1115. this.container.removeClass("select2-drop-above");
  1116. this.dropdown.removeClass("select2-drop-above");
  1117. },
  1118. /**
  1119. * Opens the dropdown
  1120. *
  1121. * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
  1122. * the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
  1123. */
  1124. // abstract
  1125. open: function () {
  1126. if (!this.shouldOpen()) return false;
  1127. this.opening();
  1128. return true;
  1129. },
  1130. /**
  1131. * Performs the opening of the dropdown
  1132. */
  1133. // abstract
  1134. opening: function() {
  1135. var cid = this.containerId,
  1136. scroll = "scroll." + cid,
  1137. resize = "resize."+cid,
  1138. orient = "orientationchange."+cid,
  1139. mask;
  1140. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  1141. this.clearDropdownAlignmentPreference();
  1142. if(this.dropdown[0] !== this.body().children().last()[0]) {
  1143. this.dropdown.detach().appendTo(this.body());
  1144. }
  1145. // create the dropdown mask if doesn't already exist
  1146. mask = $("#select2-drop-mask");
  1147. if (mask.length == 0) {
  1148. mask = $(document.createElement("div"));
  1149. mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
  1150. mask.hide();
  1151. mask.appendTo(this.body());
  1152. mask.on("mousedown touchstart click", function (e) {
  1153. // Prevent IE from generating a click event on the body
  1154. reinsertElement(mask);
  1155. var dropdown = $("#select2-drop"), self;
  1156. if (dropdown.length > 0) {
  1157. self=dropdown.data("select2");
  1158. if (self.opts.selectOnBlur) {
  1159. self.selectHighlighted({noFocus: true});
  1160. }
  1161. self.close();
  1162. e.preventDefault();
  1163. e.stopPropagation();
  1164. }
  1165. });
  1166. }
  1167. // ensure the mask is always right before the dropdown
  1168. if (this.dropdown.prev()[0] !== mask[0]) {
  1169. this.dropdown.before(mask);
  1170. }
  1171. // move the global id to the correct dropdown
  1172. $("#select2-drop").removeAttr("id");
  1173. this.dropdown.attr("id", "select2-drop");
  1174. // show the elements
  1175. mask.show();
  1176. this.positionDropdown();
  1177. this.dropdown.show();
  1178. this.positionDropdown();
  1179. this.dropdown.addClass("select2-drop-active");
  1180. // attach listeners to events that can change the position of the container and thus require
  1181. // the position of the dropdown to be updated as well so it does not come unglued from the container
  1182. var that = this;
  1183. this.container.parents().add(window).each(function () {
  1184. $(this).on(resize+" "+scroll+" "+orient, function (e) {
  1185. that.positionDropdown();
  1186. });
  1187. });
  1188. },
  1189. // abstract
  1190. close: function () {
  1191. if (!this.opened()) return;
  1192. var cid = this.containerId,
  1193. scroll = "scroll." + cid,
  1194. resize = "resize."+cid,
  1195. orient = "orientationchange."+cid;
  1196. // unbind event listeners
  1197. this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); });
  1198. this.clearDropdownAlignmentPreference();
  1199. $("#select2-drop-mask").hide();
  1200. this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id
  1201. this.dropdown.hide();
  1202. this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active");
  1203. this.results.empty();
  1204. this.clearSearch();
  1205. this.search.removeClass("select2-active");
  1206. this.opts.element.trigger($.Event("select2-close"));
  1207. },
  1208. /**
  1209. * Opens control, sets input value, and updates results.
  1210. */
  1211. // abstract
  1212. externalSearch: function (term) {
  1213. this.open();
  1214. this.search.val(term);
  1215. this.updateResults(false);
  1216. },
  1217. // abstract
  1218. clearSearch: function () {
  1219. },
  1220. //abstract
  1221. getMaximumSelectionSize: function() {
  1222. return evaluate(this.opts.maximumSelectionSize);
  1223. },
  1224. // abstract
  1225. ensureHighlightVisible: function () {
  1226. var results = this.results, children, index, child, hb, rb, y, more;
  1227. index = this.highlight();
  1228. if (index < 0) return;
  1229. if (index == 0) {
  1230. // if the first element is highlighted scroll all the way to the top,
  1231. // that way any unselectable headers above it will also be scrolled
  1232. // into view
  1233. results.scrollTop(0);
  1234. return;
  1235. }
  1236. children = this.findHighlightableChoices().find('.select2-result-label');
  1237. child = $(children[index]);
  1238. hb = child.offset().top + child.outerHeight(true);
  1239. // if this is the last child lets also make sure select2-more-results is visible
  1240. if (index === children.length - 1) {
  1241. more = results.find("li.select2-more-results");
  1242. if (more.length > 0) {
  1243. hb = more.offset().top + more.outerHeight(true);
  1244. }
  1245. }
  1246. rb = results.offset().top + results.outerHeight(true);
  1247. if (hb > rb) {
  1248. results.scrollTop(results.scrollTop() + (hb - rb));
  1249. }
  1250. y = child.offset().top - results.offset().top;
  1251. // make sure the top of the element is visible
  1252. if (y < 0 && child.css('display') != 'none' ) {
  1253. results.scrollTop(results.scrollTop() + y); // y is negative
  1254. }
  1255. },
  1256. // abstract
  1257. findHighlightableChoices: function() {
  1258. return this.results.find(".select2-result-selectable:not(.select2-disabled):not(.select2-selected)");
  1259. },
  1260. // abstract
  1261. moveHighlight: function (delta) {
  1262. var choices = this.findHighlightableChoices(),
  1263. index = this.highlight();
  1264. while (index > -1 && index < choices.length) {
  1265. index += delta;
  1266. var choice = $(choices[index]);
  1267. if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) {
  1268. this.highlight(index);
  1269. break;
  1270. }
  1271. }
  1272. },
  1273. // abstract
  1274. highlight: function (index) {
  1275. var choices = this.findHighlightableChoices(),
  1276. choice,
  1277. data;
  1278. if (arguments.length === 0) {
  1279. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  1280. }
  1281. if (index >= choices.length) index = choices.length - 1;
  1282. if (index < 0) index = 0;
  1283. this.removeHighlight();
  1284. choice = $(choices[index]);
  1285. choice.addClass("select2-highlighted");
  1286. // ensure assistive technology can determine the active choice
  1287. this.search.attr("aria-activedescendant", choice.find(".select2-result-label").attr("id"));
  1288. this.ensureHighlightVisible();
  1289. this.liveRegion.text(choice.text());
  1290. data = choice.data("select2-data");
  1291. if (data) {
  1292. this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data });
  1293. }
  1294. },
  1295. removeHighlight: function() {
  1296. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  1297. },
  1298. touchMoved: function() {
  1299. this._touchMoved = true;
  1300. },
  1301. clearTouchMoved: function() {
  1302. this._touchMoved = false;
  1303. },
  1304. // abstract
  1305. countSelectableResults: function() {
  1306. return this.findHighlightableChoices().length;
  1307. },
  1308. // abstract
  1309. highlightUnderEvent: function (event) {
  1310. var el = $(event.target).closest(".select2-result-selectable");
  1311. if (el.length > 0 && !el.is(".select2-highlighted")) {
  1312. var choices = this.findHighlightableChoices();
  1313. this.highlight(choices.index(el));
  1314. } else if (el.length == 0) {
  1315. // if we are over an unselectable item remove all highlights
  1316. this.removeHighlight();
  1317. }
  1318. },
  1319. // abstract
  1320. loadMoreIfNeeded: function () {
  1321. var results = this.results,
  1322. more = results.find("li.select2-more-results"),
  1323. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  1324. page = this.resultsPage + 1,
  1325. self=this,
  1326. term=this.search.val(),
  1327. context=this.context;
  1328. if (more.length === 0) return;
  1329. below = more.offset().top - results.offset().top - results.height();
  1330. if (below <= this.opts.loadMorePadding) {
  1331. more.addClass("select2-active");
  1332. this.opts.query({
  1333. element: this.opts.element,
  1334. term: term,
  1335. page: page,
  1336. context: context,
  1337. matcher: this.opts.matcher,
  1338. callback: this.bind(function (data) {
  1339. // ignore a response if the select2 has been closed before it was received
  1340. if (!self.opened()) return;
  1341. self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
  1342. self.postprocessResults(data, false, false);
  1343. if (data.more===true) {
  1344. more.detach().appendTo(results).text(evaluate(self.opts.formatLoadMore, page+1));
  1345. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1346. } else {
  1347. more.remove();
  1348. }
  1349. self.positionDropdown();
  1350. self.resultsPage = page;
  1351. self.context = data.context;
  1352. this.opts.element.trigger({ type: "select2-loaded", items: data });
  1353. })});
  1354. }
  1355. },
  1356. /**
  1357. * Default tokenizer function which does nothing
  1358. */
  1359. tokenize: function() {
  1360. },
  1361. /**
  1362. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  1363. */
  1364. // abstract
  1365. updateResults: function (initial) {
  1366. var search = this.search,
  1367. results = this.results,
  1368. opts = this.opts,
  1369. data,
  1370. self = this,
  1371. input,
  1372. term = search.val(),
  1373. lastTerm = $.data(this.container, "select2-last-term"),
  1374. // sequence number used to drop out-of-order responses
  1375. queryNumber;
  1376. // prevent duplicate queries against the same term
  1377. if (initial !== true && lastTerm && equal(term, lastTerm)) return;
  1378. $.data(this.container, "select2-last-term", term);
  1379. // if the search is currently hidden we do not alter the results
  1380. if (initial !== true && (this.showSearchInput === false || !this.opened())) {
  1381. return;
  1382. }
  1383. function postRender() {
  1384. search.removeClass("select2-active");
  1385. self.positionDropdown();
  1386. if (results.find('.select2-no-results,.select2-selection-limit,.select2-searching').length) {
  1387. self.liveRegion.text(results.text());
  1388. }
  1389. else {
  1390. self.liveRegion.text(self.opts.formatMatches(results.find('.select2-result-selectable').length));
  1391. }
  1392. }
  1393. function render(html) {
  1394. results.html(html);
  1395. postRender();
  1396. }
  1397. queryNumber = ++this.queryCount;
  1398. var maxSelSize = this.getMaximumSelectionSize();
  1399. if (maxSelSize >=1) {
  1400. data = this.data();
  1401. if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
  1402. render("<li class='select2-selection-limit'>" + evaluate(opts.formatSelectionTooBig, maxSelSize) + "</li>");
  1403. return;
  1404. }
  1405. }
  1406. if (search.val().length < opts.minimumInputLength) {
  1407. if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
  1408. render("<li class='select2-no-results'>" + evaluate(opts.formatInputTooShort, search.val(), opts.minimumInputLength) + "</li>");
  1409. } else {
  1410. render("");
  1411. }
  1412. if (initial && this.showSearch) this.showSearch(true);
  1413. return;
  1414. }
  1415. if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) {
  1416. if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) {
  1417. render("<li class='select2-no-results'>" + evaluate(opts.formatInputTooLong, search.val(), opts.maximumInputLength) + "</li>");
  1418. } else {
  1419. render("");
  1420. }
  1421. return;
  1422. }
  1423. if (opts.formatSearching && this.findHighlightableChoices().length === 0) {
  1424. render("<li class='select2-searching'>" + evaluate(opts.formatSearching) + "</li>");
  1425. }
  1426. search.addClass("select2-active");
  1427. this.removeHighlight();
  1428. // give the tokenizer a chance to pre-process the input
  1429. input = this.tokenize();
  1430. if (input != undefined && input != null) {
  1431. search.val(input);
  1432. }
  1433. this.resultsPage = 1;
  1434. opts.query({
  1435. element: opts.element,
  1436. term: search.val(),
  1437. page: this.resultsPage,
  1438. context: null,
  1439. matcher: opts.matcher,
  1440. callback: this.bind(function (data) {
  1441. var def; // default choice
  1442. // ignore old responses
  1443. if (queryNumber != this.queryCount) {
  1444. return;
  1445. }
  1446. // ignore a response if the select2 has been closed before it was received
  1447. if (!this.opened()) {
  1448. this.search.removeClass("select2-active");
  1449. return;
  1450. }
  1451. // save context, if any
  1452. this.context = (data.context===undefined) ? null : data.context;
  1453. // create a default choice and prepend it to the list
  1454. if (this.opts.createSearchChoice && search.val() !== "") {
  1455. def = this.opts.createSearchChoice.call(self, search.val(), data.results);
  1456. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  1457. if ($(data.results).filter(
  1458. function () {
  1459. return equal(self.id(this), self.id(def));
  1460. }).length === 0) {
  1461. this.opts.createSearchChoicePosition(data.results, def);
  1462. }
  1463. }
  1464. }
  1465. if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
  1466. render("<li class='select2-no-results'>" + evaluate(opts.formatNoMatches, search.val()) + "</li>");
  1467. return;
  1468. }
  1469. results.empty();
  1470. self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  1471. if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
  1472. results.append("<li class='select2-more-results'>" + self.opts.escapeMarkup(evaluate(opts.formatLoadMore, this.resultsPage)) + "</li>");
  1473. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1474. }
  1475. this.postprocessResults(data, initial);
  1476. postRender();
  1477. this.opts.element.trigger({ type: "select2-loaded", items: data });
  1478. })});
  1479. },
  1480. // abstract
  1481. cancel: function () {
  1482. this.close();
  1483. },
  1484. // abstract
  1485. blur: function () {
  1486. // if selectOnBlur == true, select the currently highlighted option
  1487. if (this.opts.selectOnBlur)
  1488. this.selectHighlighted({noFocus: true});
  1489. this.close();
  1490. this.container.removeClass("select2-container-active");
  1491. // synonymous to .is(':focus'), which is available in jquery >= 1.6
  1492. if (this.search[0] === document.activeElement) { this.search.blur(); }
  1493. this.clearSearch();
  1494. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1495. },
  1496. // abstract
  1497. focusSearch: function () {
  1498. focus(this.search);
  1499. },
  1500. // abstract
  1501. selectHighlighted: function (options) {
  1502. if (this._touchMoved) {
  1503. this.clearTouchMoved();
  1504. return;
  1505. }
  1506. var index=this.highlight(),
  1507. highlighted=this.results.find(".select2-highlighted"),
  1508. data = highlighted.closest('.select2-result').data("select2-data");
  1509. if (data) {
  1510. this.highlight(index);
  1511. this.onSelect(data, options);
  1512. } else if (options && options.noFocus) {
  1513. this.close();
  1514. }
  1515. },
  1516. // abstract
  1517. getPlaceholder: function () {
  1518. var placeholderOption;
  1519. return this.opts.element.attr("placeholder") ||
  1520. this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
  1521. this.opts.element.data("placeholder") ||
  1522. this.opts.placeholder ||
  1523. ((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined);
  1524. },
  1525. // abstract
  1526. getPlaceholderOption: function() {
  1527. if (this.select) {
  1528. var firstOption = this.select.children('option').first();
  1529. if (this.opts.placeholderOption !== undefined ) {
  1530. //Determine the placeholder option based on the specified placeholderOption setting
  1531. return (this.opts.placeholderOption === "first" && firstOption) ||
  1532. (typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select));
  1533. } else if ($.trim(firstOption.text()) === "" && firstOption.val() === "") {
  1534. //No explicit placeholder option specified, use the first if it's blank
  1535. return firstOption;
  1536. }
  1537. }
  1538. },
  1539. /**
  1540. * Get the desired width for the container element. This is
  1541. * derived first from option `width` passed to select2, then
  1542. * the inline 'style' on the original element, and finally
  1543. * falls back to the jQuery calculated element width.
  1544. */
  1545. // abstract
  1546. initContainerWidth: function () {
  1547. function resolveContainerWidth() {
  1548. var style, attrs, matches, i, l, attr;
  1549. if (this.opts.width === "off") {
  1550. return null;
  1551. } else if (this.opts.width === "element"){
  1552. return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px';
  1553. } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
  1554. // check if there is inline style on the element that contains width
  1555. style = this.opts.element.attr('style');
  1556. if (style !== undefined) {
  1557. attrs = style.split(';');
  1558. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  1559. attr = attrs[i].replace(/\s/g, '');
  1560. matches = attr.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i);
  1561. if (matches !== null && matches.length >= 1)
  1562. return matches[1];
  1563. }
  1564. }
  1565. if (this.opts.width === "resolve") {
  1566. // next check if css('width') can resolve a width that is percent based, this is sometimes possible
  1567. // when attached to input type=hidden or elements hidden via css
  1568. style = this.opts.element.css('width');
  1569. if (style.indexOf("%") > 0) return style;
  1570. // finally, fallback on the calculated width of the element
  1571. return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px');
  1572. }
  1573. return null;
  1574. } else if ($.isFunction(this.opts.width)) {
  1575. return this.opts.width();
  1576. } else {
  1577. return this.opts.width;
  1578. }
  1579. };
  1580. var width = resolveContainerWidth.call(this);
  1581. if (width !== null) {
  1582. this.container.css("width", width);
  1583. }
  1584. }
  1585. });
  1586. SingleSelect2 = clazz(AbstractSelect2, {
  1587. // single
  1588. createContainer: function () {
  1589. var container = $(document.createElement("div")).attr({
  1590. "class": "select2-container"
  1591. }).html([
  1592. "<a href='javascript:void(0)' class='select2-choice' tabindex='-1'>",
  1593. " <span class='select2-chosen'>&#160;</span><abbr class='select2-search-choice-close'></abbr>",
  1594. " <span class='select2-arrow' role='presentation'><b role='presentation'></b></span>",
  1595. "</a>",
  1596. "<label for='' class='select2-offscreen'></label>",
  1597. "<input class='select2-focusser select2-offscreen' type='text' aria-haspopup='true' role='button' />",
  1598. "<div class='select2-drop select2-display-none'>",
  1599. " <div class='select2-search'>",
  1600. " <label for='' class='select2-offscreen'></label>",
  1601. " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input' role='combobox' aria-expanded='true'",
  1602. " aria-autocomplete='list' />",
  1603. " </div>",
  1604. " <ul class='select2-results' role='listbox'>",
  1605. " </ul>",
  1606. "</div>"].join(""));
  1607. return container;
  1608. },
  1609. // single
  1610. enableInterface: function() {
  1611. if (this.parent.enableInterface.apply(this, arguments)) {
  1612. this.focusser.prop("disabled", !this.isInterfaceEnabled());
  1613. }
  1614. },
  1615. // single
  1616. opening: function () {
  1617. var el, range, len;
  1618. if (this.opts.minimumResultsForSearch >= 0) {
  1619. this.showSearch(true);
  1620. }
  1621. this.parent.opening.apply(this, arguments);
  1622. if (this.showSearchInput !== false) {
  1623. // IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range
  1624. // all other browsers handle this just fine
  1625. this.search.val(this.focusser.val());
  1626. }
  1627. if (this.opts.shouldFocusInput(this)) {
  1628. this.search.focus();
  1629. // move the cursor to the end after focussing, otherwise it will be at the beginning and
  1630. // new text will appear *before* focusser.val()
  1631. el = this.search.get(0);
  1632. if (el.createTextRange) {
  1633. range = el.createTextRange();
  1634. range.collapse(false);
  1635. range.select();
  1636. } else if (el.setSelectionRange) {
  1637. len = this.search.val().length;
  1638. el.setSelectionRange(len, len);
  1639. }
  1640. }
  1641. // initializes search's value with nextSearchTerm (if defined by user)
  1642. // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
  1643. if(this.search.val() === "") {
  1644. if(this.nextSearchTerm != undefined){
  1645. this.search.val(this.nextSearchTerm);
  1646. this.search.select();
  1647. }
  1648. }
  1649. this.focusser.prop("disabled", true).val("");
  1650. this.updateResults(true);
  1651. this.opts.element.trigger($.Event("select2-open"));
  1652. },
  1653. // single
  1654. close: function () {
  1655. if (!this.opened()) return;
  1656. this.parent.close.apply(this, arguments);
  1657. this.focusser.prop("disabled", false);
  1658. if (this.opts.shouldFocusInput(this)) {
  1659. this.focusser.focus();
  1660. }
  1661. },
  1662. // single
  1663. focus: function () {
  1664. if (this.opened()) {
  1665. this.close();
  1666. } else {
  1667. this.focusser.prop("disabled", false);
  1668. if (this.opts.shouldFocusInput(this)) {
  1669. this.focusser.focus();
  1670. }
  1671. }
  1672. },
  1673. // single
  1674. isFocused: function () {
  1675. return this.container.hasClass("select2-container-active");
  1676. },
  1677. // single
  1678. cancel: function () {
  1679. this.parent.cancel.apply(this, arguments);
  1680. this.focusser.prop("disabled", false);
  1681. if (this.opts.shouldFocusInput(this)) {
  1682. this.focusser.focus();
  1683. }
  1684. },
  1685. // single
  1686. destroy: function() {
  1687. $("label[for='" + this.focusser.attr('id') + "']")
  1688. .attr('for', this.opts.element.attr("id"));
  1689. this.parent.destroy.apply(this, arguments);
  1690. },
  1691. // single
  1692. initContainer: function () {
  1693. var selection,
  1694. container = this.container,
  1695. dropdown = this.dropdown,
  1696. idSuffix = nextUid(),
  1697. elementLabel;
  1698. if (this.opts.minimumResultsForSearch < 0) {
  1699. this.showSearch(false);
  1700. } else {
  1701. this.showSearch(true);
  1702. }
  1703. this.selection = selection = container.find(".select2-choice");
  1704. this.focusser = container.find(".select2-focusser");
  1705. // add aria associations
  1706. selection.find(".select2-chosen").attr("id", "select2-chosen-"+idSuffix);
  1707. this.focusser.attr("aria-labelledby", "select2-chosen-"+idSuffix);
  1708. this.results.attr("id", "select2-results-"+idSuffix);
  1709. this.search.attr("aria-owns", "select2-results-"+idSuffix);
  1710. // rewrite labels from original element to focusser
  1711. this.focusser.attr("id", "s2id_autogen"+idSuffix);
  1712. elementLabel = $("label[for='" + this.opts.element.attr("id") + "']");
  1713. this.focusser.prev()
  1714. .text(elementLabel.text())
  1715. .attr('for', this.focusser.attr('id'));
  1716. // Ensure the original element retains an accessible name
  1717. var originalTitle = this.opts.element.attr("title");
  1718. this.opts.element.attr("title", (originalTitle || elementLabel.text()));
  1719. this.focusser.attr("tabindex", this.elementTabIndex);
  1720. // write label for search field using the label from the focusser element
  1721. this.search.attr("id", this.focusser.attr('id') + '_search');
  1722. this.search.prev()
  1723. .text($("label[for='" + this.focusser.attr('id') + "']").text())
  1724. .attr('for', this.search.attr('id'));
  1725. this.search.on("keydown", this.bind(function (e) {
  1726. if (!this.isInterfaceEnabled()) return;
  1727. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1728. // prevent the page from scrolling
  1729. killEvent(e);
  1730. return;
  1731. }
  1732. switch (e.which) {
  1733. case KEY.UP:
  1734. case KEY.DOWN:
  1735. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1736. killEvent(e);
  1737. return;
  1738. case KEY.ENTER:
  1739. this.selectHighlighted();
  1740. killEvent(e);
  1741. return;
  1742. case KEY.TAB:
  1743. this.selectHighlighted({noFocus: true});
  1744. return;
  1745. case KEY.ESC:
  1746. this.cancel(e);
  1747. killEvent(e);
  1748. return;
  1749. }
  1750. }));
  1751. this.search.on("blur", this.bind(function(e) {
  1752. // a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown.
  1753. // without this the search field loses focus which is annoying
  1754. if (document.activeElement === this.body().get(0)) {
  1755. window.setTimeout(this.bind(function() {
  1756. if (this.opened()) {
  1757. this.search.focus();
  1758. }
  1759. }), 0);
  1760. }
  1761. }));
  1762. this.focusser.on("keydown", this.bind(function (e) {
  1763. if (!this.isInterfaceEnabled()) return;
  1764. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  1765. return;
  1766. }
  1767. if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
  1768. killEvent(e);
  1769. return;
  1770. }
  1771. if (e.which == KEY.DOWN || e.which == KEY.UP
  1772. || (e.which == KEY.ENTER && this.opts.openOnEnter)) {
  1773. if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return;
  1774. this.open();
  1775. killEvent(e);
  1776. return;
  1777. }
  1778. if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) {
  1779. if (this.opts.allowClear) {
  1780. this.clear();
  1781. }
  1782. killEvent(e);
  1783. return;
  1784. }
  1785. }));
  1786. installKeyUpChangeEvent(this.focusser);
  1787. this.focusser.on("keyup-change input", this.bind(function(e) {
  1788. if (this.opts.minimumResultsForSearch >= 0) {
  1789. e.stopPropagation();
  1790. if (this.opened()) return;
  1791. this.open();
  1792. }
  1793. }));
  1794. selection.on("mousedown touchstart", "abbr", this.bind(function (e) {
  1795. if (!this.isInterfaceEnabled()) return;
  1796. this.clear();
  1797. killEventImmediately(e);
  1798. this.close();
  1799. this.selection.focus();
  1800. }));
  1801. selection.on("mousedown touchstart", this.bind(function (e) {
  1802. // Prevent IE from generating a click event on the body
  1803. reinsertElement(selection);
  1804. if (!this.container.hasClass("select2-container-active")) {
  1805. this.opts.element.trigger($.Event("select2-focus"));
  1806. }
  1807. if (this.opened()) {
  1808. this.close();
  1809. } else if (this.isInterfaceEnabled()) {
  1810. this.open();
  1811. }
  1812. killEvent(e);
  1813. }));
  1814. dropdown.on("mousedown touchstart", this.bind(function() {
  1815. if (this.opts.shouldFocusInput(this)) {
  1816. this.search.focus();
  1817. }
  1818. }));
  1819. selection.on("focus", this.bind(function(e) {
  1820. killEvent(e);
  1821. }));
  1822. this.focusser.on("focus", this.bind(function(){
  1823. if (!this.container.hasClass("select2-container-active")) {
  1824. this.opts.element.trigger($.Event("select2-focus"));
  1825. }
  1826. this.container.addClass("select2-container-active");
  1827. })).on("blur", this.bind(function() {
  1828. if (!this.opened()) {
  1829. this.container.removeClass("select2-container-active");
  1830. this.opts.element.trigger($.Event("select2-blur"));
  1831. }
  1832. }));
  1833. this.search.on("focus", this.bind(function(){
  1834. if (!this.container.hasClass("select2-container-active")) {
  1835. this.opts.element.trigger($.Event("select2-focus"));
  1836. }
  1837. this.container.addClass("select2-container-active");
  1838. }));
  1839. this.initContainerWidth();
  1840. this.opts.element.addClass("select2-offscreen");
  1841. this.setPlaceholder();
  1842. },
  1843. // single
  1844. clear: function(triggerChange) {
  1845. var data=this.selection.data("select2-data");
  1846. if (data) { // guard against queued quick consecutive clicks
  1847. var evt = $.Event("select2-clearing");
  1848. this.opts.element.trigger(evt);
  1849. if (evt.isDefaultPrevented()) {
  1850. return;
  1851. }
  1852. var placeholderOption = this.getPlaceholderOption();
  1853. this.opts.element.val(placeholderOption ? placeholderOption.val() : "");
  1854. this.selection.find(".select2-chosen").empty();
  1855. this.selection.removeData("select2-data");
  1856. this.setPlaceholder();
  1857. if (triggerChange !== false){
  1858. this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
  1859. this.triggerChange({removed:data});
  1860. }
  1861. }
  1862. },
  1863. /**
  1864. * Sets selection based on source element's value
  1865. */
  1866. // single
  1867. initSelection: function () {
  1868. var selected;
  1869. if (this.isPlaceholderOptionSelected()) {
  1870. this.updateSelection(null);
  1871. this.close();
  1872. this.setPlaceholder();
  1873. } else {
  1874. var self = this;
  1875. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1876. if (selected !== undefined && selected !== null) {
  1877. self.updateSelection(selected);
  1878. self.close();
  1879. self.setPlaceholder();
  1880. self.nextSearchTerm = self.opts.nextSearchTerm(selected, self.search.val());
  1881. }
  1882. });
  1883. }
  1884. },
  1885. isPlaceholderOptionSelected: function() {
  1886. var placeholderOption;
  1887. if (this.getPlaceholder() === undefined) return false; // no placeholder specified so no option should be considered
  1888. return ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.prop("selected"))
  1889. || (this.opts.element.val() === "")
  1890. || (this.opts.element.val() === undefined)
  1891. || (this.opts.element.val() === null);
  1892. },
  1893. // single
  1894. prepareOpts: function () {
  1895. var opts = this.parent.prepareOpts.apply(this, arguments),
  1896. self=this;
  1897. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1898. // install the selection initializer
  1899. opts.initSelection = function (element, callback) {
  1900. var selected = element.find("option").filter(function() { return this.selected && !this.disabled });
  1901. // a single select box always has a value, no need to null check 'selected'
  1902. callback(self.optionToData(selected));
  1903. };
  1904. } else if ("data" in opts) {
  1905. // install default initSelection when applied to hidden input and data is local
  1906. opts.initSelection = opts.initSelection || function (element, callback) {
  1907. var id = element.val();
  1908. //search in data by id, storing the actual matching item
  1909. var match = null;
  1910. opts.query({
  1911. matcher: function(term, text, el){
  1912. var is_match = equal(id, opts.id(el));
  1913. if (is_match) {
  1914. match = el;
  1915. }
  1916. return is_match;
  1917. },
  1918. callback: !$.isFunction(callback) ? $.noop : function() {
  1919. callback(match);
  1920. }
  1921. });
  1922. };
  1923. }
  1924. return opts;
  1925. },
  1926. // single
  1927. getPlaceholder: function() {
  1928. // if a placeholder is specified on a single select without a valid placeholder option ignore it
  1929. if (this.select) {
  1930. if (this.getPlaceholderOption() === undefined) {
  1931. return undefined;
  1932. }
  1933. }
  1934. return this.parent.getPlaceholder.apply(this, arguments);
  1935. },
  1936. // single
  1937. setPlaceholder: function () {
  1938. var placeholder = this.getPlaceholder();
  1939. if (this.isPlaceholderOptionSelected() && placeholder !== undefined) {
  1940. // check for a placeholder option if attached to a select
  1941. if (this.select && this.getPlaceholderOption() === undefined) return;
  1942. this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder));
  1943. this.selection.addClass("select2-default");
  1944. this.container.removeClass("select2-allowclear");
  1945. }
  1946. },
  1947. // single
  1948. postprocessResults: function (data, initial, noHighlightUpdate) {
  1949. var selected = 0, self = this, showSearchInput = true;
  1950. // find the selected element in the result list
  1951. this.findHighlightableChoices().each2(function (i, elm) {
  1952. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  1953. selected = i;
  1954. return false;
  1955. }
  1956. });
  1957. // and highlight it
  1958. if (noHighlightUpdate !== false) {
  1959. if (initial === true && selected >= 0) {
  1960. this.highlight(selected);
  1961. } else {
  1962. this.highlight(0);
  1963. }
  1964. }
  1965. // hide the search box if this is the first we got the results and there are enough of them for search
  1966. if (initial === true) {
  1967. var min = this.opts.minimumResultsForSearch;
  1968. if (min >= 0) {
  1969. this.showSearch(countResults(data.results) >= min);
  1970. }
  1971. }
  1972. },
  1973. // single
  1974. showSearch: function(showSearchInput) {
  1975. if (this.showSearchInput === showSearchInput) return;
  1976. this.showSearchInput = showSearchInput;
  1977. this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput);
  1978. this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput);
  1979. //add "select2-with-searchbox" to the container if search box is shown
  1980. $(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput);
  1981. },
  1982. // single
  1983. onSelect: function (data, options) {
  1984. if (!this.triggerSelect(data)) { return; }
  1985. var old = this.opts.element.val(),
  1986. oldData = this.data();
  1987. this.opts.element.val(this.id(data));
  1988. this.updateSelection(data);
  1989. this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data });
  1990. this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val());
  1991. this.close();
  1992. if ((!options || !options.noFocus) && this.opts.shouldFocusInput(this)) {
  1993. this.focusser.focus();
  1994. }
  1995. if (!equal(old, this.id(data))) {
  1996. this.triggerChange({ added: data, removed: oldData });
  1997. }
  1998. },
  1999. // single
  2000. updateSelection: function (data) {
  2001. var container=this.selection.find(".select2-chosen"), formatted, cssClass;
  2002. this.selection.data("select2-data", data);
  2003. container.empty();
  2004. if (data !== null) {
  2005. formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup);
  2006. }
  2007. if (formatted !== undefined) {
  2008. container.append(formatted);
  2009. }
  2010. cssClass=this.opts.formatSelectionCssClass(data, container);
  2011. if (cssClass !== undefined) {
  2012. container.addClass(cssClass);
  2013. }
  2014. this.selection.removeClass("select2-default");
  2015. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  2016. this.container.addClass("select2-allowclear");
  2017. }
  2018. },
  2019. // single
  2020. val: function () {
  2021. var val,
  2022. triggerChange = false,
  2023. data = null,
  2024. self = this,
  2025. oldData = this.data();
  2026. if (arguments.length === 0) {
  2027. return this.opts.element.val();
  2028. }
  2029. val = arguments[0];
  2030. if (arguments.length > 1) {
  2031. triggerChange = arguments[1];
  2032. }
  2033. if (this.select) {
  2034. this.select
  2035. .val(val)
  2036. .find("option").filter(function() { return this.selected }).each2(function (i, elm) {
  2037. data = self.optionToData(elm);
  2038. return false;
  2039. });
  2040. this.updateSelection(data);
  2041. this.setPlaceholder();
  2042. if (triggerChange) {
  2043. this.triggerChange({added: data, removed:oldData});
  2044. }
  2045. } else {
  2046. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  2047. if (!val && val !== 0) {
  2048. this.clear(triggerChange);
  2049. return;
  2050. }
  2051. if (this.opts.initSelection === undefined) {
  2052. throw new Error("cannot call val() if initSelection() is not defined");
  2053. }
  2054. this.opts.element.val(val);
  2055. this.opts.initSelection(this.opts.element, function(data){
  2056. self.opts.element.val(!data ? "" : self.id(data));
  2057. self.updateSelection(data);
  2058. self.setPlaceholder();
  2059. if (triggerChange) {
  2060. self.triggerChange({added: data, removed:oldData});
  2061. }
  2062. });
  2063. }
  2064. },
  2065. // single
  2066. clearSearch: function () {
  2067. this.search.val("");
  2068. this.focusser.val("");
  2069. },
  2070. // single
  2071. data: function(value) {
  2072. var data,
  2073. triggerChange = false;
  2074. if (arguments.length === 0) {
  2075. data = this.selection.data("select2-data");
  2076. if (data == undefined) data = null;
  2077. return data;
  2078. } else {
  2079. if (arguments.length > 1) {
  2080. triggerChange = arguments[1];
  2081. }
  2082. if (!value) {
  2083. this.clear(triggerChange);
  2084. } else {
  2085. data = this.data();
  2086. this.opts.element.val(!value ? "" : this.id(value));
  2087. this.updateSelection(value);
  2088. if (triggerChange) {
  2089. this.triggerChange({added: value, removed:data});
  2090. }
  2091. }
  2092. }
  2093. }
  2094. });
  2095. MultiSelect2 = clazz(AbstractSelect2, {
  2096. // multi
  2097. createContainer: function () {
  2098. var container = $(document.createElement("div")).attr({
  2099. "class": "select2-container select2-container-multi"
  2100. }).html([
  2101. "<ul class='select2-choices'>",
  2102. " <li class='select2-search-field'>",
  2103. " <label for='' class='select2-offscreen'></label>",
  2104. " <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'>",
  2105. " </li>",
  2106. "</ul>",
  2107. "<div class='select2-drop select2-drop-multi select2-display-none'>",
  2108. " <ul class='select2-results'>",
  2109. " </ul>",
  2110. "</div>"].join(""));
  2111. return container;
  2112. },
  2113. // multi
  2114. prepareOpts: function () {
  2115. var opts = this.parent.prepareOpts.apply(this, arguments),
  2116. self=this;
  2117. // TODO validate placeholder is a string if specified
  2118. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  2119. // install the selection initializer
  2120. opts.initSelection = function (element, callback) {
  2121. var data = [];
  2122. element.find("option").filter(function() { return this.selected && !this.disabled }).each2(function (i, elm) {
  2123. data.push(self.optionToData(elm));
  2124. });
  2125. callback(data);
  2126. };
  2127. } else if ("data" in opts) {
  2128. // install default initSelection when applied to hidden input and data is local
  2129. opts.initSelection = opts.initSelection || function (element, callback) {
  2130. var ids = splitVal(element.val(), opts.separator);
  2131. //search in data by array of ids, storing matching items in a list
  2132. var matches = [];
  2133. opts.query({
  2134. matcher: function(term, text, el){
  2135. var is_match = $.grep(ids, function(id) {
  2136. return equal(id, opts.id(el));
  2137. }).length;
  2138. if (is_match) {
  2139. matches.push(el);
  2140. }
  2141. return is_match;
  2142. },
  2143. callback: !$.isFunction(callback) ? $.noop : function() {
  2144. // reorder matches based on the order they appear in the ids array because right now
  2145. // they are in the order in which they appear in data array
  2146. var ordered = [];
  2147. for (var i = 0; i < ids.length; i++) {
  2148. var id = ids[i];
  2149. for (var j = 0; j < matches.length; j++) {
  2150. var match = matches[j];
  2151. if (equal(id, opts.id(match))) {
  2152. ordered.push(match);
  2153. matches.splice(j, 1);
  2154. break;
  2155. }
  2156. }
  2157. }
  2158. callback(ordered);
  2159. }
  2160. });
  2161. };
  2162. }
  2163. return opts;
  2164. },
  2165. // multi
  2166. selectChoice: function (choice) {
  2167. var selected = this.container.find(".select2-search-choice-focus");
  2168. if (selected.length && choice && choice[0] == selected[0]) {
  2169. } else {
  2170. if (selected.length) {
  2171. this.opts.element.trigger("choice-deselected", selected);
  2172. }
  2173. selected.removeClass("select2-search-choice-focus");
  2174. if (choice && choice.length) {
  2175. this.close();
  2176. choice.addClass("select2-search-choice-focus");
  2177. this.opts.element.trigger("choice-selected", choice);
  2178. }
  2179. }
  2180. },
  2181. // multi
  2182. destroy: function() {
  2183. $("label[for='" + this.search.attr('id') + "']")
  2184. .attr('for', this.opts.element.attr("id"));
  2185. this.parent.destroy.apply(this, arguments);
  2186. },
  2187. // multi
  2188. initContainer: function () {
  2189. var selector = ".select2-choices", selection;
  2190. this.searchContainer = this.container.find(".select2-search-field");
  2191. this.selection = selection = this.container.find(selector);
  2192. var _this = this;
  2193. this.selection.on("click", ".select2-search-choice:not(.select2-locked)", function (e) {
  2194. //killEvent(e);
  2195. _this.search[0].focus();
  2196. _this.selectChoice($(this));
  2197. });
  2198. // rewrite labels from original element to focusser
  2199. this.search.attr("id", "s2id_autogen"+nextUid());
  2200. this.search.prev()
  2201. .text($("label[for='" + this.opts.element.attr("id") + "']").text())
  2202. .attr('for', this.search.attr('id'));
  2203. this.search.on("input paste", this.bind(function() {
  2204. if (!this.isInterfaceEnabled()) return;
  2205. if (!this.opened()) {
  2206. this.open();
  2207. }
  2208. }));
  2209. this.search.attr("tabindex", this.elementTabIndex);
  2210. this.keydowns = 0;
  2211. this.search.on("keydown", this.bind(function (e) {
  2212. if (!this.isInterfaceEnabled()) return;
  2213. ++this.keydowns;
  2214. var selected = selection.find(".select2-search-choice-focus");
  2215. var prev = selected.prev(".select2-search-choice:not(.select2-locked)");
  2216. var next = selected.next(".select2-search-choice:not(.select2-locked)");
  2217. var pos = getCursorInfo(this.search);
  2218. if (selected.length &&
  2219. (e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) {
  2220. var selectedChoice = selected;
  2221. if (e.which == KEY.LEFT && prev.length) {
  2222. selectedChoice = prev;
  2223. }
  2224. else if (e.which == KEY.RIGHT) {
  2225. selectedChoice = next.length ? next : null;
  2226. }
  2227. else if (e.which === KEY.BACKSPACE) {
  2228. if (this.unselect(selected.first())) {
  2229. this.search.width(10);
  2230. selectedChoice = prev.length ? prev : next;
  2231. }
  2232. } else if (e.which == KEY.DELETE) {
  2233. if (this.unselect(selected.first())) {
  2234. this.search.width(10);
  2235. selectedChoice = next.length ? next : null;
  2236. }
  2237. } else if (e.which == KEY.ENTER) {
  2238. selectedChoice = null;
  2239. }
  2240. this.selectChoice(selectedChoice);
  2241. killEvent(e);
  2242. if (!selectedChoice || !selectedChoice.length) {
  2243. this.open();
  2244. }
  2245. return;
  2246. } else if (((e.which === KEY.BACKSPACE && this.keydowns == 1)
  2247. || e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) {
  2248. this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last());
  2249. killEvent(e);
  2250. return;
  2251. } else {
  2252. this.selectChoice(null);
  2253. }
  2254. if (this.opened()) {
  2255. switch (e.which) {
  2256. case KEY.UP:
  2257. case KEY.DOWN:
  2258. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  2259. killEvent(e);
  2260. return;
  2261. case KEY.ENTER:
  2262. this.selectHighlighted();
  2263. killEvent(e);
  2264. return;
  2265. case KEY.TAB:
  2266. this.selectHighlighted({noFocus:true});
  2267. this.close();
  2268. return;
  2269. case KEY.ESC:
  2270. this.cancel(e);
  2271. killEvent(e);
  2272. return;
  2273. }
  2274. }
  2275. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
  2276. || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  2277. return;
  2278. }
  2279. if (e.which === KEY.ENTER) {
  2280. if (this.opts.openOnEnter === false) {
  2281. return;
  2282. } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
  2283. return;
  2284. }
  2285. }
  2286. this.open();
  2287. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  2288. // prevent the page from scrolling
  2289. killEvent(e);
  2290. }
  2291. if (e.which === KEY.ENTER) {
  2292. // prevent form from being submitted
  2293. killEvent(e);
  2294. }
  2295. }));
  2296. this.search.on("keyup", this.bind(function (e) {
  2297. this.keydowns = 0;
  2298. this.resizeSearch();
  2299. })
  2300. );
  2301. this.search.on("blur", this.bind(function(e) {
  2302. this.container.removeClass("select2-container-active");
  2303. this.search.removeClass("select2-focused");
  2304. this.selectChoice(null);
  2305. if (!this.opened()) this.clearSearch();
  2306. e.stopImmediatePropagation();
  2307. this.opts.element.trigger($.Event("select2-blur"));
  2308. }));
  2309. this.container.on("click", selector, this.bind(function (e) {
  2310. if (!this.isInterfaceEnabled()) return;
  2311. if ($(e.target).closest(".select2-search-choice").length > 0) {
  2312. // clicked inside a select2 search choice, do not open
  2313. return;
  2314. }
  2315. this.selectChoice(null);
  2316. this.clearPlaceholder();
  2317. if (!this.container.hasClass("select2-container-active")) {
  2318. this.opts.element.trigger($.Event("select2-focus"));
  2319. }
  2320. this.open();
  2321. this.focusSearch();
  2322. e.preventDefault();
  2323. }));
  2324. this.container.on("focus", selector, this.bind(function () {
  2325. if (!this.isInterfaceEnabled()) return;
  2326. if (!this.container.hasClass("select2-container-active")) {
  2327. this.opts.element.trigger($.Event("select2-focus"));
  2328. }
  2329. this.container.addClass("select2-container-active");
  2330. this.dropdown.addClass("select2-drop-active");
  2331. this.clearPlaceholder();
  2332. }));
  2333. this.initContainerWidth();
  2334. this.opts.element.addClass("select2-offscreen");
  2335. // set the placeholder if necessary
  2336. this.clearSearch();
  2337. },
  2338. // multi
  2339. enableInterface: function() {
  2340. if (this.parent.enableInterface.apply(this, arguments)) {
  2341. this.search.prop("disabled", !this.isInterfaceEnabled());
  2342. }
  2343. },
  2344. // multi
  2345. initSelection: function () {
  2346. var data;
  2347. if (this.opts.element.val() === "" && this.opts.element.text() === "") {
  2348. this.updateSelection([]);
  2349. this.close();
  2350. // set the placeholder if necessary
  2351. this.clearSearch();
  2352. }
  2353. if (this.select || this.opts.element.val() !== "") {
  2354. var self = this;
  2355. this.opts.initSelection.call(null, this.opts.element, function(data){
  2356. if (data !== undefined && data !== null) {
  2357. self.updateSelection(data);
  2358. self.close();
  2359. // set the placeholder if necessary
  2360. self.clearSearch();
  2361. }
  2362. });
  2363. }
  2364. },
  2365. // multi
  2366. clearSearch: function () {
  2367. var placeholder = this.getPlaceholder(),
  2368. maxWidth = this.getMaxSearchWidth();
  2369. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  2370. this.search.val(placeholder).addClass("select2-default");
  2371. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  2372. // 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
  2373. this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width"));
  2374. } else {
  2375. this.search.val("").width(10);
  2376. }
  2377. },
  2378. // multi
  2379. clearPlaceholder: function () {
  2380. if (this.search.hasClass("select2-default")) {
  2381. this.search.val("").removeClass("select2-default");
  2382. }
  2383. },
  2384. // multi
  2385. opening: function () {
  2386. this.clearPlaceholder(); // should be done before super so placeholder is not used to search
  2387. this.resizeSearch();
  2388. this.parent.opening.apply(this, arguments);
  2389. this.focusSearch();
  2390. // initializes search's value with nextSearchTerm (if defined by user)
  2391. // ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
  2392. if(this.search.val() === "") {
  2393. if(this.nextSearchTerm != undefined){
  2394. this.search.val(this.nextSearchTerm);
  2395. this.search.select();
  2396. }
  2397. }
  2398. this.updateResults(true);
  2399. if (this.opts.shouldFocusInput(this)) {
  2400. this.search.focus();
  2401. }
  2402. this.opts.element.trigger($.Event("select2-open"));
  2403. },
  2404. // multi
  2405. close: function () {
  2406. if (!this.opened()) return;
  2407. this.parent.close.apply(this, arguments);
  2408. },
  2409. // multi
  2410. focus: function () {
  2411. this.close();
  2412. this.search.focus();
  2413. },
  2414. // multi
  2415. isFocused: function () {
  2416. return this.search.hasClass("select2-focused");
  2417. },
  2418. // multi
  2419. updateSelection: function (data) {
  2420. var ids = [], filtered = [], self = this;
  2421. // filter out duplicates
  2422. $(data).each(function () {
  2423. if (indexOf(self.id(this), ids) < 0) {
  2424. ids.push(self.id(this));
  2425. filtered.push(this);
  2426. }
  2427. });
  2428. data = filtered;
  2429. this.selection.find(".select2-search-choice").remove();
  2430. $(data).each(function () {
  2431. self.addSelectedChoice(this);
  2432. });
  2433. self.postprocessResults();
  2434. },
  2435. // multi
  2436. tokenize: function() {
  2437. var input = this.search.val();
  2438. input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts);
  2439. if (input != null && input != undefined) {
  2440. this.search.val(input);
  2441. if (input.length > 0) {
  2442. this.open();
  2443. }
  2444. }
  2445. },
  2446. // multi
  2447. onSelect: function (data, options) {
  2448. if (!this.triggerSelect(data)) { return; }
  2449. this.addSelectedChoice(data);
  2450. this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
  2451. // keep track of the search's value before it gets cleared
  2452. this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val());
  2453. this.clearSearch();
  2454. this.updateResults();
  2455. if (this.select || !this.opts.closeOnSelect) this.postprocessResults(data, false, this.opts.closeOnSelect===true);
  2456. if (this.opts.closeOnSelect) {
  2457. this.close();
  2458. this.search.width(10);
  2459. } else {
  2460. if (this.countSelectableResults()>0) {
  2461. this.search.width(10);
  2462. this.resizeSearch();
  2463. if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) {
  2464. // if we reached max selection size repaint the results so choices
  2465. // are replaced with the max selection reached message
  2466. this.updateResults(true);
  2467. } else {
  2468. // initializes search's value with nextSearchTerm and update search result
  2469. if(this.nextSearchTerm != undefined){
  2470. this.search.val(this.nextSearchTerm);
  2471. this.updateResults();
  2472. this.search.select();
  2473. }
  2474. }
  2475. this.positionDropdown();
  2476. } else {
  2477. // if nothing left to select close
  2478. this.close();
  2479. this.search.width(10);
  2480. }
  2481. }
  2482. // since its not possible to select an element that has already been
  2483. // added we do not need to check if this is a new element before firing change
  2484. this.triggerChange({ added: data });
  2485. if (!options || !options.noFocus)
  2486. this.focusSearch();
  2487. },
  2488. // multi
  2489. cancel: function () {
  2490. this.close();
  2491. this.focusSearch();
  2492. },
  2493. addSelectedChoice: function (data) {
  2494. var enableChoice = !data.locked,
  2495. enabledItem = $(
  2496. "<li class='select2-search-choice'>" +
  2497. " <div></div>" +
  2498. " <a href='#' class='select2-search-choice-close' tabindex='-1'></a>" +
  2499. "</li>"),
  2500. disabledItem = $(
  2501. "<li class='select2-search-choice select2-locked'>" +
  2502. "<div></div>" +
  2503. "</li>");
  2504. var choice = enableChoice ? enabledItem : disabledItem,
  2505. id = this.id(data),
  2506. val = this.getVal(),
  2507. formatted,
  2508. cssClass;
  2509. formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup);
  2510. if (formatted != undefined) {
  2511. choice.find("div").replaceWith("<div>"+formatted+"</div>");
  2512. }
  2513. cssClass=this.opts.formatSelectionCssClass(data, choice.find("div"));
  2514. if (cssClass != undefined) {
  2515. choice.addClass(cssClass);
  2516. }
  2517. if(enableChoice){
  2518. choice.find(".select2-search-choice-close")
  2519. .on("mousedown", killEvent)
  2520. .on("click dblclick", this.bind(function (e) {
  2521. if (!this.isInterfaceEnabled()) return;
  2522. this.unselect($(e.target));
  2523. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  2524. killEvent(e);
  2525. this.close();
  2526. this.focusSearch();
  2527. })).on("focus", this.bind(function () {
  2528. if (!this.isInterfaceEnabled()) return;
  2529. this.container.addClass("select2-container-active");
  2530. this.dropdown.addClass("select2-drop-active");
  2531. }));
  2532. }
  2533. choice.data("select2-data", data);
  2534. choice.insertBefore(this.searchContainer);
  2535. val.push(id);
  2536. this.setVal(val);
  2537. },
  2538. // multi
  2539. unselect: function (selected) {
  2540. var val = this.getVal(),
  2541. data,
  2542. index;
  2543. selected = selected.closest(".select2-search-choice");
  2544. if (selected.length === 0) {
  2545. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  2546. }
  2547. data = selected.data("select2-data");
  2548. if (!data) {
  2549. // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued
  2550. // and invoked on an element already removed
  2551. return;
  2552. }
  2553. var evt = $.Event("select2-removing");
  2554. evt.val = this.id(data);
  2555. evt.choice = data;
  2556. this.opts.element.trigger(evt);
  2557. if (evt.isDefaultPrevented()) {
  2558. return false;
  2559. }
  2560. while((index = indexOf(this.id(data), val)) >= 0) {
  2561. val.splice(index, 1);
  2562. this.setVal(val);
  2563. if (this.select) this.postprocessResults();
  2564. }
  2565. selected.remove();
  2566. this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
  2567. this.triggerChange({ removed: data });
  2568. return true;
  2569. },
  2570. // multi
  2571. postprocessResults: function (data, initial, noHighlightUpdate) {
  2572. var val = this.getVal(),
  2573. choices = this.results.find(".select2-result"),
  2574. compound = this.results.find(".select2-result-with-children"),
  2575. self = this;
  2576. choices.each2(function (i, choice) {
  2577. var id = self.id(choice.data("select2-data"));
  2578. if (indexOf(id, val) >= 0) {
  2579. choice.addClass("select2-selected");
  2580. // mark all children of the selected parent as selected
  2581. choice.find(".select2-result-selectable").addClass("select2-selected");
  2582. }
  2583. });
  2584. compound.each2(function(i, choice) {
  2585. // hide an optgroup if it doesn't have any selectable children
  2586. if (!choice.is('.select2-result-selectable')
  2587. && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) {
  2588. choice.addClass("select2-selected");
  2589. }
  2590. });
  2591. if (this.highlight() == -1 && noHighlightUpdate !== false){
  2592. self.highlight(0);
  2593. }
  2594. //If all results are chosen render formatNoMatches
  2595. if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){
  2596. if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) {
  2597. if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) {
  2598. this.results.append("<li class='select2-no-results'>" + evaluate(self.opts.formatNoMatches, self.search.val()) + "</li>");
  2599. }
  2600. }
  2601. }
  2602. },
  2603. // multi
  2604. getMaxSearchWidth: function() {
  2605. return this.selection.width() - getSideBorderPadding(this.search);
  2606. },
  2607. // multi
  2608. resizeSearch: function () {
  2609. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  2610. sideBorderPadding = getSideBorderPadding(this.search);
  2611. minimumWidth = measureTextWidth(this.search) + 10;
  2612. left = this.search.offset().left;
  2613. maxWidth = this.selection.width();
  2614. containerLeft = this.selection.offset().left;
  2615. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  2616. if (searchWidth < minimumWidth) {
  2617. searchWidth = maxWidth - sideBorderPadding;
  2618. }
  2619. if (searchWidth < 40) {
  2620. searchWidth = maxWidth - sideBorderPadding;
  2621. }
  2622. if (searchWidth <= 0) {
  2623. searchWidth = minimumWidth;
  2624. }
  2625. this.search.width(Math.floor(searchWidth));
  2626. },
  2627. // multi
  2628. getVal: function () {
  2629. var val;
  2630. if (this.select) {
  2631. val = this.select.val();
  2632. return val === null ? [] : val;
  2633. } else {
  2634. val = this.opts.element.val();
  2635. return splitVal(val, this.opts.separator);
  2636. }
  2637. },
  2638. // multi
  2639. setVal: function (val) {
  2640. var unique;
  2641. if (this.select) {
  2642. this.select.val(val);
  2643. } else {
  2644. unique = [];
  2645. // filter out duplicates
  2646. $(val).each(function () {
  2647. if (indexOf(this, unique) < 0) unique.push(this);
  2648. });
  2649. this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
  2650. }
  2651. },
  2652. // multi
  2653. buildChangeDetails: function (old, current) {
  2654. var current = current.slice(0),
  2655. old = old.slice(0);
  2656. // remove intersection from each array
  2657. for (var i = 0; i < current.length; i++) {
  2658. for (var j = 0; j < old.length; j++) {
  2659. if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) {
  2660. current.splice(i, 1);
  2661. if(i>0){
  2662. i--;
  2663. }
  2664. old.splice(j, 1);
  2665. j--;
  2666. }
  2667. }
  2668. }
  2669. return {added: current, removed: old};
  2670. },
  2671. // multi
  2672. val: function (val, triggerChange) {
  2673. var oldData, self=this;
  2674. if (arguments.length === 0) {
  2675. return this.getVal();
  2676. }
  2677. oldData=this.data();
  2678. if (!oldData.length) oldData=[];
  2679. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  2680. if (!val && val !== 0) {
  2681. this.opts.element.val("");
  2682. this.updateSelection([]);
  2683. this.clearSearch();
  2684. if (triggerChange) {
  2685. this.triggerChange({added: this.data(), removed: oldData});
  2686. }
  2687. return;
  2688. }
  2689. // val is a list of ids
  2690. this.setVal(val);
  2691. if (this.select) {
  2692. this.opts.initSelection(this.select, this.bind(this.updateSelection));
  2693. if (triggerChange) {
  2694. this.triggerChange(this.buildChangeDetails(oldData, this.data()));
  2695. }
  2696. } else {
  2697. if (this.opts.initSelection === undefined) {
  2698. throw new Error("val() cannot be called if initSelection() is not defined");
  2699. }
  2700. this.opts.initSelection(this.opts.element, function(data){
  2701. var ids=$.map(data, self.id);
  2702. self.setVal(ids);
  2703. self.updateSelection(data);
  2704. self.clearSearch();
  2705. if (triggerChange) {
  2706. self.triggerChange(self.buildChangeDetails(oldData, self.data()));
  2707. }
  2708. });
  2709. }
  2710. this.clearSearch();
  2711. },
  2712. // multi
  2713. onSortStart: function() {
  2714. if (this.select) {
  2715. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  2716. }
  2717. // collapse search field into 0 width so its container can be collapsed as well
  2718. this.search.width(0);
  2719. // hide the container
  2720. this.searchContainer.hide();
  2721. },
  2722. // multi
  2723. onSortEnd:function() {
  2724. var val=[], self=this;
  2725. // show search and move it to the end of the list
  2726. this.searchContainer.show();
  2727. // make sure the search container is the last item in the list
  2728. this.searchContainer.appendTo(this.searchContainer.parent());
  2729. // since we collapsed the width in dragStarted, we resize it here
  2730. this.resizeSearch();
  2731. // update selection
  2732. this.selection.find(".select2-search-choice").each(function() {
  2733. val.push(self.opts.id($(this).data("select2-data")));
  2734. });
  2735. this.setVal(val);
  2736. this.triggerChange();
  2737. },
  2738. // multi
  2739. data: function(values, triggerChange) {
  2740. var self=this, ids, old;
  2741. if (arguments.length === 0) {
  2742. return this.selection
  2743. .children(".select2-search-choice")
  2744. .map(function() { return $(this).data("select2-data"); })
  2745. .get();
  2746. } else {
  2747. old = this.data();
  2748. if (!values) { values = []; }
  2749. ids = $.map(values, function(e) { return self.opts.id(e); });
  2750. this.setVal(ids);
  2751. this.updateSelection(values);
  2752. this.clearSearch();
  2753. if (triggerChange) {
  2754. this.triggerChange(this.buildChangeDetails(old, this.data()));
  2755. }
  2756. }
  2757. }
  2758. });
  2759. $.fn.select2 = function () {
  2760. var args = Array.prototype.slice.call(arguments, 0),
  2761. opts,
  2762. select2,
  2763. method, value, multiple,
  2764. allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "disable", "readonly", "positionDropdown", "data", "search"],
  2765. valueMethods = ["opened", "isFocused", "container", "dropdown"],
  2766. propertyMethods = ["val", "data"],
  2767. methodsMap = { search: "externalSearch" };
  2768. this.each(function () {
  2769. if (args.length === 0 || typeof(args[0]) === "object") {
  2770. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  2771. opts.element = $(this);
  2772. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  2773. multiple = opts.element.prop("multiple");
  2774. } else {
  2775. multiple = opts.multiple || false;
  2776. if ("tags" in opts) {opts.multiple = multiple = true;}
  2777. }
  2778. select2 = multiple ? new window.Select2["class"].multi() : new window.Select2["class"].single();
  2779. select2.init(opts);
  2780. } else if (typeof(args[0]) === "string") {
  2781. if (indexOf(args[0], allowedMethods) < 0) {
  2782. throw "Unknown method: " + args[0];
  2783. }
  2784. value = undefined;
  2785. select2 = $(this).data("select2");
  2786. if (select2 === undefined) return;
  2787. method=args[0];
  2788. if (method === "container") {
  2789. value = select2.container;
  2790. } else if (method === "dropdown") {
  2791. value = select2.dropdown;
  2792. } else {
  2793. if (methodsMap[method]) method = methodsMap[method];
  2794. value = select2[method].apply(select2, args.slice(1));
  2795. }
  2796. if (indexOf(args[0], valueMethods) >= 0
  2797. || (indexOf(args[0], propertyMethods) >= 0 && args.length == 1)) {
  2798. return false; // abort the iteration, ready to return first matched value
  2799. }
  2800. } else {
  2801. throw "Invalid arguments to select2 plugin: " + args;
  2802. }
  2803. });
  2804. return (value === undefined) ? this : value;
  2805. };
  2806. // plugin defaults, accessible to users
  2807. $.fn.select2.defaults = {
  2808. width: "copy",
  2809. loadMorePadding: 0,
  2810. closeOnSelect: true,
  2811. openOnEnter: true,
  2812. containerCss: {},
  2813. dropdownCss: {},
  2814. containerCssClass: "",
  2815. dropdownCssClass: "",
  2816. formatResult: function(result, container, query, escapeMarkup) {
  2817. var markup=[];
  2818. markMatch(result.text, query.term, markup, escapeMarkup);
  2819. return markup.join("");
  2820. },
  2821. formatSelection: function (data, container, escapeMarkup) {
  2822. return data ? escapeMarkup(data.text) : undefined;
  2823. },
  2824. sortResults: function (results, container, query) {
  2825. return results;
  2826. },
  2827. formatResultCssClass: function(data) {return data.css;},
  2828. formatSelectionCssClass: function(data, container) {return undefined;},
  2829. formatMatches: function (matches) { return matches + " results are available, use up and down arrow keys to navigate."; },
  2830. formatNoMatches: function () { return "No matches found"; },
  2831. formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " or more character" + (n == 1? "" : "s"); },
  2832. formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1? "" : "s"); },
  2833. formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
  2834. formatLoadMore: function (pageNumber) { return "Loading more results…"; },
  2835. formatSearching: function () { return "Searching…"; },
  2836. minimumResultsForSearch: 0,
  2837. minimumInputLength: 0,
  2838. maximumInputLength: null,
  2839. maximumSelectionSize: 0,
  2840. id: function (e) { return e == undefined ? null : e.id; },
  2841. matcher: function(term, text) {
  2842. return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0;
  2843. },
  2844. separator: ",",
  2845. tokenSeparators: [],
  2846. tokenizer: defaultTokenizer,
  2847. escapeMarkup: defaultEscapeMarkup,
  2848. blurOnChange: false,
  2849. selectOnBlur: false,
  2850. adaptContainerCssClass: function(c) { return c; },
  2851. adaptDropdownCssClass: function(c) { return null; },
  2852. nextSearchTerm: function(selectedObject, currentSearchTerm) { return undefined; },
  2853. searchInputPlaceholder: '',
  2854. createSearchChoicePosition: 'top',
  2855. shouldFocusInput: function (instance) {
  2856. // Never focus the input if search is disabled
  2857. if (instance.opts.minimumResultsForSearch < 0) {
  2858. return false;
  2859. }
  2860. return true;
  2861. }
  2862. };
  2863. $.fn.select2.ajaxDefaults = {
  2864. transport: $.ajax,
  2865. params: {
  2866. type: "GET",
  2867. cache: false,
  2868. dataType: "json"
  2869. }
  2870. };
  2871. // exports
  2872. window.Select2 = {
  2873. query: {
  2874. ajax: ajax,
  2875. local: local,
  2876. tags: tags
  2877. }, util: {
  2878. debounce: debounce,
  2879. markMatch: markMatch,
  2880. escapeMarkup: defaultEscapeMarkup,
  2881. stripDiacritics: stripDiacritics
  2882. }, "class": {
  2883. "abstract": AbstractSelect2,
  2884. "single": SingleSelect2,
  2885. "multi": MultiSelect2
  2886. }
  2887. };
  2888. }(jQuery));