jquery.autocomplete.js 33 KB

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