select2.js 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708
  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 Licesnse 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. $.fn.extend({
  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, $document;
  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. $document = $(document);
  89. nextUid=(function() { var counter=1; return function() { return counter++; }; }());
  90. function indexOf(value, array) {
  91. var i = 0, l = array.length;
  92. for (; i < l; i = i + 1) {
  93. if (equal(value, array[i])) return i;
  94. }
  95. return -1;
  96. }
  97. /**
  98. * Compares equality of a and b
  99. * @param a
  100. * @param b
  101. */
  102. function equal(a, b) {
  103. if (a === b) return true;
  104. if (a === undefined || b === undefined) return false;
  105. if (a === null || b === null) return false;
  106. if (a.constructor === String) return a === b+'';
  107. if (b.constructor === String) return b === a+'';
  108. return false;
  109. }
  110. /**
  111. * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
  112. * strings
  113. * @param string
  114. * @param separator
  115. */
  116. function splitVal(string, separator) {
  117. var val, i, l;
  118. if (string === null || string.length < 1) return [];
  119. val = string.split(separator);
  120. for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
  121. return val;
  122. }
  123. function getSideBorderPadding(element) {
  124. return element.outerWidth(false) - element.width();
  125. }
  126. function installKeyUpChangeEvent(element) {
  127. var key="keyup-change-value";
  128. element.bind("keydown", function () {
  129. if ($.data(element, key) === undefined) {
  130. $.data(element, key, element.val());
  131. }
  132. });
  133. element.bind("keyup", function () {
  134. var val= $.data(element, key);
  135. if (val !== undefined && element.val() !== val) {
  136. $.removeData(element, key);
  137. element.trigger("keyup-change");
  138. }
  139. });
  140. }
  141. $document.bind("mousemove", function (e) {
  142. lastMousePosition = {x: e.pageX, y: e.pageY};
  143. });
  144. /**
  145. * filters mouse events so an event is fired only if the mouse moved.
  146. *
  147. * filters out mouse events that occur when mouse is stationary but
  148. * the elements under the pointer are scrolled.
  149. */
  150. function installFilteredMouseMove(element) {
  151. element.bind("mousemove", function (e) {
  152. var lastpos = lastMousePosition;
  153. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  154. $(e.target).trigger("mousemove-filtered", e);
  155. }
  156. });
  157. }
  158. /**
  159. * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
  160. * within the last quietMillis milliseconds.
  161. *
  162. * @param quietMillis number of milliseconds to wait before invoking fn
  163. * @param fn function to be debounced
  164. * @param ctx object to be used as this reference within fn
  165. * @return debounced version of fn
  166. */
  167. function debounce(quietMillis, fn, ctx) {
  168. ctx = ctx || undefined;
  169. var timeout;
  170. return function () {
  171. var args = arguments;
  172. window.clearTimeout(timeout);
  173. timeout = window.setTimeout(function() {
  174. fn.apply(ctx, args);
  175. }, quietMillis);
  176. };
  177. }
  178. /**
  179. * A simple implementation of a thunk
  180. * @param formula function used to lazily initialize the thunk
  181. * @return {Function}
  182. */
  183. function thunk(formula) {
  184. var evaluated = false,
  185. value;
  186. return function() {
  187. if (evaluated === false) { value = formula(); evaluated = true; }
  188. return value;
  189. };
  190. };
  191. function installDebouncedScroll(threshold, element) {
  192. var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
  193. element.bind("scroll", function (e) {
  194. if (indexOf(e.target, element.get()) >= 0) notify(e);
  195. });
  196. }
  197. function focus($el) {
  198. if ($el[0] === document.activeElement) return;
  199. /* set the focus in a 0 timeout - that way the focus is set after the processing
  200. of the current event has finished - which seems like the only reliable way
  201. to set focus */
  202. window.setTimeout(function() {
  203. var el=$el[0], pos=$el.val().length, range;
  204. $el.focus();
  205. /* after the focus is set move the caret to the end, necessary when we val()
  206. just before setting focus */
  207. if(el.setSelectionRange)
  208. {
  209. el.setSelectionRange(pos, pos);
  210. }
  211. else if (el.createTextRange) {
  212. range = el.createTextRange();
  213. range.collapse(true);
  214. range.moveEnd('character', pos);
  215. range.moveStart('character', pos);
  216. range.select();
  217. }
  218. }, 0);
  219. }
  220. function killEvent(event) {
  221. event.preventDefault();
  222. event.stopPropagation();
  223. }
  224. function killEventImmediately(event) {
  225. event.preventDefault();
  226. event.stopImmediatePropagation();
  227. }
  228. function measureTextWidth(e) {
  229. if (!sizer){
  230. var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
  231. sizer = $(document.createElement("div")).css({
  232. position: "absolute",
  233. left: "-10000px",
  234. top: "-10000px",
  235. display: "none",
  236. fontSize: style.fontSize,
  237. fontFamily: style.fontFamily,
  238. fontStyle: style.fontStyle,
  239. fontWeight: style.fontWeight,
  240. letterSpacing: style.letterSpacing,
  241. textTransform: style.textTransform,
  242. whiteSpace: "nowrap"
  243. });
  244. sizer.attr("class","select2-sizer");
  245. $("body").append(sizer);
  246. }
  247. sizer.text(e.val());
  248. return sizer.width();
  249. }
  250. function syncCssClasses(dest, src, adapter) {
  251. var classes, replacements = [], adapted;
  252. classes = dest.attr("class");
  253. if (typeof classes === "string") {
  254. $(classes.split(" ")).each2(function() {
  255. if (this.indexOf("select2-") === 0) {
  256. replacements.push(this);
  257. }
  258. });
  259. }
  260. classes = src.attr("class");
  261. if (typeof classes === "string") {
  262. $(classes.split(" ")).each2(function() {
  263. if (this.indexOf("select2-") !== 0) {
  264. adapted = adapter(this);
  265. if (typeof adapted === "string" && adapted.length > 0) {
  266. replacements.push(this);
  267. }
  268. }
  269. });
  270. }
  271. dest.attr("class", replacements.join(" "));
  272. }
  273. function markMatch(text, term, markup, escapeMarkup) {
  274. var match=text.toUpperCase().indexOf(term.toUpperCase()),
  275. tl=term.length;
  276. if (match<0) {
  277. markup.push(escapeMarkup(text));
  278. return;
  279. }
  280. markup.push(escapeMarkup(text.substring(0, match)));
  281. markup.push("<span class='select2-match'>");
  282. markup.push(escapeMarkup(text.substring(match, match + tl)));
  283. markup.push("</span>");
  284. markup.push(escapeMarkup(text.substring(match + tl, text.length)));
  285. }
  286. /**
  287. * Produces an ajax-based query function
  288. *
  289. * @param options object containing configuration paramters
  290. * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
  291. * @param options.url url for the data
  292. * @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
  293. * @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified
  294. * @param options.traditional a boolean flag that should be true if you wish to use the traditional style of param serialization for the ajax request
  295. * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
  296. * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
  297. * The expected format is an object containing the following keys:
  298. * results array of objects that will be used as choices
  299. * more (optional) boolean indicating whether there are more results available
  300. * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
  301. */
  302. function ajax(options) {
  303. var timeout, // current scheduled but not yet executed request
  304. requestSequence = 0, // sequence used to drop out-of-order responses
  305. handler = null,
  306. quietMillis = options.quietMillis || 100;
  307. return function (query) {
  308. window.clearTimeout(timeout);
  309. timeout = window.setTimeout(function () {
  310. requestSequence += 1; // increment the sequence
  311. var requestNumber = requestSequence, // this request's sequence number
  312. data = options.data, // ajax data function
  313. url = options.url, // ajax url string or function
  314. transport = options.transport || $.ajax,
  315. type = options.type || 'GET', // set type of request (GET or POST)
  316. params = {};
  317. data = data ? data.call(this, query.term, query.page, query.context) : null;
  318. url = (typeof url === 'function') ? url.call(this, query.term, query.page, query.context) : url;
  319. if( null !== handler) { handler.abort(); }
  320. if (options.params) {
  321. if ($.isFunction(options.params)) {
  322. $.extend(params, options.params.call(null));
  323. } else {
  324. $.extend(params, options.params);
  325. }
  326. }
  327. $.extend(params, {
  328. url: url,
  329. dataType: options.dataType,
  330. data: data,
  331. type: type,
  332. cache: false,
  333. success: function (data) {
  334. if (requestNumber < requestSequence) {
  335. return;
  336. }
  337. // TODO - replace query.page with query so users have access to term, page, etc.
  338. var results = options.results(data, query.page);
  339. query.callback(results);
  340. }
  341. });
  342. handler = transport.call(null, params);
  343. }, quietMillis);
  344. };
  345. }
  346. /**
  347. * Produces a query function that works with a local array
  348. *
  349. * @param options object containing configuration parameters. The options parameter can either be an array or an
  350. * object.
  351. *
  352. * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
  353. *
  354. * If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
  355. * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
  356. * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
  357. * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
  358. * the text.
  359. */
  360. function local(options) {
  361. var data = options, // data elements
  362. dataText,
  363. tmp,
  364. text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  365. if (!$.isArray(data)) {
  366. text = data.text;
  367. // if text is not a function we assume it to be a key name
  368. if (!$.isFunction(text)) {
  369. dataText = data.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
  370. text = function (item) { return item[dataText]; };
  371. }
  372. }
  373. if ($.isArray(data)) {
  374. tmp = data;
  375. data = {results:tmp};
  376. }
  377. if ($.isFunction(data) === false) {
  378. tmp = data;
  379. data = function() { return tmp; };
  380. }
  381. return function (query) {
  382. var t = query.term, filtered = { results: [] }, process;
  383. if (t === "") {
  384. query.callback(data());
  385. return;
  386. }
  387. process = function(datum, collection) {
  388. var group, attr;
  389. datum = datum[0];
  390. if (datum.children) {
  391. group = {};
  392. for (attr in datum) {
  393. if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
  394. }
  395. group.children=[];
  396. $(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
  397. if (group.children.length || query.matcher(t, text(group), datum)) {
  398. collection.push(group);
  399. }
  400. } else {
  401. if (query.matcher(t, text(datum), datum)) {
  402. collection.push(datum);
  403. }
  404. }
  405. };
  406. $(data()).each2(function(i, datum) { process(datum, filtered.results); });
  407. query.callback(filtered);
  408. };
  409. }
  410. // TODO javadoc
  411. function tags(data) {
  412. var isFunc = $.isFunction(data);
  413. return function (query) {
  414. var t = query.term, filtered = {results: []};
  415. $(isFunc ? data() : data).each(function () {
  416. var isObject = this.text !== undefined,
  417. text = isObject ? this.text : this;
  418. if (t === "" || query.matcher(t, text)) {
  419. filtered.results.push(isObject ? this : {id: this, text: this});
  420. }
  421. });
  422. query.callback(filtered);
  423. };
  424. }
  425. /**
  426. * Checks if the formatter function should be used.
  427. *
  428. * Throws an error if it is not a function. Returns true if it should be used,
  429. * false if no formatting should be performed.
  430. *
  431. * @param formatter
  432. */
  433. function checkFormatter(formatter, formatterName) {
  434. if ($.isFunction(formatter)) return true;
  435. if (!formatter) return false;
  436. throw new Error("formatterName must be a function or a falsy value");
  437. }
  438. function evaluate(val) {
  439. return $.isFunction(val) ? val() : val;
  440. }
  441. function countResults(results) {
  442. var count = 0;
  443. $.each(results, function(i, item) {
  444. if (item.children) {
  445. count += countResults(item.children);
  446. } else {
  447. count++;
  448. }
  449. });
  450. return count;
  451. }
  452. /**
  453. * Default tokenizer. This function uses breaks the input on substring match of any string from the
  454. * opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those
  455. * two options have to be defined in order for the tokenizer to work.
  456. *
  457. * @param input text user has typed so far or pasted into the search field
  458. * @param selection currently selected choices
  459. * @param selectCallback function(choice) callback tho add the choice to selection
  460. * @param opts select2's opts
  461. * @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value
  462. */
  463. function defaultTokenizer(input, selection, selectCallback, opts) {
  464. var original = input, // store the original so we can compare and know if we need to tell the search to update its text
  465. dupe = false, // check for whether a token we extracted represents a duplicate selected choice
  466. token, // token
  467. index, // position at which the separator was found
  468. i, l, // looping variables
  469. separator; // the matched separator
  470. if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined;
  471. while (true) {
  472. index = -1;
  473. for (i = 0, l = opts.tokenSeparators.length; i < l; i++) {
  474. separator = opts.tokenSeparators[i];
  475. index = input.indexOf(separator);
  476. if (index >= 0) break;
  477. }
  478. if (index < 0) break; // did not find any token separator in the input string, bail
  479. token = input.substring(0, index);
  480. input = input.substring(index + separator.length);
  481. if (token.length > 0) {
  482. token = opts.createSearchChoice(token, selection);
  483. if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) {
  484. dupe = false;
  485. for (i = 0, l = selection.length; i < l; i++) {
  486. if (equal(opts.id(token), opts.id(selection[i]))) {
  487. dupe = true; break;
  488. }
  489. }
  490. if (!dupe) selectCallback(token);
  491. }
  492. }
  493. }
  494. if (original!==input) return input;
  495. }
  496. /**
  497. * Creates a new class
  498. *
  499. * @param superClass
  500. * @param methods
  501. */
  502. function clazz(SuperClass, methods) {
  503. var constructor = function () {};
  504. constructor.prototype = new SuperClass;
  505. constructor.prototype.constructor = constructor;
  506. constructor.prototype.parent = SuperClass.prototype;
  507. constructor.prototype = $.extend(constructor.prototype, methods);
  508. return constructor;
  509. }
  510. AbstractSelect2 = clazz(Object, {
  511. // abstract
  512. bind: function (func) {
  513. var self = this;
  514. return function () {
  515. func.apply(self, arguments);
  516. };
  517. },
  518. // abstract
  519. init: function (opts) {
  520. var results, search, resultsSelector = ".select2-results", mask;
  521. // prepare options
  522. this.opts = opts = this.prepareOpts(opts);
  523. this.id=opts.id;
  524. // destroy if called on an existing component
  525. if (opts.element.data("select2") !== undefined &&
  526. opts.element.data("select2") !== null) {
  527. this.destroy();
  528. }
  529. this.enabled=true;
  530. this.container = this.createContainer();
  531. this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid());
  532. this.containerSelector="#"+this.containerId.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
  533. this.container.attr("id", this.containerId);
  534. // cache the body so future lookups are cheap
  535. this.body = thunk(function() { return opts.element.closest("body"); });
  536. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  537. this.container.css(evaluate(opts.containerCss));
  538. this.container.addClass(evaluate(opts.containerCssClass));
  539. this.elementTabIndex = this.opts.element.attr("tabIndex");
  540. // swap container for the element
  541. this.opts.element
  542. .data("select2", this)
  543. .addClass("select2-offscreen")
  544. .bind("focus.select2", function() { $(this).select2("focus"); })
  545. .attr("tabIndex", "-1")
  546. .before(this.container);
  547. this.container.data("select2", this);
  548. this.dropdown = this.container.find(".select2-drop");
  549. this.dropdown.addClass(evaluate(opts.dropdownCssClass));
  550. this.dropdown.data("select2", this);
  551. this.results = results = this.container.find(resultsSelector);
  552. this.search = search = this.container.find("input.select2-input");
  553. search.attr("tabIndex", this.elementTabIndex);
  554. this.resultsPage = 0;
  555. this.context = null;
  556. // initialize the container
  557. this.initContainer();
  558. installFilteredMouseMove(this.results);
  559. this.dropdown.delegate(resultsSelector, "mousemove-filtered touchstart touchmove touchend", this.bind(this.highlightUnderEvent));
  560. installDebouncedScroll(80, this.results);
  561. this.dropdown.delegate(resultsSelector, "scroll-debounced", this.bind(this.loadMoreIfNeeded));
  562. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  563. if ($.fn.mousewheel) {
  564. results.mousewheel(function (e, delta, deltaX, deltaY) {
  565. var top = results.scrollTop(), height;
  566. if (deltaY > 0 && top - deltaY <= 0) {
  567. results.scrollTop(0);
  568. killEvent(e);
  569. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  570. results.scrollTop(results.get(0).scrollHeight - results.height());
  571. killEvent(e);
  572. }
  573. });
  574. }
  575. installKeyUpChangeEvent(search);
  576. search.bind("keyup-change input paste", this.bind(this.updateResults));
  577. search.bind("focus", function () { search.addClass("select2-focused"); });
  578. search.bind("blur", function () { search.removeClass("select2-focused");});
  579. this.dropdown.delegate(resultsSelector, "mouseup", this.bind(function (e) {
  580. if ($(e.target).closest(".select2-result-selectable").length > 0) {
  581. this.highlightUnderEvent(e);
  582. this.selectHighlighted(e);
  583. }
  584. }));
  585. // trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
  586. // for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
  587. // dom it will trigger the popup close, which is not what we want
  588. this.dropdown.bind("click mouseup mousedown", function (e) { e.stopPropagation(); });
  589. if ($.isFunction(this.opts.initSelection)) {
  590. // initialize selection based on the current value of the source element
  591. this.initSelection();
  592. // if the user has provided a function that can set selection based on the value of the source element
  593. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  594. this.monitorSource();
  595. }
  596. if (opts.element.is(":disabled") || opts.element.is("[readonly='readonly']")) this.disable();
  597. },
  598. // abstract
  599. destroy: function () {
  600. var select2 = this.opts.element.data("select2");
  601. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  602. if (select2 !== undefined) {
  603. select2.container.remove();
  604. select2.dropdown.remove();
  605. select2.opts.element
  606. .removeClass("select2-offscreen")
  607. .removeData("select2")
  608. .unbind(".select2")
  609. .attr({"tabIndex": this.elementTabIndex})
  610. .show();
  611. }
  612. },
  613. // abstract
  614. prepareOpts: function (opts) {
  615. var element, select, idKey, ajaxUrl;
  616. element = opts.element;
  617. if (element.get(0).tagName.toLowerCase() === "select") {
  618. this.select = select = opts.element;
  619. }
  620. if (select) {
  621. // these options are not allowed when attached to a select because they are picked up off the element itself
  622. $.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
  623. if (this in opts) {
  624. throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
  625. }
  626. });
  627. }
  628. opts = $.extend({}, {
  629. populateResults: function(container, results, query) {
  630. var populate, data, result, children, id=this.opts.id, self=this;
  631. populate=function(results, container, depth) {
  632. var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted;
  633. results = opts.sortResults(results, container, query);
  634. for (i = 0, l = results.length; i < l; i = i + 1) {
  635. result=results[i];
  636. disabled = (result.disabled === true);
  637. selectable = (!disabled) && (id(result) !== undefined);
  638. compound=result.children && result.children.length > 0;
  639. node=$("<li></li>");
  640. node.addClass("select2-results-dept-"+depth);
  641. node.addClass("select2-result");
  642. node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
  643. if (disabled) { node.addClass("select2-disabled"); }
  644. if (compound) { node.addClass("select2-result-with-children"); }
  645. node.addClass(self.opts.formatResultCssClass(result));
  646. label=$(document.createElement("div"));
  647. label.addClass("select2-result-label");
  648. formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup);
  649. if (formatted!==undefined) {
  650. label.html(formatted);
  651. }
  652. node.append(label);
  653. if (compound) {
  654. innerContainer=$("<ul></ul>");
  655. innerContainer.addClass("select2-result-sub");
  656. populate(result.children, innerContainer, depth+1);
  657. node.append(innerContainer);
  658. }
  659. node.data("select2-data", result);
  660. container.append(node);
  661. }
  662. };
  663. populate(results, container, 0);
  664. }
  665. }, $.fn.select2.defaults, opts);
  666. if (typeof(opts.id) !== "function") {
  667. idKey = opts.id;
  668. opts.id = function (e) { return e[idKey]; };
  669. }
  670. if ($.isArray(opts.element.data("select2Tags"))) {
  671. if ("tags" in opts) {
  672. throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id");
  673. }
  674. opts.tags=opts.element.attr("data-select2-tags");
  675. }
  676. if (select) {
  677. opts.query = this.bind(function (query) {
  678. var data = { results: [], more: false },
  679. term = query.term,
  680. children, firstChild, process;
  681. process=function(element, collection) {
  682. var group;
  683. if (element.is("option")) {
  684. if (query.matcher(term, element.text(), element)) {
  685. collection.push({id:element.attr("value"), text:element.text(), element: element.get(), css: element.attr("class"), disabled: equal(element.attr("disabled"), "disabled") });
  686. }
  687. } else if (element.is("optgroup")) {
  688. group={text:element.attr("label"), children:[], element: element.get(), css: element.attr("class")};
  689. element.children().each2(function(i, elm) { process(elm, group.children); });
  690. if (group.children.length>0) {
  691. collection.push(group);
  692. }
  693. }
  694. };
  695. children=element.children();
  696. // ignore the placeholder option if there is one
  697. if (this.getPlaceholder() !== undefined && children.length > 0) {
  698. firstChild = children[0];
  699. if ($(firstChild).text() === "") {
  700. children=children.not(firstChild);
  701. }
  702. }
  703. children.each2(function(i, elm) { process(elm, data.results); });
  704. query.callback(data);
  705. });
  706. // this is needed because inside val() we construct choices from options and there id is hardcoded
  707. opts.id=function(e) { return e.id; };
  708. opts.formatResultCssClass = function(data) { return data.css; };
  709. } else {
  710. if (!("query" in opts)) {
  711. if ("ajax" in opts) {
  712. ajaxUrl = opts.element.data("ajax-url");
  713. if (ajaxUrl && ajaxUrl.length > 0) {
  714. opts.ajax.url = ajaxUrl;
  715. }
  716. opts.query = ajax(opts.ajax);
  717. } else if ("data" in opts) {
  718. opts.query = local(opts.data);
  719. } else if ("tags" in opts) {
  720. opts.query = tags(opts.tags);
  721. if (opts.createSearchChoice === undefined) {
  722. opts.createSearchChoice = function (term) { return {id: term, text: term}; };
  723. }
  724. if (opts.initSelection === undefined) {
  725. opts.initSelection = function (element, callback) {
  726. var data = [];
  727. $(splitVal(element.val(), opts.separator)).each(function () {
  728. var id = this, text = this, tags=opts.tags;
  729. if ($.isFunction(tags)) tags=tags();
  730. $(tags).each(function() { if (equal(this.id, id)) { text = this.text; return false; } });
  731. data.push({id: id, text: text});
  732. });
  733. callback(data);
  734. };
  735. }
  736. }
  737. }
  738. }
  739. if (typeof(opts.query) !== "function") {
  740. throw "query function not defined for Select2 " + opts.element.attr("id");
  741. }
  742. return opts;
  743. },
  744. /**
  745. * Monitor the original element for changes and update select2 accordingly
  746. */
  747. // abstract
  748. monitorSource: function () {
  749. var el = this.opts.element, sync;
  750. el.bind("change.select2", this.bind(function (e) {
  751. if (this.opts.element.data("select2-change-triggered") !== true) {
  752. this.initSelection();
  753. }
  754. }));
  755. sync = this.bind(function () {
  756. var enabled, readonly, self = this;
  757. // sync enabled state
  758. enabled = this.opts.element.attr("disabled") !== "disabled";
  759. readonly = this.opts.element.attr("readonly") === "readonly";
  760. enabled = enabled && !readonly;
  761. if (this.enabled !== enabled) {
  762. if (enabled) {
  763. this.enable();
  764. } else {
  765. this.disable();
  766. }
  767. }
  768. syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
  769. this.container.addClass(evaluate(this.opts.containerCssClass));
  770. syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
  771. this.dropdown.addClass(evaluate(this.opts.dropdownCssClass));
  772. });
  773. // mozilla and IE
  774. el.bind("propertychange.select2 DOMAttrModified.select2", sync);
  775. // safari and chrome
  776. if (typeof WebKitMutationObserver !== "undefined") {
  777. if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
  778. this.propertyObserver = new WebKitMutationObserver(function (mutations) {
  779. mutations.forEach(sync);
  780. });
  781. this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false });
  782. }
  783. },
  784. /**
  785. * Triggers the change event on the source element
  786. */
  787. // abstract
  788. triggerChange: function (details) {
  789. details = details || {};
  790. details= $.extend({}, details, { type: "change", val: this.val() });
  791. // prevents recursive triggering
  792. this.opts.element.data("select2-change-triggered", true);
  793. this.opts.element.trigger(details);
  794. this.opts.element.data("select2-change-triggered", false);
  795. // some validation frameworks ignore the change event and listen instead to keyup, click for selects
  796. // so here we trigger the click event manually
  797. this.opts.element.click();
  798. // ValidationEngine ignorea the change event and listens instead to blur
  799. // so here we trigger the blur event manually if so desired
  800. if (this.opts.blurOnChange)
  801. this.opts.element.blur();
  802. },
  803. // abstract
  804. enable: function() {
  805. if (this.enabled) return;
  806. this.enabled=true;
  807. this.container.removeClass("select2-container-disabled");
  808. this.opts.element.removeAttr("disabled");
  809. },
  810. // abstract
  811. disable: function() {
  812. if (!this.enabled) return;
  813. this.close();
  814. this.enabled=false;
  815. this.container.addClass("select2-container-disabled");
  816. this.opts.element.attr("disabled", "disabled");
  817. },
  818. // abstract
  819. opened: function () {
  820. return this.container.hasClass("select2-dropdown-open");
  821. },
  822. // abstract
  823. positionDropdown: function() {
  824. var offset = this.container.offset(),
  825. height = this.container.outerHeight(false),
  826. width = this.container.outerWidth(false),
  827. dropHeight = this.dropdown.outerHeight(false),
  828. viewPortRight = $(window).scrollLeft() + $(window).width(),
  829. viewportBottom = $(window).scrollTop() + $(window).height(),
  830. dropTop = offset.top + height,
  831. dropLeft = offset.left,
  832. enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
  833. enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(),
  834. dropWidth = this.dropdown.outerWidth(false),
  835. enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight,
  836. aboveNow = this.dropdown.hasClass("select2-drop-above"),
  837. bodyOffset,
  838. above,
  839. css;
  840. //console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
  841. //console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove);
  842. // fix positioning when body has an offset and is not position: static
  843. if (this.body().css('position') !== 'static') {
  844. bodyOffset = this.body().offset();
  845. dropTop -= bodyOffset.top;
  846. dropLeft -= bodyOffset.left;
  847. }
  848. // always prefer the current above/below alignment, unless there is not enough room
  849. if (aboveNow) {
  850. above = true;
  851. if (!enoughRoomAbove && enoughRoomBelow) above = false;
  852. } else {
  853. above = false;
  854. if (!enoughRoomBelow && enoughRoomAbove) above = true;
  855. }
  856. if (!enoughRoomOnRight) {
  857. dropLeft = offset.left + width - dropWidth;
  858. }
  859. if (above) {
  860. dropTop = offset.top - dropHeight;
  861. this.container.addClass("select2-drop-above");
  862. this.dropdown.addClass("select2-drop-above");
  863. }
  864. else {
  865. this.container.removeClass("select2-drop-above");
  866. this.dropdown.removeClass("select2-drop-above");
  867. }
  868. css = $.extend({
  869. top: dropTop,
  870. left: dropLeft,
  871. width: width
  872. }, evaluate(this.opts.dropdownCss));
  873. this.dropdown.css(css);
  874. },
  875. // abstract
  876. shouldOpen: function() {
  877. var event;
  878. if (this.opened()) return false;
  879. event = $.Event("opening");
  880. this.opts.element.trigger(event);
  881. return !event.isDefaultPrevented();
  882. },
  883. // abstract
  884. clearDropdownAlignmentPreference: function() {
  885. // clear the classes used to figure out the preference of where the dropdown should be opened
  886. this.container.removeClass("select2-drop-above");
  887. this.dropdown.removeClass("select2-drop-above");
  888. },
  889. /**
  890. * Opens the dropdown
  891. *
  892. * @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
  893. * the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
  894. */
  895. // abstract
  896. open: function () {
  897. if (!this.shouldOpen()) return false;
  898. window.setTimeout(this.bind(this.opening), 1);
  899. return true;
  900. },
  901. /**
  902. * Performs the opening of the dropdown
  903. */
  904. // abstract
  905. opening: function() {
  906. var cid = this.containerId,
  907. scroll = "scroll." + cid,
  908. resize = "resize."+cid,
  909. orient = "orientationchange."+cid,
  910. mask;
  911. this.clearDropdownAlignmentPreference();
  912. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  913. if(this.dropdown[0] !== this.body().children().last()[0]) {
  914. this.dropdown.detach().appendTo(this.body());
  915. }
  916. this.updateResults(true);
  917. // create the dropdown mask if doesnt already exist
  918. mask = $("#select2-drop-mask");
  919. if (mask.length == 0) {
  920. mask = $(document.createElement("div"));
  921. mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
  922. mask.hide();
  923. mask.appendTo(this.body());
  924. mask.bind("mousedown touchstart", function (e) {
  925. var dropdown = $("#select2-drop"), self;
  926. if (dropdown.length > 0) {
  927. self=dropdown.data("select2");
  928. if (self.opts.selectOnBlur) {
  929. self.selectHighlighted({noFocus: true});
  930. }
  931. self.close();
  932. }
  933. });
  934. }
  935. // ensure the mask is always right before the dropdown
  936. if (this.dropdown.prev()[0] !== mask[0]) {
  937. this.dropdown.before(mask);
  938. }
  939. // move the global id to the correct dropdown
  940. $("#select2-drop").removeAttr("id");
  941. this.dropdown.attr("id", "select2-drop");
  942. // show the elements
  943. mask.css({
  944. width: document.documentElement.scrollWidth,
  945. height: document.documentElement.scrollHeight});
  946. mask.show();
  947. this.dropdown.show();
  948. this.positionDropdown();
  949. this.dropdown.addClass("select2-drop-active");
  950. this.ensureHighlightVisible();
  951. // attach listeners to events that can change the position of the container and thus require
  952. // the position of the dropdown to be updated as well so it does not come unglued from the container
  953. this.container.parents().add(window).each(function () {
  954. $(this).bind(resize+" "+scroll+" "+orient, function (e) {
  955. $("#select2-drop-mask").css({
  956. width:document.documentElement.scrollWidth,
  957. height:document.documentElement.scrollHeight});
  958. $("#select2-drop").data("select2").positionDropdown();
  959. });
  960. });
  961. this.focusSearch();
  962. },
  963. // abstract
  964. close: function () {
  965. if (!this.opened()) return;
  966. var cid = this.containerId,
  967. scroll = "scroll." + cid,
  968. resize = "resize."+cid,
  969. orient = "orientationchange."+cid;
  970. // unbind event listeners
  971. this.container.parents().add(window).each(function () { $(this).unbind(scroll).unbind(resize).unbind(orient); });
  972. this.clearDropdownAlignmentPreference();
  973. $("#select2-drop-mask").hide();
  974. this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id
  975. this.dropdown.hide();
  976. this.container.removeClass("select2-dropdown-open");
  977. this.results.empty();
  978. this.clearSearch();
  979. this.opts.element.trigger($.Event("close"));
  980. },
  981. // abstract
  982. clearSearch: function () {
  983. },
  984. //abstract
  985. getMaximumSelectionSize: function() {
  986. return evaluate(this.opts.maximumSelectionSize);
  987. },
  988. // abstract
  989. ensureHighlightVisible: function () {
  990. var results = this.results, children, index, child, hb, rb, y, more;
  991. index = this.highlight();
  992. if (index < 0) return;
  993. if (index == 0) {
  994. // if the first element is highlighted scroll all the way to the top,
  995. // that way any unselectable headers above it will also be scrolled
  996. // into view
  997. results.scrollTop(0);
  998. return;
  999. }
  1000. children = this.findHighlightableChoices();
  1001. child = $(children[index]);
  1002. hb = child.offset().top + child.outerHeight(true);
  1003. // if this is the last child lets also make sure select2-more-results is visible
  1004. if (index === children.length - 1) {
  1005. more = results.find("li.select2-more-results");
  1006. if (more.length > 0) {
  1007. hb = more.offset().top + more.outerHeight(true);
  1008. }
  1009. }
  1010. rb = results.offset().top + results.outerHeight(true);
  1011. if (hb > rb) {
  1012. results.scrollTop(results.scrollTop() + (hb - rb));
  1013. }
  1014. y = child.offset().top - results.offset().top;
  1015. // make sure the top of the element is visible
  1016. if (y < 0 && child.css('display') != 'none' ) {
  1017. results.scrollTop(results.scrollTop() + y); // y is negative
  1018. }
  1019. },
  1020. // abstract
  1021. findHighlightableChoices: function() {
  1022. var h=this.results.find(".select2-result-selectable:not(.select2-selected):not(.select2-disabled)");
  1023. return this.results.find(".select2-result-selectable:not(.select2-selected):not(.select2-disabled)");
  1024. },
  1025. // abstract
  1026. moveHighlight: function (delta) {
  1027. var choices = this.findHighlightableChoices(),
  1028. index = this.highlight();
  1029. while (index > -1 && index < choices.length) {
  1030. index += delta;
  1031. var choice = $(choices[index]);
  1032. if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) {
  1033. this.highlight(index);
  1034. break;
  1035. }
  1036. }
  1037. },
  1038. // abstract
  1039. highlight: function (index) {
  1040. var choices = this.findHighlightableChoices(),
  1041. choice,
  1042. data;
  1043. if (arguments.length === 0) {
  1044. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  1045. }
  1046. if (index >= choices.length) index = choices.length - 1;
  1047. if (index < 0) index = 0;
  1048. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  1049. choice = $(choices[index]);
  1050. choice.addClass("select2-highlighted");
  1051. this.ensureHighlightVisible();
  1052. data = choice.data("select2-data");
  1053. if (data) {
  1054. this.opts.element.trigger({ type: "highlight", val: this.id(data), choice: data });
  1055. }
  1056. },
  1057. // abstract
  1058. countSelectableResults: function() {
  1059. return this.findHighlightableChoices().length;
  1060. },
  1061. // abstract
  1062. highlightUnderEvent: function (event) {
  1063. var el = $(event.target).closest(".select2-result-selectable");
  1064. if (el.length > 0 && !el.is(".select2-highlighted")) {
  1065. var choices = this.findHighlightableChoices();
  1066. this.highlight(choices.index(el));
  1067. } else if (el.length == 0) {
  1068. // if we are over an unselectable item remove al highlights
  1069. this.results.find(".select2-highlighted").removeClass("select2-highlighted");
  1070. }
  1071. },
  1072. // abstract
  1073. loadMoreIfNeeded: function () {
  1074. var results = this.results,
  1075. more = results.find("li.select2-more-results"),
  1076. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  1077. offset = -1, // index of first element without data
  1078. page = this.resultsPage + 1,
  1079. self=this,
  1080. term=this.search.val(),
  1081. context=this.context;
  1082. if (more.length === 0) return;
  1083. below = more.offset().top - results.offset().top - results.height();
  1084. if (below <= this.opts.loadMorePadding) {
  1085. more.addClass("select2-active");
  1086. this.opts.query({
  1087. element: this.opts.element,
  1088. term: term,
  1089. page: page,
  1090. context: context,
  1091. matcher: this.opts.matcher,
  1092. callback: this.bind(function (data) {
  1093. // ignore a response if the select2 has been closed before it was received
  1094. if (!self.opened()) return;
  1095. self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
  1096. if (data.more===true) {
  1097. more.detach().appendTo(results).text(self.opts.formatLoadMore(page+1));
  1098. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1099. } else {
  1100. more.remove();
  1101. }
  1102. self.positionDropdown();
  1103. self.resultsPage = page;
  1104. self.context = data.context;
  1105. })});
  1106. }
  1107. },
  1108. /**
  1109. * Default tokenizer function which does nothing
  1110. */
  1111. tokenize: function() {
  1112. },
  1113. /**
  1114. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  1115. */
  1116. // abstract
  1117. updateResults: function (initial) {
  1118. var search = this.search, results = this.results, opts = this.opts, data, self=this, input;
  1119. // if the search is currently hidden we do not alter the results
  1120. if (initial !== true && (this.showSearchInput === false || !this.opened())) {
  1121. return;
  1122. }
  1123. search.addClass("select2-active");
  1124. function postRender() {
  1125. results.scrollTop(0);
  1126. search.removeClass("select2-active");
  1127. self.positionDropdown();
  1128. }
  1129. function render(html) {
  1130. results.html(html);
  1131. postRender();
  1132. }
  1133. var maxSelSize = this.getMaximumSelectionSize();
  1134. if (maxSelSize >=1) {
  1135. data = this.data();
  1136. if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
  1137. render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(maxSelSize) + "</li>");
  1138. return;
  1139. }
  1140. }
  1141. if (search.val().length < opts.minimumInputLength) {
  1142. if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
  1143. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  1144. } else {
  1145. render("");
  1146. }
  1147. return;
  1148. }
  1149. else if (opts.formatSearching() && initial===true) {
  1150. render("<li class='select2-searching'>" + opts.formatSearching() + "</li>");
  1151. }
  1152. if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) {
  1153. if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) {
  1154. render("<li class='select2-no-results'>" + opts.formatInputTooLong(search.val(), opts.maximumInputLength) + "</li>");
  1155. } else {
  1156. render("");
  1157. }
  1158. return;
  1159. }
  1160. // give the tokenizer a chance to pre-process the input
  1161. input = this.tokenize();
  1162. if (input != undefined && input != null) {
  1163. search.val(input);
  1164. }
  1165. this.resultsPage = 1;
  1166. opts.query({
  1167. element: opts.element,
  1168. term: search.val(),
  1169. page: this.resultsPage,
  1170. context: null,
  1171. matcher: opts.matcher,
  1172. callback: this.bind(function (data) {
  1173. var def; // default choice
  1174. // ignore a response if the select2 has been closed before it was received
  1175. if (!this.opened()) return;
  1176. // save context, if any
  1177. this.context = (data.context===undefined) ? null : data.context;
  1178. // create a default choice and prepend it to the list
  1179. if (this.opts.createSearchChoice && search.val() !== "") {
  1180. def = this.opts.createSearchChoice.call(null, search.val(), data.results);
  1181. if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
  1182. if ($(data.results).filter(
  1183. function () {
  1184. return equal(self.id(this), self.id(def));
  1185. }).length === 0) {
  1186. data.results.unshift(def);
  1187. }
  1188. }
  1189. }
  1190. if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
  1191. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  1192. return;
  1193. }
  1194. results.empty();
  1195. self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
  1196. if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
  1197. results.append("<li class='select2-more-results'>" + self.opts.escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>");
  1198. window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
  1199. }
  1200. this.postprocessResults(data, initial);
  1201. postRender();
  1202. })});
  1203. },
  1204. // abstract
  1205. cancel: function () {
  1206. this.close();
  1207. },
  1208. // abstract
  1209. blur: function () {
  1210. // if selectOnBlur == true, select the currently highlighted option
  1211. if (this.opts.selectOnBlur)
  1212. this.selectHighlighted({noFocus: true});
  1213. this.close();
  1214. this.container.removeClass("select2-container-active");
  1215. // synonymous to .is(':focus'), which is available in jquery >= 1.6
  1216. if (this.search[0] === document.activeElement) { this.search.blur(); }
  1217. this.clearSearch();
  1218. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1219. },
  1220. // abstract
  1221. focusSearch: function () {
  1222. focus(this.search);
  1223. },
  1224. // abstract
  1225. selectHighlighted: function (options) {
  1226. var index=this.highlight(),
  1227. highlighted=this.results.find(".select2-highlighted"),
  1228. data = highlighted.closest('.select2-result').data("select2-data");
  1229. if (data) {
  1230. this.highlight(index);
  1231. this.onSelect(data, options);
  1232. }
  1233. },
  1234. // abstract
  1235. getPlaceholder: function () {
  1236. return this.opts.element.attr("placeholder") ||
  1237. this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
  1238. this.opts.element.data("placeholder") ||
  1239. this.opts.placeholder;
  1240. },
  1241. /**
  1242. * Get the desired width for the container element. This is
  1243. * derived first from option `width` passed to select2, then
  1244. * the inline 'style' on the original element, and finally
  1245. * falls back to the jQuery calculated element width.
  1246. */
  1247. // abstract
  1248. initContainerWidth: function () {
  1249. function resolveContainerWidth() {
  1250. var style, attrs, matches, i, l;
  1251. if (this.opts.width === "off") {
  1252. return null;
  1253. } else if (this.opts.width === "element"){
  1254. return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px';
  1255. } else if (this.opts.width === "copy" || this.opts.width === "resolve") {
  1256. // check if there is inline style on the element that contains width
  1257. style = this.opts.element.attr('style');
  1258. if (style !== undefined) {
  1259. attrs = style.split(';');
  1260. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  1261. matches = attrs[i].replace(/\s/g, '')
  1262. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
  1263. if (matches !== null && matches.length >= 1)
  1264. return matches[1];
  1265. }
  1266. }
  1267. if (this.opts.width === "resolve") {
  1268. // next check if css('width') can resolve a width that is percent based, this is sometimes possible
  1269. // when attached to input type=hidden or elements hidden via css
  1270. style = this.opts.element.css('width');
  1271. if (style.indexOf("%") > 0) return style;
  1272. // finally, fallback on the calculated width of the element
  1273. return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px');
  1274. }
  1275. return null;
  1276. } else if ($.isFunction(this.opts.width)) {
  1277. return this.opts.width();
  1278. } else {
  1279. return this.opts.width;
  1280. }
  1281. };
  1282. var width = resolveContainerWidth.call(this);
  1283. if (width !== null) {
  1284. this.container.css("width", width);
  1285. }
  1286. }
  1287. });
  1288. SingleSelect2 = clazz(AbstractSelect2, {
  1289. // single
  1290. createContainer: function () {
  1291. var container = $(document.createElement("div")).attr({
  1292. "class": "select2-container"
  1293. }).html([
  1294. "<a href='javascript:void(0)' onclick='return false;' class='select2-choice' tabindex='-1'>",
  1295. " <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
  1296. " <div><b></b></div>" ,
  1297. "</a>",
  1298. "<input class='select2-focusser select2-offscreen' type='text'/>",
  1299. "<div class='select2-drop' style='display:none'>" ,
  1300. " <div class='select2-search'>" ,
  1301. " <input type='text' autocomplete='off' class='select2-input'/>" ,
  1302. " </div>" ,
  1303. " <ul class='select2-results'>" ,
  1304. " </ul>" ,
  1305. "</div>"].join(""));
  1306. return container;
  1307. },
  1308. // single
  1309. disable: function() {
  1310. if (!this.enabled) return;
  1311. this.parent.disable.apply(this, arguments);
  1312. this.focusser.attr("disabled", "disabled");
  1313. },
  1314. // single
  1315. enable: function() {
  1316. if (this.enabled) return;
  1317. this.parent.enable.apply(this, arguments);
  1318. this.focusser.removeAttr("disabled");
  1319. },
  1320. // single
  1321. opening: function () {
  1322. this.parent.opening.apply(this, arguments);
  1323. this.focusser.attr("disabled", "disabled");
  1324. this.opts.element.trigger($.Event("open"));
  1325. },
  1326. // single
  1327. close: function () {
  1328. if (!this.opened()) return;
  1329. this.parent.close.apply(this, arguments);
  1330. this.focusser.removeAttr("disabled");
  1331. focus(this.focusser);
  1332. },
  1333. // single
  1334. focus: function () {
  1335. if (this.opened()) {
  1336. this.close();
  1337. } else {
  1338. this.focusser.removeAttr("disabled");
  1339. this.focusser.focus();
  1340. }
  1341. },
  1342. // single
  1343. isFocused: function () {
  1344. return this.container.hasClass("select2-container-active");
  1345. },
  1346. // single
  1347. cancel: function () {
  1348. this.parent.cancel.apply(this, arguments);
  1349. this.focusser.removeAttr("disabled");
  1350. this.focusser.focus();
  1351. },
  1352. // single
  1353. initContainer: function () {
  1354. var selection,
  1355. container = this.container,
  1356. dropdown = this.dropdown,
  1357. clickingInside = false;
  1358. this.showSearch(this.opts.minimumResultsForSearch >= 0);
  1359. this.selection = selection = container.find(".select2-choice");
  1360. this.focusser = container.find(".select2-focusser");
  1361. this.search.bind("keydown", this.bind(function (e) {
  1362. if (!this.enabled) return;
  1363. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1364. // prevent the page from scrolling
  1365. killEvent(e);
  1366. return;
  1367. }
  1368. switch (e.which) {
  1369. case KEY.UP:
  1370. case KEY.DOWN:
  1371. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1372. killEvent(e);
  1373. return;
  1374. case KEY.TAB:
  1375. case KEY.ENTER:
  1376. this.selectHighlighted();
  1377. killEvent(e);
  1378. return;
  1379. case KEY.ESC:
  1380. this.cancel(e);
  1381. killEvent(e);
  1382. return;
  1383. }
  1384. }));
  1385. this.focusser.bind("keydown", this.bind(function (e) {
  1386. if (!this.enabled) return;
  1387. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  1388. return;
  1389. }
  1390. if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
  1391. killEvent(e);
  1392. return;
  1393. }
  1394. if (e.which == KEY.DOWN || e.which == KEY.UP
  1395. || (e.which == KEY.ENTER && this.opts.openOnEnter)) {
  1396. this.open();
  1397. killEvent(e);
  1398. return;
  1399. }
  1400. if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) {
  1401. if (this.opts.allowClear) {
  1402. this.clear();
  1403. }
  1404. killEvent(e);
  1405. return;
  1406. }
  1407. }));
  1408. installKeyUpChangeEvent(this.focusser);
  1409. this.focusser.bind("keyup-change input", this.bind(function(e) {
  1410. if (this.opened()) return;
  1411. this.open();
  1412. if (this.showSearchInput !== false) {
  1413. this.search.val(this.focusser.val());
  1414. }
  1415. this.focusser.val("");
  1416. killEvent(e);
  1417. }));
  1418. selection.delegate("abbr", "mousedown", this.bind(function (e) {
  1419. if (!this.enabled) return;
  1420. this.clear();
  1421. killEventImmediately(e);
  1422. this.close();
  1423. this.triggerChange();
  1424. this.selection.focus();
  1425. }));
  1426. selection.bind("mousedown", this.bind(function (e) {
  1427. clickingInside = true;
  1428. if (this.opened()) {
  1429. this.close();
  1430. } else if (this.enabled) {
  1431. this.open();
  1432. }
  1433. killEvent(e);
  1434. clickingInside = false;
  1435. }));
  1436. dropdown.bind("mousedown", this.bind(function() { this.search.focus(); }));
  1437. selection.bind("focus", this.bind(function(e) {
  1438. killEvent(e);
  1439. }));
  1440. this.focusser.bind("focus", this.bind(function(){
  1441. this.container.addClass("select2-container-active");
  1442. })).bind("blur", this.bind(function() {
  1443. if (!this.opened()) {
  1444. this.container.removeClass("select2-container-active");
  1445. }
  1446. }));
  1447. this.search.bind("focus", this.bind(function(){
  1448. this.container.addClass("select2-container-active");
  1449. }))
  1450. this.initContainerWidth();
  1451. this.setPlaceholder();
  1452. },
  1453. // single
  1454. clear: function() {
  1455. var data=this.selection.data("select2-data");
  1456. this.opts.element.val("");
  1457. this.selection.find("span").empty();
  1458. this.selection.removeData("select2-data");
  1459. this.setPlaceholder();
  1460. this.opts.element.trigger({ type: "removed", val: this.id(data), choice: data });
  1461. this.triggerChange({removed:data});
  1462. },
  1463. /**
  1464. * Sets selection based on source element's value
  1465. */
  1466. // single
  1467. initSelection: function () {
  1468. var selected;
  1469. if (this.opts.element.val() === "" && this.opts.element.text() === "") {
  1470. this.close();
  1471. this.setPlaceholder();
  1472. } else {
  1473. var self = this;
  1474. this.opts.initSelection.call(null, this.opts.element, function(selected){
  1475. if (selected !== undefined && selected !== null) {
  1476. self.updateSelection(selected);
  1477. self.close();
  1478. self.setPlaceholder();
  1479. }
  1480. });
  1481. }
  1482. },
  1483. // single
  1484. prepareOpts: function () {
  1485. var opts = this.parent.prepareOpts.apply(this, arguments);
  1486. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1487. // install the selection initializer
  1488. opts.initSelection = function (element, callback) {
  1489. var selected = element.find(":selected");
  1490. // a single select box always has a value, no need to null check 'selected'
  1491. if ($.isFunction(callback))
  1492. callback({id: selected.attr("value"), text: selected.text(), element:selected});
  1493. };
  1494. } else if ("data" in opts) {
  1495. // install default initSelection when applied to hidden input and data is local
  1496. opts.initSelection = opts.initSelection || function (element, callback) {
  1497. var id = element.val();
  1498. //search in data by id
  1499. opts.query({
  1500. matcher: function(term, text, el){
  1501. return equal(id, opts.id(el));
  1502. },
  1503. callback: !$.isFunction(callback) ? $.noop : function(filtered) {
  1504. callback(filtered.results.length ? filtered.results[0] : null);
  1505. }
  1506. });
  1507. };
  1508. }
  1509. return opts;
  1510. },
  1511. // single
  1512. getPlaceholder: function() {
  1513. // if a placeholder is specified on a single select without the first empty option ignore it
  1514. if (this.select) {
  1515. if (this.select.find("option").first().text() !== "") {
  1516. return undefined;
  1517. }
  1518. }
  1519. return this.parent.getPlaceholder.apply(this, arguments);
  1520. },
  1521. // single
  1522. setPlaceholder: function () {
  1523. var placeholder = this.getPlaceholder();
  1524. if (this.opts.element.val() === "" && placeholder !== undefined) {
  1525. // check for a first blank option if attached to a select
  1526. if (this.select && this.select.find("option:first").text() !== "") return;
  1527. this.selection.find("span").html(this.opts.escapeMarkup(placeholder));
  1528. this.selection.addClass("select2-default");
  1529. this.selection.find("abbr").hide();
  1530. }
  1531. },
  1532. // single
  1533. postprocessResults: function (data, initial) {
  1534. var selected = 0, self = this, showSearchInput = true;
  1535. // find the selected element in the result list
  1536. this.findHighlightableChoices().each2(function (i, elm) {
  1537. if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
  1538. selected = i;
  1539. return false;
  1540. }
  1541. });
  1542. // and highlight it
  1543. this.highlight(selected);
  1544. // hide the search box if this is the first we got the results and there are a few of them
  1545. if (initial === true) {
  1546. var min=this.opts.minimumResultsForSearch;
  1547. showSearchInput = min < 0 ? false : countResults(data.results) >= min;
  1548. this.showSearch(showSearchInput);
  1549. }
  1550. },
  1551. // single
  1552. showSearch: function(showSearchInput) {
  1553. this.showSearchInput = showSearchInput;
  1554. this.dropdown.find(".select2-search")[showSearchInput ? "removeClass" : "addClass"]("select2-search-hidden");
  1555. //add "select2-with-searchbox" to the container if search box is shown
  1556. $(this.dropdown, this.container)[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
  1557. },
  1558. // single
  1559. onSelect: function (data, options) {
  1560. var old = this.opts.element.val();
  1561. this.opts.element.val(this.id(data));
  1562. this.updateSelection(data);
  1563. this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
  1564. this.close();
  1565. if (!options || !options.noFocus)
  1566. this.selection.focus();
  1567. if (!equal(old, this.id(data))) { this.triggerChange(); }
  1568. },
  1569. // single
  1570. updateSelection: function (data) {
  1571. var container=this.selection.find("span"), formatted;
  1572. this.selection.data("select2-data", data);
  1573. container.empty();
  1574. formatted=this.opts.formatSelection(data, container);
  1575. if (formatted !== undefined) {
  1576. container.append(this.opts.escapeMarkup(formatted));
  1577. }
  1578. this.selection.removeClass("select2-default");
  1579. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  1580. this.selection.find("abbr").show();
  1581. }
  1582. },
  1583. // single
  1584. val: function () {
  1585. var val, triggerChange = false, data = null, self = this;
  1586. if (arguments.length === 0) {
  1587. return this.opts.element.val();
  1588. }
  1589. val = arguments[0];
  1590. if (arguments.length > 1) {
  1591. triggerChange = arguments[1];
  1592. }
  1593. if (this.select) {
  1594. this.select
  1595. .val(val)
  1596. .find(":selected").each2(function (i, elm) {
  1597. data = {id: elm.attr("value"), text: elm.text()};
  1598. return false;
  1599. });
  1600. this.updateSelection(data);
  1601. this.setPlaceholder();
  1602. if (triggerChange) {
  1603. this.triggerChange();
  1604. }
  1605. } else {
  1606. if (this.opts.initSelection === undefined) {
  1607. throw new Error("cannot call val() if initSelection() is not defined");
  1608. }
  1609. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  1610. if (!val && val !== 0) {
  1611. this.clear();
  1612. if (triggerChange) {
  1613. this.triggerChange();
  1614. }
  1615. return;
  1616. }
  1617. this.opts.element.val(val);
  1618. this.opts.initSelection(this.opts.element, function(data){
  1619. self.opts.element.val(!data ? "" : self.id(data));
  1620. self.updateSelection(data);
  1621. self.setPlaceholder();
  1622. if (triggerChange) {
  1623. self.triggerChange();
  1624. }
  1625. });
  1626. }
  1627. },
  1628. // single
  1629. clearSearch: function () {
  1630. this.search.val("");
  1631. this.focusser.val("");
  1632. },
  1633. // single
  1634. data: function(value) {
  1635. var data;
  1636. if (arguments.length === 0) {
  1637. data = this.selection.data("select2-data");
  1638. if (data == undefined) data = null;
  1639. return data;
  1640. } else {
  1641. if (!value || value === "") {
  1642. this.clear();
  1643. } else {
  1644. this.opts.element.val(!value ? "" : this.id(value));
  1645. this.updateSelection(value);
  1646. }
  1647. }
  1648. }
  1649. });
  1650. MultiSelect2 = clazz(AbstractSelect2, {
  1651. // multi
  1652. createContainer: function () {
  1653. var container = $(document.createElement("div")).attr({
  1654. "class": "select2-container select2-container-multi"
  1655. }).html([
  1656. " <ul class='select2-choices'>",
  1657. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  1658. " <li class='select2-search-field'>" ,
  1659. " <input type='text' autocomplete='off' class='select2-input'>" ,
  1660. " </li>" ,
  1661. "</ul>" ,
  1662. "<div class='select2-drop select2-drop-multi' style='display:none;'>" ,
  1663. " <ul class='select2-results'>" ,
  1664. " </ul>" ,
  1665. "</div>"].join(""));
  1666. return container;
  1667. },
  1668. // multi
  1669. prepareOpts: function () {
  1670. var opts = this.parent.prepareOpts.apply(this, arguments);
  1671. // TODO validate placeholder is a string if specified
  1672. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1673. // install sthe selection initializer
  1674. opts.initSelection = function (element, callback) {
  1675. var data = [];
  1676. element.find(":selected").each2(function (i, elm) {
  1677. data.push({id: elm.attr("value"), text: elm.text(), element: elm[0]});
  1678. });
  1679. callback(data);
  1680. };
  1681. } else if ("data" in opts) {
  1682. // install default initSelection when applied to hidden input and data is local
  1683. opts.initSelection = opts.initSelection || function (element, callback) {
  1684. var ids = splitVal(element.val(), opts.separator);
  1685. //search in data by array of ids
  1686. opts.query({
  1687. matcher: function(term, text, el){
  1688. return $.grep(ids, function(id) {
  1689. return equal(id, opts.id(el));
  1690. }).length;
  1691. },
  1692. callback: !$.isFunction(callback) ? $.noop : function(filtered) {
  1693. callback(filtered.results);
  1694. }
  1695. });
  1696. };
  1697. }
  1698. return opts;
  1699. },
  1700. // multi
  1701. initContainer: function () {
  1702. var selector = ".select2-choices", selection;
  1703. this.searchContainer = this.container.find(".select2-search-field");
  1704. this.selection = selection = this.container.find(selector);
  1705. this.search.bind("input paste", this.bind(function() {
  1706. if (!this.enabled) return;
  1707. if (!this.opened()) {
  1708. this.open();
  1709. }
  1710. }));
  1711. this.search.bind("keydown", this.bind(function (e) {
  1712. if (!this.enabled) return;
  1713. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  1714. this.close();
  1715. var choices,
  1716. selected = selection.find(".select2-search-choice-focus");
  1717. if (selected.length > 0) {
  1718. this.unselect(selected.first());
  1719. this.search.width(10);
  1720. killEvent(e);
  1721. return;
  1722. }
  1723. choices = selection.find(".select2-search-choice:not(.select2-locked)");
  1724. if (choices.length > 0) {
  1725. choices.last().addClass("select2-search-choice-focus");
  1726. }
  1727. } else {
  1728. selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1729. }
  1730. if (this.opened()) {
  1731. switch (e.which) {
  1732. case KEY.UP:
  1733. case KEY.DOWN:
  1734. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  1735. killEvent(e);
  1736. return;
  1737. case KEY.ENTER:
  1738. case KEY.TAB:
  1739. this.selectHighlighted();
  1740. killEvent(e);
  1741. return;
  1742. case KEY.ESC:
  1743. this.cancel(e);
  1744. killEvent(e);
  1745. return;
  1746. }
  1747. }
  1748. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
  1749. || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  1750. return;
  1751. }
  1752. if (e.which === KEY.ENTER) {
  1753. if (this.opts.openOnEnter === false) {
  1754. return;
  1755. } else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
  1756. return;
  1757. }
  1758. }
  1759. this.open();
  1760. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  1761. // prevent the page from scrolling
  1762. killEvent(e);
  1763. }
  1764. }));
  1765. this.search.bind("keyup", this.bind(this.resizeSearch));
  1766. this.search.bind("blur", this.bind(function(e) {
  1767. this.container.removeClass("select2-container-active");
  1768. this.search.removeClass("select2-focused");
  1769. if (!this.opened()) this.clearSearch();
  1770. e.stopImmediatePropagation();
  1771. }));
  1772. this.container.delegate(selector, "mousedown", this.bind(function (e) {
  1773. if (!this.enabled) return;
  1774. if ($(e.target).closest(".select2-search-choice").length > 0) {
  1775. // clicked inside a select2 search choice, do not open
  1776. return;
  1777. }
  1778. this.clearPlaceholder();
  1779. this.open();
  1780. this.focusSearch();
  1781. e.preventDefault();
  1782. }));
  1783. this.container.delegate(selector, "focus", this.bind(function () {
  1784. if (!this.enabled) return;
  1785. this.container.addClass("select2-container-active");
  1786. this.dropdown.addClass("select2-drop-active");
  1787. this.clearPlaceholder();
  1788. }));
  1789. this.initContainerWidth();
  1790. // set the placeholder if necessary
  1791. this.clearSearch();
  1792. },
  1793. // multi
  1794. enable: function() {
  1795. if (this.enabled) return;
  1796. this.parent.enable.apply(this, arguments);
  1797. this.search.removeAttr("disabled");
  1798. },
  1799. // multi
  1800. disable: function() {
  1801. if (!this.enabled) return;
  1802. this.parent.disable.apply(this, arguments);
  1803. this.search.attr("disabled", true);
  1804. },
  1805. // multi
  1806. initSelection: function () {
  1807. var data;
  1808. if (this.opts.element.val() === "" && this.opts.element.text() === "") {
  1809. this.updateSelection([]);
  1810. this.close();
  1811. // set the placeholder if necessary
  1812. this.clearSearch();
  1813. }
  1814. if (this.select || this.opts.element.val() !== "") {
  1815. var self = this;
  1816. this.opts.initSelection.call(null, this.opts.element, function(data){
  1817. if (data !== undefined && data !== null) {
  1818. self.updateSelection(data);
  1819. self.close();
  1820. // set the placeholder if necessary
  1821. self.clearSearch();
  1822. }
  1823. });
  1824. }
  1825. },
  1826. // multi
  1827. clearSearch: function () {
  1828. var placeholder = this.getPlaceholder();
  1829. if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
  1830. this.search.val(placeholder).addClass("select2-default");
  1831. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  1832. this.resizeSearch();
  1833. } else {
  1834. this.search.val("").width(10);
  1835. }
  1836. },
  1837. // multi
  1838. clearPlaceholder: function () {
  1839. if (this.search.hasClass("select2-default")) {
  1840. this.search.val("").removeClass("select2-default");
  1841. }
  1842. },
  1843. // multi
  1844. opening: function () {
  1845. this.parent.opening.apply(this, arguments);
  1846. this.clearPlaceholder();
  1847. this.resizeSearch();
  1848. this.focusSearch();
  1849. this.opts.element.trigger($.Event("open"));
  1850. },
  1851. // multi
  1852. close: function () {
  1853. if (!this.opened()) return;
  1854. this.parent.close.apply(this, arguments);
  1855. },
  1856. // multi
  1857. focus: function () {
  1858. this.close();
  1859. this.search.focus();
  1860. this.opts.element.triggerHandler("focus");
  1861. },
  1862. // multi
  1863. isFocused: function () {
  1864. return this.search.hasClass("select2-focused");
  1865. },
  1866. // multi
  1867. updateSelection: function (data) {
  1868. var ids = [], filtered = [], self = this;
  1869. // filter out duplicates
  1870. $(data).each(function () {
  1871. if (indexOf(self.id(this), ids) < 0) {
  1872. ids.push(self.id(this));
  1873. filtered.push(this);
  1874. }
  1875. });
  1876. data = filtered;
  1877. this.selection.find(".select2-search-choice").remove();
  1878. $(data).each(function () {
  1879. self.addSelectedChoice(this);
  1880. });
  1881. self.postprocessResults();
  1882. },
  1883. tokenize: function() {
  1884. var input = this.search.val();
  1885. input = this.opts.tokenizer(input, this.data(), this.bind(this.onSelect), this.opts);
  1886. if (input != null && input != undefined) {
  1887. this.search.val(input);
  1888. if (input.length > 0) {
  1889. this.open();
  1890. }
  1891. }
  1892. },
  1893. // multi
  1894. onSelect: function (data, options) {
  1895. this.addSelectedChoice(data);
  1896. this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
  1897. if (this.select || !this.opts.closeOnSelect) this.postprocessResults();
  1898. if (this.opts.closeOnSelect) {
  1899. this.close();
  1900. this.search.width(10);
  1901. } else {
  1902. if (this.countSelectableResults()>0) {
  1903. this.search.width(10);
  1904. this.resizeSearch();
  1905. if (this.val().length >= this.getMaximumSelectionSize()) {
  1906. // if we reached max selection size repaint the results so choices
  1907. // are replaced with the max selection reached message
  1908. this.updateResults(true);
  1909. }
  1910. this.positionDropdown();
  1911. } else {
  1912. // if nothing left to select close
  1913. this.close();
  1914. this.search.width(10);
  1915. }
  1916. }
  1917. // since its not possible to select an element that has already been
  1918. // added we do not need to check if this is a new element before firing change
  1919. this.triggerChange({ added: data });
  1920. if (!options || !options.noFocus)
  1921. this.focusSearch();
  1922. },
  1923. // multi
  1924. cancel: function () {
  1925. this.close();
  1926. this.focusSearch();
  1927. },
  1928. addSelectedChoice: function (data) {
  1929. var enableChoice = !data.locked,
  1930. enabledItem = $(
  1931. "<li class='select2-search-choice'>" +
  1932. " <div></div>" +
  1933. " <a href='#' onclick='return false;' class='select2-search-choice-close' tabindex='-1'></a>" +
  1934. "</li>"),
  1935. disabledItem = $(
  1936. "<li class='select2-search-choice select2-locked'>" +
  1937. "<div></div>" +
  1938. "</li>");
  1939. var choice = enableChoice ? enabledItem : disabledItem,
  1940. id = this.id(data),
  1941. val = this.getVal(),
  1942. formatted;
  1943. formatted=this.opts.formatSelection(data, choice.find("div"));
  1944. if (formatted != undefined) {
  1945. choice.find("div").replaceWith("<div>"+this.opts.escapeMarkup(formatted)+"</div>");
  1946. }
  1947. if(enableChoice){
  1948. choice.find(".select2-search-choice-close")
  1949. .bind("mousedown", killEvent)
  1950. .bind("click dblclick", this.bind(function (e) {
  1951. if (!this.enabled) return;
  1952. $(e.target).closest(".select2-search-choice").fadeOut('fast', this.bind(function(){
  1953. this.unselect($(e.target));
  1954. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1955. this.close();
  1956. this.focusSearch();
  1957. })).dequeue();
  1958. killEvent(e);
  1959. })).bind("focus", this.bind(function () {
  1960. if (!this.enabled) return;
  1961. this.container.addClass("select2-container-active");
  1962. this.dropdown.addClass("select2-drop-active");
  1963. }));
  1964. }
  1965. choice.data("select2-data", data);
  1966. choice.insertBefore(this.searchContainer);
  1967. val.push(id);
  1968. this.setVal(val);
  1969. },
  1970. // multi
  1971. unselect: function (selected) {
  1972. var val = this.getVal(),
  1973. data,
  1974. index;
  1975. selected = selected.closest(".select2-search-choice");
  1976. if (selected.length === 0) {
  1977. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  1978. }
  1979. data = selected.data("select2-data");
  1980. if (!data) {
  1981. // prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued
  1982. // and invoked on an element already removed
  1983. return;
  1984. }
  1985. index = indexOf(this.id(data), val);
  1986. if (index >= 0) {
  1987. val.splice(index, 1);
  1988. this.setVal(val);
  1989. if (this.select) this.postprocessResults();
  1990. }
  1991. selected.remove();
  1992. this.opts.element.trigger({ type: "removed", val: this.id(data), choice: data });
  1993. this.triggerChange({ removed: data });
  1994. },
  1995. // multi
  1996. postprocessResults: function () {
  1997. var val = this.getVal(),
  1998. choices = this.results.find(".select2-result"),
  1999. compound = this.results.find(".select2-result-with-children"),
  2000. self = this;
  2001. choices.each2(function (i, choice) {
  2002. var id = self.id(choice.data("select2-data"));
  2003. if (indexOf(id, val) >= 0) {
  2004. choice.addClass("select2-selected");
  2005. // mark all children of the selected parent as selected
  2006. choice.find(".select2-result-selectable").addClass("select2-selected");
  2007. }
  2008. });
  2009. compound.each2(function(i, choice) {
  2010. // hide an optgroup if it doesnt have any selectable children
  2011. if (!choice.is('.select2-result-selectable')
  2012. && choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) {
  2013. choice.addClass("select2-selected");
  2014. }
  2015. });
  2016. if (this.highlight() == -1){
  2017. self.highlight(0);
  2018. }
  2019. },
  2020. // multi
  2021. resizeSearch: function () {
  2022. var minimumWidth, left, maxWidth, containerLeft, searchWidth,
  2023. sideBorderPadding = getSideBorderPadding(this.search);
  2024. minimumWidth = measureTextWidth(this.search) + 10;
  2025. left = this.search.offset().left;
  2026. maxWidth = this.selection.width();
  2027. containerLeft = this.selection.offset().left;
  2028. searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
  2029. if (searchWidth < minimumWidth) {
  2030. searchWidth = maxWidth - sideBorderPadding;
  2031. }
  2032. if (searchWidth < 40) {
  2033. searchWidth = maxWidth - sideBorderPadding;
  2034. }
  2035. if (searchWidth <= 0) {
  2036. searchWidth = minimumWidth;
  2037. }
  2038. this.search.width(searchWidth);
  2039. },
  2040. // multi
  2041. getVal: function () {
  2042. var val;
  2043. if (this.select) {
  2044. val = this.select.val();
  2045. return val === null ? [] : val;
  2046. } else {
  2047. val = this.opts.element.val();
  2048. return splitVal(val, this.opts.separator);
  2049. }
  2050. },
  2051. // multi
  2052. setVal: function (val) {
  2053. var unique;
  2054. if (this.select) {
  2055. this.select.val(val);
  2056. } else {
  2057. unique = [];
  2058. // filter out duplicates
  2059. $(val).each(function () {
  2060. if (indexOf(this, unique) < 0) unique.push(this);
  2061. });
  2062. this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
  2063. }
  2064. },
  2065. // multi
  2066. val: function () {
  2067. var val, triggerChange = false, data = [], self=this;
  2068. if (arguments.length === 0) {
  2069. return this.getVal();
  2070. }
  2071. val = arguments[0];
  2072. if (arguments.length > 1) {
  2073. triggerChange = arguments[1];
  2074. }
  2075. // val is an id. !val is true for [undefined,null,'',0] - 0 is legal
  2076. if (!val && val !== 0) {
  2077. this.opts.element.val("");
  2078. this.updateSelection([]);
  2079. this.clearSearch();
  2080. if (triggerChange) {
  2081. this.triggerChange();
  2082. }
  2083. return;
  2084. }
  2085. // val is a list of ids
  2086. this.setVal(val);
  2087. if (this.select) {
  2088. this.opts.initSelection(this.select, this.bind(this.updateSelection));
  2089. if (triggerChange) {
  2090. this.triggerChange();
  2091. }
  2092. } else {
  2093. if (this.opts.initSelection === undefined) {
  2094. throw new Error("val() cannot be called if initSelection() is not defined");
  2095. }
  2096. this.opts.initSelection(this.opts.element, function(data){
  2097. var ids=$(data).map(self.id);
  2098. self.setVal(ids);
  2099. self.updateSelection(data);
  2100. self.clearSearch();
  2101. if (triggerChange) {
  2102. self.triggerChange();
  2103. }
  2104. });
  2105. }
  2106. this.clearSearch();
  2107. },
  2108. // multi
  2109. onSortStart: function() {
  2110. if (this.select) {
  2111. throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
  2112. }
  2113. // collapse search field into 0 width so its container can be collapsed as well
  2114. this.search.width(0);
  2115. // hide the container
  2116. this.searchContainer.hide();
  2117. },
  2118. // multi
  2119. onSortEnd:function() {
  2120. var val=[], self=this;
  2121. // show search and move it to the end of the list
  2122. this.searchContainer.show();
  2123. // make sure the search container is the last item in the list
  2124. this.searchContainer.appendTo(this.searchContainer.parent());
  2125. // since we collapsed the width in dragStarted, we resize it here
  2126. this.resizeSearch();
  2127. // update selection
  2128. this.selection.find(".select2-search-choice").each(function() {
  2129. val.push(self.opts.id($(this).data("select2-data")));
  2130. });
  2131. this.setVal(val);
  2132. this.triggerChange();
  2133. },
  2134. // multi
  2135. data: function(values) {
  2136. var self=this, ids;
  2137. if (arguments.length === 0) {
  2138. return this.selection
  2139. .find(".select2-search-choice")
  2140. .map(function() { return $(this).data("select2-data"); })
  2141. .get();
  2142. } else {
  2143. if (!values) { values = []; }
  2144. ids = $.map(values, function(e) { return self.opts.id(e); });
  2145. this.setVal(ids);
  2146. this.updateSelection(values);
  2147. this.clearSearch();
  2148. }
  2149. }
  2150. });
  2151. $.fn.select2 = function () {
  2152. var args = Array.prototype.slice.call(arguments, 0),
  2153. opts,
  2154. select2,
  2155. value, multiple, allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "onSortStart", "onSortEnd", "enable", "disable", "positionDropdown", "data"];
  2156. this.each(function () {
  2157. if (args.length === 0 || typeof(args[0]) === "object") {
  2158. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  2159. opts.element = $(this);
  2160. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  2161. multiple = opts.element.attr("multiple");
  2162. } else {
  2163. multiple = opts.multiple || false;
  2164. if ("tags" in opts) {opts.multiple = multiple = true;}
  2165. }
  2166. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  2167. select2.init(opts);
  2168. } else if (typeof(args[0]) === "string") {
  2169. if (indexOf(args[0], allowedMethods) < 0) {
  2170. throw "Unknown method: " + args[0];
  2171. }
  2172. value = undefined;
  2173. select2 = $(this).data("select2");
  2174. if (select2 === undefined) return;
  2175. if (args[0] === "container") {
  2176. value=select2.container;
  2177. } else {
  2178. value = select2[args[0]].apply(select2, args.slice(1));
  2179. }
  2180. if (value !== undefined) {return false;}
  2181. } else {
  2182. throw "Invalid arguments to select2 plugin: " + args;
  2183. }
  2184. });
  2185. return (value === undefined) ? this : value;
  2186. };
  2187. // plugin defaults, accessible to users
  2188. $.fn.select2.defaults = {
  2189. width: "copy",
  2190. loadMorePadding: 0,
  2191. closeOnSelect: true,
  2192. openOnEnter: true,
  2193. containerCss: {},
  2194. dropdownCss: {},
  2195. containerCssClass: "",
  2196. dropdownCssClass: "",
  2197. formatResult: function(result, container, query, escapeMarkup) {
  2198. var markup=[];
  2199. markMatch(result.text, query.term, markup, escapeMarkup);
  2200. return markup.join("");
  2201. },
  2202. formatSelection: function (data, container) {
  2203. return data ? data.text : undefined;
  2204. },
  2205. sortResults: function (results, container, query) {
  2206. return results;
  2207. },
  2208. formatResultCssClass: function(data) {return undefined;},
  2209. formatNoMatches: function () { return "No matches found"; },
  2210. formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " more character" + (n == 1? "" : "s"); },
  2211. formatInputTooLong: function (input, max) { var n = input.length - max; return "Please enter " + n + " less character" + (n == 1? "" : "s"); },
  2212. formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
  2213. formatLoadMore: function (pageNumber) { return "Loading more results..."; },
  2214. formatSearching: function () { return "Searching..."; },
  2215. minimumResultsForSearch: 0,
  2216. minimumInputLength: 0,
  2217. maximumInputLength: null,
  2218. maximumSelectionSize: 0,
  2219. id: function (e) { return e.id; },
  2220. matcher: function(term, text) {
  2221. return text.toUpperCase().indexOf(term.toUpperCase()) >= 0;
  2222. },
  2223. separator: ",",
  2224. tokenSeparators: [],
  2225. tokenizer: defaultTokenizer,
  2226. escapeMarkup: function (markup) {
  2227. var replace_map = {
  2228. '\\': '&#92;',
  2229. '&': '&amp;',
  2230. '<': '&lt;',
  2231. '>': '&gt;',
  2232. '"': '&quot;',
  2233. "'": '&apos;',
  2234. "/": '&#47;'
  2235. };
  2236. return String(markup).replace(/[&<>"'/\\]/g, function (match) {
  2237. return replace_map[match[0]];
  2238. });
  2239. },
  2240. blurOnChange: false,
  2241. selectOnBlur: false,
  2242. adaptContainerCssClass: function(c) { return c; },
  2243. adaptDropdownCssClass: function(c) { return null; }
  2244. };
  2245. // exports
  2246. window.Select2 = {
  2247. query: {
  2248. ajax: ajax,
  2249. local: local,
  2250. tags: tags
  2251. }, util: {
  2252. debounce: debounce,
  2253. markMatch: markMatch
  2254. }, "class": {
  2255. "abstract": AbstractSelect2,
  2256. "single": SingleSelect2,
  2257. "multi": MultiSelect2
  2258. }
  2259. };
  2260. }(jQuery));