typeahead.jquery.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  1. /*!
  2. * typeahead.js 0.10.5
  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 html = function() {
  129. return {
  130. wrapper: '<span class="twitter-typeahead"></span>',
  131. dropdown: '<span class="tt-dropdown-menu"></span>',
  132. dataset: '<div class="tt-dataset-%CLASS%"></div>',
  133. suggestions: '<span class="tt-suggestions"></span>',
  134. suggestion: '<div class="tt-suggestion"></div>'
  135. };
  136. }();
  137. var css = function() {
  138. "use strict";
  139. var css = {
  140. wrapper: {
  141. position: "relative",
  142. display: "inline-block"
  143. },
  144. hint: {
  145. position: "absolute",
  146. top: "0",
  147. left: "0",
  148. borderColor: "transparent",
  149. boxShadow: "none",
  150. opacity: "1"
  151. },
  152. input: {
  153. position: "relative",
  154. verticalAlign: "top",
  155. backgroundColor: "transparent"
  156. },
  157. inputWithNoHint: {
  158. position: "relative",
  159. verticalAlign: "top"
  160. },
  161. dropdown: {
  162. position: "absolute",
  163. top: "100%",
  164. left: "0",
  165. zIndex: "100",
  166. display: "none"
  167. },
  168. suggestions: {
  169. display: "block"
  170. },
  171. suggestion: {
  172. whiteSpace: "nowrap",
  173. cursor: "pointer"
  174. },
  175. suggestionChild: {
  176. whiteSpace: "normal"
  177. },
  178. ltr: {
  179. left: "0",
  180. right: "auto"
  181. },
  182. rtl: {
  183. left: "auto",
  184. right: " 0"
  185. }
  186. };
  187. if (_.isMsie()) {
  188. _.mixin(css.input, {
  189. backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
  190. });
  191. }
  192. if (_.isMsie() && _.isMsie() <= 7) {
  193. _.mixin(css.input, {
  194. marginTop: "-1px"
  195. });
  196. }
  197. return css;
  198. }();
  199. var EventBus = function() {
  200. "use strict";
  201. var namespace = "typeahead:";
  202. function EventBus(o) {
  203. if (!o || !o.el) {
  204. $.error("EventBus initialized without el");
  205. }
  206. this.$el = $(o.el);
  207. }
  208. _.mixin(EventBus.prototype, {
  209. trigger: function(type) {
  210. var args = [].slice.call(arguments, 1);
  211. this.$el.trigger(namespace + type, args);
  212. }
  213. });
  214. return EventBus;
  215. }();
  216. var EventEmitter = function() {
  217. "use strict";
  218. var splitter = /\s+/, nextTick = getNextTick();
  219. return {
  220. onSync: onSync,
  221. onAsync: onAsync,
  222. off: off,
  223. trigger: trigger
  224. };
  225. function on(method, types, cb, context) {
  226. var type;
  227. if (!cb) {
  228. return this;
  229. }
  230. types = types.split(splitter);
  231. cb = context ? bindContext(cb, context) : cb;
  232. this._callbacks = this._callbacks || {};
  233. while (type = types.shift()) {
  234. this._callbacks[type] = this._callbacks[type] || {
  235. sync: [],
  236. async: []
  237. };
  238. this._callbacks[type][method].push(cb);
  239. }
  240. return this;
  241. }
  242. function onAsync(types, cb, context) {
  243. return on.call(this, "async", types, cb, context);
  244. }
  245. function onSync(types, cb, context) {
  246. return on.call(this, "sync", types, cb, context);
  247. }
  248. function off(types) {
  249. var type;
  250. if (!this._callbacks) {
  251. return this;
  252. }
  253. types = types.split(splitter);
  254. while (type = types.shift()) {
  255. delete this._callbacks[type];
  256. }
  257. return this;
  258. }
  259. function trigger(types) {
  260. var type, callbacks, args, syncFlush, asyncFlush;
  261. if (!this._callbacks) {
  262. return this;
  263. }
  264. types = types.split(splitter);
  265. args = [].slice.call(arguments, 1);
  266. while ((type = types.shift()) && (callbacks = this._callbacks[type])) {
  267. syncFlush = getFlush(callbacks.sync, this, [ type ].concat(args));
  268. asyncFlush = getFlush(callbacks.async, this, [ type ].concat(args));
  269. syncFlush() && nextTick(asyncFlush);
  270. }
  271. return this;
  272. }
  273. function getFlush(callbacks, context, args) {
  274. return flush;
  275. function flush() {
  276. var cancelled;
  277. for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) {
  278. cancelled = callbacks[i].apply(context, args) === false;
  279. }
  280. return !cancelled;
  281. }
  282. }
  283. function getNextTick() {
  284. var nextTickFn;
  285. if (window.setImmediate) {
  286. nextTickFn = function nextTickSetImmediate(fn) {
  287. setImmediate(function() {
  288. fn();
  289. });
  290. };
  291. } else {
  292. nextTickFn = function nextTickSetTimeout(fn) {
  293. setTimeout(function() {
  294. fn();
  295. }, 0);
  296. };
  297. }
  298. return nextTickFn;
  299. }
  300. function bindContext(fn, context) {
  301. return fn.bind ? fn.bind(context) : function() {
  302. fn.apply(context, [].slice.call(arguments, 0));
  303. };
  304. }
  305. }();
  306. var highlight = function(doc) {
  307. "use strict";
  308. var defaults = {
  309. node: null,
  310. pattern: null,
  311. tagName: "strong",
  312. className: null,
  313. wordsOnly: false,
  314. caseSensitive: false
  315. };
  316. return function hightlight(o) {
  317. var regex;
  318. o = _.mixin({}, defaults, o);
  319. if (!o.node || !o.pattern) {
  320. return;
  321. }
  322. o.pattern = _.isArray(o.pattern) ? o.pattern : [ o.pattern ];
  323. regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly);
  324. traverse(o.node, hightlightTextNode);
  325. function hightlightTextNode(textNode) {
  326. var match, patternNode, wrapperNode;
  327. if (match = regex.exec(textNode.data)) {
  328. wrapperNode = doc.createElement(o.tagName);
  329. o.className && (wrapperNode.className = o.className);
  330. patternNode = textNode.splitText(match.index);
  331. patternNode.splitText(match[0].length);
  332. wrapperNode.appendChild(patternNode.cloneNode(true));
  333. textNode.parentNode.replaceChild(wrapperNode, patternNode);
  334. }
  335. return !!match;
  336. }
  337. function traverse(el, hightlightTextNode) {
  338. var childNode, TEXT_NODE_TYPE = 3;
  339. for (var i = 0; i < el.childNodes.length; i++) {
  340. childNode = el.childNodes[i];
  341. if (childNode.nodeType === TEXT_NODE_TYPE) {
  342. i += hightlightTextNode(childNode) ? 1 : 0;
  343. } else {
  344. traverse(childNode, hightlightTextNode);
  345. }
  346. }
  347. }
  348. };
  349. function getRegex(patterns, caseSensitive, wordsOnly) {
  350. var escapedPatterns = [], regexStr;
  351. for (var i = 0, len = patterns.length; i < len; i++) {
  352. escapedPatterns.push(_.escapeRegExChars(patterns[i]));
  353. }
  354. regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")";
  355. return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i");
  356. }
  357. }(window.document);
  358. var Input = function() {
  359. "use strict";
  360. var specialKeyCodeMap;
  361. specialKeyCodeMap = {
  362. 9: "tab",
  363. 27: "esc",
  364. 37: "left",
  365. 39: "right",
  366. 13: "enter",
  367. 38: "up",
  368. 40: "down"
  369. };
  370. function Input(o) {
  371. var that = this, onBlur, onFocus, onKeydown, onInput;
  372. o = o || {};
  373. if (!o.input) {
  374. $.error("input is missing");
  375. }
  376. onBlur = _.bind(this._onBlur, this);
  377. onFocus = _.bind(this._onFocus, this);
  378. onKeydown = _.bind(this._onKeydown, this);
  379. onInput = _.bind(this._onInput, this);
  380. this.$hint = $(o.hint);
  381. this.$input = $(o.input).on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown);
  382. if (this.$hint.length === 0) {
  383. this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop;
  384. }
  385. if (!_.isMsie()) {
  386. this.$input.on("input.tt", onInput);
  387. } else {
  388. this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) {
  389. if (specialKeyCodeMap[$e.which || $e.keyCode]) {
  390. return;
  391. }
  392. _.defer(_.bind(that._onInput, that, $e));
  393. });
  394. }
  395. this.query = this.$input.val();
  396. this.$overflowHelper = buildOverflowHelper(this.$input);
  397. }
  398. Input.normalizeQuery = function(str) {
  399. return (str || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
  400. };
  401. _.mixin(Input.prototype, EventEmitter, {
  402. _onBlur: function onBlur() {
  403. this.resetInputValue();
  404. this.trigger("blurred");
  405. },
  406. _onFocus: function onFocus() {
  407. this.trigger("focused");
  408. },
  409. _onKeydown: function onKeydown($e) {
  410. var keyName = specialKeyCodeMap[$e.which || $e.keyCode];
  411. this._managePreventDefault(keyName, $e);
  412. if (keyName && this._shouldTrigger(keyName, $e)) {
  413. this.trigger(keyName + "Keyed", $e);
  414. }
  415. },
  416. _onInput: function onInput() {
  417. this._checkInputValue();
  418. },
  419. _managePreventDefault: function managePreventDefault(keyName, $e) {
  420. var preventDefault, hintValue, inputValue;
  421. switch (keyName) {
  422. case "tab":
  423. hintValue = this.getHint();
  424. inputValue = this.getInputValue();
  425. preventDefault = hintValue && hintValue !== inputValue && !withModifier($e);
  426. break;
  427. case "up":
  428. case "down":
  429. preventDefault = !withModifier($e);
  430. break;
  431. default:
  432. preventDefault = false;
  433. }
  434. preventDefault && $e.preventDefault();
  435. },
  436. _shouldTrigger: function shouldTrigger(keyName, $e) {
  437. var trigger;
  438. switch (keyName) {
  439. case "tab":
  440. trigger = !withModifier($e);
  441. break;
  442. default:
  443. trigger = true;
  444. }
  445. return trigger;
  446. },
  447. _checkInputValue: function checkInputValue() {
  448. var inputValue, areEquivalent, hasDifferentWhitespace;
  449. inputValue = this.getInputValue();
  450. areEquivalent = areQueriesEquivalent(inputValue, this.query);
  451. hasDifferentWhitespace = areEquivalent ? this.query.length !== inputValue.length : false;
  452. this.query = inputValue;
  453. if (!areEquivalent) {
  454. this.trigger("queryChanged", this.query);
  455. } else if (hasDifferentWhitespace) {
  456. this.trigger("whitespaceChanged", this.query);
  457. }
  458. },
  459. focus: function focus() {
  460. this.$input.focus();
  461. },
  462. blur: function blur() {
  463. this.$input.blur();
  464. },
  465. getQuery: function getQuery() {
  466. return this.query;
  467. },
  468. setQuery: function setQuery(query) {
  469. this.query = query;
  470. },
  471. getInputValue: function getInputValue() {
  472. return this.$input.val();
  473. },
  474. setInputValue: function setInputValue(value, silent) {
  475. this.$input.val(value);
  476. silent ? this.clearHint() : this._checkInputValue();
  477. },
  478. resetInputValue: function resetInputValue() {
  479. this.setInputValue(this.query, true);
  480. },
  481. getHint: function getHint() {
  482. return this.$hint.val();
  483. },
  484. setHint: function setHint(value) {
  485. this.$hint.val(value);
  486. },
  487. clearHint: function clearHint() {
  488. this.setHint("");
  489. },
  490. clearHintIfInvalid: function clearHintIfInvalid() {
  491. var val, hint, valIsPrefixOfHint, isValid;
  492. val = this.getInputValue();
  493. hint = this.getHint();
  494. valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0;
  495. isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow();
  496. !isValid && this.clearHint();
  497. },
  498. getLanguageDirection: function getLanguageDirection() {
  499. return (this.$input.css("direction") || "ltr").toLowerCase();
  500. },
  501. hasOverflow: function hasOverflow() {
  502. var constraint = this.$input.width() - 2;
  503. this.$overflowHelper.text(this.getInputValue());
  504. return this.$overflowHelper.width() >= constraint;
  505. },
  506. isCursorAtEnd: function() {
  507. var valueLength, selectionStart, range;
  508. valueLength = this.$input.val().length;
  509. selectionStart = this.$input[0].selectionStart;
  510. if (_.isNumber(selectionStart)) {
  511. return selectionStart === valueLength;
  512. } else if (document.selection) {
  513. range = document.selection.createRange();
  514. range.moveStart("character", -valueLength);
  515. return valueLength === range.text.length;
  516. }
  517. return true;
  518. },
  519. destroy: function destroy() {
  520. this.$hint.off(".tt");
  521. this.$input.off(".tt");
  522. this.$hint = this.$input = this.$overflowHelper = null;
  523. }
  524. });
  525. return Input;
  526. function buildOverflowHelper($input) {
  527. return $('<pre aria-hidden="true"></pre>').css({
  528. position: "absolute",
  529. visibility: "hidden",
  530. whiteSpace: "pre",
  531. fontFamily: $input.css("font-family"),
  532. fontSize: $input.css("font-size"),
  533. fontStyle: $input.css("font-style"),
  534. fontVariant: $input.css("font-variant"),
  535. fontWeight: $input.css("font-weight"),
  536. wordSpacing: $input.css("word-spacing"),
  537. letterSpacing: $input.css("letter-spacing"),
  538. textIndent: $input.css("text-indent"),
  539. textRendering: $input.css("text-rendering"),
  540. textTransform: $input.css("text-transform")
  541. }).insertAfter($input);
  542. }
  543. function areQueriesEquivalent(a, b) {
  544. return Input.normalizeQuery(a) === Input.normalizeQuery(b);
  545. }
  546. function withModifier($e) {
  547. return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey;
  548. }
  549. }();
  550. var Dataset = function() {
  551. "use strict";
  552. var datasetKey = "ttDataset", valueKey = "ttValue", datumKey = "ttDatum";
  553. function Dataset(o) {
  554. o = o || {};
  555. o.templates = o.templates || {};
  556. if (!o.source) {
  557. $.error("missing source");
  558. }
  559. if (o.name && !isValidName(o.name)) {
  560. $.error("invalid dataset name: " + o.name);
  561. }
  562. this.query = null;
  563. this.highlight = !!o.highlight;
  564. this.name = o.name || _.getUniqueId();
  565. this.source = o.source;
  566. this.displayFn = getDisplayFn(o.display || o.displayKey);
  567. this.templates = getTemplates(o.templates, this.displayFn);
  568. this.$el = $(html.dataset.replace("%CLASS%", this.name));
  569. }
  570. Dataset.extractDatasetName = function extractDatasetName(el) {
  571. return $(el).data(datasetKey);
  572. };
  573. Dataset.extractValue = function extractDatum(el) {
  574. return $(el).data(valueKey);
  575. };
  576. Dataset.extractDatum = function extractDatum(el) {
  577. return $(el).data(datumKey);
  578. };
  579. _.mixin(Dataset.prototype, EventEmitter, {
  580. _render: function render(query, suggestions) {
  581. if (!this.$el) {
  582. return;
  583. }
  584. var that = this, hasSuggestions;
  585. this.$el.empty();
  586. hasSuggestions = suggestions && suggestions.length;
  587. if (!hasSuggestions && this.templates.empty) {
  588. this.$el.html(getEmptyHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
  589. } else if (hasSuggestions) {
  590. this.$el.html(getSuggestionsHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
  591. }
  592. this.trigger("rendered");
  593. function getEmptyHtml() {
  594. return that.templates.empty({
  595. query: query,
  596. isEmpty: true
  597. });
  598. }
  599. function getSuggestionsHtml() {
  600. var $suggestions, nodes;
  601. $suggestions = $(html.suggestions).css(css.suggestions);
  602. nodes = _.map(suggestions, getSuggestionNode);
  603. $suggestions.append.apply($suggestions, nodes);
  604. that.highlight && highlight({
  605. className: "tt-highlight",
  606. node: $suggestions[0],
  607. pattern: query
  608. });
  609. return $suggestions;
  610. function getSuggestionNode(suggestion) {
  611. var $el;
  612. $el = $(html.suggestion).append(that.templates.suggestion(suggestion)).data(datasetKey, that.name).data(valueKey, that.displayFn(suggestion)).data(datumKey, suggestion);
  613. $el.children().each(function() {
  614. $(this).css(css.suggestionChild);
  615. });
  616. return $el;
  617. }
  618. }
  619. function getHeaderHtml() {
  620. return that.templates.header({
  621. query: query,
  622. isEmpty: !hasSuggestions
  623. });
  624. }
  625. function getFooterHtml() {
  626. return that.templates.footer({
  627. query: query,
  628. isEmpty: !hasSuggestions
  629. });
  630. }
  631. },
  632. getRoot: function getRoot() {
  633. return this.$el;
  634. },
  635. update: function update(query) {
  636. var that = this;
  637. this.query = query;
  638. this.canceled = false;
  639. this.source(query, render);
  640. function render(suggestions) {
  641. if (!that.canceled && query === that.query) {
  642. that._render(query, suggestions);
  643. }
  644. }
  645. },
  646. cancel: function cancel() {
  647. this.canceled = true;
  648. },
  649. clear: function clear() {
  650. this.cancel();
  651. this.$el.empty();
  652. this.trigger("rendered");
  653. },
  654. isEmpty: function isEmpty() {
  655. return this.$el.is(":empty");
  656. },
  657. destroy: function destroy() {
  658. this.$el = null;
  659. }
  660. });
  661. return Dataset;
  662. function getDisplayFn(display) {
  663. display = display || "value";
  664. return _.isFunction(display) ? display : displayFn;
  665. function displayFn(obj) {
  666. return obj[display];
  667. }
  668. }
  669. function getTemplates(templates, displayFn) {
  670. return {
  671. empty: templates.empty && _.templatify(templates.empty),
  672. header: templates.header && _.templatify(templates.header),
  673. footer: templates.footer && _.templatify(templates.footer),
  674. suggestion: templates.suggestion || suggestionTemplate
  675. };
  676. function suggestionTemplate(context) {
  677. return "<p>" + displayFn(context) + "</p>";
  678. }
  679. }
  680. function isValidName(str) {
  681. return /^[_a-zA-Z0-9-]+$/.test(str);
  682. }
  683. }();
  684. var Dropdown = function() {
  685. "use strict";
  686. function Dropdown(o) {
  687. var that = this, onSuggestionClick, onSuggestionMouseEnter, onSuggestionMouseLeave;
  688. o = o || {};
  689. if (!o.menu) {
  690. $.error("menu is required");
  691. }
  692. this.isOpen = false;
  693. this.isEmpty = true;
  694. this.datasets = _.map(o.datasets, initializeDataset);
  695. onSuggestionClick = _.bind(this._onSuggestionClick, this);
  696. onSuggestionMouseEnter = _.bind(this._onSuggestionMouseEnter, this);
  697. onSuggestionMouseLeave = _.bind(this._onSuggestionMouseLeave, this);
  698. this.$menu = $(o.menu).on("click.tt", ".tt-suggestion", onSuggestionClick).on("mouseenter.tt", ".tt-suggestion", onSuggestionMouseEnter).on("mouseleave.tt", ".tt-suggestion", onSuggestionMouseLeave);
  699. _.each(this.datasets, function(dataset) {
  700. that.$menu.append(dataset.getRoot());
  701. dataset.onSync("rendered", that._onRendered, that);
  702. });
  703. }
  704. _.mixin(Dropdown.prototype, EventEmitter, {
  705. _onSuggestionClick: function onSuggestionClick($e) {
  706. this.trigger("suggestionClicked", $($e.currentTarget));
  707. },
  708. _onSuggestionMouseEnter: function onSuggestionMouseEnter($e) {
  709. this._removeCursor();
  710. this._setCursor($($e.currentTarget), true);
  711. },
  712. _onSuggestionMouseLeave: function onSuggestionMouseLeave() {
  713. this._removeCursor();
  714. },
  715. _onRendered: function onRendered() {
  716. this.isEmpty = _.every(this.datasets, isDatasetEmpty);
  717. this.isEmpty ? this._hide() : this.isOpen && this._show();
  718. this.trigger("datasetRendered");
  719. function isDatasetEmpty(dataset) {
  720. return dataset.isEmpty();
  721. }
  722. },
  723. _hide: function() {
  724. this.$menu.hide();
  725. },
  726. _show: function() {
  727. this.$menu.css("display", "block");
  728. },
  729. _getSuggestions: function getSuggestions() {
  730. return this.$menu.find(".tt-suggestion");
  731. },
  732. _getCursor: function getCursor() {
  733. return this.$menu.find(".tt-cursor").first();
  734. },
  735. _setCursor: function setCursor($el, silent) {
  736. $el.first().addClass("tt-cursor");
  737. !silent && this.trigger("cursorMoved");
  738. },
  739. _removeCursor: function removeCursor() {
  740. this._getCursor().removeClass("tt-cursor");
  741. },
  742. _moveCursor: function moveCursor(increment) {
  743. var $suggestions, $oldCursor, newCursorIndex, $newCursor;
  744. if (!this.isOpen) {
  745. return;
  746. }
  747. $oldCursor = this._getCursor();
  748. $suggestions = this._getSuggestions();
  749. this._removeCursor();
  750. newCursorIndex = $suggestions.index($oldCursor) + increment;
  751. newCursorIndex = (newCursorIndex + 1) % ($suggestions.length + 1) - 1;
  752. if (newCursorIndex === -1) {
  753. this.trigger("cursorRemoved");
  754. return;
  755. } else if (newCursorIndex < -1) {
  756. newCursorIndex = $suggestions.length - 1;
  757. }
  758. this._setCursor($newCursor = $suggestions.eq(newCursorIndex));
  759. this._ensureVisible($newCursor);
  760. },
  761. _ensureVisible: function ensureVisible($el) {
  762. var elTop, elBottom, menuScrollTop, menuHeight;
  763. elTop = $el.position().top;
  764. elBottom = elTop + $el.outerHeight(true);
  765. menuScrollTop = this.$menu.scrollTop();
  766. menuHeight = this.$menu.height() + parseInt(this.$menu.css("paddingTop"), 10) + parseInt(this.$menu.css("paddingBottom"), 10);
  767. if (elTop < 0) {
  768. this.$menu.scrollTop(menuScrollTop + elTop);
  769. } else if (menuHeight < elBottom) {
  770. this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight));
  771. }
  772. },
  773. close: function close() {
  774. if (this.isOpen) {
  775. this.isOpen = false;
  776. this._removeCursor();
  777. this._hide();
  778. this.trigger("closed");
  779. }
  780. },
  781. open: function open() {
  782. if (!this.isOpen) {
  783. this.isOpen = true;
  784. !this.isEmpty && this._show();
  785. this.trigger("opened");
  786. }
  787. },
  788. setLanguageDirection: function setLanguageDirection(dir) {
  789. this.$menu.css(dir === "ltr" ? css.ltr : css.rtl);
  790. },
  791. moveCursorUp: function moveCursorUp() {
  792. this._moveCursor(-1);
  793. },
  794. moveCursorDown: function moveCursorDown() {
  795. this._moveCursor(+1);
  796. },
  797. getDatumForSuggestion: function getDatumForSuggestion($el) {
  798. var datum = null;
  799. if ($el.length) {
  800. datum = {
  801. raw: Dataset.extractDatum($el),
  802. value: Dataset.extractValue($el),
  803. datasetName: Dataset.extractDatasetName($el)
  804. };
  805. }
  806. return datum;
  807. },
  808. getDatumForCursor: function getDatumForCursor() {
  809. return this.getDatumForSuggestion(this._getCursor().first());
  810. },
  811. getDatumForTopSuggestion: function getDatumForTopSuggestion() {
  812. return this.getDatumForSuggestion(this._getSuggestions().first());
  813. },
  814. update: function update(query) {
  815. _.each(this.datasets, updateDataset);
  816. function updateDataset(dataset) {
  817. dataset.update(query);
  818. }
  819. },
  820. empty: function empty() {
  821. _.each(this.datasets, clearDataset);
  822. this.isEmpty = true;
  823. function clearDataset(dataset) {
  824. dataset.clear();
  825. }
  826. },
  827. isVisible: function isVisible() {
  828. return this.isOpen && !this.isEmpty;
  829. },
  830. destroy: function destroy() {
  831. this.$menu.off(".tt");
  832. this.$menu = null;
  833. _.each(this.datasets, destroyDataset);
  834. function destroyDataset(dataset) {
  835. dataset.destroy();
  836. }
  837. }
  838. });
  839. return Dropdown;
  840. function initializeDataset(oDataset) {
  841. return new Dataset(oDataset);
  842. }
  843. }();
  844. var Typeahead = function() {
  845. "use strict";
  846. var attrsKey = "ttAttrs";
  847. function Typeahead(o) {
  848. var $menu, $input, $hint;
  849. o = o || {};
  850. if (!o.input) {
  851. $.error("missing input");
  852. }
  853. this.isActivated = false;
  854. this.autoselect = !!o.autoselect;
  855. this.minLength = _.isNumber(o.minLength) ? o.minLength : 1;
  856. this.$node = buildDom(o.input, o.withHint);
  857. $menu = this.$node.find(".tt-dropdown-menu");
  858. $input = this.$node.find(".tt-input");
  859. $hint = this.$node.find(".tt-hint");
  860. $input.on("blur.tt", function($e) {
  861. var active, isActive, hasActive;
  862. active = document.activeElement;
  863. isActive = $menu.is(active);
  864. hasActive = $menu.has(active).length > 0;
  865. if (_.isMsie() && (isActive || hasActive)) {
  866. $e.preventDefault();
  867. $e.stopImmediatePropagation();
  868. _.defer(function() {
  869. $input.focus();
  870. });
  871. }
  872. });
  873. $menu.on("mousedown.tt", function($e) {
  874. $e.preventDefault();
  875. });
  876. this.eventBus = o.eventBus || new EventBus({
  877. el: $input
  878. });
  879. this.dropdown = new Dropdown({
  880. menu: $menu,
  881. datasets: o.datasets
  882. }).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);
  883. this.input = new Input({
  884. input: $input,
  885. hint: $hint
  886. }).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);
  887. this._setLanguageDirection();
  888. }
  889. _.mixin(Typeahead.prototype, {
  890. _onSuggestionClicked: function onSuggestionClicked(type, $el) {
  891. var datum;
  892. if (datum = this.dropdown.getDatumForSuggestion($el)) {
  893. this._select(datum);
  894. }
  895. },
  896. _onCursorMoved: function onCursorMoved() {
  897. var datum = this.dropdown.getDatumForCursor();
  898. this.input.setInputValue(datum.value, true);
  899. this.eventBus.trigger("cursorchanged", datum.raw, datum.datasetName);
  900. },
  901. _onCursorRemoved: function onCursorRemoved() {
  902. this.input.resetInputValue();
  903. this._updateHint();
  904. },
  905. _onDatasetRendered: function onDatasetRendered() {
  906. this._updateHint();
  907. },
  908. _onOpened: function onOpened() {
  909. this._updateHint();
  910. this.eventBus.trigger("opened");
  911. },
  912. _onClosed: function onClosed() {
  913. this.input.clearHint();
  914. this.eventBus.trigger("closed");
  915. },
  916. _onFocused: function onFocused() {
  917. this.isActivated = true;
  918. this.dropdown.open();
  919. },
  920. _onBlurred: function onBlurred() {
  921. this.isActivated = false;
  922. this.dropdown.empty();
  923. this.dropdown.close();
  924. },
  925. _onEnterKeyed: function onEnterKeyed(type, $e) {
  926. var cursorDatum, topSuggestionDatum;
  927. cursorDatum = this.dropdown.getDatumForCursor();
  928. topSuggestionDatum = this.dropdown.getDatumForTopSuggestion();
  929. if (cursorDatum) {
  930. this._select(cursorDatum);
  931. $e.preventDefault();
  932. } else if (this.autoselect && topSuggestionDatum) {
  933. this._select(topSuggestionDatum);
  934. $e.preventDefault();
  935. }
  936. },
  937. _onTabKeyed: function onTabKeyed(type, $e) {
  938. var datum;
  939. if (datum = this.dropdown.getDatumForCursor()) {
  940. this._select(datum);
  941. $e.preventDefault();
  942. } else {
  943. this._autocomplete(true);
  944. }
  945. },
  946. _onEscKeyed: function onEscKeyed() {
  947. this.dropdown.close();
  948. this.input.resetInputValue();
  949. },
  950. _onUpKeyed: function onUpKeyed() {
  951. var query = this.input.getQuery();
  952. this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorUp();
  953. this.dropdown.open();
  954. },
  955. _onDownKeyed: function onDownKeyed() {
  956. var query = this.input.getQuery();
  957. this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorDown();
  958. this.dropdown.open();
  959. },
  960. _onLeftKeyed: function onLeftKeyed() {
  961. this.dir === "rtl" && this._autocomplete();
  962. },
  963. _onRightKeyed: function onRightKeyed() {
  964. this.dir === "ltr" && this._autocomplete();
  965. },
  966. _onQueryChanged: function onQueryChanged(e, query) {
  967. this.input.clearHintIfInvalid();
  968. query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.empty();
  969. this.dropdown.open();
  970. this._setLanguageDirection();
  971. },
  972. _onWhitespaceChanged: function onWhitespaceChanged() {
  973. this._updateHint();
  974. this.dropdown.open();
  975. },
  976. _setLanguageDirection: function setLanguageDirection() {
  977. var dir;
  978. if (this.dir !== (dir = this.input.getLanguageDirection())) {
  979. this.dir = dir;
  980. this.$node.css("direction", dir);
  981. this.dropdown.setLanguageDirection(dir);
  982. }
  983. },
  984. _updateHint: function updateHint() {
  985. var datum, val, query, escapedQuery, frontMatchRegEx, match;
  986. datum = this.dropdown.getDatumForTopSuggestion();
  987. if (datum && this.dropdown.isVisible() && !this.input.hasOverflow()) {
  988. val = this.input.getInputValue();
  989. query = Input.normalizeQuery(val);
  990. escapedQuery = _.escapeRegExChars(query);
  991. frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i");
  992. match = frontMatchRegEx.exec(datum.value);
  993. match ? this.input.setHint(val + match[1]) : this.input.clearHint();
  994. } else {
  995. this.input.clearHint();
  996. }
  997. },
  998. _autocomplete: function autocomplete(laxCursor) {
  999. var hint, query, isCursorAtEnd, datum;
  1000. hint = this.input.getHint();
  1001. query = this.input.getQuery();
  1002. isCursorAtEnd = laxCursor || this.input.isCursorAtEnd();
  1003. if (hint && query !== hint && isCursorAtEnd) {
  1004. datum = this.dropdown.getDatumForTopSuggestion();
  1005. datum && this.input.setInputValue(datum.value);
  1006. this.eventBus.trigger("autocompleted", datum.raw, datum.datasetName);
  1007. }
  1008. },
  1009. _select: function select(datum) {
  1010. this.input.setQuery(datum.value);
  1011. this.input.setInputValue(datum.value, true);
  1012. this._setLanguageDirection();
  1013. this.eventBus.trigger("selected", datum.raw, datum.datasetName);
  1014. this.dropdown.close();
  1015. _.defer(_.bind(this.dropdown.empty, this.dropdown));
  1016. },
  1017. open: function open() {
  1018. this.dropdown.open();
  1019. },
  1020. close: function close() {
  1021. this.dropdown.close();
  1022. },
  1023. setVal: function setVal(val) {
  1024. val = _.toStr(val);
  1025. if (this.isActivated) {
  1026. this.input.setInputValue(val);
  1027. } else {
  1028. this.input.setQuery(val);
  1029. this.input.setInputValue(val, true);
  1030. }
  1031. this._setLanguageDirection();
  1032. },
  1033. getVal: function getVal() {
  1034. return this.input.getQuery();
  1035. },
  1036. destroy: function destroy() {
  1037. this.input.destroy();
  1038. this.dropdown.destroy();
  1039. destroyDomStructure(this.$node);
  1040. this.$node = null;
  1041. }
  1042. });
  1043. return Typeahead;
  1044. function buildDom(input, withHint) {
  1045. var $input, $wrapper, $dropdown, $hint;
  1046. $input = $(input);
  1047. $wrapper = $(html.wrapper).css(css.wrapper);
  1048. $dropdown = $(html.dropdown).css(css.dropdown);
  1049. $hint = $input.clone().css(css.hint).css(getBackgroundStyles($input));
  1050. $hint.val("").removeData().addClass("tt-hint").removeAttr("id name placeholder required").prop("readonly", true).attr({
  1051. autocomplete: "off",
  1052. spellcheck: "false",
  1053. tabindex: -1
  1054. });
  1055. $input.data(attrsKey, {
  1056. dir: $input.attr("dir"),
  1057. autocomplete: $input.attr("autocomplete"),
  1058. spellcheck: $input.attr("spellcheck"),
  1059. style: $input.attr("style")
  1060. });
  1061. $input.addClass("tt-input").attr({
  1062. autocomplete: "off",
  1063. spellcheck: false
  1064. }).css(withHint ? css.input : css.inputWithNoHint);
  1065. try {
  1066. !$input.attr("dir") && $input.attr("dir", "auto");
  1067. } catch (e) {}
  1068. return $input.wrap($wrapper).parent().prepend(withHint ? $hint : null).append($dropdown);
  1069. }
  1070. function getBackgroundStyles($el) {
  1071. return {
  1072. backgroundAttachment: $el.css("background-attachment"),
  1073. backgroundClip: $el.css("background-clip"),
  1074. backgroundColor: $el.css("background-color"),
  1075. backgroundImage: $el.css("background-image"),
  1076. backgroundOrigin: $el.css("background-origin"),
  1077. backgroundPosition: $el.css("background-position"),
  1078. backgroundRepeat: $el.css("background-repeat"),
  1079. backgroundSize: $el.css("background-size")
  1080. };
  1081. }
  1082. function destroyDomStructure($node) {
  1083. var $input = $node.find(".tt-input");
  1084. _.each($input.data(attrsKey), function(val, key) {
  1085. _.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val);
  1086. });
  1087. $input.detach().removeData(attrsKey).removeClass("tt-input").insertAfter($node);
  1088. $node.remove();
  1089. }
  1090. }();
  1091. (function() {
  1092. "use strict";
  1093. var old, typeaheadKey, methods;
  1094. old = $.fn.typeahead;
  1095. typeaheadKey = "ttTypeahead";
  1096. methods = {
  1097. initialize: function initialize(o, datasets) {
  1098. datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1);
  1099. o = o || {};
  1100. return this.each(attach);
  1101. function attach() {
  1102. var $input = $(this), eventBus, typeahead;
  1103. _.each(datasets, function(d) {
  1104. d.highlight = !!o.highlight;
  1105. });
  1106. typeahead = new Typeahead({
  1107. input: $input,
  1108. eventBus: eventBus = new EventBus({
  1109. el: $input
  1110. }),
  1111. withHint: _.isUndefined(o.hint) ? true : !!o.hint,
  1112. minLength: o.minLength,
  1113. autoselect: o.autoselect,
  1114. datasets: datasets
  1115. });
  1116. $input.data(typeaheadKey, typeahead);
  1117. }
  1118. },
  1119. open: function open() {
  1120. return this.each(openTypeahead);
  1121. function openTypeahead() {
  1122. var $input = $(this), typeahead;
  1123. if (typeahead = $input.data(typeaheadKey)) {
  1124. typeahead.open();
  1125. }
  1126. }
  1127. },
  1128. close: function close() {
  1129. return this.each(closeTypeahead);
  1130. function closeTypeahead() {
  1131. var $input = $(this), typeahead;
  1132. if (typeahead = $input.data(typeaheadKey)) {
  1133. typeahead.close();
  1134. }
  1135. }
  1136. },
  1137. val: function val(newVal) {
  1138. return !arguments.length ? getVal(this.first()) : this.each(setVal);
  1139. function setVal() {
  1140. var $input = $(this), typeahead;
  1141. if (typeahead = $input.data(typeaheadKey)) {
  1142. typeahead.setVal(newVal);
  1143. }
  1144. }
  1145. function getVal($input) {
  1146. var typeahead, query;
  1147. if (typeahead = $input.data(typeaheadKey)) {
  1148. query = typeahead.getVal();
  1149. }
  1150. return query;
  1151. }
  1152. },
  1153. destroy: function destroy() {
  1154. return this.each(unattach);
  1155. function unattach() {
  1156. var $input = $(this), typeahead;
  1157. if (typeahead = $input.data(typeaheadKey)) {
  1158. typeahead.destroy();
  1159. $input.removeData(typeaheadKey);
  1160. }
  1161. }
  1162. }
  1163. };
  1164. $.fn.typeahead = function(method) {
  1165. var tts;
  1166. if (methods[method] && method !== "initialize") {
  1167. tts = this.filter(function() {
  1168. return !!$(this).data(typeaheadKey);
  1169. });
  1170. return methods[method].apply(tts, [].slice.call(arguments, 1));
  1171. } else {
  1172. return methods.initialize.apply(this, arguments);
  1173. }
  1174. };
  1175. $.fn.typeahead.noConflict = function noConflict() {
  1176. $.fn.typeahead = old;
  1177. return this;
  1178. };
  1179. })();
  1180. })(window.jQuery);