select2.js 45 KB

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