select2.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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 ($) {
  18. "use strict";
  19. /*global document, window, jQuery, console */
  20. var KEY, Util, DropDown, ResultList, Selection, Select2, Queries;
  21. function createClass(def) {
  22. var type = function (attrs) {
  23. var self = this;
  24. if (def.attrs !== undefined) {
  25. $.each(def.attrs, function (name, body) {
  26. if (attrs[name] !== undefined) {
  27. self[name] = attrs[name];
  28. } else {
  29. if (body.required === true) {
  30. throw "Value for required attribute: " + name + " not defined";
  31. }
  32. if (body.init !== undefined) {
  33. self[name] = typeof (body.init) === "function" ? body.init.apply(self) : body.init;
  34. }
  35. }
  36. });
  37. }
  38. if (def.methods !== undefined && def.methods.init !== undefined) {
  39. self.init(attrs);
  40. }
  41. };
  42. if (def.methods !== undefined) {
  43. if (def.methods.bind !== undefined) {
  44. throw "Class cannot declare a method called 'bind'";
  45. }
  46. $.each(def.methods, function (name, body) {
  47. type.prototype[name] = body;
  48. });
  49. type.prototype.bind = function (func) {
  50. var self = this;
  51. return function () {
  52. func.apply(self, arguments);
  53. };
  54. };
  55. }
  56. return type;
  57. }
  58. KEY = {
  59. TAB: 9,
  60. ENTER: 13,
  61. ESC: 27,
  62. SPACE: 32,
  63. LEFT: 37,
  64. UP: 38,
  65. RIGHT: 39,
  66. DOWN: 40,
  67. SHIFT: 16,
  68. CTRL: 17,
  69. ALT: 18,
  70. PAGE_UP: 33,
  71. PAGE_DOWN: 34,
  72. HOME: 36,
  73. END: 35,
  74. BACKSPACE: 8,
  75. DELETE: 46
  76. };
  77. Util = {};
  78. Util.debounce = function (threshold, fn) {
  79. var timeout;
  80. return function () {
  81. window.clearTimeout(timeout);
  82. timeout = window.setTimeout(fn, threshold);
  83. };
  84. };
  85. Util.debounceEvent = function (element, threshold, event, debouncedEvent, direct) {
  86. debouncedEvent = debouncedEvent || event + "-debounced";
  87. direct = direct || true;
  88. var notify = Util.debounce(threshold, function (e) {
  89. element.trigger(debouncedEvent, e);
  90. });
  91. element.on(event, function (e) {
  92. if (direct && element.get().indexOf(e.target) < 0) {
  93. return;
  94. }
  95. notify(e);
  96. });
  97. };
  98. (function () {
  99. var lastpos;
  100. /**
  101. * Filters mouse events so an event is fired only if the mouse moved.
  102. * Filters out mouse events that occur when mouse is stationary but
  103. * the elements under the pointer are scrolled
  104. */
  105. Util.filterMouseEvent = function (element, event, filteredEvent, direct) {
  106. filteredEvent = filteredEvent || event + "-filtered";
  107. direct = direct || false;
  108. element.on(event, "*", function (e) {
  109. if (direct && element.get().indexOf(e.target) < 0) {
  110. return;
  111. }
  112. if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
  113. $(e.target).trigger(filteredEvent, e);
  114. lastpos = {x: e.pageX, y: e.pageY};
  115. }
  116. });
  117. };
  118. }());
  119. DropDown = createClass({
  120. attrs: {
  121. container: {required: true},
  122. element: {required: true},
  123. bus: {required: true}
  124. },
  125. methods: {
  126. open: function () {
  127. if (this.isOpen()) {
  128. return;
  129. }
  130. this.container.addClass("select2-dropdown-open");
  131. // register click-outside-closes-dropdown listener
  132. $(document).on("mousedown.dropdown", this.bind(function (e) {
  133. var inside = false,
  134. container = this.container.get(0);
  135. $(e.target).parents().each(function () {
  136. return !(inside = (this === container));
  137. });
  138. if (!inside) {
  139. this.close();
  140. }
  141. }));
  142. this.element.show();
  143. this.bus.trigger("opened");
  144. },
  145. close: function () {
  146. if (!this.isOpen()) {
  147. return;
  148. }
  149. this.container.removeClass("select2-dropdown-open");
  150. $(document).off("mousedown.dropdown");
  151. this.element.hide();
  152. this.bus.trigger("closed");
  153. },
  154. isOpen: function () {
  155. return this.container.hasClass("select2-dropdown-open");
  156. },
  157. toggle: function () {
  158. if (this.isOpen()) {
  159. this.close();
  160. } else {
  161. this.open();
  162. }
  163. }
  164. }
  165. });
  166. ResultList = createClass({
  167. attrs: {
  168. element: {required: true},
  169. bus: {required: true},
  170. formatInputTooShort: {required: true},
  171. formatNoMatches: {required: true},
  172. formatResult: {required: true},
  173. minimumInputLength: {required: true},
  174. query: {required: true},
  175. selection: {required: true}
  176. },
  177. methods: {
  178. init: function () {
  179. var self = this;
  180. this.search = this.element.find("input");
  181. this.results = this.element.find("ul");
  182. this.scrollPosition = 0;
  183. this.vars = {};
  184. this.search.on("keyup", function (e) {
  185. if (e.which >= 48 || e.which === KEY.SPACE || e.which === KEY.BACKSPACE || e.which === KEY.DELETE) {
  186. self.update();
  187. }
  188. });
  189. this.search.on("keydown", function (e) {
  190. switch (e.which) {
  191. case KEY.TAB:
  192. e.preventDefault();
  193. self.select();
  194. return;
  195. case KEY.ENTER:
  196. e.preventDefault();
  197. e.stopPropagation();
  198. self.select();
  199. return;
  200. case KEY.UP:
  201. self.moveSelection(-1);
  202. e.preventDefault();
  203. e.stopPropagation();
  204. return;
  205. case KEY.DOWN:
  206. self.moveSelection(1);
  207. e.preventDefault();
  208. e.stopPropagation();
  209. return;
  210. case KEY.ESC:
  211. e.preventDefault();
  212. e.stopPropagation();
  213. self.cancel();
  214. return;
  215. }
  216. });
  217. // this.results.on("mouseleave", "li.select2-result", this.bind(this.unhighlight));
  218. Util.filterMouseEvent(this.results, "mousemove");
  219. this.results.on("mousemove-filtered", this.bind(function (e) {
  220. var el = $(e.target).closest("li.select2-result");
  221. if (el.length < 1) {
  222. return;
  223. }
  224. this.setSelection(el.index());
  225. }));
  226. this.results.on("click", this.bind(function (e) {
  227. var el = $(e.target).closest("li.select2-result");
  228. if (el.length < 1) {
  229. return;
  230. }
  231. this.bus.trigger("selected", [el.data("select2-result")]);
  232. }));
  233. Util.debounceEvent(this.results, 100, "scroll");
  234. this.results.on("scroll-debounced", this.bind(function (e) {
  235. this.scrollPosition = this.results.scrollTop();
  236. var more = this.results.find("li.select2-more-results"), below;
  237. if (more.length === 0) {
  238. return;
  239. }
  240. // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
  241. below = more.offset().top - this.results.offset().top - this.results.height();
  242. if (below <= 0) {
  243. more.addClass("select2-active");
  244. this.query({term: this.search.val(), vars: this.vars, callback: this.bind(this.append)});
  245. }
  246. }));
  247. },
  248. open: function (e) {
  249. this.search.focus();
  250. this.results.scrollTop(this.scrollPosition);
  251. if (this.results.children().length === 0) {
  252. // first time the dropdown is opened, update the results
  253. this.update();
  254. }
  255. },
  256. close: function () {
  257. //this.search.val("");
  258. //this.clear();
  259. },
  260. clear: function () {
  261. this.results.empty();
  262. },
  263. showInputTooShort: function () {
  264. this.show("<li class='select2-no-results'>" + this.formatInputTooShort(this.search.val(), this.minimumInputLength) + "</li>");
  265. },
  266. showNoMatches: function () {
  267. this.show("<li class='select2-no-results'>" + this.formatNoMatches(this.search.val()) + "</li>");
  268. },
  269. show: function (html) {
  270. this.results.html(html);
  271. this.results.scrollTop(0);
  272. this.search.removeClass("select2-active");
  273. },
  274. update: function () {
  275. var html = "";
  276. if (this.search.val().length < this.minimumInputLength) {
  277. this.showInputTooShort();
  278. return;
  279. }
  280. this.search.addClass("select2-active");
  281. this.vars = {};
  282. this.query({term: this.search.val(), vars: this.vars, callback: this.bind(this.process)});
  283. },
  284. process: function (data) {
  285. if (data.results.length === 0) {
  286. this.showNoMatches();
  287. return;
  288. }
  289. var html = this.stringizeResults(data.results), selectedId = this.selection.val(), selectedIndex = 0;
  290. if (data.more === true) {
  291. html += "<li class='select2-more-results'>Loading more results...</li>";
  292. }
  293. this.vars = data.vars || {};
  294. this.show(html);
  295. this.findChoices().each(function (i) {
  296. if (selectedId === data.results[i].id) {
  297. selectedIndex = i;
  298. }
  299. $(this).data("select2-result", data.results[i]);
  300. });
  301. this.setSelection(selectedIndex);
  302. },
  303. append: function (data) {
  304. var more = this.results.find("li.select2-more-results"), html, offset;
  305. this.vars = data.vars || {};
  306. if (data.results.length === 0) {
  307. more.remove();
  308. return;
  309. }
  310. html = this.stringizeResults(data.results);
  311. offset = this.results.find("li.select2-result").length;
  312. more.before(html);
  313. this.results.find("li.select2-result").each(function (i) {
  314. if (i >= offset) {
  315. $(this).data("select2-result", data.results[i - offset]);
  316. }
  317. });
  318. if (data.more !== true) {
  319. more.remove();
  320. } else {
  321. more.removeClass("select2-active");
  322. }
  323. },
  324. stringizeResults: function (results, html) {
  325. var i, l, classes;
  326. html = html || "";
  327. for (i = 0, l = results.length; i < l; i += 1) {
  328. html += "<li class='select2-result'>";
  329. html += this.formatResult(results[i]);
  330. html += "</li>";
  331. }
  332. return html;
  333. },
  334. findChoices: function () {
  335. return this.results.children("li.select2-result");
  336. },
  337. removeSelection: function () {
  338. this.findChoices().each(function () {
  339. $(this).removeClass("select2-highlighted");
  340. });
  341. },
  342. setSelection: function (index) {
  343. this.removeSelection();
  344. var children = this.findChoices(),
  345. child = $(children[index]),
  346. hb,
  347. rb,
  348. y,
  349. more;
  350. child.addClass("select2-highlighted");
  351. this.search.focus();
  352. hb = child.offset().top + child.outerHeight();
  353. // if this is the last child lets also make sure select2-more-results is visible
  354. if (index === children.length - 1) {
  355. more = this.results.find("li.select2-more-results");
  356. if (more.length > 0) {
  357. hb = more.offset().top + more.outerHeight();
  358. }
  359. }
  360. rb = this.results.offset().top + this.results.outerHeight();
  361. if (hb > rb) {
  362. this.results.scrollTop(this.results.scrollTop() + (hb - rb));
  363. }
  364. y = child.offset().top - this.results.offset().top;
  365. // make sure the top of the element is visible
  366. if (y < 0) {
  367. this.results.scrollTop(this.results.scrollTop() + y); // y is negative
  368. }
  369. },
  370. getSelectionIndex: function () {
  371. var children = this.findChoices(), i = 0, l = children.length;
  372. for (; i < l; i += 1) {
  373. if ($(children[i]).hasClass("select2-highlighted")) {
  374. return i;
  375. }
  376. }
  377. return -1;
  378. },
  379. moveSelection: function (delta) {
  380. var current = this.getSelectionIndex(),
  381. children = this.findChoices(),
  382. next = current + delta;
  383. if (current >= 0 && next >= 0 && next < children.length) {
  384. this.setSelection(next);
  385. }
  386. },
  387. select: function () {
  388. var selected = this.results.find("li.select2-highlighted");
  389. if (selected.length > 0) {
  390. this.bus.trigger("selected", [selected.data("select2-result")]);
  391. }
  392. },
  393. cancel: function () {
  394. this.bus.trigger("cancelled");
  395. },
  396. val: function (data) {
  397. var choices = this.findChoices(), index;
  398. choices.each(function (i) {
  399. if ($(this).data("select2-result").id === data) {
  400. index = i;
  401. return false;
  402. }
  403. });
  404. if (index === undefined && data.id !== undefined) {
  405. choices.each(function (i) {
  406. if ($(this).data("select2-result").id === data.id) {
  407. index = i;
  408. return false;
  409. }
  410. });
  411. }
  412. if (index !== undefined) {
  413. this.setSelection(index);
  414. this.select();
  415. return;
  416. }
  417. this.bus.trigger("selected", data);
  418. }
  419. }
  420. });
  421. Selection = createClass({
  422. attrs: {
  423. bus: {required: true},
  424. element: {required: true},
  425. display: {init: function () {
  426. return this.element.find("span");
  427. }},
  428. hidden: {required: true},
  429. formatSelection: {required: true},
  430. placeholder: {},
  431. dropdown: {required: true}
  432. },
  433. methods: {
  434. init: function () {
  435. if (this.placeholder) {
  436. this.select(this.placeholder);
  437. }
  438. this.element.click(this.dropdown.bind(this.dropdown.toggle));
  439. var self = this;
  440. this.element.on("keydown", function (e) {
  441. switch (e.which) {
  442. case KEY.TAB:
  443. case KEY.SHIFT:
  444. case KEY.CTRL:
  445. case KEY.ALT:
  446. case KEY.LEFT:
  447. case KEY.RIGHT:
  448. return;
  449. }
  450. self.dropdown.open();
  451. });
  452. },
  453. select: function (data) {
  454. this.display.html(this.formatSelection(data));
  455. this.hidden.val(data.id);
  456. },
  457. focus: function () {
  458. this.element.focus();
  459. },
  460. val: function () {
  461. return this.hidden.val();
  462. }
  463. }
  464. });
  465. Queries = {};
  466. Queries.select = function (select2, element) {
  467. var options = [];
  468. element.find("option").each(function () {
  469. var e = $(this);
  470. options.push({id: e.attr("value"), text: e.text()});
  471. });
  472. return function (query) {
  473. var data = {results: [], more: false},
  474. text = query.term.toUpperCase();
  475. $.each(options, function (i) {
  476. if (this.text.toUpperCase().indexOf(text) >= 0) {
  477. data.results.push(this);
  478. }
  479. });
  480. query.callback(data);
  481. };
  482. };
  483. Queries.ajax = function (select2, el) {
  484. var timeout, // current scheduled but not yet executed request
  485. requestSequence = 0, // sequence used to drop out-of-order responses
  486. quietMillis = select2.ajax.quietMillis || 100;
  487. return function (query) {
  488. window.clearTimeout(timeout);
  489. timeout = window.setTimeout(function () {
  490. requestSequence += 1; // increment the sequence
  491. var requestNumber = requestSequence, // this request's sequence number
  492. options = select2.ajax, // ajax parameters
  493. data = options.data; // ajax data function
  494. data = data.call(this, query.term, query.vars);
  495. $.ajax({
  496. url: options.url,
  497. dataType: options.dataType,
  498. data: data
  499. }).success(
  500. function (data) {
  501. if (requestNumber < requestSequence) {
  502. return;
  503. }
  504. query.callback(options.results(data, query.vars));
  505. }
  506. );
  507. }, quietMillis);
  508. };
  509. };
  510. Select2 = createClass({
  511. attrs: {
  512. el: {required: true},
  513. formatResult: {init: function () {
  514. return function (data) {
  515. return data.text;
  516. };
  517. }},
  518. formatSelection: {init: function () {
  519. return function (data) {
  520. return data.text;
  521. };
  522. }},
  523. formatNoMatches: {init: function () {
  524. return function () {
  525. return "No matches found";
  526. };
  527. }},
  528. formatInputTooShort: {init: function () {
  529. return function (input, min) {
  530. return "Please enter " + (min - input.length) + " more characters to start search";
  531. };
  532. }},
  533. minimumInputLength: {init: 0},
  534. placeholder: {init: undefined},
  535. ajax: {init: undefined},
  536. query: {init: undefined}
  537. },
  538. methods: {
  539. init: function () {
  540. var self = this, width, dropdown, results, selected, select;
  541. this.el = $(this.el);
  542. width = this.el.outerWidth();
  543. this.container = $("<div></div>", {
  544. "class": "select2-container",
  545. style: "width: " + width + "px"
  546. });
  547. this.container.html(
  548. " <a href='javascript:void(0)' class='select2-choice'>" +
  549. " <span></span>" +
  550. " <div><b></b></div>" +
  551. "</a>" +
  552. "<div class='select2-drop' style='display:none;'>" +
  553. " <div class='select2-search'>" +
  554. " <input type='text' autocomplete='off'/>" +
  555. " </div>" +
  556. " <ul class='select2-results'>" +
  557. " </ul>" +
  558. "</div>" +
  559. "<input type='hidden'/>"
  560. );
  561. this.el.data("select2", this);
  562. this.el.hide();
  563. this.el.after(self.container);
  564. if (this.el.attr("class") !== undefined) {
  565. this.container.addClass(this.el.attr("class"));
  566. }
  567. this.container.data("select2", this);
  568. this.container.find("input[type=hidden]").attr("name", this.el.attr("name"));
  569. if (this.query === undefined && this.el.get(0).tagName.toUpperCase() === "SELECT") {
  570. this.query = "select";
  571. select = true;
  572. }
  573. if (Queries[this.query] !== undefined) {
  574. this.query = Queries[this.query](this, this.el);
  575. }
  576. (function () {
  577. var dropdown, searchContainer, search, width;
  578. function getSideBorderPadding(e) {
  579. return e.outerWidth() - e.width();
  580. }
  581. // position and size dropdown
  582. dropdown = self.container.find("div.select2-drop");
  583. width = self.container.outerWidth() - getSideBorderPadding(dropdown);
  584. dropdown.css({top: self.container.height(), width: width});
  585. // size search field
  586. searchContainer = self.container.find(".select2-search");
  587. search = searchContainer.find("input");
  588. width = dropdown.width();
  589. width -= getSideBorderPadding(searchContainer);
  590. width -= getSideBorderPadding(search);
  591. search.css({width: width});
  592. }());
  593. dropdown = new DropDown({
  594. element: this.container.find("div.select2-drop"),
  595. container: this.container,
  596. bus: this.el
  597. });
  598. this.selection = new Selection({
  599. bus: this.el,
  600. element: this.container.find(".select2-choice"),
  601. hidden: this.container.find("input[type=hidden]"),
  602. formatSelection: this.formatSelection,
  603. placeholder: this.placeholder,
  604. dropdown: dropdown
  605. });
  606. this.results = new ResultList({
  607. element: this.container.find("div.select2-drop"),
  608. bus: this.el,
  609. formatInputTooShort: this.formatInputTooShort,
  610. formatNoMatches: this.formatNoMatches,
  611. formatResult: this.formatResult,
  612. minimumInputLength: this.minimumInputLength,
  613. query: this.query,
  614. selection: this.selection
  615. });
  616. this.el.on("selected", function (e, result) {
  617. dropdown.close();
  618. self.selection.select(result);
  619. });
  620. this.el.on("cancelled", function () {
  621. dropdown.close();
  622. });
  623. this.el.on("opened", this.bind(function () {
  624. this.results.open();
  625. }));
  626. this.el.on("closed", this.bind(function () {
  627. this.container.removeClass("select2-dropdown-open");
  628. this.results.close();
  629. this.selection.focus();
  630. }));
  631. // if attached to a select do some default initialization
  632. if (select) {
  633. this.results.update(); // build the results
  634. selected = this.el.find("option[selected]");
  635. if (selected.length < 1 && this.placeholder === undefined) {
  636. selected = $(this.el.find("option")[0]);
  637. }
  638. if (selected.length > 0) {
  639. this.val({id: selected.attr("value"), text: selected.text()});
  640. }
  641. }
  642. },
  643. val: function () {
  644. var data;
  645. if (arguments.length === 0) {
  646. return this.selection.val();
  647. } else {
  648. data = arguments[0];
  649. this.results.val(data);
  650. }
  651. }
  652. }
  653. });
  654. $.fn.select2 = function () {
  655. var args = Array.prototype.slice.call(arguments, 0), value, tmp;
  656. this.each(function () {
  657. if (args.length === 0) {
  658. tmp = new Select2({el: this});
  659. } else if (typeof (args[0]) === "object") {
  660. args[0].el = this;
  661. tmp = new Select2(args[0]);
  662. } else if (typeof (args[0]) === "string") {
  663. var select2 = $(this).data("select2");
  664. value = select2[args[0]].apply(select2, args.slice(1));
  665. return false;
  666. } else {
  667. throw "Invalid arguments to select2 plugin: " + args;
  668. }
  669. });
  670. return (value === undefined) ? this : value;
  671. };
  672. }(jQuery));