PageRenderTime 26ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/jquery/jquery.autocomlete.js

https://bitbucket.org/seyar/kinda.local
JavaScript | 541 lines | 423 code | 67 blank | 51 comment | 125 complexity | 6ab78801a43665af6c3bffc5ada2c915 MD5 | raw file
  1. jQuery.autocomplete = function(input, options) {
  2. // Create a link to self
  3. var me = this;
  4. // Create jQuery object for input element
  5. var $input = $(input).attr("autocomplete", "off");
  6. // Apply inputClass if necessary
  7. if (options.inputClass) {
  8. $input.addClass(options.inputClass);
  9. }
  10. // Create results
  11. var results = document.createElement("div");
  12. // Create jQuery object for results
  13. // var $results = $(results);
  14. var $results = $(results).hide().addClass(options.resultsClass).css("position", "absolute");
  15. if( options.width > 0 ) {
  16. $results.css("width", options.width);
  17. }
  18. // Add to body element
  19. $("body").append(results);
  20. input.autocompleter = me;
  21. var timeout = null;
  22. var prev = "";
  23. var active = -1;
  24. var cache = {};
  25. var keyb = false;
  26. var hasFocus = false;
  27. var lastKeyPressCode = null;
  28. var mouseDownOnSelect = false;
  29. var hidingResults = false;
  30. // flush cache
  31. function flushCache(){
  32. cache = {};
  33. cache.data = {};
  34. cache.length = 0;
  35. };
  36. // flush cache
  37. flushCache();
  38. // if there is a data array supplied
  39. if( options.data != null ){
  40. var sFirstChar = "", stMatchSets = {}, row = [];
  41. // no url was specified, we need to adjust the cache length to make sure it fits the local data store
  42. if( typeof options.url != "string" ) {
  43. options.cacheLength = 1;
  44. }
  45. // loop through the array and create a lookup structure
  46. for( var i=0; i < options.data.length; i++ ){
  47. // if row is a string, make an array otherwise just reference the array
  48. row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);
  49. // if the length is zero, don't add to list
  50. if( row[0].length > 0 ){
  51. // get the first character
  52. sFirstChar = row[0].substring(0, 1).toLowerCase();
  53. // if no lookup array for this character exists, look it up now
  54. if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
  55. // if the match is a string
  56. stMatchSets[sFirstChar].push(row);
  57. }
  58. }
  59. // add the data items to the cache
  60. for( var k in stMatchSets ) {
  61. // increase the cache size
  62. options.cacheLength++;
  63. // add to the cache
  64. addToCache(k, stMatchSets[k]);
  65. }
  66. }
  67. $input
  68. .keydown(function(e) {
  69. // track last key pressed
  70. lastKeyPressCode = e.keyCode;
  71. switch(e.keyCode) {
  72. case 38: // up
  73. e.preventDefault();
  74. moveSelect(-1);
  75. break;
  76. case 40: // down
  77. e.preventDefault();
  78. moveSelect(1);
  79. break;
  80. case 9: // tab
  81. case 13: // return
  82. if( selectCurrent() ){
  83. // make sure to blur off the current field
  84. $input.get(0).blur();
  85. e.preventDefault();
  86. }
  87. break;
  88. default:
  89. active = -1;
  90. if (timeout) clearTimeout(timeout);
  91. timeout = setTimeout(function(){onChange();}, options.delay);
  92. break;
  93. }
  94. })
  95. .focus(function(){
  96. // track whether the field has focus, we shouldn't process any results if the field no longer has focus
  97. hasFocus = true;
  98. })
  99. .blur(function() {
  100. // track whether the field has focus
  101. hasFocus = false;
  102. if (!mouseDownOnSelect) {
  103. hideResults();
  104. }
  105. });
  106. hideResultsNow();
  107. function onChange() {
  108. // ignore if the following keys are pressed: [del] [shift] [capslock]
  109. if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
  110. var v = $input.val();
  111. if (v == prev) return;
  112. prev = v;
  113. if (v.length >= options.minChars) {
  114. $input.addClass(options.loadingClass);
  115. requestData(v);
  116. } else {
  117. $input.removeClass(options.loadingClass);
  118. $results.hide();
  119. }
  120. };
  121. function moveSelect(step) {
  122. var lis = $("li", results);
  123. if (!lis) return;
  124. active += step;
  125. if (active < 0) {
  126. active = 0;
  127. } else if (active >= lis.size()) {
  128. active = lis.size() - 1;
  129. }
  130. lis.removeClass("ac_over");
  131. $(lis[active]).addClass("ac_over");
  132. // Weird behaviour in IE
  133. // if (lis[active] && lis[active].scrollIntoView) {
  134. // lis[active].scrollIntoView(false);
  135. // }
  136. };
  137. function selectCurrent() {
  138. var li = $("li.ac_over", results)[0];
  139. if (!li) {
  140. var $li = $("li", results);
  141. if (options.selectOnly) {
  142. if ($li.length == 1) li = $li[0];
  143. } else if (options.selectFirst) {
  144. li = $li[0];
  145. }
  146. }
  147. if (li) {
  148. selectItem(li);
  149. return true;
  150. } else {
  151. return false;
  152. }
  153. };
  154. function selectItem(li) {
  155. if (!li) {
  156. li = document.createElement("li");
  157. li.extra = [];
  158. li.selectValue = "";
  159. }
  160. var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
  161. input.lastSelected = v;
  162. prev = v;
  163. $results.html("");
  164. $input.val(v);
  165. hideResultsNow();
  166. if (options.onItemSelect) {
  167. setTimeout(function() { options.onItemSelect(li) }, 1);
  168. }
  169. };
  170. // selects a portion of the input string
  171. function createSelection(start, end){
  172. // get a reference to the input element
  173. var field = $input.get(0);
  174. if( field.createTextRange ){
  175. var selRange = field.createTextRange();
  176. selRange.collapse(true);
  177. selRange.moveStart("character", start);
  178. selRange.moveEnd("character", end);
  179. selRange.select();
  180. } else if( field.setSelectionRange ){
  181. field.setSelectionRange(start, end);
  182. } else {
  183. if( field.selectionStart ){
  184. field.selectionStart = start;
  185. field.selectionEnd = end;
  186. }
  187. }
  188. field.focus();
  189. };
  190. // fills in the input box w/the first match (assumed to be the best match)
  191. function autoFill(sValue){
  192. // if the last user key pressed was backspace, don't autofill
  193. if( lastKeyPressCode != 8 ){
  194. // fill in the value (keep the case the user has typed)
  195. $input.val($input.val() + sValue.substring(prev.length));
  196. // select the portion of the value not typed by the user (so the next character will erase)
  197. createSelection(prev.length, sValue.length);
  198. }
  199. };
  200. function showResults() {
  201. // get the position of the input field right now (in case the DOM is shifted)
  202. var pos = findPos(input);
  203. // either use the specified width, or autocalculate based on form element
  204. var iWidth = (options.width > 0) ? options.width : $input.width();
  205. // reposition
  206. $results.css({
  207. width: parseInt(iWidth) + "px",
  208. top: (pos.y + input.offsetHeight) + "px",
  209. left: pos.x + "px"
  210. }).show();
  211. };
  212. function hideResults() {
  213. if (timeout) clearTimeout(timeout);
  214. timeout = setTimeout(hideResultsNow, 200);
  215. };
  216. function hideResultsNow() {
  217. if (hidingResults) {
  218. return;
  219. }
  220. hidingResults = true;
  221. if (timeout) {
  222. clearTimeout(timeout);
  223. }
  224. var v = $input.removeClass(options.loadingClass).val();
  225. if ($results.is(":visible")) {
  226. $results.hide();
  227. }
  228. if (options.mustMatch) {
  229. if (!input.lastSelected || input.lastSelected != v) {
  230. selectItem(null);
  231. }
  232. }
  233. hidingResults = false;
  234. };
  235. function receiveData(q, data) {
  236. if (data) {
  237. $input.removeClass(options.loadingClass);
  238. results.innerHTML = "";
  239. // if the field no longer has focus or if there are no matches, do not display the drop down
  240. if( !hasFocus || data.length == 0 ) return hideResultsNow();
  241. if ($.browser.msie) {
  242. // we put a styled iframe behind the calendar so HTML SELECT elements don't show through
  243. $results.append(document.createElement('iframe'));
  244. }
  245. results.appendChild(dataToDom(data));
  246. // autofill in the complete box w/the first match as long as the user hasn't entered in more data
  247. if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
  248. showResults();
  249. } else {
  250. hideResultsNow();
  251. }
  252. };
  253. function parseData(data) {
  254. if (!data) return null;
  255. var parsed = [];
  256. var rows = data.split(options.lineSeparator);
  257. for (var i=0; i < rows.length; i++) {
  258. var row = $.trim(rows[i]);
  259. if (row) {
  260. parsed[parsed.length] = row.split(options.cellSeparator);
  261. }
  262. }
  263. return parsed;
  264. };
  265. function dataToDom(data) {
  266. var ul = document.createElement("ul");
  267. var num = data.length;
  268. // limited results to a max number
  269. if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;
  270. for (var i=0; i < num; i++) {
  271. var row = data[i];
  272. if (!row) continue;
  273. var li = document.createElement("li");
  274. if (options.formatItem) {
  275. li.innerHTML = options.formatItem(row, i, num);
  276. li.selectValue = row[0];
  277. } else {
  278. li.innerHTML = row[0];
  279. li.selectValue = row[0];
  280. }
  281. var extra = null;
  282. if (row.length > 1) {
  283. extra = [];
  284. for (var j=1; j < row.length; j++) {
  285. extra[extra.length] = row[j];
  286. }
  287. }
  288. li.extra = extra;
  289. ul.appendChild(li);
  290. $(li).hover(
  291. function() { $("li", ul).removeClass("ac_over"); $(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); },
  292. function() { $(this).removeClass("ac_over"); }
  293. ).click(function(e) {
  294. e.preventDefault();
  295. e.stopPropagation();
  296. selectItem(this)
  297. });
  298. }
  299. $(ul).mousedown(function() {
  300. mouseDownOnSelect = true;
  301. }).mouseup(function() {
  302. mouseDownOnSelect = false;
  303. });
  304. return ul;
  305. };
  306. function requestData(q) {
  307. if (!options.matchCase) q = q.toLowerCase();
  308. var data = options.cacheLength ? loadFromCache(q) : null;
  309. // recieve the cached data
  310. if (data) {
  311. receiveData(q, data);
  312. // if an AJAX url has been supplied, try loading the data now
  313. } else if( (typeof options.url == "string") && (options.url.length > 0) ){
  314. $.get(makeUrl(q), function(data) {
  315. data = parseData(data);
  316. addToCache(q, data);
  317. receiveData(q, data);
  318. });
  319. // if there's been no data found, remove the loading class
  320. } else {
  321. $input.removeClass(options.loadingClass);
  322. }
  323. };
  324. function makeUrl(q) {
  325. var sep = options.url.indexOf('?') == -1 ? '?' : '&';
  326. var url = options.url + sep + "q=" + encodeURI(q);
  327. for (var i in options.extraParams) {
  328. url += "&" + i + "=" + encodeURI(options.extraParams[i]);
  329. }
  330. return url;
  331. };
  332. function loadFromCache(q) {
  333. if (!q) return null;
  334. if (cache.data[q]) return cache.data[q];
  335. if (options.matchSubset) {
  336. for (var i = q.length - 1; i >= options.minChars; i--) {
  337. var qs = q.substr(0, i);
  338. var c = cache.data[qs];
  339. if (c) {
  340. var csub = [];
  341. for (var j = 0; j < c.length; j++) {
  342. var x = c[j];
  343. var x0 = x[0];
  344. if (matchSubset(x0, q)) {
  345. csub[csub.length] = x;
  346. }
  347. }
  348. return csub;
  349. }
  350. }
  351. }
  352. return null;
  353. };
  354. function matchSubset(s, sub) {
  355. if (!options.matchCase) s = s.toLowerCase();
  356. var i = s.indexOf(sub);
  357. if (i == -1) return false;
  358. return i == 0 || options.matchContains;
  359. };
  360. this.flushCache = function() {
  361. flushCache();
  362. };
  363. this.setExtraParams = function(p) {
  364. options.extraParams = p;
  365. };
  366. this.findValue = function(){
  367. var q = $input.val();
  368. if (!options.matchCase) q = q.toLowerCase();
  369. var data = options.cacheLength ? loadFromCache(q) : null;
  370. if (data) {
  371. findValueCallback(q, data);
  372. } else if( (typeof options.url == "string") && (options.url.length > 0) ){
  373. $.get(makeUrl(q), function(data) {
  374. data = parseData(data)
  375. addToCache(q, data);
  376. findValueCallback(q, data);
  377. });
  378. } else {
  379. // no matches
  380. findValueCallback(q, null);
  381. }
  382. }
  383. function findValueCallback(q, data){
  384. if (data) $input.removeClass(options.loadingClass);
  385. var num = (data) ? data.length : 0;
  386. var li = null;
  387. for (var i=0; i < num; i++) {
  388. var row = data[i];
  389. if( row[0].toLowerCase() == q.toLowerCase() ){
  390. li = document.createElement("li");
  391. if (options.formatItem) {
  392. li.innerHTML = options.formatItem(row, i, num);
  393. li.selectValue = row[0];
  394. } else {
  395. li.innerHTML = row[0];
  396. li.selectValue = row[0];
  397. }
  398. var extra = null;
  399. if( row.length > 1 ){
  400. extra = [];
  401. for (var j=1; j < row.length; j++) {
  402. extra[extra.length] = row[j];
  403. }
  404. }
  405. li.extra = extra;
  406. }
  407. }
  408. if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
  409. }
  410. function addToCache(q, data) {
  411. if (!data || !q || !options.cacheLength) return;
  412. if (!cache.length || cache.length > options.cacheLength) {
  413. flushCache();
  414. cache.length++;
  415. } else if (!cache[q]) {
  416. cache.length++;
  417. }
  418. cache.data[q] = data;
  419. };
  420. function findPos(obj) {
  421. var curleft = obj.offsetLeft || 0;
  422. var curtop = obj.offsetTop || 0;
  423. while (obj = obj.offsetParent) {
  424. curleft += obj.offsetLeft
  425. curtop += obj.offsetTop
  426. }
  427. return {x:curleft,y:curtop};
  428. }
  429. }
  430. jQuery.fn.autocomplete = function(url, options, data) {
  431. // Make sure options exists
  432. options = options || {};
  433. // Set url as option
  434. options.url = url;
  435. // set some bulk local data
  436. options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;
  437. // Set default values for required options
  438. options = $.extend({
  439. inputClass: "ac_input",
  440. resultsClass: "ac_results",
  441. lineSeparator: "\n",
  442. cellSeparator: "|",
  443. minChars: 1,
  444. delay: 400,
  445. matchCase: 0,
  446. matchSubset: 1,
  447. matchContains: 0,
  448. cacheLength: 1,
  449. mustMatch: 0,
  450. extraParams: {},
  451. loadingClass: "ac_loading",
  452. selectFirst: false,
  453. selectOnly: false,
  454. maxItemsToShow: -1,
  455. autoFill: false,
  456. width: 0
  457. }, options);
  458. options.width = parseInt(options.width, 10);
  459. this.each(function() {
  460. var input = this;
  461. new jQuery.autocomplete(input, options);
  462. });
  463. // Don't break the chain
  464. return this;
  465. }
  466. jQuery.fn.autocompleteArray = function(data, options) {
  467. return this.autocomplete(null, options, data);
  468. }
  469. jQuery.fn.indexOf = function(e){
  470. for( var i=0; i<this.length; i++ ){
  471. if( this[i] == e ) return i;
  472. }
  473. return -1;
  474. };