typeahead.js 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. /*!
  2. * typeahead.js 0.9.0
  3. * https://github.com/twitter/typeahead
  4. * Copyright 2013 Twitter, Inc. and other contributors; Licensed MIT
  5. */
  6. (function($) {
  7. var VERSION = "0.9.0";
  8. var utils = {
  9. isMsie: function() {
  10. var match = /(msie) ([\w.]+)/i.exec(navigator.userAgent);
  11. return match ? parseInt(match[2], 10) : false;
  12. },
  13. isBlankString: function(str) {
  14. return !str || /^\s*$/.test(str);
  15. },
  16. escapeRegExChars: function(str) {
  17. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18. },
  19. isString: function(obj) {
  20. return typeof obj === "string";
  21. },
  22. isNumber: function(obj) {
  23. return typeof obj === "number";
  24. },
  25. isArray: $.isArray,
  26. isFunction: $.isFunction,
  27. isObject: $.isPlainObject,
  28. isUndefined: function(obj) {
  29. return typeof obj === "undefined";
  30. },
  31. bind: $.proxy,
  32. bindAll: function(obj) {
  33. var val;
  34. for (var key in obj) {
  35. $.isFunction(val = obj[key]) && (obj[key] = $.proxy(val, obj));
  36. }
  37. },
  38. indexOf: function(haystack, needle) {
  39. for (var i = 0; i < haystack.length; i++) {
  40. if (haystack[i] === needle) {
  41. return i;
  42. }
  43. }
  44. return -1;
  45. },
  46. each: $.each,
  47. map: $.map,
  48. filter: $.grep,
  49. every: function(obj, test) {
  50. var result = true;
  51. if (!obj) {
  52. return result;
  53. }
  54. $.each(obj, function(key, val) {
  55. if (!(result = test.call(null, val, key, obj))) {
  56. return false;
  57. }
  58. });
  59. return !!result;
  60. },
  61. some: function(obj, test) {
  62. var result = false;
  63. if (!obj) {
  64. return result;
  65. }
  66. $.each(obj, function(key, val) {
  67. if (result = test.call(null, val, key, obj)) {
  68. return false;
  69. }
  70. });
  71. return !!result;
  72. },
  73. mixin: $.extend,
  74. getUniqueId: function() {
  75. var counter = 0;
  76. return function() {
  77. return counter++;
  78. };
  79. }(),
  80. defer: function(fn) {
  81. setTimeout(fn, 0);
  82. },
  83. debounce: function(func, wait, immediate) {
  84. var timeout, result;
  85. return function() {
  86. var context = this, args = arguments, later, callNow;
  87. later = function() {
  88. timeout = null;
  89. if (!immediate) {
  90. result = func.apply(context, args);
  91. }
  92. };
  93. callNow = immediate && !timeout;
  94. clearTimeout(timeout);
  95. timeout = setTimeout(later, wait);
  96. if (callNow) {
  97. result = func.apply(context, args);
  98. }
  99. return result;
  100. };
  101. },
  102. throttle: function(func, wait) {
  103. var context, args, timeout, result, previous, later;
  104. previous = 0;
  105. later = function() {
  106. previous = new Date();
  107. timeout = null;
  108. result = func.apply(context, args);
  109. };
  110. return function() {
  111. var now = new Date(), remaining = wait - (now - previous);
  112. context = this;
  113. args = arguments;
  114. if (remaining <= 0) {
  115. clearTimeout(timeout);
  116. timeout = null;
  117. previous = now;
  118. result = func.apply(context, args);
  119. } else if (!timeout) {
  120. timeout = setTimeout(later, remaining);
  121. }
  122. return result;
  123. };
  124. },
  125. tokenizeQuery: function(str) {
  126. return $.trim(str).toLowerCase().split(/[\s]+/);
  127. },
  128. tokenizeText: function(str) {
  129. return $.trim(str).toLowerCase().split(/[\s\-_]+/);
  130. },
  131. getProtocol: function() {
  132. return location.protocol;
  133. },
  134. noop: function() {}
  135. };
  136. var EventTarget = function() {
  137. var eventSplitter = /\s+/;
  138. return {
  139. on: function(events, callback) {
  140. var event;
  141. if (!callback) {
  142. return this;
  143. }
  144. this._callbacks = this._callbacks || {};
  145. events = events.split(eventSplitter);
  146. while (event = events.shift()) {
  147. this._callbacks[event] = this._callbacks[event] || [];
  148. this._callbacks[event].push(callback);
  149. }
  150. return this;
  151. },
  152. trigger: function(events, data) {
  153. var event, callbacks;
  154. if (!this._callbacks) {
  155. return this;
  156. }
  157. events = events.split(eventSplitter);
  158. while (event = events.shift()) {
  159. if (callbacks = this._callbacks[event]) {
  160. for (var i = 0; i < callbacks.length; i += 1) {
  161. callbacks[i].call(this, {
  162. type: event,
  163. data: data
  164. });
  165. }
  166. }
  167. }
  168. return this;
  169. }
  170. };
  171. }();
  172. var EventBus = function() {
  173. var namespace = "typeahead:";
  174. function EventBus(o) {
  175. if (!o || !o.el) {
  176. $.error("EventBus initialized without el");
  177. }
  178. this.$el = $(o.el);
  179. }
  180. utils.mixin(EventBus.prototype, {
  181. trigger: function(type) {
  182. var args = [].slice.call(arguments, 1);
  183. this.$el.trigger(namespace + type, args);
  184. }
  185. });
  186. return EventBus;
  187. }();
  188. var PersistentStorage = function() {
  189. var ls = window.localStorage, methods;
  190. function PersistentStorage(namespace) {
  191. this.prefix = [ "__", namespace, "__" ].join("");
  192. this.ttlKey = "__ttl__";
  193. this.keyMatcher = new RegExp("^" + this.prefix);
  194. }
  195. if (window.localStorage && window.JSON) {
  196. methods = {
  197. _prefix: function(key) {
  198. return this.prefix + key;
  199. },
  200. _ttlKey: function(key) {
  201. return this._prefix(key) + this.ttlKey;
  202. },
  203. get: function(key) {
  204. if (this.isExpired(key)) {
  205. this.remove(key);
  206. }
  207. return decode(ls.getItem(this._prefix(key)));
  208. },
  209. set: function(key, val, ttl) {
  210. if (utils.isNumber(ttl)) {
  211. ls.setItem(this._ttlKey(key), encode(now() + ttl));
  212. } else {
  213. ls.removeItem(this._ttlKey(key));
  214. }
  215. return ls.setItem(this._prefix(key), encode(val));
  216. },
  217. remove: function(key) {
  218. ls.removeItem(this._ttlKey(key));
  219. ls.removeItem(this._prefix(key));
  220. return this;
  221. },
  222. clear: function() {
  223. var i, key, keys = [], len = ls.length;
  224. for (i = 0; i < len; i++) {
  225. if ((key = ls.key(i)).match(this.keyMatcher)) {
  226. keys.push(key.replace(this.keyMatcher, ""));
  227. }
  228. }
  229. for (i = keys.length; i--; ) {
  230. this.remove(keys[i]);
  231. }
  232. return this;
  233. },
  234. isExpired: function(key) {
  235. var ttl = decode(ls.getItem(this._ttlKey(key)));
  236. return utils.isNumber(ttl) && now() > ttl ? true : false;
  237. }
  238. };
  239. } else {
  240. methods = {
  241. get: utils.noop,
  242. set: utils.noop,
  243. remove: utils.noop,
  244. clear: utils.noop,
  245. isExpired: utils.noop
  246. };
  247. }
  248. utils.mixin(PersistentStorage.prototype, methods);
  249. return PersistentStorage;
  250. function now() {
  251. return new Date().getTime();
  252. }
  253. function encode(val) {
  254. return JSON.stringify(utils.isUndefined(val) ? null : val);
  255. }
  256. function decode(val) {
  257. return JSON.parse(val);
  258. }
  259. }();
  260. var RequestCache = function() {
  261. function RequestCache(o) {
  262. utils.bindAll(this);
  263. o = o || {};
  264. this.sizeLimit = o.sizeLimit || 10;
  265. this.cache = {};
  266. this.cachedKeysByAge = [];
  267. }
  268. utils.mixin(RequestCache.prototype, {
  269. get: function(url) {
  270. return this.cache[url];
  271. },
  272. set: function(url, resp) {
  273. var requestToEvict;
  274. if (this.cachedKeysByAge.length === this.sizeLimit) {
  275. requestToEvict = this.cachedKeysByAge.shift();
  276. delete this.cache[requestToEvict];
  277. }
  278. this.cache[url] = resp;
  279. this.cachedKeysByAge.push(url);
  280. }
  281. });
  282. return RequestCache;
  283. }();
  284. var Transport = function() {
  285. var pendingRequests = 0, maxParallelRequests, requestCache;
  286. function Transport(o) {
  287. utils.bindAll(this);
  288. o = utils.isString(o) ? {
  289. url: o
  290. } : o;
  291. requestCache = requestCache || new RequestCache();
  292. maxParallelRequests = utils.isNumber(o.maxParallelRequests) ? o.maxParallelRequests : maxParallelRequests || 6;
  293. this.url = o.url;
  294. this.wildcard = o.wildcard || "%QUERY";
  295. this.filter = o.filter;
  296. this.replace = o.replace;
  297. this.ajaxSettings = {
  298. type: "get",
  299. cache: o.cache,
  300. timeout: o.timeout,
  301. dataType: o.dataType || "json",
  302. beforeSend: o.beforeSend
  303. };
  304. this.get = (/^throttle$/i.test(o.rateLimitFn) ? utils.throttle : utils.debounce)(this.get, o.rateLimitWait || 300);
  305. }
  306. utils.mixin(Transport.prototype, {
  307. get: function(query, cb) {
  308. var that = this, encodedQuery = encodeURIComponent(query || ""), url, resp;
  309. url = this.replace ? this.replace(this.url, encodedQuery) : this.url.replace(this.wildcard, encodedQuery);
  310. if (resp = requestCache.get(url)) {
  311. cb && cb(resp);
  312. } else if (belowPendingRequestsThreshold()) {
  313. incrementPendingRequests();
  314. $.ajax(url, this.ajaxSettings).done(done).always(always);
  315. } else {
  316. this.onDeckRequestArgs = [].slice.call(arguments, 0);
  317. }
  318. function done(resp) {
  319. resp = that.filter ? that.filter(resp) : resp;
  320. cb && cb(resp);
  321. requestCache.set(url, resp);
  322. }
  323. function always() {
  324. decrementPendingRequests();
  325. if (that.onDeckRequestArgs) {
  326. that.get.apply(that, that.onDeckRequestArgs);
  327. that.onDeckRequestArgs = null;
  328. }
  329. }
  330. }
  331. });
  332. return Transport;
  333. function incrementPendingRequests() {
  334. pendingRequests++;
  335. }
  336. function decrementPendingRequests() {
  337. pendingRequests--;
  338. }
  339. function belowPendingRequestsThreshold() {
  340. return pendingRequests < maxParallelRequests;
  341. }
  342. }();
  343. var Dataset = function() {
  344. function Dataset(o) {
  345. utils.bindAll(this);
  346. if (o.template && !o.engine) {
  347. $.error("no template engine specified");
  348. }
  349. if (!o.local && !o.prefetch && !o.remote) {
  350. $.error("one of local, prefetch, or remote is requried");
  351. }
  352. this.name = o.name || utils.getUniqueId();
  353. this.limit = o.limit || 5;
  354. this.header = o.header;
  355. this.footer = o.footer;
  356. this.valueKey = o.valueKey || "value";
  357. this.template = compileTemplate(o.template, o.engine, this.valueKey);
  358. this.local = o.local;
  359. this.prefetch = o.prefetch;
  360. this.remote = o.remote;
  361. this.keys = {
  362. version: "version",
  363. protocol: "protocol",
  364. itemHash: "itemHash",
  365. adjacencyList: "adjacencyList"
  366. };
  367. this.itemHash = {};
  368. this.adjacencyList = {};
  369. this.storage = o.name ? new PersistentStorage(o.name) : null;
  370. }
  371. utils.mixin(Dataset.prototype, {
  372. _processLocalData: function(data) {
  373. this._mergeProcessedData(this._processData(data));
  374. },
  375. _loadPrefetchData: function(o) {
  376. var that = this, deferred, version, protocol, itemHash, adjacencyList, isExpired;
  377. if (this.storage) {
  378. version = this.storage.get(this.keys.version);
  379. protocol = this.storage.get(this.keys.protocol);
  380. itemHash = this.storage.get(this.keys.itemHash);
  381. adjacencyList = this.storage.get(this.keys.adjacencyList);
  382. isExpired = version !== VERSION || protocol !== utils.getProtocol();
  383. }
  384. o = utils.isString(o) ? {
  385. url: o
  386. } : o;
  387. o.ttl = utils.isNumber(o.ttl) ? o.ttl : 24 * 60 * 60 * 1e3;
  388. if (itemHash && adjacencyList && !isExpired) {
  389. this._mergeProcessedData({
  390. itemHash: itemHash,
  391. adjacencyList: adjacencyList
  392. });
  393. deferred = $.Deferred().resolve();
  394. } else {
  395. deferred = $.getJSON(o.url).done(processPrefetchData);
  396. }
  397. return deferred;
  398. function processPrefetchData(data) {
  399. var filteredData = o.filter ? o.filter(data) : data, processedData = that._processData(filteredData), itemHash = processedData.itemHash, adjacencyList = processedData.adjacencyList;
  400. if (that.storage) {
  401. that.storage.set(that.keys.itemHash, itemHash, o.ttl);
  402. that.storage.set(that.keys.adjacencyList, adjacencyList, o.ttl);
  403. that.storage.set(that.keys.version, VERSION, o.ttl);
  404. that.storage.set(that.keys.protocol, utils.getProtocol(), o.ttl);
  405. }
  406. that._mergeProcessedData(processedData);
  407. }
  408. },
  409. _transformDatum: function(datum) {
  410. var value = utils.isString(datum) ? datum : datum[this.valueKey], tokens = datum.tokens || utils.tokenizeText(value), item = {
  411. value: value,
  412. tokens: tokens
  413. };
  414. if (utils.isString(datum)) {
  415. item.datum = {};
  416. item.datum[this.valueKey] = datum;
  417. } else {
  418. item.datum = datum;
  419. }
  420. item.tokens = utils.filter(item.tokens, function(token) {
  421. return !utils.isBlankString(token);
  422. });
  423. item.tokens = utils.map(item.tokens, function(token) {
  424. return token.toLowerCase();
  425. });
  426. return item;
  427. },
  428. _processData: function(data) {
  429. var that = this, itemHash = {}, adjacencyList = {};
  430. utils.each(data, function(i, datum) {
  431. var item = that._transformDatum(datum), id = utils.getUniqueId(item.value);
  432. itemHash[id] = item;
  433. utils.each(item.tokens, function(i, token) {
  434. var character = token.charAt(0), adjacency = adjacencyList[character] || (adjacencyList[character] = [ id ]);
  435. !~utils.indexOf(adjacency, id) && adjacency.push(id);
  436. });
  437. });
  438. return {
  439. itemHash: itemHash,
  440. adjacencyList: adjacencyList
  441. };
  442. },
  443. _mergeProcessedData: function(processedData) {
  444. var that = this;
  445. utils.mixin(this.itemHash, processedData.itemHash);
  446. utils.each(processedData.adjacencyList, function(character, adjacency) {
  447. var masterAdjacency = that.adjacencyList[character];
  448. that.adjacencyList[character] = masterAdjacency ? masterAdjacency.concat(adjacency) : adjacency;
  449. });
  450. },
  451. _getLocalSuggestions: function(terms) {
  452. var that = this, firstChars = [], lists = [], shortestList, suggestions = [];
  453. utils.each(terms, function(i, term) {
  454. var firstChar = term.charAt(0);
  455. !~utils.indexOf(firstChars, firstChar) && firstChars.push(firstChar);
  456. });
  457. utils.each(firstChars, function(i, firstChar) {
  458. var list = that.adjacencyList[firstChar];
  459. if (!list) {
  460. return false;
  461. }
  462. lists.push(list);
  463. if (!shortestList || list.length < shortestList.length) {
  464. shortestList = list;
  465. }
  466. });
  467. if (lists.length < firstChars.length) {
  468. return [];
  469. }
  470. utils.each(shortestList, function(i, id) {
  471. var item = that.itemHash[id], isCandidate, isMatch;
  472. isCandidate = utils.every(lists, function(list) {
  473. return ~utils.indexOf(list, id);
  474. });
  475. isMatch = isCandidate && utils.every(terms, function(term) {
  476. return utils.some(item.tokens, function(token) {
  477. return token.indexOf(term) === 0;
  478. });
  479. });
  480. isMatch && suggestions.push(item);
  481. });
  482. return suggestions;
  483. },
  484. initialize: function() {
  485. var deferred;
  486. this.local && this._processLocalData(this.local);
  487. this.transport = this.remote ? new Transport(this.remote) : null;
  488. deferred = this.prefetch ? this._loadPrefetchData(this.prefetch) : $.Deferred().resolve();
  489. this.local = this.prefetch = this.remote = null;
  490. this.initialize = function() {
  491. return deferred;
  492. };
  493. return deferred;
  494. },
  495. getSuggestions: function(query, cb) {
  496. var that = this, terms = utils.tokenizeQuery(query), suggestions = this._getLocalSuggestions(terms).slice(0, this.limit);
  497. cb && cb(suggestions);
  498. if (suggestions.length < this.limit && this.transport) {
  499. this.transport.get(query, processRemoteData);
  500. }
  501. function processRemoteData(data) {
  502. suggestions = suggestions.slice(0);
  503. utils.each(data, function(i, datum) {
  504. var item = that._transformDatum(datum), isDuplicate;
  505. isDuplicate = utils.some(suggestions, function(suggestion) {
  506. return item.value === suggestion.value;
  507. });
  508. !isDuplicate && suggestions.push(item);
  509. return suggestions.length < that.limit;
  510. });
  511. cb && cb(suggestions);
  512. }
  513. }
  514. });
  515. return Dataset;
  516. function compileTemplate(template, engine, valueKey) {
  517. var wrapper = '<div class="tt-suggestion">%body</div>', compiledTemplate;
  518. if (template) {
  519. compiledTemplate = engine.compile(wrapper.replace("%body", template));
  520. } else {
  521. compiledTemplate = {
  522. render: function(context) {
  523. return wrapper.replace("%body", "<p>" + context[valueKey] + "</p>");
  524. }
  525. };
  526. }
  527. return compiledTemplate;
  528. }
  529. }();
  530. var InputView = function() {
  531. function InputView(o) {
  532. var that = this;
  533. utils.bindAll(this);
  534. this.specialKeyCodeMap = {
  535. 9: "tab",
  536. 27: "esc",
  537. 37: "left",
  538. 39: "right",
  539. 13: "enter",
  540. 38: "up",
  541. 40: "down"
  542. };
  543. this.$hint = $(o.hint);
  544. this.$input = $(o.input).on("blur.tt", this._handleBlur).on("focus.tt", this._handleFocus).on("keydown.tt", this._handleSpecialKeyEvent);
  545. if (!utils.isMsie()) {
  546. this.$input.on("input.tt", this._compareQueryToInputValue);
  547. } else {
  548. this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) {
  549. if (that.specialKeyCodeMap[$e.which || $e.keyCode]) {
  550. return;
  551. }
  552. utils.defer(that._compareQueryToInputValue);
  553. });
  554. }
  555. this.query = this.$input.val();
  556. this.$overflowHelper = buildOverflowHelper(this.$input);
  557. }
  558. utils.mixin(InputView.prototype, EventTarget, {
  559. _handleFocus: function() {
  560. this.trigger("focused");
  561. },
  562. _handleBlur: function() {
  563. this.trigger("blured");
  564. },
  565. _handleSpecialKeyEvent: function($e) {
  566. var keyName = this.specialKeyCodeMap[$e.which || $e.keyCode];
  567. keyName && this.trigger(keyName + "Keyed", $e);
  568. },
  569. _compareQueryToInputValue: function() {
  570. var inputValue = this.getInputValue(), isSameQuery = compareQueries(this.query, inputValue), isSameQueryExceptWhitespace = isSameQuery ? this.query.length !== inputValue.length : false;
  571. if (isSameQueryExceptWhitespace) {
  572. this.trigger("whitespaceChanged", {
  573. value: this.query
  574. });
  575. } else if (!isSameQuery) {
  576. this.trigger("queryChanged", {
  577. value: this.query = inputValue
  578. });
  579. }
  580. },
  581. destroy: function() {
  582. this.$hint.off(".tt");
  583. this.$input.off(".tt");
  584. this.$hint = this.$input = this.$overflowHelper = null;
  585. },
  586. focus: function() {
  587. this.$input.focus();
  588. },
  589. blur: function() {
  590. this.$input.blur();
  591. },
  592. getQuery: function() {
  593. return this.query;
  594. },
  595. getInputValue: function() {
  596. return this.$input.val();
  597. },
  598. setInputValue: function(value, silent) {
  599. this.$input.val(value);
  600. if (silent !== true) {
  601. this._compareQueryToInputValue();
  602. }
  603. },
  604. getHintValue: function() {
  605. return this.$hint.val();
  606. },
  607. setHintValue: function(value) {
  608. this.$hint.val(value);
  609. },
  610. getLanguageDirection: function() {
  611. return (this.$input.css("direction") || "ltr").toLowerCase();
  612. },
  613. isOverflow: function() {
  614. this.$overflowHelper.text(this.getInputValue());
  615. return this.$overflowHelper.width() > this.$input.width();
  616. },
  617. isCursorAtEnd: function() {
  618. var valueLength = this.$input.val().length, selectionStart = this.$input[0].selectionStart, range;
  619. if (utils.isNumber(selectionStart)) {
  620. return selectionStart === valueLength;
  621. } else if (document.selection) {
  622. range = document.selection.createRange();
  623. range.moveStart("character", -valueLength);
  624. return valueLength === range.text.length;
  625. }
  626. return true;
  627. }
  628. });
  629. return InputView;
  630. function buildOverflowHelper($input) {
  631. return $("<span></span>").css({
  632. position: "absolute",
  633. left: "-9999px",
  634. visibility: "hidden",
  635. whiteSpace: "nowrap",
  636. fontFamily: $input.css("font-family"),
  637. fontSize: $input.css("font-size"),
  638. fontStyle: $input.css("font-style"),
  639. fontVariant: $input.css("font-variant"),
  640. fontWeight: $input.css("font-weight"),
  641. wordSpacing: $input.css("word-spacing"),
  642. letterSpacing: $input.css("letter-spacing"),
  643. textIndent: $input.css("text-indent"),
  644. textRendering: $input.css("text-rendering"),
  645. textTransform: $input.css("text-transform")
  646. }).insertAfter($input);
  647. }
  648. function compareQueries(a, b) {
  649. a = (a || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
  650. b = (b || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
  651. return a === b;
  652. }
  653. }();
  654. var DropdownView = function() {
  655. var html = {
  656. suggestionsList: '<span class="tt-suggestions"></span>'
  657. }, css = {
  658. suggestionsList: {
  659. display: "block"
  660. },
  661. suggestion: {
  662. whiteSpace: "nowrap",
  663. cursor: "pointer"
  664. },
  665. suggestionChild: {
  666. whiteSpace: "normal"
  667. }
  668. };
  669. function DropdownView(o) {
  670. utils.bindAll(this);
  671. this.isOpen = false;
  672. this.isEmpty = true;
  673. this.isMouseOverDropdown = false;
  674. this.$menu = $(o.menu).on("mouseenter.tt", this._handleMouseenter).on("mouseleave.tt", this._handleMouseleave).on("click.tt", ".tt-suggestion", this._handleSelection).on("mouseover.tt", ".tt-suggestion", this._handleMouseover);
  675. }
  676. utils.mixin(DropdownView.prototype, EventTarget, {
  677. _handleMouseenter: function() {
  678. this.isMouseOverDropdown = true;
  679. },
  680. _handleMouseleave: function() {
  681. this.isMouseOverDropdown = false;
  682. },
  683. _handleMouseover: function($e) {
  684. var $suggestion = $($e.currentTarget);
  685. this._getSuggestions().removeClass("tt-is-under-cursor");
  686. $suggestion.addClass("tt-is-under-cursor");
  687. },
  688. _handleSelection: function($e) {
  689. var $suggestion = $($e.currentTarget);
  690. this.trigger("suggestionSelected", extractSuggestion($suggestion));
  691. },
  692. _show: function() {
  693. this.$menu.css("display", "block");
  694. },
  695. _hide: function() {
  696. this.$menu.hide();
  697. },
  698. _moveCursor: function(increment) {
  699. var $suggestions, $cur, nextIndex, $underCursor;
  700. if (!this.isVisible()) {
  701. return;
  702. }
  703. $suggestions = this._getSuggestions();
  704. $cur = $suggestions.filter(".tt-is-under-cursor");
  705. $cur.removeClass("tt-is-under-cursor");
  706. nextIndex = $suggestions.index($cur) + increment;
  707. nextIndex = (nextIndex + 1) % ($suggestions.length + 1) - 1;
  708. if (nextIndex === -1) {
  709. this.trigger("cursorRemoved");
  710. return;
  711. } else if (nextIndex < -1) {
  712. nextIndex = $suggestions.length - 1;
  713. }
  714. $underCursor = $suggestions.eq(nextIndex).addClass("tt-is-under-cursor");
  715. this.trigger("cursorMoved", extractSuggestion($underCursor));
  716. },
  717. _getSuggestions: function() {
  718. return this.$menu.find(".tt-suggestions > .tt-suggestion");
  719. },
  720. destroy: function() {
  721. this.$menu.off(".tt");
  722. this.$menu = null;
  723. },
  724. isVisible: function() {
  725. return this.isOpen && !this.isEmpty;
  726. },
  727. closeUnlessMouseIsOverDropdown: function() {
  728. if (!this.isMouseOverDropdown) {
  729. this.close();
  730. }
  731. },
  732. close: function() {
  733. if (this.isOpen) {
  734. this.isOpen = false;
  735. this._hide();
  736. this.$menu.find(".tt-suggestions > .tt-suggestion").removeClass("tt-is-under-cursor");
  737. this.trigger("closed");
  738. }
  739. },
  740. open: function() {
  741. if (!this.isOpen) {
  742. this.isOpen = true;
  743. !this.isEmpty && this._show();
  744. this.trigger("opened");
  745. }
  746. },
  747. setLanguageDirection: function(dir) {
  748. var ltrCss = {
  749. left: "0",
  750. right: "auto"
  751. }, rtlCss = {
  752. left: "auto",
  753. right: " 0"
  754. };
  755. dir === "ltr" ? this.$menu.css(ltrCss) : this.$menu.css(rtlCss);
  756. },
  757. moveCursorUp: function() {
  758. this._moveCursor(-1);
  759. },
  760. moveCursorDown: function() {
  761. this._moveCursor(+1);
  762. },
  763. getSuggestionUnderCursor: function() {
  764. var $suggestion = this._getSuggestions().filter(".tt-is-under-cursor").first();
  765. return $suggestion.length > 0 ? extractSuggestion($suggestion) : null;
  766. },
  767. getFirstSuggestion: function() {
  768. var $suggestion = this._getSuggestions().first();
  769. return $suggestion.length > 0 ? extractSuggestion($suggestion) : null;
  770. },
  771. renderSuggestions: function(dataset, suggestions) {
  772. var datasetClassName = "tt-dataset-" + dataset.name, $suggestionsList, $dataset = this.$menu.find("." + datasetClassName), elBuilder, fragment, $el;
  773. if ($dataset.length === 0) {
  774. $suggestionsList = $(html.suggestionsList).css(css.suggestionsList);
  775. $dataset = $("<div></div>").addClass(datasetClassName).append(dataset.header).append($suggestionsList).append(dataset.footer).appendTo(this.$menu);
  776. }
  777. if (suggestions.length > 0) {
  778. this.isEmpty = false;
  779. this.isOpen && this._show();
  780. elBuilder = document.createElement("div");
  781. fragment = document.createDocumentFragment();
  782. utils.each(suggestions, function(i, suggestion) {
  783. elBuilder.innerHTML = dataset.template.render(suggestion.datum);
  784. $el = $(elBuilder.firstChild).css(css.suggestion).data("suggestion", suggestion);
  785. $el.children().each(function() {
  786. $(this).css(css.suggestionChild);
  787. });
  788. fragment.appendChild($el[0]);
  789. });
  790. $dataset.show().find(".tt-suggestions").html(fragment);
  791. } else {
  792. this.clearSuggestions(dataset.name);
  793. }
  794. this.trigger("suggestionsRendered");
  795. },
  796. clearSuggestions: function(datasetName) {
  797. var $datasets = datasetName ? this.$menu.find(".tt-dataset-" + datasetName) : this.$menu.find('[class^="tt-dataset-"]'), $suggestions = $datasets.find(".tt-suggestions");
  798. $datasets.hide();
  799. $suggestions.empty();
  800. if (this._getSuggestions().length === 0) {
  801. this.isEmpty = true;
  802. this._hide();
  803. }
  804. }
  805. });
  806. return DropdownView;
  807. function extractSuggestion($el) {
  808. return $el.data("suggestion");
  809. }
  810. }();
  811. var TypeaheadView = function() {
  812. var html = {
  813. wrapper: '<span class="twitter-typeahead"></span>',
  814. hint: '<input class="tt-hint" type="text" autocomplete="off" spellcheck="off" disabled>',
  815. dropdown: '<span class="tt-dropdown-menu"></span>'
  816. }, css = {
  817. wrapper: {
  818. position: "relative",
  819. display: "inline-block"
  820. },
  821. hint: {
  822. position: "absolute",
  823. top: "0",
  824. left: "0",
  825. borderColor: "transparent",
  826. boxShadow: "none"
  827. },
  828. query: {
  829. position: "relative",
  830. verticalAlign: "top",
  831. backgroundColor: "transparent"
  832. },
  833. dropdown: {
  834. position: "absolute",
  835. top: "100%",
  836. left: "0",
  837. zIndex: "100",
  838. display: "none"
  839. }
  840. };
  841. if (utils.isMsie()) {
  842. utils.mixin(css.query, {
  843. backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
  844. });
  845. }
  846. if (utils.isMsie() && utils.isMsie() <= 7) {
  847. utils.mixin(css.wrapper, {
  848. display: "inline",
  849. zoom: "1"
  850. });
  851. utils.mixin(css.query, {
  852. marginTop: "-1px"
  853. });
  854. }
  855. function TypeaheadView(o) {
  856. var $menu, $input, $hint;
  857. utils.bindAll(this);
  858. this.$node = buildDomStructure(o.input);
  859. this.datasets = o.datasets;
  860. this.dir = null;
  861. this.eventBus = o.eventBus;
  862. $menu = this.$node.find(".tt-dropdown-menu");
  863. $input = this.$node.find(".tt-query");
  864. $hint = this.$node.find(".tt-hint");
  865. this.dropdownView = new DropdownView({
  866. menu: $menu
  867. }).on("suggestionSelected", this._handleSelection).on("cursorMoved", this._clearHint).on("cursorMoved", this._setInputValueToSuggestionUnderCursor).on("cursorRemoved", this._setInputValueToQuery).on("cursorRemoved", this._updateHint).on("suggestionsRendered", this._updateHint).on("opened", this._updateHint).on("closed", this._clearHint).on("opened closed", this._propagateEvent);
  868. this.inputView = new InputView({
  869. input: $input,
  870. hint: $hint
  871. }).on("focused", this._openDropdown).on("blured", this._closeDropdown).on("blured", this._setInputValueToQuery).on("enterKeyed", this._handleSelection).on("queryChanged", this._clearHint).on("queryChanged", this._clearSuggestions).on("queryChanged", this._getSuggestions).on("whitespaceChanged", this._updateHint).on("queryChanged whitespaceChanged", this._openDropdown).on("queryChanged whitespaceChanged", this._setLanguageDirection).on("escKeyed", this._closeDropdown).on("escKeyed", this._setInputValueToQuery).on("tabKeyed upKeyed downKeyed", this._managePreventDefault).on("upKeyed downKeyed", this._moveDropdownCursor).on("upKeyed downKeyed", this._openDropdown).on("tabKeyed leftKeyed rightKeyed", this._autocomplete);
  872. }
  873. utils.mixin(TypeaheadView.prototype, EventTarget, {
  874. _managePreventDefault: function(e) {
  875. var $e = e.data, hint, inputValue, preventDefault = false;
  876. switch (e.type) {
  877. case "tabKeyed":
  878. hint = this.inputView.getHintValue();
  879. inputValue = this.inputView.getInputValue();
  880. preventDefault = hint && hint !== inputValue;
  881. break;
  882. case "upKeyed":
  883. case "downKeyed":
  884. preventDefault = !$e.shiftKey && !$e.ctrlKey && !$e.metaKey;
  885. break;
  886. }
  887. preventDefault && $e.preventDefault();
  888. },
  889. _setLanguageDirection: function() {
  890. var dir = this.inputView.getLanguageDirection();
  891. if (dir !== this.dir) {
  892. this.dir = dir;
  893. this.$node.css("direction", dir);
  894. this.dropdownView.setLanguageDirection(dir);
  895. }
  896. },
  897. _updateHint: function() {
  898. var suggestion = this.dropdownView.getFirstSuggestion(), hint = suggestion ? suggestion.value : null, dropdownIsVisible = this.dropdownView.isVisible(), inputHasOverflow = this.inputView.isOverflow(), inputValue, query, escapedQuery, beginsWithQuery, match;
  899. if (hint && dropdownIsVisible && !inputHasOverflow) {
  900. inputValue = this.inputView.getInputValue();
  901. query = inputValue.replace(/\s{2,}/g, " ").replace(/^\s+/g, "");
  902. escapedQuery = utils.escapeRegExChars(query);
  903. beginsWithQuery = new RegExp("^(?:" + escapedQuery + ")(.*$)", "i");
  904. match = beginsWithQuery.exec(hint);
  905. this.inputView.setHintValue(inputValue + (match ? match[1] : ""));
  906. }
  907. },
  908. _clearHint: function() {
  909. this.inputView.setHintValue("");
  910. },
  911. _clearSuggestions: function() {
  912. this.dropdownView.clearSuggestions();
  913. },
  914. _setInputValueToQuery: function() {
  915. this.inputView.setInputValue(this.inputView.getQuery());
  916. },
  917. _setInputValueToSuggestionUnderCursor: function(e) {
  918. var suggestion = e.data;
  919. this.inputView.setInputValue(suggestion.value, true);
  920. },
  921. _openDropdown: function() {
  922. this.dropdownView.open();
  923. },
  924. _closeDropdown: function(e) {
  925. this.dropdownView[e.type === "blured" ? "closeUnlessMouseIsOverDropdown" : "close"]();
  926. },
  927. _moveDropdownCursor: function(e) {
  928. var $e = e.data;
  929. if (!$e.shiftKey && !$e.ctrlKey && !$e.metaKey) {
  930. this.dropdownView[e.type === "upKeyed" ? "moveCursorUp" : "moveCursorDown"]();
  931. }
  932. },
  933. _handleSelection: function(e) {
  934. var byClick = e.type === "suggestionSelected", suggestion = byClick ? e.data : this.dropdownView.getSuggestionUnderCursor();
  935. if (suggestion) {
  936. this.inputView.setInputValue(suggestion.value);
  937. byClick ? this.inputView.focus() : e.data.preventDefault();
  938. byClick && utils.isMsie() ? utils.defer(this.dropdownView.close) : this.dropdownView.close();
  939. this.eventBus.trigger("selected", suggestion.datum);
  940. }
  941. },
  942. _getSuggestions: function() {
  943. var that = this, query = this.inputView.getQuery();
  944. if (utils.isBlankString(query)) {
  945. return;
  946. }
  947. utils.each(this.datasets, function(i, dataset) {
  948. dataset.getSuggestions(query, function(suggestions) {
  949. if (query === that.inputView.getQuery()) {
  950. that.dropdownView.renderSuggestions(dataset, suggestions);
  951. }
  952. });
  953. });
  954. },
  955. _autocomplete: function(e) {
  956. var isCursorAtEnd, ignoreEvent, query, hint, suggestion;
  957. if (e.type === "rightKeyed" || e.type === "leftKeyed") {
  958. isCursorAtEnd = this.inputView.isCursorAtEnd();
  959. ignoreEvent = this.inputView.getLanguageDirection() === "ltr" ? e.type === "leftKeyed" : e.type === "rightKeyed";
  960. if (!isCursorAtEnd || ignoreEvent) {
  961. return;
  962. }
  963. }
  964. query = this.inputView.getQuery();
  965. hint = this.inputView.getHintValue();
  966. if (hint !== "" && query !== hint) {
  967. suggestion = this.dropdownView.getFirstSuggestion();
  968. this.inputView.setInputValue(suggestion.value);
  969. }
  970. },
  971. _propagateEvent: function(e) {
  972. this.eventBus.trigger(e.type);
  973. },
  974. destroy: function() {
  975. this.inputView.destroy();
  976. this.dropdownView.destroy();
  977. destroyDomStructure(this.$node);
  978. this.$node = null;
  979. }
  980. });
  981. return TypeaheadView;
  982. function buildDomStructure(input) {
  983. var $wrapper = $(html.wrapper), $dropdown = $(html.dropdown), $input = $(input), $hint = $(html.hint);
  984. $wrapper = $wrapper.css(css.wrapper);
  985. $dropdown = $dropdown.css(css.dropdown);
  986. $hint.css(css.hint).css({
  987. backgroundAttachment: $input.css("background-attachment"),
  988. backgroundClip: $input.css("background-clip"),
  989. backgroundColor: $input.css("background-color"),
  990. backgroundImage: $input.css("background-image"),
  991. backgroundOrigin: $input.css("background-origin"),
  992. backgroundPosition: $input.css("background-position"),
  993. backgroundRepeat: $input.css("background-repeat"),
  994. backgroundSize: $input.css("background-size")
  995. });
  996. $input.data("ttAttrs", {
  997. dir: $input.attr("dir"),
  998. autocomplete: $input.attr("autocomplete"),
  999. spellcheck: $input.attr("spellcheck"),
  1000. style: $input.attr("style")
  1001. });
  1002. $input.addClass("tt-query").attr({
  1003. autocomplete: "off",
  1004. spellcheck: false
  1005. }).css(css.query);
  1006. try {
  1007. !$input.attr("dir") && $input.attr("dir", "auto");
  1008. } catch (e) {}
  1009. return $input.wrap($wrapper).parent().prepend($hint).append($dropdown);
  1010. }
  1011. function destroyDomStructure($node) {
  1012. var $input = $node.find(".tt-query");
  1013. utils.each($input.data("ttAttrs"), function(key, val) {
  1014. utils.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val);
  1015. });
  1016. $input.detach().removeData("ttAttrs").removeClass("tt-query").insertAfter($node);
  1017. $node.remove();
  1018. }
  1019. }();
  1020. (function() {
  1021. var cache = {}, viewKey = "ttView", methods;
  1022. methods = {
  1023. initialize: function(datasetDefs) {
  1024. var datasets;
  1025. datasetDefs = utils.isArray(datasetDefs) ? datasetDefs : [ datasetDefs ];
  1026. if (this.length === 0) {
  1027. $.error("typeahead initialized without DOM element");
  1028. }
  1029. if (datasetDefs.length === 0) {
  1030. $.error("no datasets provided");
  1031. }
  1032. datasets = utils.map(datasetDefs, function(o) {
  1033. var dataset = cache[o.name] ? cache[o.name] : new Dataset(o);
  1034. if (o.name) {
  1035. cache[o.name] = dataset;
  1036. }
  1037. return dataset;
  1038. });
  1039. return this.each(initialize);
  1040. function initialize() {
  1041. var $input = $(this), deferreds, eventBus = new EventBus({
  1042. el: $input
  1043. });
  1044. deferreds = utils.map(datasets, function(dataset) {
  1045. return dataset.initialize();
  1046. });
  1047. $input.data(viewKey, new TypeaheadView({
  1048. input: $input,
  1049. eventBus: eventBus = new EventBus({
  1050. el: $input
  1051. }),
  1052. datasets: datasets
  1053. }));
  1054. $.when.apply($, deferreds).always(function() {
  1055. utils.defer(function() {
  1056. eventBus.trigger("initialized");
  1057. });
  1058. });
  1059. }
  1060. },
  1061. destroy: function() {
  1062. this.each(function() {
  1063. var $this = $(this), view = $this.data(viewKey);
  1064. if (view) {
  1065. view.destroy();
  1066. $this.removeData(viewKey);
  1067. }
  1068. });
  1069. }
  1070. };
  1071. jQuery.fn.typeahead = function(method) {
  1072. if (methods[method]) {
  1073. return methods[method].apply(this, [].slice.call(arguments, 1));
  1074. } else {
  1075. return methods.initialize.apply(this, arguments);
  1076. }
  1077. };
  1078. })();
  1079. })(window.jQuery);