autocomplete.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. /**
  2. * Ajax Autocomplete for jQuery, version 1.4.11
  3. * (c) 2017 Tomas Kirda
  4. *
  5. * Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.
  6. * For details, see the web site: https://github.com/devbridge/jQuery-Autocomplete
  7. */
  8. /*jslint browser: true, white: true, single: true, this: true, multivar: true */
  9. /*global define, window, document, jQuery, exports, require */
  10. // Expose plugin as an AMD module if AMD loader is present:
  11. (function (factory) {
  12. "use strict";
  13. if (typeof define === 'function' && define.amd) {
  14. // AMD. Register as an anonymous module.
  15. define(['jquery'], factory);
  16. } else if (typeof exports === 'object' && typeof require === 'function') {
  17. // Browserify
  18. factory(require('jquery'));
  19. } else {
  20. // Browser globals
  21. factory(jQuery);
  22. }
  23. }(function ($) {
  24. 'use strict';
  25. var
  26. utils = (function () {
  27. return {
  28. escapeRegExChars: function (value) {
  29. return value.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
  30. },
  31. createNode: function (containerClass) {
  32. var div = document.createElement('div');
  33. div.className = containerClass;
  34. div.style.position = 'absolute';
  35. div.style.display = 'none';
  36. return div;
  37. }
  38. };
  39. }()),
  40. keys = {
  41. ESC: 27,
  42. TAB: 9,
  43. RETURN: 13,
  44. LEFT: 37,
  45. UP: 38,
  46. RIGHT: 39,
  47. DOWN: 40
  48. },
  49. noop = $.noop;
  50. function Autocomplete(el, options) {
  51. var that = this;
  52. // Shared variables:
  53. that.element = el;
  54. that.el = $(el);
  55. that.suggestions = [];
  56. that.badQueries = [];
  57. that.selectedIndex = -1;
  58. that.currentValue = that.element.value;
  59. that.timeoutId = null;
  60. that.cachedResponse = {};
  61. that.onChangeTimeout = null;
  62. that.onChange = null;
  63. that.isLocal = false;
  64. that.suggestionsContainer = null;
  65. that.noSuggestionsContainer = null;
  66. that.options = $.extend(true, {}, Autocomplete.defaults, options);
  67. if (typeof that.options.url !== 'undefined') {
  68. that.options.serviceUrl = that.options.url;
  69. }
  70. that.classes = {
  71. selected: 'autocomplete-selected',
  72. suggestion: 'autocomplete-suggestion'
  73. };
  74. that.hint = null;
  75. that.hintValue = '';
  76. that.selection = null;
  77. // Initialize and set options:
  78. that.initialize();
  79. that.setOptions(options);
  80. }
  81. Autocomplete.utils = utils;
  82. $.Autocomplete = Autocomplete;
  83. Autocomplete.defaults = {
  84. ajaxSettings: {},
  85. autoSelectFirst: false,
  86. appendTo: 'body',
  87. serviceUrl: null,
  88. lookup: null,
  89. onSelect: null,
  90. onHint: null,
  91. width: 'auto',
  92. minChars: 1,
  93. maxHeight: 300,
  94. deferRequestBy: 0,
  95. params: {},
  96. formatResult: _formatResult,
  97. formatGroup: _formatGroup,
  98. delimiter: null,
  99. zIndex: 9999,
  100. type: 'GET',
  101. noCache: false,
  102. onSearchStart: noop,
  103. onSearchComplete: noop,
  104. onSearchError: noop,
  105. preserveInput: false,
  106. containerClass: 'autocomplete-suggestions',
  107. tabDisabled: false,
  108. dataType: 'text',
  109. currentRequest: null,
  110. triggerSelectOnValidInput: true,
  111. preventBadQueries: true,
  112. lookupFilter: _lookupFilter,
  113. paramName: 'query',
  114. transformResult: _transformResult,
  115. showNoSuggestionNotice: false,
  116. noSuggestionNotice: 'No results',
  117. orientation: 'bottom',
  118. forceFixPosition: false
  119. };
  120. function _lookupFilter(suggestion, originalQuery, queryLowerCase) {
  121. return suggestion.value.toLowerCase().indexOf(queryLowerCase) !== -1;
  122. };
  123. function _transformResult(response) {
  124. return typeof response === 'string' ? $.parseJSON(response) : response;
  125. };
  126. function _formatResult(suggestion, currentValue) {
  127. // Do not replace anything if the current value is empty
  128. if (!currentValue) {
  129. return suggestion.value;
  130. }
  131. var pattern = '(' + utils.escapeRegExChars(currentValue) + ')';
  132. return suggestion.value
  133. .replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>')
  134. .replace(/&/g, '&amp;')
  135. .replace(/</g, '&lt;')
  136. .replace(/>/g, '&gt;')
  137. .replace(/"/g, '&quot;')
  138. .replace(/&lt;(\/?strong)&gt;/g, '<$1>');
  139. };
  140. function _formatGroup(suggestion, category) {
  141. return '<div class="autocomplete-group">' + category + '</div>';
  142. };
  143. Autocomplete.prototype = {
  144. initialize: function () {
  145. var that = this,
  146. suggestionSelector = '.' + that.classes.suggestion,
  147. selected = that.classes.selected,
  148. options = that.options,
  149. container;
  150. that.element.setAttribute('autocomplete', 'off');
  151. // html() deals with many types: htmlString or Element or Array or jQuery
  152. that.noSuggestionsContainer = $('<div class="autocomplete-no-suggestion"></div>')
  153. .html(this.options.noSuggestionNotice).get(0);
  154. that.suggestionsContainer = Autocomplete.utils.createNode(options.containerClass);
  155. container = $(that.suggestionsContainer);
  156. container.appendTo(options.appendTo || 'body');
  157. // Only set width if it was provided:
  158. if (options.width !== 'auto') {
  159. container.css('width', options.width);
  160. }
  161. // Listen for mouse over event on suggestions list:
  162. container.on('mouseover.autocomplete', suggestionSelector, function () {
  163. that.activate($(this).data('index'));
  164. });
  165. // Deselect active element when mouse leaves suggestions container:
  166. container.on('mouseout.autocomplete', function () {
  167. that.selectedIndex = -1;
  168. container.children('.' + selected).removeClass(selected);
  169. });
  170. // Listen for click event on suggestions list:
  171. container.on('click.autocomplete', suggestionSelector, function () {
  172. that.select($(this).data('index'));
  173. });
  174. container.on('click.autocomplete', function () {
  175. clearTimeout(that.blurTimeoutId);
  176. });
  177. that.fixPositionCapture = function () {
  178. if (that.visible) {
  179. that.fixPosition();
  180. }
  181. };
  182. $(window).on('resize.autocomplete', that.fixPositionCapture);
  183. that.el.on('keydown.autocomplete', function (e) {
  184. that.onKeyPress(e);
  185. });
  186. that.el.on('keyup.autocomplete', function (e) {
  187. that.onKeyUp(e);
  188. });
  189. that.el.on('blur.autocomplete', function () {
  190. that.onBlur();
  191. });
  192. that.el.on('focus.autocomplete', function () {
  193. that.onFocus();
  194. });
  195. that.el.on('change.autocomplete', function (e) {
  196. that.onKeyUp(e);
  197. });
  198. that.el.on('input.autocomplete', function (e) {
  199. that.onKeyUp(e);
  200. });
  201. },
  202. onFocus: function () {
  203. var that = this;
  204. if (that.disabled) {
  205. return;
  206. }
  207. that.fixPosition();
  208. if (that.el.val().length >= that.options.minChars) {
  209. that.onValueChange();
  210. }
  211. },
  212. onBlur: function () {
  213. var that = this,
  214. options = that.options,
  215. value = that.el.val(),
  216. query = that.getQuery(value);
  217. // If user clicked on a suggestion, hide() will
  218. // be canceled, otherwise close suggestions
  219. that.blurTimeoutId = setTimeout(function () {
  220. that.hide();
  221. if (that.selection && that.currentValue !== query) {
  222. (options.onInvalidateSelection || $.noop).call(that.element);
  223. }
  224. }, 200);
  225. },
  226. abortAjax: function () {
  227. var that = this;
  228. if (that.currentRequest) {
  229. that.currentRequest.abort();
  230. that.currentRequest = null;
  231. }
  232. },
  233. setOptions: function (suppliedOptions) {
  234. var that = this,
  235. options = $.extend({}, that.options, suppliedOptions);
  236. that.isLocal = Array.isArray(options.lookup);
  237. if (that.isLocal) {
  238. options.lookup = that.verifySuggestionsFormat(options.lookup);
  239. }
  240. options.orientation = that.validateOrientation(options.orientation, 'bottom');
  241. // Adjust height, width and z-index:
  242. $(that.suggestionsContainer).css({
  243. 'max-height': options.maxHeight + 'px',
  244. 'width': options.width + 'px',
  245. 'z-index': options.zIndex
  246. });
  247. this.options = options;
  248. },
  249. clearCache: function () {
  250. this.cachedResponse = {};
  251. this.badQueries = [];
  252. },
  253. clear: function () {
  254. this.clearCache();
  255. this.currentValue = '';
  256. this.suggestions = [];
  257. },
  258. disable: function () {
  259. var that = this;
  260. that.disabled = true;
  261. clearTimeout(that.onChangeTimeout);
  262. that.abortAjax();
  263. },
  264. enable: function () {
  265. this.disabled = false;
  266. },
  267. fixPosition: function () {
  268. // Use only when container has already its content
  269. var that = this,
  270. $container = $(that.suggestionsContainer),
  271. containerParent = $container.parent().get(0);
  272. // Fix position automatically when appended to body.
  273. // In other cases force parameter must be given.
  274. if (containerParent !== document.body && !that.options.forceFixPosition) {
  275. return;
  276. }
  277. // Choose orientation
  278. var orientation = that.options.orientation,
  279. containerHeight = $container.outerHeight(),
  280. height = that.el.outerHeight(),
  281. offset = that.el.offset(),
  282. styles = {'top': offset.top, 'left': offset.left};
  283. if (orientation === 'auto') {
  284. var viewPortHeight = $(window).height(),
  285. scrollTop = $(window).scrollTop(),
  286. topOverflow = -scrollTop + offset.top - containerHeight,
  287. bottomOverflow = scrollTop + viewPortHeight - (offset.top + height + containerHeight);
  288. orientation = (Math.max(topOverflow, bottomOverflow) === topOverflow) ? 'top' : 'bottom';
  289. }
  290. if (orientation === 'top') {
  291. styles.top += -containerHeight;
  292. } else {
  293. styles.top += height;
  294. }
  295. // If container is not positioned to body,
  296. // correct its position using offset parent offset
  297. if (containerParent !== document.body) {
  298. var opacity = $container.css('opacity'),
  299. parentOffsetDiff;
  300. if (!that.visible) {
  301. $container.css('opacity', 0).show();
  302. }
  303. parentOffsetDiff = $container.offsetParent().offset();
  304. styles.top -= parentOffsetDiff.top;
  305. styles.top += containerParent.scrollTop;
  306. styles.left -= parentOffsetDiff.left;
  307. if (!that.visible) {
  308. $container.css('opacity', opacity).hide();
  309. }
  310. }
  311. if (that.options.width === 'auto') {
  312. styles.width = that.el.outerWidth() + 'px';
  313. }
  314. $container.css(styles);
  315. },
  316. isCursorAtEnd: function () {
  317. var that = this,
  318. valLength = that.el.val().length,
  319. selectionStart = that.element.selectionStart,
  320. range;
  321. if (typeof selectionStart === 'number') {
  322. return selectionStart === valLength;
  323. }
  324. if (document.selection) {
  325. range = document.selection.createRange();
  326. range.moveStart('character', -valLength);
  327. return valLength === range.text.length;
  328. }
  329. return true;
  330. },
  331. onKeyPress: function (e) {
  332. var that = this;
  333. // If suggestions are hidden and user presses arrow down, display suggestions:
  334. if (!that.disabled && !that.visible && e.which === keys.DOWN && that.currentValue) {
  335. that.suggest();
  336. return;
  337. }
  338. if (that.disabled || !that.visible) {
  339. return;
  340. }
  341. switch (e.which) {
  342. case keys.ESC:
  343. that.el.val(that.currentValue);
  344. that.hide();
  345. break;
  346. case keys.RIGHT:
  347. if (that.hint && that.options.onHint && that.isCursorAtEnd()) {
  348. that.selectHint();
  349. break;
  350. }
  351. return;
  352. case keys.TAB:
  353. if (that.hint && that.options.onHint) {
  354. that.selectHint();
  355. return;
  356. }
  357. if (that.selectedIndex === -1) {
  358. that.hide();
  359. return;
  360. }
  361. that.select(that.selectedIndex);
  362. if (that.options.tabDisabled === false) {
  363. return;
  364. }
  365. break;
  366. case keys.RETURN:
  367. if (that.selectedIndex === -1) {
  368. that.hide();
  369. return;
  370. }
  371. that.select(that.selectedIndex);
  372. break;
  373. case keys.UP:
  374. that.moveUp();
  375. break;
  376. case keys.DOWN:
  377. that.moveDown();
  378. break;
  379. default:
  380. return;
  381. }
  382. // Cancel event if function did not return:
  383. e.stopImmediatePropagation();
  384. e.preventDefault();
  385. },
  386. onKeyUp: function (e) {
  387. var that = this;
  388. if (that.disabled) {
  389. return;
  390. }
  391. switch (e.which) {
  392. case keys.UP:
  393. case keys.DOWN:
  394. return;
  395. }
  396. clearTimeout(that.onChangeTimeout);
  397. if (that.currentValue !== that.el.val()) {
  398. that.findBestHint();
  399. if (that.options.deferRequestBy > 0) {
  400. // Defer lookup in case when value changes very quickly:
  401. that.onChangeTimeout = setTimeout(function () {
  402. that.onValueChange();
  403. }, that.options.deferRequestBy);
  404. } else {
  405. that.onValueChange();
  406. }
  407. }
  408. },
  409. onValueChange: function () {
  410. if (this.ignoreValueChange) {
  411. this.ignoreValueChange = false;
  412. return;
  413. }
  414. var that = this,
  415. options = that.options,
  416. value = that.el.val(),
  417. query = that.getQuery(value);
  418. if (that.selection && that.currentValue !== query) {
  419. that.selection = null;
  420. (options.onInvalidateSelection || $.noop).call(that.element);
  421. }
  422. clearTimeout(that.onChangeTimeout);
  423. that.currentValue = value;
  424. that.selectedIndex = -1;
  425. // Check existing suggestion for the match before proceeding:
  426. if (options.triggerSelectOnValidInput && that.isExactMatch(query)) {
  427. that.select(0);
  428. return;
  429. }
  430. if (query.length < options.minChars) {
  431. that.hide();
  432. } else {
  433. that.getSuggestions(query);
  434. }
  435. },
  436. isExactMatch: function (query) {
  437. var suggestions = this.suggestions;
  438. return (suggestions.length === 1 && suggestions[0].value.toLowerCase() === query.toLowerCase());
  439. },
  440. getQuery: function (value) {
  441. var delimiter = this.options.delimiter,
  442. parts;
  443. if (!delimiter) {
  444. return value;
  445. }
  446. parts = value.split(delimiter);
  447. return $.trim(parts[parts.length - 1]);
  448. },
  449. getSuggestionsLocal: function (query) {
  450. var that = this,
  451. options = that.options,
  452. queryLowerCase = query.toLowerCase(),
  453. filter = options.lookupFilter,
  454. limit = parseInt(options.lookupLimit, 10),
  455. data;
  456. data = {
  457. suggestions: $.grep(options.lookup, function (suggestion) {
  458. return filter(suggestion, query, queryLowerCase);
  459. })
  460. };
  461. if (limit && data.suggestions.length > limit) {
  462. data.suggestions = data.suggestions.slice(0, limit);
  463. }
  464. return data;
  465. },
  466. getSuggestions: function (q) {
  467. var response,
  468. that = this,
  469. options = that.options,
  470. serviceUrl = options.serviceUrl,
  471. params,
  472. cacheKey,
  473. ajaxSettings;
  474. params = options.params;
  475. params = $.isFunction(params) ? params.call(that.element, q) : params;
  476. params[options.paramName] = q;
  477. if (options.onSearchStart.call(that.element, params) === false) {
  478. return;
  479. }
  480. params = options.ignoreParams ? null : params;
  481. if ($.isFunction(options.lookup)) {
  482. options.lookup(q, function (data) {
  483. that.suggestions = data.suggestions;
  484. that.suggest();
  485. options.onSearchComplete.call(that.element, q, data.suggestions);
  486. });
  487. return;
  488. }
  489. if (that.isLocal) {
  490. response = that.getSuggestionsLocal(q);
  491. } else {
  492. if ($.isFunction(serviceUrl)) {
  493. serviceUrl = serviceUrl.call(that.element, q);
  494. }
  495. cacheKey = serviceUrl + '?' + $.param(params || {});
  496. response = that.cachedResponse[cacheKey];
  497. }
  498. if (response && Array.isArray(response.suggestions)) {
  499. that.suggestions = response.suggestions;
  500. that.suggest();
  501. options.onSearchComplete.call(that.element, q, response.suggestions);
  502. } else if (!that.isBadQuery(q)) {
  503. that.abortAjax();
  504. ajaxSettings = {
  505. url: serviceUrl,
  506. data: params,
  507. type: options.type,
  508. dataType: options.dataType
  509. };
  510. $.extend(ajaxSettings, options.ajaxSettings);
  511. that.currentRequest = $.ajax(ajaxSettings).done(function (data) {
  512. var result;
  513. that.currentRequest = null;
  514. result = options.transformResult(data, q);
  515. that.processResponse(result, q, cacheKey);
  516. options.onSearchComplete.call(that.element, q, result.suggestions);
  517. }).fail(function (jqXHR, textStatus, errorThrown) {
  518. options.onSearchError.call(that.element, q, jqXHR, textStatus, errorThrown);
  519. });
  520. } else {
  521. options.onSearchComplete.call(that.element, q, []);
  522. }
  523. },
  524. isBadQuery: function (q) {
  525. if (!this.options.preventBadQueries) {
  526. return false;
  527. }
  528. var badQueries = this.badQueries,
  529. i = badQueries.length;
  530. while (i--) {
  531. if (q.indexOf(badQueries[i]) === 0) {
  532. return true;
  533. }
  534. }
  535. return false;
  536. },
  537. hide: function () {
  538. var that = this,
  539. container = $(that.suggestionsContainer);
  540. if ($.isFunction(that.options.onHide) && that.visible) {
  541. that.options.onHide.call(that.element, container);
  542. }
  543. that.visible = false;
  544. that.selectedIndex = -1;
  545. clearTimeout(that.onChangeTimeout);
  546. $(that.suggestionsContainer).hide();
  547. that.onHint(null);
  548. },
  549. suggest: function () {
  550. if (!this.suggestions.length) {
  551. if (this.options.showNoSuggestionNotice) {
  552. this.noSuggestions();
  553. } else {
  554. this.hide();
  555. }
  556. return;
  557. }
  558. var that = this,
  559. options = that.options,
  560. groupBy = options.groupBy,
  561. formatResult = options.formatResult,
  562. value = that.getQuery(that.currentValue),
  563. className = that.classes.suggestion,
  564. classSelected = that.classes.selected,
  565. container = $(that.suggestionsContainer),
  566. noSuggestionsContainer = $(that.noSuggestionsContainer),
  567. beforeRender = options.beforeRender,
  568. html = '',
  569. category,
  570. formatGroup = function (suggestion, index) {
  571. var currentCategory = suggestion.data[groupBy];
  572. if (category === currentCategory) {
  573. return '';
  574. }
  575. category = currentCategory;
  576. return options.formatGroup(suggestion, category);
  577. };
  578. if (options.triggerSelectOnValidInput && that.isExactMatch(value)) {
  579. that.select(0);
  580. return;
  581. }
  582. // Build suggestions inner HTML:
  583. $.each(that.suggestions, function (i, suggestion) {
  584. if (groupBy) {
  585. html += formatGroup(suggestion, value, i);
  586. }
  587. html += '<div class="' + className + '" data-index="' + i + '">' + formatResult(suggestion, value, i) + '</div>';
  588. });
  589. this.adjustContainerWidth();
  590. noSuggestionsContainer.detach();
  591. container.html(html);
  592. if ($.isFunction(beforeRender)) {
  593. beforeRender.call(that.element, container, that.suggestions);
  594. }
  595. that.fixPosition();
  596. container.show();
  597. // Select first value by default:
  598. if (options.autoSelectFirst) {
  599. that.selectedIndex = 0;
  600. container.scrollTop(0);
  601. container.children('.' + className).first().addClass(classSelected);
  602. }
  603. that.visible = true;
  604. that.findBestHint();
  605. },
  606. noSuggestions: function () {
  607. var that = this,
  608. beforeRender = that.options.beforeRender,
  609. container = $(that.suggestionsContainer),
  610. noSuggestionsContainer = $(that.noSuggestionsContainer);
  611. this.adjustContainerWidth();
  612. // Some explicit steps. Be careful here as it easy to get
  613. // noSuggestionsContainer removed from DOM if not detached properly.
  614. noSuggestionsContainer.detach();
  615. // clean suggestions if any
  616. container.empty();
  617. container.append(noSuggestionsContainer);
  618. if ($.isFunction(beforeRender)) {
  619. beforeRender.call(that.element, container, that.suggestions);
  620. }
  621. that.fixPosition();
  622. container.show();
  623. that.visible = true;
  624. },
  625. adjustContainerWidth: function () {
  626. var that = this,
  627. options = that.options,
  628. width,
  629. container = $(that.suggestionsContainer);
  630. // If width is auto, adjust width before displaying suggestions,
  631. // because if instance was created before input had width, it will be zero.
  632. // Also it adjusts if input width has changed.
  633. if (options.width === 'auto') {
  634. width = that.el.outerWidth();
  635. container.css('width', width > 0 ? width : 300);
  636. } else if (options.width === 'flex') {
  637. // Trust the source! Unset the width property so it will be the max length
  638. // the containing elements.
  639. container.css('width', '');
  640. }
  641. },
  642. findBestHint: function () {
  643. var that = this,
  644. value = that.el.val().toLowerCase(),
  645. bestMatch = null;
  646. if (!value) {
  647. return;
  648. }
  649. $.each(that.suggestions, function (i, suggestion) {
  650. var foundMatch = suggestion.value.toLowerCase().indexOf(value) === 0;
  651. if (foundMatch) {
  652. bestMatch = suggestion;
  653. }
  654. return !foundMatch;
  655. });
  656. that.onHint(bestMatch);
  657. },
  658. onHint: function (suggestion) {
  659. var that = this,
  660. onHintCallback = that.options.onHint,
  661. hintValue = '';
  662. if (suggestion) {
  663. hintValue = that.currentValue + suggestion.value.substr(that.currentValue.length);
  664. }
  665. if (that.hintValue !== hintValue) {
  666. that.hintValue = hintValue;
  667. that.hint = suggestion;
  668. if ($.isFunction(onHintCallback)) {
  669. onHintCallback.call(that.element, hintValue);
  670. }
  671. }
  672. },
  673. verifySuggestionsFormat: function (suggestions) {
  674. // If suggestions is string array, convert them to supported format:
  675. if (suggestions.length && typeof suggestions[0] === 'string') {
  676. return $.map(suggestions, function (value) {
  677. return {value: value, data: null};
  678. });
  679. }
  680. return suggestions;
  681. },
  682. validateOrientation: function (orientation, fallback) {
  683. orientation = $.trim(orientation || '').toLowerCase();
  684. if ($.inArray(orientation, ['auto', 'bottom', 'top']) === -1) {
  685. orientation = fallback;
  686. }
  687. return orientation;
  688. },
  689. processResponse: function (result, originalQuery, cacheKey) {
  690. var that = this,
  691. options = that.options;
  692. result.suggestions = that.verifySuggestionsFormat(result.suggestions);
  693. // Cache results if cache is not disabled:
  694. if (!options.noCache) {
  695. that.cachedResponse[cacheKey] = result;
  696. if (options.preventBadQueries && !result.suggestions.length) {
  697. that.badQueries.push(originalQuery);
  698. }
  699. }
  700. // Return if originalQuery is not matching current query:
  701. if (originalQuery !== that.getQuery(that.currentValue)) {
  702. return;
  703. }
  704. that.suggestions = result.suggestions;
  705. that.suggest();
  706. },
  707. activate: function (index) {
  708. var that = this,
  709. activeItem,
  710. selected = that.classes.selected,
  711. container = $(that.suggestionsContainer),
  712. children = container.find('.' + that.classes.suggestion);
  713. container.find('.' + selected).removeClass(selected);
  714. that.selectedIndex = index;
  715. if (that.selectedIndex !== -1 && children.length > that.selectedIndex) {
  716. activeItem = children.get(that.selectedIndex);
  717. $(activeItem).addClass(selected);
  718. return activeItem;
  719. }
  720. return null;
  721. },
  722. selectHint: function () {
  723. var that = this,
  724. i = $.inArray(that.hint, that.suggestions);
  725. that.select(i);
  726. },
  727. select: function (i) {
  728. var that = this;
  729. that.hide();
  730. that.onSelect(i);
  731. },
  732. moveUp: function () {
  733. var that = this;
  734. if (that.selectedIndex === -1) {
  735. return;
  736. }
  737. if (that.selectedIndex === 0) {
  738. $(that.suggestionsContainer).children('.' + that.classes.suggestion).first().removeClass(that.classes.selected);
  739. that.selectedIndex = -1;
  740. that.ignoreValueChange = false;
  741. that.el.val(that.currentValue);
  742. that.findBestHint();
  743. return;
  744. }
  745. that.adjustScroll(that.selectedIndex - 1);
  746. },
  747. moveDown: function () {
  748. var that = this;
  749. if (that.selectedIndex === (that.suggestions.length - 1)) {
  750. return;
  751. }
  752. that.adjustScroll(that.selectedIndex + 1);
  753. },
  754. adjustScroll: function (index) {
  755. var that = this,
  756. activeItem = that.activate(index);
  757. if (!activeItem) {
  758. return;
  759. }
  760. var offsetTop,
  761. upperBound,
  762. lowerBound,
  763. heightDelta = $(activeItem).outerHeight();
  764. offsetTop = activeItem.offsetTop;
  765. upperBound = $(that.suggestionsContainer).scrollTop();
  766. lowerBound = upperBound + that.options.maxHeight - heightDelta;
  767. if (offsetTop < upperBound) {
  768. $(that.suggestionsContainer).scrollTop(offsetTop);
  769. } else if (offsetTop > lowerBound) {
  770. $(that.suggestionsContainer).scrollTop(offsetTop - that.options.maxHeight + heightDelta);
  771. }
  772. if (!that.options.preserveInput) {
  773. // During onBlur event, browser will trigger "change" event,
  774. // because value has changed, to avoid side effect ignore,
  775. // that event, so that correct suggestion can be selected
  776. // when clicking on suggestion with a mouse
  777. that.ignoreValueChange = true;
  778. that.el.val(that.getValue(that.suggestions[index].value));
  779. }
  780. that.onHint(null);
  781. },
  782. onSelect: function (index) {
  783. var that = this,
  784. onSelectCallback = that.options.onSelect,
  785. suggestion = that.suggestions[index];
  786. that.currentValue = that.getValue(suggestion.value);
  787. if (that.currentValue !== that.el.val() && !that.options.preserveInput) {
  788. that.el.val(that.currentValue);
  789. }
  790. that.onHint(null);
  791. that.suggestions = [];
  792. that.selection = suggestion;
  793. if ($.isFunction(onSelectCallback)) {
  794. onSelectCallback.call(that.element, suggestion);
  795. }
  796. },
  797. getValue: function (value) {
  798. var that = this,
  799. delimiter = that.options.delimiter,
  800. currentValue,
  801. parts;
  802. if (!delimiter) {
  803. return value;
  804. }
  805. currentValue = that.currentValue;
  806. parts = currentValue.split(delimiter);
  807. if (parts.length === 1) {
  808. return value;
  809. }
  810. return currentValue.substr(0, currentValue.length - parts[parts.length - 1].length) + value;
  811. },
  812. dispose: function () {
  813. var that = this;
  814. that.el.off('.autocomplete').removeData('autocomplete');
  815. $(window).off('resize.autocomplete', that.fixPositionCapture);
  816. $(that.suggestionsContainer).remove();
  817. }
  818. };
  819. // Create chainable jQuery plugin:
  820. $.fn.devbridgeAutocomplete = function (options, args) {
  821. var dataKey = 'autocomplete';
  822. var results = [];
  823. this.each(function () {
  824. var inputElement = $(this),
  825. instance = inputElement.data(dataKey);
  826. if (typeof options === 'string') {
  827. if (instance && typeof instance[options] === 'function') {
  828. var retVal = instance[options](args);
  829. results.push(retVal);
  830. }
  831. } else {
  832. // If instance already exists, destroy it:
  833. // if (instance && instance.dispose) {
  834. // instance.dispose();
  835. // }
  836. if (!instance) {
  837. instance = new Autocomplete(this, $.extend(true, {}, options, $(this).data('autocomplete-options') || {}));
  838. inputElement.data(dataKey, instance);
  839. }
  840. results.push(instance);
  841. }
  842. });
  843. return results.length > 1 ? results : results[0];
  844. };
  845. // Don't overwrite if it already exists
  846. if (!$.fn.autocomplete) {
  847. $.fn.autocomplete = $.fn.devbridgeAutocomplete;
  848. }
  849. }));