select2.js 95 KB

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