select2.js 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469
  1. /*
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. (function ($, undefined) {
  18. "use strict";
  19. /*global document, window, jQuery, console */
  20. if (window.Select2 !== undefined) {
  21. return;
  22. }
  23. var KEY, AbstractSelect2, SingleSelect2, MultiSelect2;
  24. KEY = {
  25. TAB: 9,
  26. ENTER: 13,
  27. ESC: 27,
  28. SPACE: 32,
  29. LEFT: 37,
  30. UP: 38,
  31. RIGHT: 39,
  32. DOWN: 40,
  33. SHIFT: 16,
  34. CTRL: 17,
  35. ALT: 18,
  36. PAGE_UP: 33,
  37. PAGE_DOWN: 34,
  38. HOME: 36,
  39. END: 35,
  40. BACKSPACE: 8,
  41. DELETE: 46,
  42. isArrow: function (k) {
  43. k = k.which ? k.which : k;
  44. switch (k) {
  45. case KEY.LEFT:
  46. case KEY.RIGHT:
  47. case KEY.UP:
  48. case KEY.DOWN:
  49. return true;
  50. }
  51. return false;
  52. },
  53. isControl: function (k) {
  54. k = k.which ? k.which : k;
  55. switch (k) {
  56. case KEY.SHIFT:
  57. case KEY.CTRL:
  58. case KEY.ALT:
  59. return true;
  60. }
  61. return false;
  62. },
  63. isFunctionKey: function (k) {
  64. k = k.which ? k.which : k;
  65. return k >= 112 && k <= 123;
  66. }
  67. };
  68. function indexOf(value, array) {
  69. var i = 0, l = array.length, v;
  70. if (value.constructor === String) {
  71. for (; i < l; i = i + 1) if (value.localeCompare(array[i]) === 0) return i;
  72. } else {
  73. for (; i < l; i = i + 1) {
  74. v = array[i];
  75. if (v.constructor === String) {
  76. if (v.localeCompare(value) === 0) return i;
  77. } else {
  78. if (v === value) return i;
  79. }
  80. }
  81. }
  82. return -1;
  83. }
  84. /**
  85. * Compares equality of a and b taking into account that a and b may be strings, in which case localCompare is used
  86. * @param a
  87. * @param b
  88. */
  89. function equal(a, b) {
  90. if (a === b) return true;
  91. if (a === undefined || b === undefined) return false;
  92. if (a === null || b === null) return false;
  93. if (a.constructor === String) return a.localeCompare(b) === 0;
  94. if (b.constructor === String) return b.localeCompare(a) === 0;
  95. return false;
  96. }
  97. /**
  98. * Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
  99. * strings
  100. * @param string
  101. * @param separator
  102. */
  103. function splitVal(string, separator) {
  104. var val, i, l;
  105. if (string === null || string.length < 1) return [];
  106. val = string.split(separator);
  107. for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
  108. return val;
  109. }
  110. function getSideBorderPadding(element) {
  111. return element.outerWidth() - element.width();
  112. }
  113. function installKeyUpChangeEvent(element) {
  114. element.bind("keydown", function () {
  115. element.data("keyup-change-value", element.val());
  116. });
  117. element.bind("keyup", function () {
  118. if (element.val() !== element.data("keyup-change-value")) {
  119. element.trigger("keyup-change");
  120. }
  121. });
  122. }
  123. /**
  124. * filters mouse events so an event is fired only if the mouse moved.
  125. *
  126. * filters out mouse events that occur when mouse is stationary but
  127. * the elements under the pointer are scrolled.
  128. */
  129. $(document).delegate("*", "mousemove", function (e) {
  130. $(document).data("select2-lastpos", {x: e.pageX, y: e.pageY});
  131. });
  132. function installFilteredMouseMove(element) {
  133. element.bind("mousemove", function (e) {
  134. var lastpos = $(document).data("select2-lastpos");
  135. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  136. $(e.target).trigger("mousemove-filtered", e);
  137. }
  138. });
  139. }
  140. /**
  141. * Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
  142. * within the last quietMillis milliseconds.
  143. *
  144. * @param quietMillis number of milliseconds to wait before invoking fn
  145. * @param fn function to be debounced
  146. * @return debounced version of fn
  147. */
  148. function debounce(quietMillis, fn) {
  149. var timeout;
  150. return function () {
  151. window.clearTimeout(timeout);
  152. timeout = window.setTimeout(fn, quietMillis);
  153. };
  154. }
  155. function installDebouncedScroll(threshold, element) {
  156. var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
  157. element.bind("scroll", function (e) {
  158. if (indexOf(e.target, element.get()) >= 0) notify(e);
  159. });
  160. }
  161. function killEvent(event) {
  162. event.preventDefault();
  163. event.stopPropagation();
  164. }
  165. function measureTextWidth(e) {
  166. var sizer, width;
  167. sizer = $("<div></div>").css({
  168. position: "absolute",
  169. left: "-1000px",
  170. top: "-1000px",
  171. display: "none",
  172. fontSize: e.css("fontSize"),
  173. fontFamily: e.css("fontFamily"),
  174. fontStyle: e.css("fontStyle"),
  175. fontWeight: e.css("fontWeight"),
  176. letterSpacing: e.css("letterSpacing"),
  177. textTransform: e.css("textTransform"),
  178. whiteSpace: "nowrap"
  179. });
  180. sizer.text(e.val());
  181. $("body").append(sizer);
  182. width = sizer.width();
  183. sizer.remove();
  184. return width;
  185. }
  186. /**
  187. * Produces an ajax-based query function
  188. *
  189. * @param options object containing configuration paramters
  190. * @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
  191. * @param options.url url for the data
  192. * @param options.data a function(searchTerm, pageNumber) that should return an object containing query string parameters for the above url.
  193. * @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified
  194. * @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
  195. * @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
  196. * The expected format is an object containing the following keys:
  197. * results array of objects that will be used as choices
  198. * more (optional) boolean indicating whether there are more results available
  199. * Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
  200. */
  201. function ajax(options) {
  202. var timeout, // current scheduled but not yet executed request
  203. requestSequence = 0, // sequence used to drop out-of-order responses
  204. quietMillis = options.quietMillis || 100;
  205. return function (query) {
  206. window.clearTimeout(timeout);
  207. timeout = window.setTimeout(function () {
  208. requestSequence += 1; // increment the sequence
  209. var requestNumber = requestSequence, // this request's sequence number
  210. data = options.data, // ajax data function
  211. transport = options.transport || $.ajax;
  212. data = data.call(this, query.term, query.page);
  213. transport.call(null, {
  214. url: options.url,
  215. dataType: options.dataType,
  216. data: data,
  217. success: function (data) {
  218. if (requestNumber < requestSequence) {
  219. return;
  220. }
  221. // TODO 3.0 - replace query.page with query so users have access to term, page, etc.
  222. query.callback(options.results(data, query.page));
  223. }
  224. });
  225. }, quietMillis);
  226. };
  227. }
  228. /**
  229. * Produces a query function that works with a local array
  230. *
  231. * @param options object containing configuration parameters. The options parameter can either be an array or an
  232. * object.
  233. *
  234. * If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
  235. *
  236. * If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
  237. * an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
  238. * key can either be a String in which case it is expected that each element in the 'data' array has a key with the
  239. * value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
  240. * the text.
  241. */
  242. function local(options) {
  243. var data = options, // data elements
  244. text = function (item) { return item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
  245. if (!$.isArray(data)) {
  246. text = data.text;
  247. // if text is not a function we assume it to be a key name
  248. if (!$.isFunction(text)) text = function (item) { return item[data.text]; };
  249. data = data.results;
  250. }
  251. return function (query) {
  252. var t = query.term.toUpperCase(), filtered = {};
  253. if (t === "") {
  254. query.callback({results: data});
  255. return;
  256. }
  257. filtered.results = $(data)
  258. .filter(function () {return text(this).toUpperCase().indexOf(t) >= 0;})
  259. .get();
  260. query.callback(filtered);
  261. };
  262. }
  263. // TODO javadoc
  264. function tags(data) {
  265. // TODO even for a function we should probably return a wrapper that does the same object/string check as
  266. // the function for arrays. otherwise only functions that return objects are supported.
  267. if ($.isFunction(data)) {
  268. return data;
  269. }
  270. // if not a function we assume it to be an array
  271. return function (query) {
  272. var t = query.term.toUpperCase(), filtered = {results: []};
  273. $(data).each(function () {
  274. var isObject = this.text!==undefined,
  275. text = isObject ? this.text : this;
  276. if (t === "" || text.toUpperCase().indexOf(t) >= 0) {
  277. filtered.results.push(isObject ? this : {id: this, text: this});
  278. }
  279. });
  280. query.callback(filtered);
  281. };
  282. }
  283. /**
  284. * blurs any Select2 container that has focus when an element outside them was clicked or received focus
  285. */
  286. $(document).ready(function () {
  287. $(document).delegate("*", "mousedown focusin", function (e) {
  288. var target = $(e.target).closest("div.select2-container").get(0);
  289. $(document).find("div.select2-container-active").each(function () {
  290. if (this !== target) $(this).data("select2").blur();
  291. });
  292. });
  293. });
  294. /**
  295. * Creates a new class
  296. *
  297. * @param superClass
  298. * @param methods
  299. */
  300. function clazz(SuperClass, methods) {
  301. var constructor = function () {};
  302. constructor.prototype = new SuperClass;
  303. constructor.prototype.constructor = constructor;
  304. constructor.prototype.parent = SuperClass.prototype;
  305. constructor.prototype = $.extend(constructor.prototype, methods);
  306. return constructor;
  307. }
  308. AbstractSelect2 = clazz(Object, {
  309. bind: function (func) {
  310. var self = this;
  311. return function () {
  312. func.apply(self, arguments);
  313. };
  314. },
  315. init: function (opts) {
  316. var results, search, resultsSelector = ".select2-results";
  317. // prepare options
  318. this.opts = this.prepareOpts(opts);
  319. // destroy if called on an existing component
  320. if (opts.element.data("select2") !== undefined) {
  321. this.destroy();
  322. }
  323. this.container = this.createContainer();
  324. if (opts.element.attr("class") !== undefined) {
  325. this.container.addClass(opts.element.attr("class"));
  326. }
  327. // swap container for the element
  328. this.opts.element
  329. .data("select2", this)
  330. .hide()
  331. .after(this.container);
  332. this.container.data("select2", this);
  333. this.dropdown = this.container.find(".select2-drop");
  334. this.results = results = this.container.find(resultsSelector);
  335. this.search = search = this.container.find("input[type=text]");
  336. this.resultsPage = 0;
  337. // initialize the container
  338. this.initContainer();
  339. installFilteredMouseMove(this.results);
  340. this.container.delegate(resultsSelector, "mousemove-filtered", this.bind(this.highlightUnderEvent));
  341. installDebouncedScroll(80, this.results);
  342. this.container.delegate(resultsSelector, "scroll-debounced", this.bind(this.loadMoreIfNeeded));
  343. // if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
  344. if ($.fn.mousewheel) {
  345. results.mousewheel(function (e, delta, deltaX, deltaY) {
  346. var top = results.scrollTop(), height;
  347. if (deltaY > 0 && top - deltaY <= 0) {
  348. results.scrollTop(0);
  349. killEvent(e);
  350. } else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
  351. results.scrollTop(results.get(0).scrollHeight - results.height());
  352. killEvent(e);
  353. }
  354. });
  355. }
  356. installKeyUpChangeEvent(search);
  357. search.bind("keyup-change", this.bind(this.updateResults));
  358. search.bind("focus", function() { search.addClass("select2-focused");});
  359. search.bind("blur", function() { search.removeClass("select2-focused");});
  360. this.container.delegate(resultsSelector, "click", this.bind(function (e) {
  361. if ($(e.target).closest(".select2-result:not(.select2-disabled)").length > 0) {
  362. this.highlightUnderEvent(e);
  363. this.selectHighlighted(e);
  364. } else {
  365. killEvent(e);
  366. this.focusSearch();
  367. }
  368. }));
  369. if ($.isFunction(this.opts.initSelection)) {
  370. // initialize selection based on the current value of the source element
  371. this.initSelection();
  372. // if the user has provided a function that can set selection based on the value of the source element
  373. // we monitor the change event on the element and trigger it, allowing for two way synchronization
  374. this.monitorSource();
  375. }
  376. },
  377. destroy: function () {
  378. var select2 = this.opts.element.data("select2");
  379. if (select2 !== undefined) {
  380. select2.container.remove();
  381. select2.opts.element
  382. .removeData("select2")
  383. .unbind(".select2")
  384. .show();
  385. }
  386. },
  387. prepareOpts: function (opts) {
  388. var element, select;
  389. opts = $.extend({}, {
  390. formatResult: function (data) { return data.text; },
  391. formatSelection: function (data) { return data.text; },
  392. formatNoMatches: function () { return "No matches found"; },
  393. formatInputTooShort: function (input, min) { return "Please enter " + (min - input.length) + " more characters"; },
  394. minimumResultsForSearch: 0
  395. }, opts);
  396. element = opts.element;
  397. if (element.get(0).tagName.toLowerCase() === "select") {
  398. this.select = select = opts.element;
  399. }
  400. // TODO add missing validation logic
  401. if (select) {
  402. /*$.each(["multiple", "ajax", "query", "minimumInputLength"], function () {
  403. if (this in opts) {
  404. throw "Option '" + this + "' is not allowed for Select2 when attached to a select element";
  405. }
  406. });*/
  407. this.opts = opts = $.extend({}, {
  408. miniumInputLength: 0
  409. }, opts);
  410. } else {
  411. this.opts = opts = $.extend({}, {
  412. miniumInputLength: 0
  413. }, opts);
  414. }
  415. if (select) {
  416. opts.query = this.bind(function (query) {
  417. var data = {results: [], more: false},
  418. term = query.term.toUpperCase(),
  419. placeholder = this.getPlaceholder();
  420. element.find("option").each(function (i) {
  421. var e = $(this),
  422. text = e.text();
  423. if (i === 0 && placeholder !== undefined && text === "") return true;
  424. if (text.toUpperCase().indexOf(term) >= 0) {
  425. data.results.push({id: e.attr("value"), text: text});
  426. }
  427. });
  428. query.callback(data);
  429. });
  430. } else {
  431. if (!("query" in opts)) {
  432. if ("ajax" in opts) {
  433. opts.query = ajax(opts.ajax);
  434. } else if ("data" in opts) {
  435. opts.query = local(opts.data);
  436. } else if ("tags" in opts) {
  437. opts.query = tags(opts.tags);
  438. opts.createSearchChoice = function (term) { return {id: term, text: term}; };
  439. opts.initSelection = function (element) {
  440. var data = [];
  441. $(splitVal(element.val(), ",")).each(function () {
  442. data.push({id: this, text: this});
  443. });
  444. return data;
  445. };
  446. }
  447. }
  448. }
  449. if (typeof(opts.query) !== "function") {
  450. throw "query function not defined for Select2 " + opts.element.attr("id");
  451. }
  452. return opts;
  453. },
  454. /**
  455. * Monitor the original element for changes and update select2 accordingly
  456. */
  457. monitorSource: function () {
  458. this.opts.element.bind("change.select2", this.bind(function (e) {
  459. if (this.opts.element.data("select2-change-triggered") !== true) {
  460. this.initSelection();
  461. }
  462. }));
  463. },
  464. /**
  465. * Triggers the change event on the source element
  466. */
  467. triggerChange: function () {
  468. // Prevents recursive triggering
  469. this.opts.element.data("select2-change-triggered", true);
  470. this.opts.element.trigger("change");
  471. this.opts.element.data("select2-change-triggered", false);
  472. },
  473. opened: function () {
  474. return this.container.hasClass("select2-dropdown-open");
  475. },
  476. open: function () {
  477. if (this.opened()) return;
  478. this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
  479. this.updateResults(true);
  480. this.dropdown.show();
  481. this.focusSearch();
  482. },
  483. close: function () {
  484. if (!this.opened()) return;
  485. this.dropdown.hide();
  486. this.container.removeClass("select2-dropdown-open");
  487. this.results.empty();
  488. this.clearSearch();
  489. },
  490. clearSearch: function () {
  491. },
  492. ensureHighlightVisible: function () {
  493. var results = this.results, children, index, child, hb, rb, y, more;
  494. children = results.children(".select2-result");
  495. index = this.highlight();
  496. if (index < 0) return;
  497. child = $(children[index]);
  498. hb = child.offset().top + child.outerHeight();
  499. // if this is the last child lets also make sure select2-more-results is visible
  500. if (index === children.length - 1) {
  501. more = results.find("li.select2-more-results");
  502. if (more.length > 0) {
  503. hb = more.offset().top + more.outerHeight();
  504. }
  505. }
  506. rb = results.offset().top + results.outerHeight();
  507. if (hb > rb) {
  508. results.scrollTop(results.scrollTop() + (hb - rb));
  509. }
  510. y = child.offset().top - results.offset().top;
  511. // make sure the top of the element is visible
  512. if (y < 0) {
  513. results.scrollTop(results.scrollTop() + y); // y is negative
  514. }
  515. },
  516. moveHighlight: function (delta) {
  517. var choices = this.results.children(".select2-result"),
  518. index = this.highlight();
  519. while (index > -1 && index < choices.length) {
  520. index += delta;
  521. if (!$(choices[index]).hasClass("select2-disabled")) {
  522. this.highlight(index);
  523. break;
  524. }
  525. }
  526. },
  527. highlight: function (index) {
  528. var choices = this.results.children(".select2-result");
  529. if (arguments.length === 0) {
  530. return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
  531. }
  532. choices.removeClass("select2-highlighted");
  533. if (index >= choices.length) index = choices.length - 1;
  534. if (index < 0) index = 0;
  535. $(choices[index]).addClass("select2-highlighted");
  536. this.ensureHighlightVisible();
  537. if (this.opened()) this.focusSearch();
  538. },
  539. highlightUnderEvent: function (event) {
  540. var el = $(event.target).closest(".select2-result");
  541. if (el.length > 0) {
  542. this.highlight(el.index());
  543. }
  544. },
  545. loadMoreIfNeeded: function () {
  546. var results = this.results,
  547. more = results.find("li.select2-more-results"),
  548. below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  549. offset = -1, // index of first element without data
  550. page = this.resultsPage + 1;
  551. if (more.length === 0) return;
  552. below = more.offset().top - results.offset().top - results.height();
  553. if (below <= 0) {
  554. more.addClass("select2-active");
  555. this.opts.query({term: this.search.val(), page: page, callback: this.bind(function (data) {
  556. var parts = [], self = this;
  557. $(data.results).each(function () {
  558. parts.push("<li class='select2-result'>");
  559. parts.push(self.opts.formatResult(this));
  560. parts.push("</li>");
  561. });
  562. more.before(parts.join(""));
  563. results.find(".select2-result").each(function (i) {
  564. var e = $(this);
  565. if (e.data("select2-data") !== undefined) {
  566. offset = i;
  567. } else {
  568. e.data("select2-data", data.results[i - offset - 1]);
  569. }
  570. });
  571. if (data.more) {
  572. more.removeClass("select2-active");
  573. } else {
  574. more.remove();
  575. }
  576. this.resultsPage = page;
  577. })});
  578. }
  579. },
  580. /**
  581. * @param initial whether or not this is the call to this method right after the dropdown has been opened
  582. */
  583. updateResults: function (initial) {
  584. var search = this.search, results = this.results, opts = this.opts;
  585. search.addClass("select2-active");
  586. function render(html) {
  587. results.html(html);
  588. results.scrollTop(0);
  589. search.removeClass("select2-active");
  590. }
  591. if (search.val().length < opts.minimumInputLength) {
  592. render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
  593. return;
  594. }
  595. this.resultsPage = 1;
  596. opts.query({term: search.val(), page: this.resultsPage, callback: this.bind(function (data) {
  597. var parts = [], // html parts
  598. def; // default choice
  599. // create a default choice and prepend it to the list
  600. if (this.opts.createSearchChoice && search.val() !== "") {
  601. def = this.opts.createSearchChoice.call(null, search.val(), data.results);
  602. if (def !== undefined && def !== null && def.id !== undefined && def.id !== null) {
  603. if ($(data.results).filter(
  604. function () {
  605. return equal(this.id, def.id);
  606. }).length === 0) {
  607. data.results.unshift(def);
  608. }
  609. }
  610. }
  611. if (data.results.length === 0) {
  612. render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
  613. return;
  614. }
  615. $(data.results).each(function () {
  616. parts.push("<li class='select2-result'>");
  617. parts.push(opts.formatResult(this));
  618. parts.push("</li>");
  619. });
  620. if (data.more === true) {
  621. parts.push("<li class='select2-more-results'>Loading more results...</li>");
  622. }
  623. render(parts.join(""));
  624. results.children(".select2-result").each(function (i) {
  625. var d = data.results[i];
  626. $(this).data("select2-data", d);
  627. });
  628. this.postprocessResults(data, initial);
  629. })});
  630. },
  631. cancel: function () {
  632. this.close();
  633. },
  634. blur: function () {
  635. /* we do this in a timeout so that current event processing can complete before this code is executed.
  636. this allows tab index to be preserved even if this code blurs the textfield */
  637. window.setTimeout(this.bind(function () {
  638. this.close();
  639. this.container.removeClass("select2-container-active");
  640. this.clearSearch();
  641. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  642. this.search.blur();
  643. }), 10);
  644. },
  645. focusSearch: function () {
  646. /* we do this in a timeout so that current event processing can complete before this code is executed.
  647. this makes sure the search field is focussed even if the current event would blur it */
  648. window.setTimeout(this.bind(function () {
  649. this.search.focus();
  650. }), 10);
  651. },
  652. selectHighlighted: function () {
  653. var data = this.results.find(".select2-highlighted:not(.select2-disabled)").data("select2-data");
  654. if (data) {
  655. this.onSelect(data);
  656. }
  657. },
  658. getPlaceholder: function () {
  659. return this.opts.element.attr("placeholder") || this.opts.element.data("placeholder") || this.opts.placeholder;
  660. },
  661. /**
  662. * Get the desired width for the container element. This is
  663. * derived first from option `width` passed to select2, then
  664. * the inline 'style' on the original element, and finally
  665. * falls back to the jQuery calculated element width.
  666. *
  667. * @returns The width string (with units) for the container.
  668. */
  669. getContainerWidth: function () {
  670. var style, attrs, matches, i, l;
  671. if (this.opts.width !== undefined)
  672. return this.opts.width;
  673. style = this.opts.element.attr('style');
  674. if (style !== undefined) {
  675. attrs = style.split(';');
  676. for (i = 0, l = attrs.length; i < l; i = i + 1) {
  677. matches = attrs[i].replace(/\s/g, '')
  678. .match(/width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/);
  679. if (matches !== null && matches.length >= 1)
  680. return matches[1];
  681. }
  682. }
  683. return this.opts.element.width() + 'px';
  684. }
  685. });
  686. SingleSelect2 = clazz(AbstractSelect2, {
  687. createContainer: function () {
  688. return $("<div></div>", {
  689. "class": "select2-container",
  690. "style": "width: " + this.getContainerWidth()
  691. }).html([
  692. " <a href='javascript:void(0)' class='select2-choice'>",
  693. " <span></span><abbr class='select2-search-choice-close' style='display:none;'></abbr>",
  694. " <div><b></b></div>" ,
  695. "</a>",
  696. " <div class='select2-drop' style='display:none;'>" ,
  697. " <div class='select2-search'>" ,
  698. " <input type='text' autocomplete='off'/>" ,
  699. " </div>" ,
  700. " <ul class='select2-results'>" ,
  701. " </ul>" ,
  702. "</div>"].join(""));
  703. },
  704. open: function () {
  705. if (this.opened()) return;
  706. this.parent.open.apply(this, arguments);
  707. },
  708. close: function () {
  709. if (!this.opened()) return;
  710. this.parent.close.apply(this, arguments);
  711. },
  712. focus: function () {
  713. this.close();
  714. this.selection.focus();
  715. },
  716. isFocused: function () {
  717. return this.selection.is(":focus");
  718. },
  719. cancel: function () {
  720. this.parent.cancel.apply(this, arguments);
  721. this.selection.focus();
  722. },
  723. initContainer: function () {
  724. var selection, container = this.container, clickingInside = false,
  725. selector = ".select2-choice";
  726. this.selection = selection = container.find(selector);
  727. this.search.bind("keydown", this.bind(function (e) {
  728. switch (e.which) {
  729. case KEY.UP:
  730. case KEY.DOWN:
  731. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  732. killEvent(e);
  733. return;
  734. case KEY.TAB:
  735. case KEY.ENTER:
  736. this.selectHighlighted();
  737. killEvent(e);
  738. return;
  739. case KEY.ESC:
  740. this.cancel(e);
  741. e.preventDefault();
  742. return;
  743. }
  744. }));
  745. container.delegate(selector, "click", this.bind(function (e) {
  746. clickingInside = true;
  747. if (this.opened()) {
  748. this.close();
  749. selection.focus();
  750. } else {
  751. this.open();
  752. }
  753. e.preventDefault();
  754. clickingInside = false;
  755. }));
  756. container.delegate(selector, "keydown", this.bind(function (e) {
  757. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  758. return;
  759. }
  760. this.open();
  761. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN || e.which === KEY.SPACE) {
  762. // prevent the page from scrolling
  763. killEvent(e);
  764. }
  765. if (e.which === KEY.ENTER) {
  766. // do not propagate the event otherwise we open, and propagate enter which closes
  767. killEvent(e);
  768. }
  769. }));
  770. container.delegate(selector, "focus", function () { container.addClass("select2-container-active"); });
  771. container.delegate(selector, "blur", this.bind(function () {
  772. if (clickingInside) return;
  773. if (!this.opened()) this.blur();
  774. }));
  775. selection.delegate("abbr", "click", this.bind(function (e) {
  776. this.val("");
  777. killEvent(e);
  778. this.close();
  779. this.triggerChange();
  780. }));
  781. this.setPlaceholder();
  782. },
  783. /**
  784. * Sets selection based on source element's value
  785. */
  786. initSelection: function () {
  787. var selected;
  788. if (this.opts.element.val() === "") {
  789. this.updateSelection({id: "", text: ""});
  790. } else {
  791. selected = this.opts.initSelection.call(null, this.opts.element);
  792. if (selected !== undefined && selected !== null) {
  793. this.updateSelection(selected);
  794. }
  795. }
  796. this.close();
  797. this.setPlaceholder();
  798. },
  799. prepareOpts: function () {
  800. var opts = this.parent.prepareOpts.apply(this, arguments);
  801. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  802. // install sthe selection initializer
  803. opts.initSelection = function (element) {
  804. var selected = element.find(":selected");
  805. // a single select box always has a value, no need to null check 'selected'
  806. return {id: selected.attr("value"), text: selected.text()};
  807. };
  808. }
  809. return opts;
  810. },
  811. setPlaceholder: function () {
  812. var placeholder = this.getPlaceholder();
  813. if (this.opts.element.val() === "" && placeholder !== undefined) {
  814. // check for a first blank option if attached to a select
  815. if (this.select && this.select.find("option:first").text() !== "") return;
  816. if (typeof(placeholder) === "object") {
  817. this.updateSelection(placeholder);
  818. } else {
  819. this.selection.find("span").html(placeholder);
  820. }
  821. this.selection.addClass("select2-default");
  822. this.selection.find("abbr").hide();
  823. }
  824. },
  825. postprocessResults: function (data, initial) {
  826. var selected = 0, self = this, showSearchInput = true;
  827. // find the selected element in the result list
  828. this.results.find(".select2-result").each(function (i) {
  829. if (equal($(this).data("select2-data").id, self.opts.element.val())) {
  830. selected = i;
  831. return false;
  832. }
  833. });
  834. // and highlight it
  835. this.highlight(selected);
  836. // hide the search box if this is the first we got the results and there are a few of them
  837. if (initial === true) {
  838. showSearchInput = data.results.length >= this.opts.minimumResultsForSearch;
  839. this.search.parent().toggle(showSearchInput);
  840. //add "select2-with-searchbox" to the container if search box is shown
  841. this.container[showSearchInput ? "addClass" : "removeClass"]("select2-with-searchbox");
  842. }
  843. },
  844. onSelect: function (data) {
  845. var old = this.opts.element.val();
  846. this.opts.element.val(data.id);
  847. this.updateSelection(data);
  848. this.close();
  849. this.selection.focus();
  850. if (!equal(old, data.id)) { this.triggerChange(); }
  851. },
  852. updateSelection: function (data) {
  853. this.selection
  854. .find("span")
  855. .html(this.opts.formatSelection(data));
  856. this.selection.removeClass("select2-default");
  857. if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
  858. this.selection.find("abbr").show();
  859. }
  860. },
  861. val: function () {
  862. var val, data = null;
  863. if (arguments.length === 0) {
  864. return this.opts.element.val();
  865. }
  866. val = arguments[0];
  867. if (this.select) {
  868. // val is an id
  869. this.select
  870. .val(val)
  871. .find(":selected").each(function () {
  872. data = {id: $(this).attr("value"), text: $(this).text()};
  873. return false;
  874. });
  875. this.updateSelection(data);
  876. } else {
  877. // val is an object. !val is true for [undefined,null,'']
  878. this.opts.element.val(!val ? "" : val.id);
  879. this.updateSelection(val);
  880. }
  881. this.setPlaceholder();
  882. },
  883. clearSearch: function () {
  884. this.search.val("");
  885. }
  886. });
  887. MultiSelect2 = clazz(AbstractSelect2, {
  888. createContainer: function () {
  889. return $("<div></div>", {
  890. "class": "select2-container select2-container-multi",
  891. "style": "width: " + this.getContainerWidth()
  892. }).html([
  893. " <ul class='select2-choices'>",
  894. //"<li class='select2-search-choice'><span>California</span><a href="javascript:void(0)" class="select2-search-choice-close"></a></li>" ,
  895. " <li class='select2-search-field'>" ,
  896. " <input type='text' autocomplete='off' style='width: 25px;'>" ,
  897. " </li>" ,
  898. "</ul>" ,
  899. "<div class='select2-drop' style='display:none;'>" ,
  900. " <ul class='select2-results'>" ,
  901. " </ul>" ,
  902. "</div>"].join(""));
  903. },
  904. prepareOpts: function () {
  905. var opts = this.parent.prepareOpts.apply(this, arguments);
  906. opts = $.extend({}, {
  907. closeOnSelect: true
  908. }, opts);
  909. // TODO validate placeholder is a string if specified
  910. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  911. // install sthe selection initializer
  912. opts.initSelection = function (element) {
  913. var data = [];
  914. element.find(":selected").each(function () {
  915. data.push({id: $(this).attr("value"), text: $(this).text()});
  916. });
  917. return data;
  918. };
  919. }
  920. return opts;
  921. },
  922. initContainer: function () {
  923. var selector = ".select2-choices", selection;
  924. this.searchContainer = this.container.find(".select2-search-field");
  925. this.selection = selection = this.container.find(selector);
  926. this.search.bind("keydown", this.bind(function (e) {
  927. if (e.which === KEY.BACKSPACE && this.search.val() === "") {
  928. this.close();
  929. var choices,
  930. selected = selection.find(".select2-search-choice-focus");
  931. if (selected.length > 0) {
  932. this.unselect(selected.first());
  933. this.search.width(10);
  934. killEvent(e);
  935. return;
  936. }
  937. choices = selection.find(".select2-search-choice");
  938. if (choices.length > 0) {
  939. choices.last().addClass("select2-search-choice-focus");
  940. }
  941. } else {
  942. selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  943. }
  944. if (this.opened()) {
  945. switch (e.which) {
  946. case KEY.UP:
  947. case KEY.DOWN:
  948. this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
  949. killEvent(e);
  950. return;
  951. case KEY.ENTER:
  952. this.selectHighlighted();
  953. killEvent(e);
  954. return;
  955. case KEY.ESC:
  956. this.cancel(e);
  957. e.preventDefault();
  958. return;
  959. }
  960. }
  961. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
  962. return;
  963. }
  964. this.open();
  965. if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
  966. // prevent the page from scrolling
  967. killEvent(e);
  968. }
  969. }));
  970. this.search.bind("keyup", this.bind(this.resizeSearch));
  971. this.container.delegate(selector, "click", this.bind(function (e) {
  972. this.open();
  973. this.focusSearch();
  974. e.preventDefault();
  975. }));
  976. this.container.delegate(selector, "focus", this.bind(function () {
  977. this.container.addClass("select2-container-active");
  978. this.clearPlaceholder();
  979. }));
  980. // set the placeholder if necessary
  981. this.clearSearch();
  982. },
  983. initSelection: function () {
  984. var data;
  985. if (this.opts.element.val() === "") {
  986. this.updateSelection([]);
  987. }
  988. if (this.select || this.opts.element.val() !== "") {
  989. data = this.opts.initSelection.call(null, this.opts.element);
  990. if (data !== undefined && data !== null) {
  991. this.updateSelection(data);
  992. }
  993. }
  994. this.close();
  995. // set the placeholder if necessary
  996. this.clearSearch();
  997. },
  998. clearSearch: function () {
  999. var placeholder = this.getPlaceholder();
  1000. if (placeholder !== undefined
  1001. && this.getVal().length === 0
  1002. && this.search.hasClass("select2-focused")===false) {
  1003. this.search.val(placeholder).addClass("select2-default");
  1004. // stretch the search box to full width of the container so as much of the placeholder is visible as possible
  1005. this.search.width(this.getContainerWidth());
  1006. } else {
  1007. this.search.val("").width(10);
  1008. }
  1009. },
  1010. clearPlaceholder: function () {
  1011. if (this.search.hasClass("select2-default")) {
  1012. this.search.val("").removeClass("select2-default");
  1013. }
  1014. },
  1015. open: function () {
  1016. if (this.opened()) return;
  1017. this.parent.open.apply(this, arguments);
  1018. this.resizeSearch();
  1019. this.focusSearch();
  1020. },
  1021. close: function () {
  1022. if (!this.opened()) return;
  1023. this.parent.close.apply(this, arguments);
  1024. },
  1025. focus: function () {
  1026. this.close();
  1027. this.search.focus();
  1028. },
  1029. isFocused: function () {
  1030. return this.search.hasClass("select2-focused");
  1031. },
  1032. updateSelection: function (data) {
  1033. var ids = [], filtered = [], self = this;
  1034. // filter out duplicates
  1035. $(data).each(function () {
  1036. if (indexOf(this.id, ids) < 0) {
  1037. ids.push(this.id);
  1038. filtered.push(this);
  1039. }
  1040. });
  1041. data = filtered;
  1042. this.selection.find(".select2-search-choice").remove();
  1043. $(data).each(function () {
  1044. self.addSelectedChoice(this);
  1045. });
  1046. self.postprocessResults();
  1047. },
  1048. onSelect: function (data) {
  1049. this.addSelectedChoice(data);
  1050. if (this.select) { this.postprocessResults(); }
  1051. if (this.opts.closeOnSelect) {
  1052. this.close();
  1053. this.search.width(10);
  1054. } else {
  1055. this.search.width(10);
  1056. this.resizeSearch();
  1057. }
  1058. // since its not possible to select an element that has already been
  1059. // added we do not need to check if this is a new element before firing change
  1060. this.triggerChange();
  1061. this.focusSearch();
  1062. },
  1063. cancel: function () {
  1064. this.close();
  1065. this.focusSearch();
  1066. },
  1067. addSelectedChoice: function (data) {
  1068. var choice,
  1069. id = data.id,
  1070. parts,
  1071. val = this.getVal();
  1072. parts = ["<li class='select2-search-choice'>",
  1073. this.opts.formatSelection(data),
  1074. "<a href='javascript:void(0)' class='select2-search-choice-close' tabindex='-1'></a>",
  1075. "</li>"
  1076. ];
  1077. choice = $(parts.join(""));
  1078. choice.find("a")
  1079. .bind("click dblclick", this.bind(function (e) {
  1080. this.unselect($(e.target));
  1081. this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
  1082. killEvent(e);
  1083. this.close();
  1084. this.focusSearch();
  1085. })).bind("focus", this.bind(function () {
  1086. this.container.addClass("select2-container-active");
  1087. }));
  1088. choice.data("select2-data", data);
  1089. choice.insertBefore(this.searchContainer);
  1090. val.push(id);
  1091. this.setVal(val);
  1092. },
  1093. unselect: function (selected) {
  1094. var val = this.getVal(),
  1095. index;
  1096. selected = selected.closest(".select2-search-choice");
  1097. if (selected.length === 0) {
  1098. throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
  1099. }
  1100. index = indexOf(selected.data("select2-data").id, val);
  1101. if (index >= 0) {
  1102. val.splice(index, 1);
  1103. this.setVal(val);
  1104. if (this.select) this.postprocessResults();
  1105. }
  1106. selected.remove();
  1107. this.triggerChange();
  1108. },
  1109. postprocessResults: function () {
  1110. var val = this.getVal(),
  1111. choices = this.results.find(".select2-result"),
  1112. self = this;
  1113. choices.each(function () {
  1114. var choice = $(this), id = choice.data("select2-data").id;
  1115. if (indexOf(id, val) >= 0) {
  1116. choice.addClass("select2-disabled");
  1117. } else {
  1118. choice.removeClass("select2-disabled");
  1119. }
  1120. });
  1121. choices.each(function (i) {
  1122. if (!$(this).hasClass("select2-disabled")) {
  1123. self.highlight(i);
  1124. return false;
  1125. }
  1126. });
  1127. },
  1128. resizeSearch: function () {
  1129. var minimumWidth, left, maxWidth, containerLeft, searchWidth;
  1130. minimumWidth = measureTextWidth(this.search) + 10;
  1131. left = this.search.offset().left;
  1132. maxWidth = this.selection.width();
  1133. containerLeft = this.selection.offset().left;
  1134. searchWidth = maxWidth - (left - containerLeft) - getSideBorderPadding(this.search);
  1135. if (searchWidth < minimumWidth) {
  1136. searchWidth = maxWidth - getSideBorderPadding(this.search);
  1137. }
  1138. if (searchWidth < 40) {
  1139. searchWidth = maxWidth - getSideBorderPadding(this.search);
  1140. }
  1141. this.search.width(searchWidth);
  1142. },
  1143. getVal: function () {
  1144. var val;
  1145. if (this.select) {
  1146. val = this.select.val();
  1147. return val === null ? [] : val;
  1148. } else {
  1149. val = this.opts.element.val();
  1150. return splitVal(val, ",");
  1151. }
  1152. },
  1153. setVal: function (val) {
  1154. var unique = [];
  1155. if (this.select) {
  1156. this.select.val(val);
  1157. } else {
  1158. // filter out duplicates
  1159. $(val).each(function () {
  1160. if (indexOf(this, unique) < 0) unique.push(this);
  1161. });
  1162. this.opts.element.val(unique.length === 0 ? "" : unique.join(","));
  1163. }
  1164. },
  1165. val: function () {
  1166. var val, data = [];
  1167. if (arguments.length === 0) {
  1168. return this.getVal();
  1169. }
  1170. val = arguments[0];
  1171. if (this.select) {
  1172. // val is a list of ids
  1173. this.setVal(val);
  1174. this.select.find(":selected").each(function () {
  1175. data.push({id: $(this).attr("value"), text: $(this).text()});
  1176. });
  1177. this.updateSelection(data);
  1178. } else {
  1179. val = (val === null) ? [] : val;
  1180. this.setVal(val);
  1181. // val is a list of objects
  1182. $(val).each(function () { data.push(this.id); });
  1183. this.setVal(data);
  1184. this.updateSelection(val);
  1185. }
  1186. this.clearSearch();
  1187. }
  1188. });
  1189. $.fn.select2 = function () {
  1190. var args = Array.prototype.slice.call(arguments, 0),
  1191. opts,
  1192. select2,
  1193. value, multiple, allowedMethods = ["val", "destroy", "open", "close", "focus", "isFocused"];
  1194. this.each(function () {
  1195. if (args.length === 0 || typeof(args[0]) === "object") {
  1196. opts = args.length === 0 ? {} : $.extend({}, args[0]);
  1197. opts.element = $(this);
  1198. if (opts.element.get(0).tagName.toLowerCase() === "select") {
  1199. multiple = opts.element.attr("multiple");
  1200. } else {
  1201. multiple = opts.multiple || false;
  1202. if ("tags" in opts) {opts.multiple = multiple = true;}
  1203. }
  1204. select2 = multiple ? new MultiSelect2() : new SingleSelect2();
  1205. select2.init(opts);
  1206. } else if (typeof(args[0]) === "string") {
  1207. if (indexOf(args[0], allowedMethods) < 0) {
  1208. throw "Unknown method: " + args[0];
  1209. }
  1210. value = undefined;
  1211. select2 = $(this).data("select2");
  1212. if (select2 === undefined) return;
  1213. value = select2[args[0]].apply(select2, args.slice(1));
  1214. if (value !== undefined) {return false;}
  1215. } else {
  1216. throw "Invalid arguments to select2 plugin: " + args;
  1217. }
  1218. });
  1219. return (value === undefined) ? this : value;
  1220. };
  1221. // exports
  1222. window.Select2 = {
  1223. query: {
  1224. ajax: ajax,
  1225. local: local,
  1226. tags: tags
  1227. }, util: {
  1228. debounce: debounce
  1229. }, "class": {
  1230. "abstract": AbstractSelect2,
  1231. "single": SingleSelect2,
  1232. "multi": MultiSelect2
  1233. }
  1234. };
  1235. }(jQuery));