bootstrap-typeahead.js 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782
  1. /*!
  2. * typeahead.js 0.10.4
  3. * https://github.com/twitter/typeahead.js
  4. * Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
  5. */
  6. (function($) {
  7. var _ = function() {
  8. "use strict";
  9. return {
  10. isMsie: function() {
  11. return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : 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. toStr: function toStr(s) {
  32. return _.isUndefined(s) || s === null ? "" : s + "";
  33. },
  34. bind: $.proxy,
  35. each: function(collection, cb) {
  36. $.each(collection, reverseArgs);
  37. function reverseArgs(index, value) {
  38. return cb(value, index);
  39. }
  40. },
  41. map: $.map,
  42. filter: $.grep,
  43. every: function(obj, test) {
  44. var result = true;
  45. if (!obj) {
  46. return result;
  47. }
  48. $.each(obj, function(key, val) {
  49. if (!(result = test.call(null, val, key, obj))) {
  50. return false;
  51. }
  52. });
  53. return !!result;
  54. },
  55. some: function(obj, test) {
  56. var result = false;
  57. if (!obj) {
  58. return result;
  59. }
  60. $.each(obj, function(key, val) {
  61. if (result = test.call(null, val, key, obj)) {
  62. return false;
  63. }
  64. });
  65. return !!result;
  66. },
  67. mixin: $.extend,
  68. getUniqueId: function() {
  69. var counter = 0;
  70. return function() {
  71. return counter++;
  72. };
  73. }(),
  74. templatify: function templatify(obj) {
  75. return $.isFunction(obj) ? obj : template;
  76. function template() {
  77. return String(obj);
  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. noop: function() {}
  126. };
  127. }();
  128. var VERSION = "0.10.4";
  129. var tokenizers = function() {
  130. "use strict";
  131. return {
  132. nonword: nonword,
  133. whitespace: whitespace,
  134. obj: {
  135. nonword: getObjTokenizer(nonword),
  136. whitespace: getObjTokenizer(whitespace)
  137. }
  138. };
  139. function whitespace(str) {
  140. str = _.toStr(str);
  141. return str ? str.split(/\s+/) : [];
  142. }
  143. function nonword(str) {
  144. str = _.toStr(str);
  145. return str ? str.split(/\W+/) : [];
  146. }
  147. function getObjTokenizer(tokenizer) {
  148. return function setKey() {
  149. var args = [].slice.call(arguments, 0);
  150. return function tokenize(o) {
  151. var tokens = [];
  152. _.each(args, function(k) {
  153. tokens = tokens.concat(tokenizer(_.toStr(o[k])));
  154. });
  155. return tokens;
  156. };
  157. };
  158. }
  159. }();
  160. var LruCache = function() {
  161. "use strict";
  162. function LruCache(maxSize) {
  163. this.maxSize = _.isNumber(maxSize) ? maxSize : 100;
  164. this.reset();
  165. if (this.maxSize <= 0) {
  166. this.set = this.get = $.noop;
  167. }
  168. }
  169. _.mixin(LruCache.prototype, {
  170. set: function set(key, val) {
  171. var tailItem = this.list.tail, node;
  172. if (this.size >= this.maxSize) {
  173. this.list.remove(tailItem);
  174. delete this.hash[tailItem.key];
  175. }
  176. if (node = this.hash[key]) {
  177. node.val = val;
  178. this.list.moveToFront(node);
  179. } else {
  180. node = new Node(key, val);
  181. this.list.add(node);
  182. this.hash[key] = node;
  183. this.size++;
  184. }
  185. },
  186. get: function get(key) {
  187. var node = this.hash[key];
  188. if (node) {
  189. this.list.moveToFront(node);
  190. return node.val;
  191. }
  192. },
  193. reset: function reset() {
  194. this.size = 0;
  195. this.hash = {};
  196. this.list = new List();
  197. }
  198. });
  199. function List() {
  200. this.head = this.tail = null;
  201. }
  202. _.mixin(List.prototype, {
  203. add: function add(node) {
  204. if (this.head) {
  205. node.next = this.head;
  206. this.head.prev = node;
  207. }
  208. this.head = node;
  209. this.tail = this.tail || node;
  210. },
  211. remove: function remove(node) {
  212. node.prev ? node.prev.next = node.next : this.head = node.next;
  213. node.next ? node.next.prev = node.prev : this.tail = node.prev;
  214. },
  215. moveToFront: function(node) {
  216. this.remove(node);
  217. this.add(node);
  218. }
  219. });
  220. function Node(key, val) {
  221. this.key = key;
  222. this.val = val;
  223. this.prev = this.next = null;
  224. }
  225. return LruCache;
  226. }();
  227. var PersistentStorage = function() {
  228. "use strict";
  229. var ls, methods;
  230. try {
  231. ls = window.localStorage;
  232. ls.setItem("~~~", "!");
  233. ls.removeItem("~~~");
  234. } catch (err) {
  235. ls = null;
  236. }
  237. function PersistentStorage(namespace) {
  238. this.prefix = [ "__", namespace, "__" ].join("");
  239. this.ttlKey = "__ttl__";
  240. this.keyMatcher = new RegExp("^" + _.escapeRegExChars(this.prefix));
  241. }
  242. if (ls && window.JSON) {
  243. methods = {
  244. _prefix: function(key) {
  245. return this.prefix + key;
  246. },
  247. _ttlKey: function(key) {
  248. return this._prefix(key) + this.ttlKey;
  249. },
  250. get: function(key) {
  251. if (this.isExpired(key)) {
  252. this.remove(key);
  253. }
  254. return decode(ls.getItem(this._prefix(key)));
  255. },
  256. set: function(key, val, ttl) {
  257. if (_.isNumber(ttl)) {
  258. ls.setItem(this._ttlKey(key), encode(now() + ttl));
  259. } else {
  260. ls.removeItem(this._ttlKey(key));
  261. }
  262. return ls.setItem(this._prefix(key), encode(val));
  263. },
  264. remove: function(key) {
  265. ls.removeItem(this._ttlKey(key));
  266. ls.removeItem(this._prefix(key));
  267. return this;
  268. },
  269. clear: function() {
  270. var i, key, keys = [], len = ls.length;
  271. for (i = 0; i < len; i++) {
  272. if ((key = ls.key(i)).match(this.keyMatcher)) {
  273. keys.push(key.replace(this.keyMatcher, ""));
  274. }
  275. }
  276. for (i = keys.length; i--; ) {
  277. this.remove(keys[i]);
  278. }
  279. return this;
  280. },
  281. isExpired: function(key) {
  282. var ttl = decode(ls.getItem(this._ttlKey(key)));
  283. return _.isNumber(ttl) && now() > ttl ? true : false;
  284. }
  285. };
  286. } else {
  287. methods = {
  288. get: _.noop,
  289. set: _.noop,
  290. remove: _.noop,
  291. clear: _.noop,
  292. isExpired: _.noop
  293. };
  294. }
  295. _.mixin(PersistentStorage.prototype, methods);
  296. return PersistentStorage;
  297. function now() {
  298. return new Date().getTime();
  299. }
  300. function encode(val) {
  301. return JSON.stringify(_.isUndefined(val) ? null : val);
  302. }
  303. function decode(val) {
  304. return JSON.parse(val);
  305. }
  306. }();
  307. var Transport = function() {
  308. "use strict";
  309. var pendingRequestsCount = 0, pendingRequests = {}, maxPendingRequests = 6, sharedCache = new LruCache(10);
  310. function Transport(o) {
  311. o = o || {};
  312. this.cancelled = false;
  313. this.lastUrl = null;
  314. this._send = o.transport ? callbackToDeferred(o.transport) : $.ajax;
  315. this._get = o.rateLimiter ? o.rateLimiter(this._get) : this._get;
  316. this._cache = o.cache === false ? new LruCache(0) : sharedCache;
  317. }
  318. Transport.setMaxPendingRequests = function setMaxPendingRequests(num) {
  319. maxPendingRequests = num;
  320. };
  321. Transport.resetCache = function resetCache() {
  322. sharedCache.reset();
  323. };
  324. _.mixin(Transport.prototype, {
  325. _get: function(url, o, cb) {
  326. var that = this, jqXhr;
  327. if (this.cancelled || url !== this.lastUrl) {
  328. return;
  329. }
  330. if (jqXhr = pendingRequests[url]) {
  331. jqXhr.done(done).fail(fail);
  332. } else if (pendingRequestsCount < maxPendingRequests) {
  333. pendingRequestsCount++;
  334. pendingRequests[url] = this._send(url, o).done(done).fail(fail).always(always);
  335. } else {
  336. this.onDeckRequestArgs = [].slice.call(arguments, 0);
  337. }
  338. function done(resp) {
  339. cb && cb(null, resp);
  340. that._cache.set(url, resp);
  341. }
  342. function fail() {
  343. cb && cb(true);
  344. }
  345. function always() {
  346. pendingRequestsCount--;
  347. delete pendingRequests[url];
  348. if (that.onDeckRequestArgs) {
  349. that._get.apply(that, that.onDeckRequestArgs);
  350. that.onDeckRequestArgs = null;
  351. }
  352. }
  353. },
  354. get: function(url, o, cb) {
  355. var resp;
  356. if (_.isFunction(o)) {
  357. cb = o;
  358. o = {};
  359. }
  360. this.cancelled = false;
  361. this.lastUrl = url;
  362. if (resp = this._cache.get(url)) {
  363. _.defer(function() {
  364. cb && cb(null, resp);
  365. });
  366. } else {
  367. this._get(url, o, cb);
  368. }
  369. return !!resp;
  370. },
  371. cancel: function() {
  372. this.cancelled = true;
  373. }
  374. });
  375. return Transport;
  376. function callbackToDeferred(fn) {
  377. return function customSendWrapper(url, o) {
  378. var deferred = $.Deferred();
  379. fn(url, o, onSuccess, onError);
  380. return deferred;
  381. function onSuccess(resp) {
  382. _.defer(function() {
  383. deferred.resolve(resp);
  384. });
  385. }
  386. function onError(err) {
  387. _.defer(function() {
  388. deferred.reject(err);
  389. });
  390. }
  391. };
  392. }
  393. }();
  394. var SearchIndex = function() {
  395. "use strict";
  396. function SearchIndex(o) {
  397. o = o || {};
  398. if (!o.datumTokenizer || !o.queryTokenizer) {
  399. $.error("datumTokenizer and queryTokenizer are both required");
  400. }
  401. this.datumTokenizer = o.datumTokenizer;
  402. this.queryTokenizer = o.queryTokenizer;
  403. this.reset();
  404. }
  405. _.mixin(SearchIndex.prototype, {
  406. bootstrap: function bootstrap(o) {
  407. this.datums = o.datums;
  408. this.trie = o.trie;
  409. },
  410. add: function(data) {
  411. var that = this;
  412. data = _.isArray(data) ? data : [ data ];
  413. _.each(data, function(datum) {
  414. var id, tokens;
  415. id = that.datums.push(datum) - 1;
  416. tokens = normalizeTokens(that.datumTokenizer(datum));
  417. _.each(tokens, function(token) {
  418. var node, chars, ch;
  419. node = that.trie;
  420. chars = token.split("");
  421. while (ch = chars.shift()) {
  422. node = node.children[ch] || (node.children[ch] = newNode());
  423. node.ids.push(id);
  424. }
  425. });
  426. });
  427. },
  428. get: function get(query) {
  429. var that = this, tokens, matches;
  430. tokens = normalizeTokens(this.queryTokenizer(query));
  431. _.each(tokens, function(token) {
  432. var node, chars, ch, ids;
  433. if (matches && matches.length === 0) {
  434. return false;
  435. }
  436. node = that.trie;
  437. chars = token.split("");
  438. while (node && (ch = chars.shift())) {
  439. node = node.children[ch];
  440. }
  441. if (node && chars.length === 0) {
  442. ids = node.ids.slice(0);
  443. matches = matches ? getIntersection(matches, ids) : ids;
  444. } else {
  445. matches = [];
  446. return false;
  447. }
  448. });
  449. return matches ? _.map(unique(matches), function(id) {
  450. return that.datums[id];
  451. }) : [];
  452. },
  453. reset: function reset() {
  454. this.datums = [];
  455. this.trie = newNode();
  456. },
  457. serialize: function serialize() {
  458. return {
  459. datums: this.datums,
  460. trie: this.trie
  461. };
  462. }
  463. });
  464. return SearchIndex;
  465. function normalizeTokens(tokens) {
  466. tokens = _.filter(tokens, function(token) {
  467. return !!token;
  468. });
  469. tokens = _.map(tokens, function(token) {
  470. return token.toLowerCase();
  471. });
  472. return tokens;
  473. }
  474. function newNode() {
  475. return {
  476. ids: [],
  477. children: {}
  478. };
  479. }
  480. function unique(array) {
  481. var seen = {}, uniques = [];
  482. for (var i = 0, len = array.length; i < len; i++) {
  483. if (!seen[array[i]]) {
  484. seen[array[i]] = true;
  485. uniques.push(array[i]);
  486. }
  487. }
  488. return uniques;
  489. }
  490. function getIntersection(arrayA, arrayB) {
  491. var ai = 0, bi = 0, intersection = [];
  492. arrayA = arrayA.sort(compare);
  493. arrayB = arrayB.sort(compare);
  494. var lenArrayA = arrayA.length, lenArrayB = arrayB.length;
  495. while (ai < lenArrayA && bi < lenArrayB) {
  496. if (arrayA[ai] < arrayB[bi]) {
  497. ai++;
  498. } else if (arrayA[ai] > arrayB[bi]) {
  499. bi++;
  500. } else {
  501. intersection.push(arrayA[ai]);
  502. ai++;
  503. bi++;
  504. }
  505. }
  506. return intersection;
  507. function compare(a, b) {
  508. return a - b;
  509. }
  510. }
  511. }();
  512. var oParser = function() {
  513. "use strict";
  514. return {
  515. local: getLocal,
  516. prefetch: getPrefetch,
  517. remote: getRemote
  518. };
  519. function getLocal(o) {
  520. return o.local || null;
  521. }
  522. function getPrefetch(o) {
  523. var prefetch, defaults;
  524. defaults = {
  525. url: null,
  526. thumbprint: "",
  527. ttl: 24 * 60 * 60 * 1e3,
  528. filter: null,
  529. ajax: {}
  530. };
  531. if (prefetch = o.prefetch || null) {
  532. prefetch = _.isString(prefetch) ? {
  533. url: prefetch
  534. } : prefetch;
  535. prefetch = _.mixin(defaults, prefetch);
  536. prefetch.thumbprint = VERSION + prefetch.thumbprint;
  537. prefetch.ajax.type = prefetch.ajax.type || "GET";
  538. prefetch.ajax.dataType = prefetch.ajax.dataType || "json";
  539. !prefetch.url && $.error("prefetch requires url to be set");
  540. }
  541. return prefetch;
  542. }
  543. function getRemote(o) {
  544. var remote, defaults;
  545. defaults = {
  546. url: null,
  547. cache: true,
  548. wildcard: "%QUERY",
  549. replace: null,
  550. rateLimitBy: "debounce",
  551. rateLimitWait: 300,
  552. send: null,
  553. filter: null,
  554. ajax: {}
  555. };
  556. if (remote = o.remote || null) {
  557. remote = _.isString(remote) ? {
  558. url: remote
  559. } : remote;
  560. remote = _.mixin(defaults, remote);
  561. remote.rateLimiter = /^throttle$/i.test(remote.rateLimitBy) ? byThrottle(remote.rateLimitWait) : byDebounce(remote.rateLimitWait);
  562. remote.ajax.type = remote.ajax.type || "GET";
  563. remote.ajax.dataType = remote.ajax.dataType || "json";
  564. delete remote.rateLimitBy;
  565. delete remote.rateLimitWait;
  566. !remote.url && $.error("remote requires url to be set");
  567. }
  568. return remote;
  569. function byDebounce(wait) {
  570. return function(fn) {
  571. return _.debounce(fn, wait);
  572. };
  573. }
  574. function byThrottle(wait) {
  575. return function(fn) {
  576. return _.throttle(fn, wait);
  577. };
  578. }
  579. }
  580. }();
  581. (function(root) {
  582. "use strict";
  583. var old, keys;
  584. old = root.Bloodhound;
  585. keys = {
  586. data: "data",
  587. protocol: "protocol",
  588. thumbprint: "thumbprint"
  589. };
  590. root.Bloodhound = Bloodhound;
  591. function Bloodhound(o) {
  592. if (!o || !o.local && !o.prefetch && !o.remote) {
  593. $.error("one of local, prefetch, or remote is required");
  594. }
  595. this.limit = o.limit || 5;
  596. this.sorter = getSorter(o.sorter);
  597. this.dupDetector = o.dupDetector || ignoreDuplicates;
  598. this.local = oParser.local(o);
  599. this.prefetch = oParser.prefetch(o);
  600. this.remote = oParser.remote(o);
  601. this.cacheKey = this.prefetch ? this.prefetch.cacheKey || this.prefetch.url : null;
  602. this.index = new SearchIndex({
  603. datumTokenizer: o.datumTokenizer,
  604. queryTokenizer: o.queryTokenizer
  605. });
  606. this.storage = this.cacheKey ? new PersistentStorage(this.cacheKey) : null;
  607. }
  608. Bloodhound.noConflict = function noConflict() {
  609. root.Bloodhound = old;
  610. return Bloodhound;
  611. };
  612. Bloodhound.tokenizers = tokenizers;
  613. _.mixin(Bloodhound.prototype, {
  614. _loadPrefetch: function loadPrefetch(o) {
  615. var that = this, serialized, deferred;
  616. if (serialized = this._readFromStorage(o.thumbprint)) {
  617. this.index.bootstrap(serialized);
  618. deferred = $.Deferred().resolve();
  619. } else {
  620. deferred = $.ajax(o.url, o.ajax).done(handlePrefetchResponse);
  621. }
  622. return deferred;
  623. function handlePrefetchResponse(resp) {
  624. that.clear();
  625. that.add(o.filter ? o.filter(resp) : resp);
  626. that._saveToStorage(that.index.serialize(), o.thumbprint, o.ttl);
  627. }
  628. },
  629. _getFromRemote: function getFromRemote(query, cb) {
  630. var that = this, url, uriEncodedQuery;
  631. if (!this.transport) {
  632. return;
  633. }
  634. query = query || "";
  635. uriEncodedQuery = encodeURIComponent(query);
  636. url = this.remote.replace ? this.remote.replace(this.remote.url, query) : this.remote.url.replace(this.remote.wildcard, uriEncodedQuery);
  637. return this.transport.get(url, this.remote.ajax, handleRemoteResponse);
  638. function handleRemoteResponse(err, resp) {
  639. err ? cb([]) : cb(that.remote.filter ? that.remote.filter(resp) : resp);
  640. }
  641. },
  642. _cancelLastRemoteRequest: function cancelLastRemoteRequest() {
  643. this.transport && this.transport.cancel();
  644. },
  645. _saveToStorage: function saveToStorage(data, thumbprint, ttl) {
  646. if (this.storage) {
  647. this.storage.set(keys.data, data, ttl);
  648. this.storage.set(keys.protocol, location.protocol, ttl);
  649. this.storage.set(keys.thumbprint, thumbprint, ttl);
  650. }
  651. },
  652. _readFromStorage: function readFromStorage(thumbprint) {
  653. var stored = {}, isExpired;
  654. if (this.storage) {
  655. stored.data = this.storage.get(keys.data);
  656. stored.protocol = this.storage.get(keys.protocol);
  657. stored.thumbprint = this.storage.get(keys.thumbprint);
  658. }
  659. isExpired = stored.thumbprint !== thumbprint || stored.protocol !== location.protocol;
  660. return stored.data && !isExpired ? stored.data : null;
  661. },
  662. _initialize: function initialize() {
  663. var that = this, local = this.local, deferred;
  664. deferred = this.prefetch ? this._loadPrefetch(this.prefetch) : $.Deferred().resolve();
  665. local && deferred.done(addLocalToIndex);
  666. this.transport = this.remote ? new Transport(this.remote) : null;
  667. return this.initPromise = deferred.promise();
  668. function addLocalToIndex() {
  669. that.add(_.isFunction(local) ? local() : local);
  670. }
  671. },
  672. initialize: function initialize(force) {
  673. return !this.initPromise || force ? this._initialize() : this.initPromise;
  674. },
  675. add: function add(data) {
  676. this.index.add(data);
  677. },
  678. get: function get(query, cb) {
  679. var that = this, matches = [], cacheHit = false;
  680. matches = this.index.get(query);
  681. matches = this.sorter(matches).slice(0, this.limit);
  682. matches.length < this.limit ? cacheHit = this._getFromRemote(query, returnRemoteMatches) : this._cancelLastRemoteRequest();
  683. if (!cacheHit) {
  684. (matches.length > 0 || !this.transport) && cb && cb(matches);
  685. }
  686. function returnRemoteMatches(remoteMatches) {
  687. var matchesWithBackfill = matches.slice(0);
  688. _.each(remoteMatches, function(remoteMatch) {
  689. var isDuplicate;
  690. isDuplicate = _.some(matchesWithBackfill, function(match) {
  691. return that.dupDetector(remoteMatch, match);
  692. });
  693. !isDuplicate && matchesWithBackfill.push(remoteMatch);
  694. return matchesWithBackfill.length < that.limit;
  695. });
  696. cb && cb(that.sorter(matchesWithBackfill));
  697. }
  698. },
  699. clear: function clear() {
  700. this.index.reset();
  701. },
  702. clearPrefetchCache: function clearPrefetchCache() {
  703. this.storage && this.storage.clear();
  704. },
  705. clearRemoteCache: function clearRemoteCache() {
  706. this.transport && Transport.resetCache();
  707. },
  708. ttAdapter: function ttAdapter() {
  709. return _.bind(this.get, this);
  710. }
  711. });
  712. return Bloodhound;
  713. function getSorter(sortFn) {
  714. return _.isFunction(sortFn) ? sort : noSort;
  715. function sort(array) {
  716. return array.sort(sortFn);
  717. }
  718. function noSort(array) {
  719. return array;
  720. }
  721. }
  722. function ignoreDuplicates() {
  723. return false;
  724. }
  725. })(this);
  726. var html = function() {
  727. return {
  728. wrapper: '<span class="twitter-typeahead"></span>',
  729. dropdown: '<span class="tt-dropdown-menu"></span>',
  730. dataset: '<div class="tt-dataset-%CLASS%"></div>',
  731. suggestions: '<span class="tt-suggestions"></span>',
  732. suggestion: '<div class="tt-suggestion"></div>'
  733. };
  734. }();
  735. var css = function() {
  736. "use strict";
  737. var css = {
  738. wrapper: {
  739. position: "relative",
  740. display: "inline-block"
  741. },
  742. hint: {
  743. position: "absolute",
  744. top: "0",
  745. left: "0",
  746. borderColor: "transparent",
  747. boxShadow: "none",
  748. opacity: "1"
  749. },
  750. input: {
  751. position: "relative",
  752. verticalAlign: "top",
  753. backgroundColor: "transparent"
  754. },
  755. inputWithNoHint: {
  756. position: "relative",
  757. verticalAlign: "top"
  758. },
  759. dropdown: {
  760. position: "absolute",
  761. top: "100%",
  762. left: "0",
  763. zIndex: "100",
  764. display: "none"
  765. },
  766. suggestions: {
  767. display: "block"
  768. },
  769. suggestion: {
  770. whiteSpace: "nowrap",
  771. cursor: "pointer"
  772. },
  773. suggestionChild: {
  774. whiteSpace: "normal"
  775. },
  776. ltr: {
  777. left: "0",
  778. right: "auto"
  779. },
  780. rtl: {
  781. left: "auto",
  782. right: " 0"
  783. }
  784. };
  785. if (_.isMsie()) {
  786. _.mixin(css.input, {
  787. backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
  788. });
  789. }
  790. if (_.isMsie() && _.isMsie() <= 7) {
  791. _.mixin(css.input, {
  792. marginTop: "-1px"
  793. });
  794. }
  795. return css;
  796. }();
  797. var EventBus = function() {
  798. "use strict";
  799. var namespace = "typeahead:";
  800. function EventBus(o) {
  801. if (!o || !o.el) {
  802. $.error("EventBus initialized without el");
  803. }
  804. this.$el = $(o.el);
  805. }
  806. _.mixin(EventBus.prototype, {
  807. trigger: function(type) {
  808. var args = [].slice.call(arguments, 1);
  809. this.$el.trigger(namespace + type, args);
  810. }
  811. });
  812. return EventBus;
  813. }();
  814. var EventEmitter = function() {
  815. "use strict";
  816. var splitter = /\s+/, nextTick = getNextTick();
  817. return {
  818. onSync: onSync,
  819. onAsync: onAsync,
  820. off: off,
  821. trigger: trigger
  822. };
  823. function on(method, types, cb, context) {
  824. var type;
  825. if (!cb) {
  826. return this;
  827. }
  828. types = types.split(splitter);
  829. cb = context ? bindContext(cb, context) : cb;
  830. this._callbacks = this._callbacks || {};
  831. while (type = types.shift()) {
  832. this._callbacks[type] = this._callbacks[type] || {
  833. sync: [],
  834. async: []
  835. };
  836. this._callbacks[type][method].push(cb);
  837. }
  838. return this;
  839. }
  840. function onAsync(types, cb, context) {
  841. return on.call(this, "async", types, cb, context);
  842. }
  843. function onSync(types, cb, context) {
  844. return on.call(this, "sync", types, cb, context);
  845. }
  846. function off(types) {
  847. var type;
  848. if (!this._callbacks) {
  849. return this;
  850. }
  851. types = types.split(splitter);
  852. while (type = types.shift()) {
  853. delete this._callbacks[type];
  854. }
  855. return this;
  856. }
  857. function trigger(types) {
  858. var type, callbacks, args, syncFlush, asyncFlush;
  859. if (!this._callbacks) {
  860. return this;
  861. }
  862. types = types.split(splitter);
  863. args = [].slice.call(arguments, 1);
  864. while ((type = types.shift()) && (callbacks = this._callbacks[type])) {
  865. syncFlush = getFlush(callbacks.sync, this, [ type ].concat(args));
  866. asyncFlush = getFlush(callbacks.async, this, [ type ].concat(args));
  867. syncFlush() && nextTick(asyncFlush);
  868. }
  869. return this;
  870. }
  871. function getFlush(callbacks, context, args) {
  872. return flush;
  873. function flush() {
  874. var cancelled;
  875. for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) {
  876. cancelled = callbacks[i].apply(context, args) === false;
  877. }
  878. return !cancelled;
  879. }
  880. }
  881. function getNextTick() {
  882. var nextTickFn;
  883. if (window.setImmediate) {
  884. nextTickFn = function nextTickSetImmediate(fn) {
  885. setImmediate(function() {
  886. fn();
  887. });
  888. };
  889. } else {
  890. nextTickFn = function nextTickSetTimeout(fn) {
  891. setTimeout(function() {
  892. fn();
  893. }, 0);
  894. };
  895. }
  896. return nextTickFn;
  897. }
  898. function bindContext(fn, context) {
  899. return fn.bind ? fn.bind(context) : function() {
  900. fn.apply(context, [].slice.call(arguments, 0));
  901. };
  902. }
  903. }();
  904. var highlight = function(doc) {
  905. "use strict";
  906. var defaults = {
  907. node: null,
  908. pattern: null,
  909. tagName: "strong",
  910. className: null,
  911. wordsOnly: false,
  912. caseSensitive: false
  913. };
  914. return function hightlight(o) {
  915. var regex;
  916. o = _.mixin({}, defaults, o);
  917. if (!o.node || !o.pattern) {
  918. return;
  919. }
  920. o.pattern = _.isArray(o.pattern) ? o.pattern : [ o.pattern ];
  921. regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly);
  922. traverse(o.node, hightlightTextNode);
  923. function hightlightTextNode(textNode) {
  924. var match, patternNode, wrapperNode;
  925. if (match = regex.exec(textNode.data)) {
  926. wrapperNode = doc.createElement(o.tagName);
  927. o.className && (wrapperNode.className = o.className);
  928. patternNode = textNode.splitText(match.index);
  929. patternNode.splitText(match[0].length);
  930. wrapperNode.appendChild(patternNode.cloneNode(true));
  931. textNode.parentNode.replaceChild(wrapperNode, patternNode);
  932. }
  933. return !!match;
  934. }
  935. function traverse(el, hightlightTextNode) {
  936. var childNode, TEXT_NODE_TYPE = 3;
  937. for (var i = 0; i < el.childNodes.length; i++) {
  938. childNode = el.childNodes[i];
  939. if (childNode.nodeType === TEXT_NODE_TYPE) {
  940. i += hightlightTextNode(childNode) ? 1 : 0;
  941. } else {
  942. traverse(childNode, hightlightTextNode);
  943. }
  944. }
  945. }
  946. };
  947. function getRegex(patterns, caseSensitive, wordsOnly) {
  948. var escapedPatterns = [], regexStr;
  949. for (var i = 0, len = patterns.length; i < len; i++) {
  950. escapedPatterns.push(_.escapeRegExChars(patterns[i]));
  951. }
  952. regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")";
  953. return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i");
  954. }
  955. }(window.document);
  956. var Input = function() {
  957. "use strict";
  958. var specialKeyCodeMap;
  959. specialKeyCodeMap = {
  960. 9: "tab",
  961. 27: "esc",
  962. 37: "left",
  963. 39: "right",
  964. 13: "enter",
  965. 38: "up",
  966. 40: "down"
  967. };
  968. function Input(o) {
  969. var that = this, onBlur, onFocus, onKeydown, onInput;
  970. o = o || {};
  971. if (!o.input) {
  972. $.error("input is missing");
  973. }
  974. onBlur = _.bind(this._onBlur, this);
  975. onFocus = _.bind(this._onFocus, this);
  976. onKeydown = _.bind(this._onKeydown, this);
  977. onInput = _.bind(this._onInput, this);
  978. this.$hint = $(o.hint);
  979. this.$input = $(o.input).on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown);
  980. if (this.$hint.length === 0) {
  981. this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop;
  982. }
  983. if (!_.isMsie()) {
  984. this.$input.on("input.tt", onInput);
  985. } else {
  986. this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) {
  987. if (specialKeyCodeMap[$e.which || $e.keyCode]) {
  988. return;
  989. }
  990. _.defer(_.bind(that._onInput, that, $e));
  991. });
  992. }
  993. this.query = this.$input.val();
  994. this.$overflowHelper = buildOverflowHelper(this.$input);
  995. }
  996. Input.normalizeQuery = function(str) {
  997. return (str || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
  998. };
  999. _.mixin(Input.prototype, EventEmitter, {
  1000. _onBlur: function onBlur() {
  1001. this.resetInputValue();
  1002. this.trigger("blurred");
  1003. },
  1004. _onFocus: function onFocus() {
  1005. this.trigger("focused");
  1006. },
  1007. _onKeydown: function onKeydown($e) {
  1008. var keyName = specialKeyCodeMap[$e.which || $e.keyCode];
  1009. this._managePreventDefault(keyName, $e);
  1010. if (keyName && this._shouldTrigger(keyName, $e)) {
  1011. this.trigger(keyName + "Keyed", $e);
  1012. }
  1013. },
  1014. _onInput: function onInput() {
  1015. this._checkInputValue();
  1016. },
  1017. _managePreventDefault: function managePreventDefault(keyName, $e) {
  1018. var preventDefault, hintValue, inputValue;
  1019. switch (keyName) {
  1020. case "tab":
  1021. hintValue = this.getHint();
  1022. inputValue = this.getInputValue();
  1023. preventDefault = hintValue && hintValue !== inputValue && !withModifier($e);
  1024. break;
  1025. case "up":
  1026. case "down":
  1027. preventDefault = !withModifier($e);
  1028. break;
  1029. default:
  1030. preventDefault = false;
  1031. }
  1032. preventDefault && $e.preventDefault();
  1033. },
  1034. _shouldTrigger: function shouldTrigger(keyName, $e) {
  1035. var trigger;
  1036. switch (keyName) {
  1037. case "tab":
  1038. trigger = !withModifier($e);
  1039. break;
  1040. default:
  1041. trigger = true;
  1042. }
  1043. return trigger;
  1044. },
  1045. _checkInputValue: function checkInputValue() {
  1046. var inputValue, areEquivalent, hasDifferentWhitespace;
  1047. inputValue = this.getInputValue();
  1048. areEquivalent = areQueriesEquivalent(inputValue, this.query);
  1049. hasDifferentWhitespace = areEquivalent ? this.query.length !== inputValue.length : false;
  1050. this.query = inputValue;
  1051. if (!areEquivalent) {
  1052. this.trigger("queryChanged", this.query);
  1053. } else if (hasDifferentWhitespace) {
  1054. this.trigger("whitespaceChanged", this.query);
  1055. }
  1056. },
  1057. focus: function focus() {
  1058. this.$input.focus();
  1059. },
  1060. blur: function blur() {
  1061. this.$input.blur();
  1062. },
  1063. getQuery: function getQuery() {
  1064. return this.query;
  1065. },
  1066. setQuery: function setQuery(query) {
  1067. this.query = query;
  1068. },
  1069. getInputValue: function getInputValue() {
  1070. return this.$input.val();
  1071. },
  1072. setInputValue: function setInputValue(value, silent) {
  1073. this.$input.val(value);
  1074. silent ? this.clearHint() : this._checkInputValue();
  1075. },
  1076. resetInputValue: function resetInputValue() {
  1077. this.setInputValue(this.query, true);
  1078. },
  1079. getHint: function getHint() {
  1080. return this.$hint.val();
  1081. },
  1082. setHint: function setHint(value) {
  1083. this.$hint.val(value);
  1084. },
  1085. clearHint: function clearHint() {
  1086. this.setHint("");
  1087. },
  1088. clearHintIfInvalid: function clearHintIfInvalid() {
  1089. var val, hint, valIsPrefixOfHint, isValid;
  1090. val = this.getInputValue();
  1091. hint = this.getHint();
  1092. valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0;
  1093. isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow();
  1094. !isValid && this.clearHint();
  1095. },
  1096. getLanguageDirection: function getLanguageDirection() {
  1097. return (this.$input.css("direction") || "ltr").toLowerCase();
  1098. },
  1099. hasOverflow: function hasOverflow() {
  1100. var constraint = this.$input.width() - 2;
  1101. this.$overflowHelper.text(this.getInputValue());
  1102. return this.$overflowHelper.width() >= constraint;
  1103. },
  1104. isCursorAtEnd: function() {
  1105. var valueLength, selectionStart, range;
  1106. valueLength = this.$input.val().length;
  1107. selectionStart = this.$input[0].selectionStart;
  1108. if (_.isNumber(selectionStart)) {
  1109. return selectionStart === valueLength;
  1110. } else if (document.selection) {
  1111. range = document.selection.createRange();
  1112. range.moveStart("character", -valueLength);
  1113. return valueLength === range.text.length;
  1114. }
  1115. return true;
  1116. },
  1117. destroy: function destroy() {
  1118. this.$hint.off(".tt");
  1119. this.$input.off(".tt");
  1120. this.$hint = this.$input = this.$overflowHelper = null;
  1121. }
  1122. });
  1123. return Input;
  1124. function buildOverflowHelper($input) {
  1125. return $('<pre aria-hidden="true"></pre>').css({
  1126. position: "absolute",
  1127. visibility: "hidden",
  1128. whiteSpace: "pre",
  1129. fontFamily: $input.css("font-family"),
  1130. fontSize: $input.css("font-size"),
  1131. fontStyle: $input.css("font-style"),
  1132. fontVariant: $input.css("font-variant"),
  1133. fontWeight: $input.css("font-weight"),
  1134. wordSpacing: $input.css("word-spacing"),
  1135. letterSpacing: $input.css("letter-spacing"),
  1136. textIndent: $input.css("text-indent"),
  1137. textRendering: $input.css("text-rendering"),
  1138. textTransform: $input.css("text-transform")
  1139. }).insertAfter($input);
  1140. }
  1141. function areQueriesEquivalent(a, b) {
  1142. return Input.normalizeQuery(a) === Input.normalizeQuery(b);
  1143. }
  1144. function withModifier($e) {
  1145. return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey;
  1146. }
  1147. }();
  1148. var Dataset = function() {
  1149. "use strict";
  1150. var datasetKey = "ttDataset", valueKey = "ttValue", datumKey = "ttDatum";
  1151. function Dataset(o) {
  1152. o = o || {};
  1153. o.templates = o.templates || {};
  1154. if (!o.source) {
  1155. $.error("missing source");
  1156. }
  1157. if (o.name && !isValidName(o.name)) {
  1158. $.error("invalid dataset name: " + o.name);
  1159. }
  1160. this.query = null;
  1161. this.highlight = !!o.highlight;
  1162. this.name = o.name || _.getUniqueId();
  1163. this.source = o.source;
  1164. this.displayFn = getDisplayFn(o.display || o.displayKey);
  1165. this.templates = getTemplates(o.templates, this.displayFn);
  1166. this.$el = $(html.dataset.replace("%CLASS%", this.name));
  1167. }
  1168. Dataset.extractDatasetName = function extractDatasetName(el) {
  1169. return $(el).data(datasetKey);
  1170. };
  1171. Dataset.extractValue = function extractDatum(el) {
  1172. return $(el).data(valueKey);
  1173. };
  1174. Dataset.extractDatum = function extractDatum(el) {
  1175. return $(el).data(datumKey);
  1176. };
  1177. _.mixin(Dataset.prototype, EventEmitter, {
  1178. _render: function render(query, suggestions) {
  1179. if (!this.$el) {
  1180. return;
  1181. }
  1182. var that = this, hasSuggestions;
  1183. this.$el.empty();
  1184. hasSuggestions = suggestions && suggestions.length;
  1185. if (!hasSuggestions && this.templates.empty) {
  1186. this.$el.html(getEmptyHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
  1187. } else if (hasSuggestions) {
  1188. this.$el.html(getSuggestionsHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
  1189. }
  1190. this.trigger("rendered");
  1191. function getEmptyHtml() {
  1192. return that.templates.empty({
  1193. query: query,
  1194. isEmpty: true
  1195. });
  1196. }
  1197. function getSuggestionsHtml() {
  1198. var $suggestions, nodes;
  1199. $suggestions = $(html.suggestions).css(css.suggestions);
  1200. nodes = _.map(suggestions, getSuggestionNode);
  1201. $suggestions.append.apply($suggestions, nodes);
  1202. that.highlight && highlight({
  1203. className: "tt-highlight",
  1204. node: $suggestions[0],
  1205. pattern: query
  1206. });
  1207. return $suggestions;
  1208. function getSuggestionNode(suggestion) {
  1209. var $el;
  1210. $el = $(html.suggestion).append(that.templates.suggestion(suggestion)).data(datasetKey, that.name).data(valueKey, that.displayFn(suggestion)).data(datumKey, suggestion);
  1211. $el.children().each(function() {
  1212. $(this).css(css.suggestionChild);
  1213. });
  1214. return $el;
  1215. }
  1216. }
  1217. function getHeaderHtml() {
  1218. return that.templates.header({
  1219. query: query,
  1220. isEmpty: !hasSuggestions
  1221. });
  1222. }
  1223. function getFooterHtml() {
  1224. return that.templates.footer({
  1225. query: query,
  1226. isEmpty: !hasSuggestions
  1227. });
  1228. }
  1229. },
  1230. getRoot: function getRoot() {
  1231. return this.$el;
  1232. },
  1233. update: function update(query) {
  1234. var that = this;
  1235. this.query = query;
  1236. this.canceled = false;
  1237. this.source(query, render);
  1238. function render(suggestions) {
  1239. if (!that.canceled && query === that.query) {
  1240. that._render(query, suggestions);
  1241. }
  1242. }
  1243. },
  1244. cancel: function cancel() {
  1245. this.canceled = true;
  1246. },
  1247. clear: function clear() {
  1248. this.cancel();
  1249. this.$el.empty();
  1250. this.trigger("rendered");
  1251. },
  1252. isEmpty: function isEmpty() {
  1253. return this.$el.is(":empty");
  1254. },
  1255. destroy: function destroy() {
  1256. this.$el = null;
  1257. }
  1258. });
  1259. return Dataset;
  1260. function getDisplayFn(display) {
  1261. display = display || "value";
  1262. return _.isFunction(display) ? display : displayFn;
  1263. function displayFn(obj) {
  1264. return obj[display];
  1265. }
  1266. }
  1267. function getTemplates(templates, displayFn) {
  1268. return {
  1269. empty: templates.empty && _.templatify(templates.empty),
  1270. header: templates.header && _.templatify(templates.header),
  1271. footer: templates.footer && _.templatify(templates.footer),
  1272. suggestion: templates.suggestion || suggestionTemplate
  1273. };
  1274. function suggestionTemplate(context) {
  1275. return "<p>" + displayFn(context) + "</p>";
  1276. }
  1277. }
  1278. function isValidName(str) {
  1279. return /^[_a-zA-Z0-9-]+$/.test(str);
  1280. }
  1281. }();
  1282. var Dropdown = function() {
  1283. "use strict";
  1284. function Dropdown(o) {
  1285. var that = this, onSuggestionClick, onSuggestionMouseEnter, onSuggestionMouseLeave;
  1286. o = o || {};
  1287. if (!o.menu) {
  1288. $.error("menu is required");
  1289. }
  1290. this.isOpen = false;
  1291. this.isEmpty = true;
  1292. this.datasets = _.map(o.datasets, initializeDataset);
  1293. onSuggestionClick = _.bind(this._onSuggestionClick, this);
  1294. onSuggestionMouseEnter = _.bind(this._onSuggestionMouseEnter, this);
  1295. onSuggestionMouseLeave = _.bind(this._onSuggestionMouseLeave, this);
  1296. this.$menu = $(o.menu).on("click.tt", ".tt-suggestion", onSuggestionClick).on("mouseenter.tt", ".tt-suggestion", onSuggestionMouseEnter).on("mouseleave.tt", ".tt-suggestion", onSuggestionMouseLeave);
  1297. _.each(this.datasets, function(dataset) {
  1298. that.$menu.append(dataset.getRoot());
  1299. dataset.onSync("rendered", that._onRendered, that);
  1300. });
  1301. }
  1302. _.mixin(Dropdown.prototype, EventEmitter, {
  1303. _onSuggestionClick: function onSuggestionClick($e) {
  1304. this.trigger("suggestionClicked", $($e.currentTarget));
  1305. },
  1306. _onSuggestionMouseEnter: function onSuggestionMouseEnter($e) {
  1307. this._removeCursor();
  1308. this._setCursor($($e.currentTarget), true);
  1309. },
  1310. _onSuggestionMouseLeave: function onSuggestionMouseLeave() {
  1311. this._removeCursor();
  1312. },
  1313. _onRendered: function onRendered() {
  1314. this.isEmpty = _.every(this.datasets, isDatasetEmpty);
  1315. this.isEmpty ? this._hide() : this.isOpen && this._show();
  1316. this.trigger("datasetRendered");
  1317. function isDatasetEmpty(dataset) {
  1318. return dataset.isEmpty();
  1319. }
  1320. },
  1321. _hide: function() {
  1322. this.$menu.hide();
  1323. },
  1324. _show: function() {
  1325. this.$menu.css("display", "block");
  1326. },
  1327. _getSuggestions: function getSuggestions() {
  1328. return this.$menu.find(".tt-suggestion");
  1329. },
  1330. _getCursor: function getCursor() {
  1331. return this.$menu.find(".tt-cursor").first();
  1332. },
  1333. _setCursor: function setCursor($el, silent) {
  1334. $el.first().addClass("tt-cursor");
  1335. !silent && this.trigger("cursorMoved");
  1336. },
  1337. _removeCursor: function removeCursor() {
  1338. this._getCursor().removeClass("tt-cursor");
  1339. },
  1340. _moveCursor: function moveCursor(increment) {
  1341. var $suggestions, $oldCursor, newCursorIndex, $newCursor;
  1342. if (!this.isOpen) {
  1343. return;
  1344. }
  1345. $oldCursor = this._getCursor();
  1346. $suggestions = this._getSuggestions();
  1347. this._removeCursor();
  1348. newCursorIndex = $suggestions.index($oldCursor) + increment;
  1349. newCursorIndex = (newCursorIndex + 1) % ($suggestions.length + 1) - 1;
  1350. if (newCursorIndex === -1) {
  1351. this.trigger("cursorRemoved");
  1352. return;
  1353. } else if (newCursorIndex < -1) {
  1354. newCursorIndex = $suggestions.length - 1;
  1355. }
  1356. this._setCursor($newCursor = $suggestions.eq(newCursorIndex));
  1357. this._ensureVisible($newCursor);
  1358. },
  1359. _ensureVisible: function ensureVisible($el) {
  1360. var elTop, elBottom, menuScrollTop, menuHeight;
  1361. elTop = $el.position().top;
  1362. elBottom = elTop + $el.outerHeight(true);
  1363. menuScrollTop = this.$menu.scrollTop();
  1364. menuHeight = this.$menu.height() + parseInt(this.$menu.css("paddingTop"), 10) + parseInt(this.$menu.css("paddingBottom"), 10);
  1365. if (elTop < 0) {
  1366. this.$menu.scrollTop(menuScrollTop + elTop);
  1367. } else if (menuHeight < elBottom) {
  1368. this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight));
  1369. }
  1370. },
  1371. close: function close() {
  1372. if (this.isOpen) {
  1373. this.isOpen = false;
  1374. this._removeCursor();
  1375. this._hide();
  1376. this.trigger("closed");
  1377. }
  1378. },
  1379. open: function open() {
  1380. if (!this.isOpen) {
  1381. this.isOpen = true;
  1382. !this.isEmpty && this._show();
  1383. this.trigger("opened");
  1384. }
  1385. },
  1386. setLanguageDirection: function setLanguageDirection(dir) {
  1387. this.$menu.css(dir === "ltr" ? css.ltr : css.rtl);
  1388. },
  1389. moveCursorUp: function moveCursorUp() {
  1390. this._moveCursor(-1);
  1391. },
  1392. moveCursorDown: function moveCursorDown() {
  1393. this._moveCursor(+1);
  1394. },
  1395. getDatumForSuggestion: function getDatumForSuggestion($el) {
  1396. var datum = null;
  1397. if ($el.length) {
  1398. datum = {
  1399. raw: Dataset.extractDatum($el),
  1400. value: Dataset.extractValue($el),
  1401. datasetName: Dataset.extractDatasetName($el)
  1402. };
  1403. }
  1404. return datum;
  1405. },
  1406. getDatumForCursor: function getDatumForCursor() {
  1407. return this.getDatumForSuggestion(this._getCursor().first());
  1408. },
  1409. getDatumForTopSuggestion: function getDatumForTopSuggestion() {
  1410. return this.getDatumForSuggestion(this._getSuggestions().first());
  1411. },
  1412. update: function update(query) {
  1413. _.each(this.datasets, updateDataset);
  1414. function updateDataset(dataset) {
  1415. dataset.update(query);
  1416. }
  1417. },
  1418. empty: function empty() {
  1419. _.each(this.datasets, clearDataset);
  1420. this.isEmpty = true;
  1421. function clearDataset(dataset) {
  1422. dataset.clear();
  1423. }
  1424. },
  1425. isVisible: function isVisible() {
  1426. return this.isOpen && !this.isEmpty;
  1427. },
  1428. destroy: function destroy() {
  1429. this.$menu.off(".tt");
  1430. this.$menu = null;
  1431. _.each(this.datasets, destroyDataset);
  1432. function destroyDataset(dataset) {
  1433. dataset.destroy();
  1434. }
  1435. }
  1436. });
  1437. return Dropdown;
  1438. function initializeDataset(oDataset) {
  1439. return new Dataset(oDataset);
  1440. }
  1441. }();
  1442. var Typeahead = function() {
  1443. "use strict";
  1444. var attrsKey = "ttAttrs";
  1445. function Typeahead(o) {
  1446. var $menu, $input, $hint;
  1447. o = o || {};
  1448. if (!o.input) {
  1449. $.error("missing input");
  1450. }
  1451. this.isActivated = false;
  1452. this.autoselect = !!o.autoselect;
  1453. this.minLength = _.isNumber(o.minLength) ? o.minLength : 1;
  1454. this.$node = buildDom(o.input, o.withHint);
  1455. $menu = this.$node.find(".tt-dropdown-menu");
  1456. $input = this.$node.find(".tt-input");
  1457. $hint = this.$node.find(".tt-hint");
  1458. $input.on("blur.tt", function($e) {
  1459. var active, isActive, hasActive;
  1460. active = document.activeElement;
  1461. isActive = $menu.is(active);
  1462. hasActive = $menu.has(active).length > 0;
  1463. if (_.isMsie() && (isActive || hasActive)) {
  1464. $e.preventDefault();
  1465. $e.stopImmediatePropagation();
  1466. _.defer(function() {
  1467. $input.focus();
  1468. });
  1469. }
  1470. });
  1471. $menu.on("mousedown.tt", function($e) {
  1472. $e.preventDefault();
  1473. });
  1474. this.eventBus = o.eventBus || new EventBus({
  1475. el: $input
  1476. });
  1477. this.dropdown = new Dropdown({
  1478. menu: $menu,
  1479. datasets: o.datasets
  1480. }).onSync("suggestionClicked", this._onSuggestionClicked, this).onSync("cursorMoved", this._onCursorMoved, this).onSync("cursorRemoved", this._onCursorRemoved, this).onSync("opened", this._onOpened, this).onSync("closed", this._onClosed, this).onAsync("datasetRendered", this._onDatasetRendered, this);
  1481. this.input = new Input({
  1482. input: $input,
  1483. hint: $hint
  1484. }).onSync("focused", this._onFocused, this).onSync("blurred", this._onBlurred, this).onSync("enterKeyed", this._onEnterKeyed, this).onSync("tabKeyed", this._onTabKeyed, this).onSync("escKeyed", this._onEscKeyed, this).onSync("upKeyed", this._onUpKeyed, this).onSync("downKeyed", this._onDownKeyed, this).onSync("leftKeyed", this._onLeftKeyed, this).onSync("rightKeyed", this._onRightKeyed, this).onSync("queryChanged", this._onQueryChanged, this).onSync("whitespaceChanged", this._onWhitespaceChanged, this);
  1485. this._setLanguageDirection();
  1486. }
  1487. _.mixin(Typeahead.prototype, {
  1488. _onSuggestionClicked: function onSuggestionClicked(type, $el) {
  1489. var datum;
  1490. if (datum = this.dropdown.getDatumForSuggestion($el)) {
  1491. this._select(datum);
  1492. }
  1493. },
  1494. _onCursorMoved: function onCursorMoved() {
  1495. var datum = this.dropdown.getDatumForCursor();
  1496. this.input.setInputValue(datum.value, true);
  1497. this.eventBus.trigger("cursorchanged", datum.raw, datum.datasetName);
  1498. },
  1499. _onCursorRemoved: function onCursorRemoved() {
  1500. this.input.resetInputValue();
  1501. this._updateHint();
  1502. },
  1503. _onDatasetRendered: function onDatasetRendered() {
  1504. this._updateHint();
  1505. },
  1506. _onOpened: function onOpened() {
  1507. this._updateHint();
  1508. this.eventBus.trigger("opened");
  1509. },
  1510. _onClosed: function onClosed() {
  1511. this.input.clearHint();
  1512. this.eventBus.trigger("closed");
  1513. },
  1514. _onFocused: function onFocused() {
  1515. this.isActivated = true;
  1516. this.dropdown.open();
  1517. },
  1518. _onBlurred: function onBlurred() {
  1519. this.isActivated = false;
  1520. this.dropdown.empty();
  1521. this.dropdown.close();
  1522. },
  1523. _onEnterKeyed: function onEnterKeyed(type, $e) {
  1524. var cursorDatum, topSuggestionDatum;
  1525. cursorDatum = this.dropdown.getDatumForCursor();
  1526. topSuggestionDatum = this.dropdown.getDatumForTopSuggestion();
  1527. if (cursorDatum) {
  1528. this._select(cursorDatum);
  1529. $e.preventDefault();
  1530. } else if (this.autoselect && topSuggestionDatum) {
  1531. this._select(topSuggestionDatum);
  1532. $e.preventDefault();
  1533. }
  1534. },
  1535. _onTabKeyed: function onTabKeyed(type, $e) {
  1536. var datum;
  1537. if (datum = this.dropdown.getDatumForCursor()) {
  1538. this._select(datum);
  1539. $e.preventDefault();
  1540. } else {
  1541. this._autocomplete(true);
  1542. }
  1543. },
  1544. _onEscKeyed: function onEscKeyed() {
  1545. this.dropdown.close();
  1546. this.input.resetInputValue();
  1547. },
  1548. _onUpKeyed: function onUpKeyed() {
  1549. var query = this.input.getQuery();
  1550. this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorUp();
  1551. this.dropdown.open();
  1552. },
  1553. _onDownKeyed: function onDownKeyed() {
  1554. var query = this.input.getQuery();
  1555. this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorDown();
  1556. this.dropdown.open();
  1557. },
  1558. _onLeftKeyed: function onLeftKeyed() {
  1559. this.dir === "rtl" && this._autocomplete();
  1560. },
  1561. _onRightKeyed: function onRightKeyed() {
  1562. this.dir === "ltr" && this._autocomplete();
  1563. },
  1564. _onQueryChanged: function onQueryChanged(e, query) {
  1565. this.input.clearHintIfInvalid();
  1566. query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.empty();
  1567. this.dropdown.open();
  1568. this._setLanguageDirection();
  1569. },
  1570. _onWhitespaceChanged: function onWhitespaceChanged() {
  1571. this._updateHint();
  1572. this.dropdown.open();
  1573. },
  1574. _setLanguageDirection: function setLanguageDirection() {
  1575. var dir;
  1576. if (this.dir !== (dir = this.input.getLanguageDirection())) {
  1577. this.dir = dir;
  1578. this.$node.css("direction", dir);
  1579. this.dropdown.setLanguageDirection(dir);
  1580. }
  1581. },
  1582. _updateHint: function updateHint() {
  1583. var datum, val, query, escapedQuery, frontMatchRegEx, match;
  1584. datum = this.dropdown.getDatumForTopSuggestion();
  1585. if (datum && this.dropdown.isVisible() && !this.input.hasOverflow()) {
  1586. val = this.input.getInputValue();
  1587. query = Input.normalizeQuery(val);
  1588. escapedQuery = _.escapeRegExChars(query);
  1589. frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i");
  1590. match = frontMatchRegEx.exec(datum.value);
  1591. match ? this.input.setHint(val + match[1]) : this.input.clearHint();
  1592. } else {
  1593. this.input.clearHint();
  1594. }
  1595. },
  1596. _autocomplete: function autocomplete(laxCursor) {
  1597. var hint, query, isCursorAtEnd, datum;
  1598. hint = this.input.getHint();
  1599. query = this.input.getQuery();
  1600. isCursorAtEnd = laxCursor || this.input.isCursorAtEnd();
  1601. if (hint && query !== hint && isCursorAtEnd) {
  1602. datum = this.dropdown.getDatumForTopSuggestion();
  1603. datum && this.input.setInputValue(datum.value);
  1604. this.eventBus.trigger("autocompleted", datum.raw, datum.datasetName);
  1605. }
  1606. },
  1607. _select: function select(datum) {
  1608. this.input.setQuery(datum.value);
  1609. this.input.setInputValue(datum.value, true);
  1610. this._setLanguageDirection();
  1611. this.eventBus.trigger("selected", datum.raw, datum.datasetName);
  1612. this.dropdown.close();
  1613. _.defer(_.bind(this.dropdown.empty, this.dropdown));
  1614. },
  1615. open: function open() {
  1616. this.dropdown.open();
  1617. },
  1618. close: function close() {
  1619. this.dropdown.close();
  1620. },
  1621. setVal: function setVal(val) {
  1622. val = _.toStr(val);
  1623. if (this.isActivated) {
  1624. this.input.setInputValue(val);
  1625. } else {
  1626. this.input.setQuery(val);
  1627. this.input.setInputValue(val, true);
  1628. }
  1629. this._setLanguageDirection();
  1630. },
  1631. getVal: function getVal() {
  1632. return this.input.getQuery();
  1633. },
  1634. destroy: function destroy() {
  1635. this.input.destroy();
  1636. this.dropdown.destroy();
  1637. destroyDomStructure(this.$node);
  1638. this.$node = null;
  1639. }
  1640. });
  1641. return Typeahead;
  1642. function buildDom(input, withHint) {
  1643. var $input, $wrapper, $dropdown, $hint;
  1644. $input = $(input);
  1645. $wrapper = $(html.wrapper).css(css.wrapper);
  1646. $dropdown = $(html.dropdown).css(css.dropdown);
  1647. $hint = $input.clone().css(css.hint).css(getBackgroundStyles($input));
  1648. $hint.val("").removeData().addClass("tt-hint").removeAttr("id name placeholder required").prop("readonly", true).attr({
  1649. autocomplete: "off",
  1650. spellcheck: "false",
  1651. tabindex: -1
  1652. });
  1653. $input.data(attrsKey, {
  1654. dir: $input.attr("dir"),
  1655. autocomplete: $input.attr("autocomplete"),
  1656. spellcheck: $input.attr("spellcheck"),
  1657. style: $input.attr("style")
  1658. });
  1659. $input.addClass("tt-input").attr({
  1660. autocomplete: "off",
  1661. spellcheck: false
  1662. }).css(withHint ? css.input : css.inputWithNoHint);
  1663. try {
  1664. !$input.attr("dir") && $input.attr("dir", "auto");
  1665. } catch (e) {}
  1666. return $input.wrap($wrapper).parent().prepend(withHint ? $hint : null).append($dropdown);
  1667. }
  1668. function getBackgroundStyles($el) {
  1669. return {
  1670. backgroundAttachment: $el.css("background-attachment"),
  1671. backgroundClip: $el.css("background-clip"),
  1672. backgroundColor: $el.css("background-color"),
  1673. backgroundImage: $el.css("background-image"),
  1674. backgroundOrigin: $el.css("background-origin"),
  1675. backgroundPosition: $el.css("background-position"),
  1676. backgroundRepeat: $el.css("background-repeat"),
  1677. backgroundSize: $el.css("background-size")
  1678. };
  1679. }
  1680. function destroyDomStructure($node) {
  1681. var $input = $node.find(".tt-input");
  1682. _.each($input.data(attrsKey), function(val, key) {
  1683. _.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val);
  1684. });
  1685. $input.detach().removeData(attrsKey).removeClass("tt-input").insertAfter($node);
  1686. $node.remove();
  1687. }
  1688. }();
  1689. (function() {
  1690. "use strict";
  1691. var old, typeaheadKey, methods;
  1692. old = $.fn.typeahead;
  1693. typeaheadKey = "ttTypeahead";
  1694. methods = {
  1695. initialize: function initialize(o, datasets) {
  1696. datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1);
  1697. o = o || {};
  1698. return this.each(attach);
  1699. function attach() {
  1700. var $input = $(this), eventBus, typeahead;
  1701. _.each(datasets, function(d) {
  1702. d.highlight = !!o.highlight;
  1703. });
  1704. typeahead = new Typeahead({
  1705. input: $input,
  1706. eventBus: eventBus = new EventBus({
  1707. el: $input
  1708. }),
  1709. withHint: _.isUndefined(o.hint) ? true : !!o.hint,
  1710. minLength: o.minLength,
  1711. autoselect: o.autoselect,
  1712. datasets: datasets
  1713. });
  1714. $input.data(typeaheadKey, typeahead);
  1715. }
  1716. },
  1717. open: function open() {
  1718. return this.each(openTypeahead);
  1719. function openTypeahead() {
  1720. var $input = $(this), typeahead;
  1721. if (typeahead = $input.data(typeaheadKey)) {
  1722. typeahead.open();
  1723. }
  1724. }
  1725. },
  1726. close: function close() {
  1727. return this.each(closeTypeahead);
  1728. function closeTypeahead() {
  1729. var $input = $(this), typeahead;
  1730. if (typeahead = $input.data(typeaheadKey)) {
  1731. typeahead.close();
  1732. }
  1733. }
  1734. },
  1735. val: function val(newVal) {
  1736. return !arguments.length ? getVal(this.first()) : this.each(setVal);
  1737. function setVal() {
  1738. var $input = $(this), typeahead;
  1739. if (typeahead = $input.data(typeaheadKey)) {
  1740. typeahead.setVal(newVal);
  1741. }
  1742. }
  1743. function getVal($input) {
  1744. var typeahead, query;
  1745. if (typeahead = $input.data(typeaheadKey)) {
  1746. query = typeahead.getVal();
  1747. }
  1748. return query;
  1749. }
  1750. },
  1751. destroy: function destroy() {
  1752. return this.each(unattach);
  1753. function unattach() {
  1754. var $input = $(this), typeahead;
  1755. if (typeahead = $input.data(typeaheadKey)) {
  1756. typeahead.destroy();
  1757. $input.removeData(typeaheadKey);
  1758. }
  1759. }
  1760. }
  1761. };
  1762. $.fn.typeahead = function(method) {
  1763. var tts;
  1764. if (methods[method] && method !== "initialize") {
  1765. tts = this.filter(function() {
  1766. return !!$(this).data(typeaheadKey);
  1767. });
  1768. return methods[method].apply(tts, [].slice.call(arguments, 1));
  1769. } else {
  1770. return methods.initialize.apply(this, arguments);
  1771. }
  1772. };
  1773. $.fn.typeahead.noConflict = function noConflict() {
  1774. $.fn.typeahead = old;
  1775. return this;
  1776. };
  1777. })();
  1778. })(window.jQuery);