jquery.autocomplete.js 33 KB

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