typeahead.jquery.js 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674
  1. /*!
  2. * typeahead.js 1.2.0
  3. * https://github.com/twitter/typeahead.js
  4. * Copyright 2013-2017 Twitter, Inc. and other contributors; Licensed MIT
  5. */
  6. (function(root, factory) {
  7. if (typeof define === "function" && define.amd) {
  8. define([ "jquery" ], function(a0) {
  9. return factory(a0);
  10. });
  11. } else if (typeof exports === "object") {
  12. module.exports = factory(require("jquery"));
  13. } else {
  14. factory(root["jQuery"]);
  15. }
  16. })(this, function($) {
  17. var _ = function() {
  18. "use strict";
  19. return {
  20. isMsie: function() {
  21. return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false;
  22. },
  23. isBlankString: function(str) {
  24. return !str || /^\s*$/.test(str);
  25. },
  26. escapeRegExChars: function(str) {
  27. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  28. },
  29. isString: function(obj) {
  30. return typeof obj === "string";
  31. },
  32. isNumber: function(obj) {
  33. return typeof obj === "number";
  34. },
  35. isArray: $.isArray,
  36. isFunction: $.isFunction,
  37. isObject: $.isPlainObject,
  38. isUndefined: function(obj) {
  39. return typeof obj === "undefined";
  40. },
  41. isElement: function(obj) {
  42. return !!(obj && obj.nodeType === 1);
  43. },
  44. isJQuery: function(obj) {
  45. return obj instanceof $;
  46. },
  47. toStr: function toStr(s) {
  48. return _.isUndefined(s) || s === null ? "" : s + "";
  49. },
  50. bind: $.proxy,
  51. each: function(collection, cb) {
  52. $.each(collection, reverseArgs);
  53. function reverseArgs(index, value) {
  54. return cb(value, index);
  55. }
  56. },
  57. map: $.map,
  58. filter: $.grep,
  59. every: function(obj, test) {
  60. var result = true;
  61. if (!obj) {
  62. return result;
  63. }
  64. $.each(obj, function(key, val) {
  65. if (!(result = test.call(null, val, key, obj))) {
  66. return false;
  67. }
  68. });
  69. return !!result;
  70. },
  71. some: function(obj, test) {
  72. var result = false;
  73. if (!obj) {
  74. return result;
  75. }
  76. $.each(obj, function(key, val) {
  77. if (result = test.call(null, val, key, obj)) {
  78. return false;
  79. }
  80. });
  81. return !!result;
  82. },
  83. mixin: $.extend,
  84. identity: function(x) {
  85. return x;
  86. },
  87. clone: function(obj) {
  88. return $.extend(true, {}, obj);
  89. },
  90. getIdGenerator: function() {
  91. var counter = 0;
  92. return function() {
  93. return counter++;
  94. };
  95. },
  96. templatify: function templatify(obj) {
  97. return $.isFunction(obj) ? obj : template;
  98. function template() {
  99. return String(obj);
  100. }
  101. },
  102. defer: function(fn) {
  103. setTimeout(fn, 0);
  104. },
  105. debounce: function(func, wait, immediate) {
  106. var timeout, result;
  107. return function() {
  108. var context = this, args = arguments, later, callNow;
  109. later = function() {
  110. timeout = null;
  111. if (!immediate) {
  112. result = func.apply(context, args);
  113. }
  114. };
  115. callNow = immediate && !timeout;
  116. clearTimeout(timeout);
  117. timeout = setTimeout(later, wait);
  118. if (callNow) {
  119. result = func.apply(context, args);
  120. }
  121. return result;
  122. };
  123. },
  124. throttle: function(func, wait) {
  125. var context, args, timeout, result, previous, later;
  126. previous = 0;
  127. later = function() {
  128. previous = new Date();
  129. timeout = null;
  130. result = func.apply(context, args);
  131. };
  132. return function() {
  133. var now = new Date(), remaining = wait - (now - previous);
  134. context = this;
  135. args = arguments;
  136. if (remaining <= 0) {
  137. clearTimeout(timeout);
  138. timeout = null;
  139. previous = now;
  140. result = func.apply(context, args);
  141. } else if (!timeout) {
  142. timeout = setTimeout(later, remaining);
  143. }
  144. return result;
  145. };
  146. },
  147. stringify: function(val) {
  148. return _.isString(val) ? val : JSON.stringify(val);
  149. },
  150. guid: function() {
  151. function _p8(s) {
  152. var p = (Math.random().toString(16) + "000000000").substr(2, 8);
  153. return s ? "-" + p.substr(0, 4) + "-" + p.substr(4, 4) : p;
  154. }
  155. return "tt-" + _p8() + _p8(true) + _p8(true) + _p8();
  156. },
  157. noop: function() {}
  158. };
  159. }();
  160. var WWW = function() {
  161. "use strict";
  162. var defaultClassNames = {
  163. wrapper: "twitter-typeahead",
  164. input: "tt-input",
  165. hint: "tt-hint",
  166. menu: "tt-menu",
  167. dataset: "tt-dataset",
  168. suggestion: "tt-suggestion",
  169. selectable: "tt-selectable",
  170. empty: "tt-empty",
  171. open: "tt-open",
  172. cursor: "tt-cursor",
  173. highlight: "tt-highlight"
  174. };
  175. return build;
  176. function build(o) {
  177. var www, classes;
  178. classes = _.mixin({}, defaultClassNames, o);
  179. www = {
  180. css: buildCss(),
  181. classes: classes,
  182. html: buildHtml(classes),
  183. selectors: buildSelectors(classes)
  184. };
  185. return {
  186. css: www.css,
  187. html: www.html,
  188. classes: www.classes,
  189. selectors: www.selectors,
  190. mixin: function(o) {
  191. _.mixin(o, www);
  192. }
  193. };
  194. }
  195. function buildHtml(c) {
  196. return {
  197. wrapper: '<span class="' + c.wrapper + '"></span>',
  198. menu: '<div role="listbox" class="' + c.menu + '"></div>'
  199. };
  200. }
  201. function buildSelectors(classes) {
  202. var selectors = {};
  203. _.each(classes, function(v, k) {
  204. selectors[k] = "." + v;
  205. });
  206. return selectors;
  207. }
  208. function buildCss() {
  209. var css = {
  210. wrapper: {
  211. position: "relative",
  212. display: "inline-block"
  213. },
  214. hint: {
  215. position: "absolute",
  216. top: "0",
  217. left: "0",
  218. borderColor: "transparent",
  219. boxShadow: "none",
  220. opacity: "1"
  221. },
  222. input: {
  223. position: "relative",
  224. verticalAlign: "top",
  225. backgroundColor: "transparent"
  226. },
  227. inputWithNoHint: {
  228. position: "relative",
  229. verticalAlign: "top"
  230. },
  231. menu: {
  232. position: "absolute",
  233. top: "100%",
  234. left: "0",
  235. zIndex: "100",
  236. display: "none"
  237. },
  238. ltr: {
  239. left: "0",
  240. right: "auto"
  241. },
  242. rtl: {
  243. left: "auto",
  244. right: " 0"
  245. }
  246. };
  247. if (_.isMsie()) {
  248. _.mixin(css.input, {
  249. backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
  250. });
  251. }
  252. return css;
  253. }
  254. }();
  255. var EventBus = function() {
  256. "use strict";
  257. var namespace, deprecationMap;
  258. namespace = "typeahead:";
  259. deprecationMap = {
  260. render: "rendered",
  261. cursorchange: "cursorchanged",
  262. select: "selected",
  263. autocomplete: "autocompleted"
  264. };
  265. function EventBus(o) {
  266. if (!o || !o.el) {
  267. $.error("EventBus initialized without el");
  268. }
  269. this.$el = $(o.el);
  270. }
  271. _.mixin(EventBus.prototype, {
  272. _trigger: function(type, args) {
  273. var $e = $.Event(namespace + type);
  274. this.$el.trigger.call(this.$el, $e, args || []);
  275. return $e;
  276. },
  277. before: function(type) {
  278. var args, $e;
  279. args = [].slice.call(arguments, 1);
  280. $e = this._trigger("before" + type, args);
  281. return $e.isDefaultPrevented();
  282. },
  283. trigger: function(type) {
  284. var deprecatedType;
  285. this._trigger(type, [].slice.call(arguments, 1));
  286. if (deprecatedType = deprecationMap[type]) {
  287. this._trigger(deprecatedType, [].slice.call(arguments, 1));
  288. }
  289. }
  290. });
  291. return EventBus;
  292. }();
  293. var EventEmitter = function() {
  294. "use strict";
  295. var splitter = /\s+/, nextTick = getNextTick();
  296. return {
  297. onSync: onSync,
  298. onAsync: onAsync,
  299. off: off,
  300. trigger: trigger
  301. };
  302. function on(method, types, cb, context) {
  303. var type;
  304. if (!cb) {
  305. return this;
  306. }
  307. types = types.split(splitter);
  308. cb = context ? bindContext(cb, context) : cb;
  309. this._callbacks = this._callbacks || {};
  310. while (type = types.shift()) {
  311. this._callbacks[type] = this._callbacks[type] || {
  312. sync: [],
  313. async: []
  314. };
  315. this._callbacks[type][method].push(cb);
  316. }
  317. return this;
  318. }
  319. function onAsync(types, cb, context) {
  320. return on.call(this, "async", types, cb, context);
  321. }
  322. function onSync(types, cb, context) {
  323. return on.call(this, "sync", types, cb, context);
  324. }
  325. function off(types) {
  326. var type;
  327. if (!this._callbacks) {
  328. return this;
  329. }
  330. types = types.split(splitter);
  331. while (type = types.shift()) {
  332. delete this._callbacks[type];
  333. }
  334. return this;
  335. }
  336. function trigger(types) {
  337. var type, callbacks, args, syncFlush, asyncFlush;
  338. if (!this._callbacks) {
  339. return this;
  340. }
  341. types = types.split(splitter);
  342. args = [].slice.call(arguments, 1);
  343. while ((type = types.shift()) && (callbacks = this._callbacks[type])) {
  344. syncFlush = getFlush(callbacks.sync, this, [ type ].concat(args));
  345. asyncFlush = getFlush(callbacks.async, this, [ type ].concat(args));
  346. syncFlush() && nextTick(asyncFlush);
  347. }
  348. return this;
  349. }
  350. function getFlush(callbacks, context, args) {
  351. return flush;
  352. function flush() {
  353. var cancelled;
  354. for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) {
  355. cancelled = callbacks[i].apply(context, args) === false;
  356. }
  357. return !cancelled;
  358. }
  359. }
  360. function getNextTick() {
  361. var nextTickFn;
  362. if (window.setImmediate) {
  363. nextTickFn = function nextTickSetImmediate(fn) {
  364. setImmediate(function() {
  365. fn();
  366. });
  367. };
  368. } else {
  369. nextTickFn = function nextTickSetTimeout(fn) {
  370. setTimeout(function() {
  371. fn();
  372. }, 0);
  373. };
  374. }
  375. return nextTickFn;
  376. }
  377. function bindContext(fn, context) {
  378. return fn.bind ? fn.bind(context) : function() {
  379. fn.apply(context, [].slice.call(arguments, 0));
  380. };
  381. }
  382. }();
  383. var highlight = function(doc) {
  384. "use strict";
  385. var defaults = {
  386. node: null,
  387. pattern: null,
  388. tagName: "strong",
  389. className: null,
  390. wordsOnly: false,
  391. caseSensitive: false,
  392. diacriticInsensitive: false
  393. };
  394. var accented = {
  395. A: "[AaªÀ-Åà-åĀ-ąǍǎȀ-ȃȦȧᴬᵃḀḁẚẠ-ảₐ℀℁℻⒜Ⓐⓐ㍱-㍴㎀-㎄㎈㎉㎩-㎯㏂㏊㏟㏿Aa]",
  396. B: "[BbᴮᵇḂ-ḇℬ⒝Ⓑⓑ㍴㎅-㎇㏃㏈㏔㏝Bb]",
  397. C: "[CcÇçĆ-čᶜ℀ℂ℃℅℆ℭⅭⅽ⒞Ⓒⓒ㍶㎈㎉㎝㎠㎤㏄-㏇Cc]",
  398. D: "[DdĎďDŽ-džDZ-dzᴰᵈḊ-ḓⅅⅆⅮⅾ⒟Ⓓⓓ㋏㍲㍷-㍹㎗㎭-㎯㏅㏈Dd]",
  399. E: "[EeÈ-Ëè-ëĒ-ěȄ-ȇȨȩᴱᵉḘ-ḛẸ-ẽₑ℡ℯℰⅇ⒠Ⓔⓔ㉐㋍㋎Ee]",
  400. F: "[FfᶠḞḟ℉ℱ℻⒡Ⓕⓕ㎊-㎌㎙ff-fflFf]",
  401. G: "[GgĜ-ģǦǧǴǵᴳᵍḠḡℊ⒢Ⓖⓖ㋌㋍㎇㎍-㎏㎓㎬㏆㏉㏒㏿Gg]",
  402. H: "[HhĤĥȞȟʰᴴḢ-ḫẖℋ-ℎ⒣Ⓗⓗ㋌㍱㎐-㎔㏊㏋㏗Hh]",
  403. I: "[IiÌ-Ïì-ïĨ-İIJijǏǐȈ-ȋᴵᵢḬḭỈ-ịⁱℐℑℹⅈⅠ-ⅣⅥ-ⅨⅪⅫⅰ-ⅳⅵ-ⅸⅺⅻ⒤Ⓘⓘ㍺㏌㏕fiffiIi]",
  404. J: "[JjIJ-ĵLJ-njǰʲᴶⅉ⒥ⒿⓙⱼJj]",
  405. K: "[KkĶķǨǩᴷᵏḰ-ḵK⒦Ⓚⓚ㎄㎅㎉㎏㎑㎘㎞㎢㎦㎪㎸㎾㏀㏆㏍-㏏Kk]",
  406. L: "[LlĹ-ŀLJ-ljˡᴸḶḷḺ-ḽℒℓ℡Ⅼⅼ⒧Ⓛⓛ㋏㎈㎉㏐-㏓㏕㏖㏿flfflLl]",
  407. M: "[MmᴹᵐḾ-ṃ℠™ℳⅯⅿ⒨Ⓜⓜ㍷-㍹㎃㎆㎎㎒㎖㎙-㎨㎫㎳㎷㎹㎽㎿㏁㏂㏎㏐㏔-㏖㏘㏙㏞㏟Mm]",
  408. N: "[NnÑñŃ-ʼnNJ-njǸǹᴺṄ-ṋⁿℕ№⒩Ⓝⓝ㎁㎋㎚㎱㎵㎻㏌㏑Nn]",
  409. O: "[OoºÒ-Öò-öŌ-őƠơǑǒǪǫȌ-ȏȮȯᴼᵒỌ-ỏₒ℅№ℴ⒪Ⓞⓞ㍵㏇㏒㏖Oo]",
  410. P: "[PpᴾᵖṔ-ṗℙ⒫Ⓟⓟ㉐㍱㍶㎀㎊㎩-㎬㎰㎴㎺㏋㏗-㏚Pp]",
  411. Q: "[Qqℚ⒬Ⓠⓠ㏃Qq]",
  412. R: "[RrŔ-řȐ-ȓʳᴿᵣṘ-ṛṞṟ₨ℛ-ℝ⒭Ⓡⓡ㋍㍴㎭-㎯㏚㏛Rr]",
  413. S: "[SsŚ-šſȘșˢṠ-ṣ₨℁℠⒮Ⓢⓢ㎧㎨㎮-㎳㏛㏜stSs]",
  414. T: "[TtŢ-ťȚțᵀᵗṪ-ṱẗ℡™⒯Ⓣⓣ㉐㋏㎔㏏ſtstTt]",
  415. U: "[UuÙ-Üù-üŨ-ųƯưǓǔȔ-ȗᵁᵘᵤṲ-ṷỤ-ủ℆⒰Ⓤⓤ㍳㍺Uu]",
  416. V: "[VvᵛᵥṼ-ṿⅣ-Ⅷⅳ-ⅷ⒱Ⓥⓥⱽ㋎㍵㎴-㎹㏜㏞Vv]",
  417. W: "[WwŴŵʷᵂẀ-ẉẘ⒲Ⓦⓦ㎺-㎿㏝Ww]",
  418. X: "[XxˣẊ-ẍₓ℻Ⅸ-Ⅻⅸ-ⅻ⒳Ⓧⓧ㏓Xx]",
  419. Y: "[YyÝýÿŶ-ŸȲȳʸẎẏẙỲ-ỹ⒴Ⓨⓨ㏉Yy]",
  420. Z: "[ZzŹ-žDZ-dzᶻẐ-ẕℤℨ⒵Ⓩⓩ㎐-㎔Zz]"
  421. };
  422. return function hightlight(o) {
  423. var regex;
  424. o = _.mixin({}, defaults, o);
  425. if (!o.node || !o.pattern) {
  426. return;
  427. }
  428. o.pattern = _.isArray(o.pattern) ? o.pattern : [ o.pattern ];
  429. regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly, o.diacriticInsensitive);
  430. traverse(o.node, hightlightTextNode);
  431. function hightlightTextNode(textNode) {
  432. var match, patternNode, wrapperNode;
  433. if (match = regex.exec(textNode.data)) {
  434. wrapperNode = doc.createElement(o.tagName);
  435. o.className && (wrapperNode.className = o.className);
  436. patternNode = textNode.splitText(match.index);
  437. patternNode.splitText(match[0].length);
  438. wrapperNode.appendChild(patternNode.cloneNode(true));
  439. textNode.parentNode.replaceChild(wrapperNode, patternNode);
  440. }
  441. return !!match;
  442. }
  443. function traverse(el, hightlightTextNode) {
  444. var childNode, TEXT_NODE_TYPE = 3;
  445. for (var i = 0; i < el.childNodes.length; i++) {
  446. childNode = el.childNodes[i];
  447. if (childNode.nodeType === TEXT_NODE_TYPE) {
  448. i += hightlightTextNode(childNode) ? 1 : 0;
  449. } else {
  450. traverse(childNode, hightlightTextNode);
  451. }
  452. }
  453. }
  454. };
  455. function accent_replacer(chr) {
  456. return accented[chr.toUpperCase()] || chr;
  457. }
  458. function getRegex(patterns, caseSensitive, wordsOnly, diacriticInsensitive) {
  459. var escapedPatterns = [], regexStr;
  460. for (var i = 0, len = patterns.length; i < len; i++) {
  461. var escapedWord = _.escapeRegExChars(patterns[i]);
  462. if (diacriticInsensitive) {
  463. escapedWord = escapedWord.replace(/\S/g, accent_replacer);
  464. }
  465. escapedPatterns.push(escapedWord);
  466. }
  467. regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")";
  468. return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i");
  469. }
  470. }(window.document);
  471. var Input = function() {
  472. "use strict";
  473. var specialKeyCodeMap;
  474. specialKeyCodeMap = {
  475. 9: "tab",
  476. 27: "esc",
  477. 37: "left",
  478. 39: "right",
  479. 13: "enter",
  480. 38: "up",
  481. 40: "down"
  482. };
  483. function Input(o, www) {
  484. o = o || {};
  485. if (!o.input) {
  486. $.error("input is missing");
  487. }
  488. www.mixin(this);
  489. this.$hint = $(o.hint);
  490. this.$input = $(o.input);
  491. this.$input.attr({
  492. "aria-activedescendant": "",
  493. "aria-owns": this.$input.attr("id") + "_listbox",
  494. role: "combobox",
  495. "aria-readonly": "true",
  496. "aria-autocomplete": "list"
  497. });
  498. $(www.menu).attr("id", this.$input.attr("id") + "_listbox");
  499. this.query = this.$input.val();
  500. this.queryWhenFocused = this.hasFocus() ? this.query : null;
  501. this.$overflowHelper = buildOverflowHelper(this.$input);
  502. this._checkLanguageDirection();
  503. if (this.$hint.length === 0) {
  504. this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop;
  505. }
  506. this.onSync("cursorchange", this._updateDescendent);
  507. }
  508. Input.normalizeQuery = function(str) {
  509. return _.toStr(str).replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
  510. };
  511. _.mixin(Input.prototype, EventEmitter, {
  512. _onBlur: function onBlur() {
  513. this.resetInputValue();
  514. this.trigger("blurred");
  515. },
  516. _onFocus: function onFocus() {
  517. this.queryWhenFocused = this.query;
  518. this.trigger("focused");
  519. },
  520. _onKeydown: function onKeydown($e) {
  521. var keyName = specialKeyCodeMap[$e.which || $e.keyCode];
  522. this._managePreventDefault(keyName, $e);
  523. if (keyName && this._shouldTrigger(keyName, $e)) {
  524. this.trigger(keyName + "Keyed", $e);
  525. }
  526. },
  527. _onInput: function onInput() {
  528. this._setQuery(this.getInputValue());
  529. this.clearHintIfInvalid();
  530. this._checkLanguageDirection();
  531. },
  532. _managePreventDefault: function managePreventDefault(keyName, $e) {
  533. var preventDefault;
  534. switch (keyName) {
  535. case "up":
  536. case "down":
  537. preventDefault = !withModifier($e);
  538. break;
  539. default:
  540. preventDefault = false;
  541. }
  542. preventDefault && $e.preventDefault();
  543. },
  544. _shouldTrigger: function shouldTrigger(keyName, $e) {
  545. var trigger;
  546. switch (keyName) {
  547. case "tab":
  548. trigger = !withModifier($e);
  549. break;
  550. default:
  551. trigger = true;
  552. }
  553. return trigger;
  554. },
  555. _checkLanguageDirection: function checkLanguageDirection() {
  556. var dir = (this.$input.css("direction") || "ltr").toLowerCase();
  557. if (this.dir !== dir) {
  558. this.dir = dir;
  559. this.$hint.attr("dir", dir);
  560. this.trigger("langDirChanged", dir);
  561. }
  562. },
  563. _setQuery: function setQuery(val, silent) {
  564. var areEquivalent, hasDifferentWhitespace;
  565. areEquivalent = areQueriesEquivalent(val, this.query);
  566. hasDifferentWhitespace = areEquivalent ? this.query.length !== val.length : false;
  567. this.query = val;
  568. if (!silent && !areEquivalent) {
  569. this.trigger("queryChanged", this.query);
  570. } else if (!silent && hasDifferentWhitespace) {
  571. this.trigger("whitespaceChanged", this.query);
  572. }
  573. },
  574. _updateDescendent: function updateDescendent(event, id) {
  575. this.$input.attr("aria-activedescendant", id);
  576. },
  577. bind: function() {
  578. var that = this, onBlur, onFocus, onKeydown, onInput;
  579. onBlur = _.bind(this._onBlur, this);
  580. onFocus = _.bind(this._onFocus, this);
  581. onKeydown = _.bind(this._onKeydown, this);
  582. onInput = _.bind(this._onInput, this);
  583. this.$input.on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown);
  584. if (!_.isMsie() || _.isMsie() > 9) {
  585. this.$input.on("input.tt", onInput);
  586. } else {
  587. this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) {
  588. if (specialKeyCodeMap[$e.which || $e.keyCode]) {
  589. return;
  590. }
  591. _.defer(_.bind(that._onInput, that, $e));
  592. });
  593. }
  594. return this;
  595. },
  596. focus: function focus() {
  597. this.$input.focus();
  598. },
  599. blur: function blur() {
  600. this.$input.blur();
  601. },
  602. getLangDir: function getLangDir() {
  603. return this.dir;
  604. },
  605. getQuery: function getQuery() {
  606. return this.query || "";
  607. },
  608. setQuery: function setQuery(val, silent) {
  609. this.setInputValue(val);
  610. this._setQuery(val, silent);
  611. },
  612. hasQueryChangedSinceLastFocus: function hasQueryChangedSinceLastFocus() {
  613. return this.query !== this.queryWhenFocused;
  614. },
  615. getInputValue: function getInputValue() {
  616. return this.$input.val();
  617. },
  618. setInputValue: function setInputValue(value) {
  619. this.$input.val(value);
  620. this.clearHintIfInvalid();
  621. this._checkLanguageDirection();
  622. },
  623. resetInputValue: function resetInputValue() {
  624. this.setInputValue(this.query);
  625. },
  626. getHint: function getHint() {
  627. return this.$hint.val();
  628. },
  629. setHint: function setHint(value) {
  630. this.$hint.val(value);
  631. },
  632. clearHint: function clearHint() {
  633. this.setHint("");
  634. },
  635. clearHintIfInvalid: function clearHintIfInvalid() {
  636. var val, hint, valIsPrefixOfHint, isValid;
  637. val = this.getInputValue();
  638. hint = this.getHint();
  639. valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0;
  640. isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow();
  641. !isValid && this.clearHint();
  642. },
  643. hasFocus: function hasFocus() {
  644. return this.$input.is(":focus");
  645. },
  646. hasOverflow: function hasOverflow() {
  647. var constraint = this.$input.width() - 2;
  648. this.$overflowHelper.text(this.getInputValue());
  649. return this.$overflowHelper.width() >= constraint;
  650. },
  651. isCursorAtEnd: function() {
  652. var valueLength, selectionStart, range;
  653. valueLength = this.$input.val().length;
  654. selectionStart = this.$input[0].selectionStart;
  655. if (_.isNumber(selectionStart)) {
  656. return selectionStart === valueLength;
  657. } else if (document.selection) {
  658. range = document.selection.createRange();
  659. range.moveStart("character", -valueLength);
  660. return valueLength === range.text.length;
  661. }
  662. return true;
  663. },
  664. destroy: function destroy() {
  665. this.$hint.off(".tt");
  666. this.$input.off(".tt");
  667. this.$overflowHelper.remove();
  668. this.$hint = this.$input = this.$overflowHelper = $("<div>");
  669. }
  670. });
  671. return Input;
  672. function buildOverflowHelper($input) {
  673. return $('<pre aria-hidden="true"></pre>').css({
  674. position: "absolute",
  675. visibility: "hidden",
  676. whiteSpace: "pre",
  677. fontFamily: $input.css("font-family"),
  678. fontSize: $input.css("font-size"),
  679. fontStyle: $input.css("font-style"),
  680. fontVariant: $input.css("font-variant"),
  681. fontWeight: $input.css("font-weight"),
  682. wordSpacing: $input.css("word-spacing"),
  683. letterSpacing: $input.css("letter-spacing"),
  684. textIndent: $input.css("text-indent"),
  685. textRendering: $input.css("text-rendering"),
  686. textTransform: $input.css("text-transform")
  687. }).insertAfter($input);
  688. }
  689. function areQueriesEquivalent(a, b) {
  690. return Input.normalizeQuery(a) === Input.normalizeQuery(b);
  691. }
  692. function withModifier($e) {
  693. return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey;
  694. }
  695. }();
  696. var Dataset = function() {
  697. "use strict";
  698. var keys, nameGenerator;
  699. keys = {
  700. dataset: "tt-selectable-dataset",
  701. val: "tt-selectable-display",
  702. obj: "tt-selectable-object"
  703. };
  704. nameGenerator = _.getIdGenerator();
  705. function Dataset(o, www) {
  706. o = o || {};
  707. o.templates = o.templates || {};
  708. o.templates.notFound = o.templates.notFound || o.templates.empty;
  709. if (!o.source) {
  710. $.error("missing source");
  711. }
  712. if (!o.node) {
  713. $.error("missing node");
  714. }
  715. if (o.name && !isValidName(o.name)) {
  716. $.error("invalid dataset name: " + o.name);
  717. }
  718. www.mixin(this);
  719. this.highlight = !!o.highlight;
  720. this.name = _.toStr(o.name || nameGenerator());
  721. this.limit = o.limit || 5;
  722. this.displayFn = getDisplayFn(o.display || o.displayKey);
  723. this.templates = getTemplates(o.templates, this.displayFn);
  724. this.source = o.source.__ttAdapter ? o.source.__ttAdapter() : o.source;
  725. this.async = _.isUndefined(o.async) ? this.source.length > 2 : !!o.async;
  726. this._resetLastSuggestion();
  727. this.$el = $(o.node).attr("role", "presentation").addClass(this.classes.dataset).addClass(this.classes.dataset + "-" + this.name);
  728. }
  729. Dataset.extractData = function extractData(el) {
  730. var $el = $(el);
  731. if ($el.data(keys.obj)) {
  732. return {
  733. dataset: $el.data(keys.dataset) || "",
  734. val: $el.data(keys.val) || "",
  735. obj: $el.data(keys.obj) || null
  736. };
  737. }
  738. return null;
  739. };
  740. _.mixin(Dataset.prototype, EventEmitter, {
  741. _overwrite: function overwrite(query, suggestions) {
  742. suggestions = suggestions || [];
  743. if (suggestions.length) {
  744. this._renderSuggestions(query, suggestions);
  745. } else if (this.async && this.templates.pending) {
  746. this._renderPending(query);
  747. } else if (!this.async && this.templates.notFound) {
  748. this._renderNotFound(query);
  749. } else {
  750. this._empty();
  751. }
  752. this.trigger("rendered", suggestions, false, this.name);
  753. },
  754. _append: function append(query, suggestions) {
  755. suggestions = suggestions || [];
  756. if (suggestions.length && this.$lastSuggestion.length) {
  757. this._appendSuggestions(query, suggestions);
  758. } else if (suggestions.length) {
  759. this._renderSuggestions(query, suggestions);
  760. } else if (!this.$lastSuggestion.length && this.templates.notFound) {
  761. this._renderNotFound(query);
  762. }
  763. this.trigger("rendered", suggestions, true, this.name);
  764. },
  765. _renderSuggestions: function renderSuggestions(query, suggestions) {
  766. var $fragment;
  767. $fragment = this._getSuggestionsFragment(query, suggestions);
  768. this.$lastSuggestion = $fragment.children().last();
  769. this.$el.html($fragment).prepend(this._getHeader(query, suggestions)).append(this._getFooter(query, suggestions));
  770. },
  771. _appendSuggestions: function appendSuggestions(query, suggestions) {
  772. var $fragment, $lastSuggestion;
  773. $fragment = this._getSuggestionsFragment(query, suggestions);
  774. $lastSuggestion = $fragment.children().last();
  775. this.$lastSuggestion.after($fragment);
  776. this.$lastSuggestion = $lastSuggestion;
  777. },
  778. _renderPending: function renderPending(query) {
  779. var template = this.templates.pending;
  780. this._resetLastSuggestion();
  781. template && this.$el.html(template({
  782. query: query,
  783. dataset: this.name
  784. }));
  785. },
  786. _renderNotFound: function renderNotFound(query) {
  787. var template = this.templates.notFound;
  788. this._resetLastSuggestion();
  789. template && this.$el.html(template({
  790. query: query,
  791. dataset: this.name
  792. }));
  793. },
  794. _empty: function empty() {
  795. this.$el.empty();
  796. this._resetLastSuggestion();
  797. },
  798. _getSuggestionsFragment: function getSuggestionsFragment(query, suggestions) {
  799. var that = this, fragment;
  800. fragment = document.createDocumentFragment();
  801. _.each(suggestions, function getSuggestionNode(suggestion) {
  802. var $el, context;
  803. context = that._injectQuery(query, suggestion);
  804. $el = $(that.templates.suggestion(context)).data(keys.dataset, that.name).data(keys.obj, suggestion).data(keys.val, that.displayFn(suggestion)).addClass(that.classes.suggestion + " " + that.classes.selectable);
  805. fragment.appendChild($el[0]);
  806. });
  807. this.highlight && highlight({
  808. className: this.classes.highlight,
  809. node: fragment,
  810. pattern: query
  811. });
  812. return $(fragment);
  813. },
  814. _getFooter: function getFooter(query, suggestions) {
  815. return this.templates.footer ? this.templates.footer({
  816. query: query,
  817. suggestions: suggestions,
  818. dataset: this.name
  819. }) : null;
  820. },
  821. _getHeader: function getHeader(query, suggestions) {
  822. return this.templates.header ? this.templates.header({
  823. query: query,
  824. suggestions: suggestions,
  825. dataset: this.name
  826. }) : null;
  827. },
  828. _resetLastSuggestion: function resetLastSuggestion() {
  829. this.$lastSuggestion = $();
  830. },
  831. _injectQuery: function injectQuery(query, obj) {
  832. return _.isObject(obj) ? _.mixin({
  833. _query: query
  834. }, obj) : obj;
  835. },
  836. update: function update(query) {
  837. var that = this, canceled = false, syncCalled = false, rendered = 0;
  838. this.cancel();
  839. this.cancel = function cancel() {
  840. canceled = true;
  841. that.cancel = $.noop;
  842. that.async && that.trigger("asyncCanceled", query, that.name);
  843. };
  844. this.source(query, sync, async);
  845. !syncCalled && sync([]);
  846. function sync(suggestions) {
  847. if (syncCalled) {
  848. return;
  849. }
  850. syncCalled = true;
  851. suggestions = (suggestions || []).slice(0, that.limit);
  852. rendered = suggestions.length;
  853. that._overwrite(query, suggestions);
  854. if (rendered < that.limit && that.async) {
  855. that.trigger("asyncRequested", query, that.name);
  856. }
  857. }
  858. function async(suggestions) {
  859. suggestions = suggestions || [];
  860. if (!canceled && rendered < that.limit) {
  861. that.cancel = $.noop;
  862. var idx = Math.abs(rendered - that.limit);
  863. rendered += idx;
  864. that._append(query, suggestions.slice(0, idx));
  865. that.async && that.trigger("asyncReceived", query, that.name);
  866. }
  867. }
  868. },
  869. cancel: $.noop,
  870. clear: function clear() {
  871. this._empty();
  872. this.cancel();
  873. this.trigger("cleared");
  874. },
  875. isEmpty: function isEmpty() {
  876. return this.$el.is(":empty");
  877. },
  878. destroy: function destroy() {
  879. this.$el = $("<div>");
  880. }
  881. });
  882. return Dataset;
  883. function getDisplayFn(display) {
  884. display = display || _.stringify;
  885. return _.isFunction(display) ? display : displayFn;
  886. function displayFn(obj) {
  887. return obj[display];
  888. }
  889. }
  890. function getTemplates(templates, displayFn) {
  891. return {
  892. notFound: templates.notFound && _.templatify(templates.notFound),
  893. pending: templates.pending && _.templatify(templates.pending),
  894. header: templates.header && _.templatify(templates.header),
  895. footer: templates.footer && _.templatify(templates.footer),
  896. suggestion: templates.suggestion || suggestionTemplate
  897. };
  898. function suggestionTemplate(context) {
  899. return $('<div role="option">').attr("id", _.guid()).text(displayFn(context));
  900. }
  901. }
  902. function isValidName(str) {
  903. return /^[_a-zA-Z0-9-]+$/.test(str);
  904. }
  905. }();
  906. var Menu = function() {
  907. "use strict";
  908. function Menu(o, www) {
  909. var that = this;
  910. o = o || {};
  911. if (!o.node) {
  912. $.error("node is required");
  913. }
  914. www.mixin(this);
  915. this.$node = $(o.node);
  916. this.query = null;
  917. this.datasets = _.map(o.datasets, initializeDataset);
  918. function initializeDataset(oDataset) {
  919. var node = that.$node.find(oDataset.node).first();
  920. oDataset.node = node.length ? node : $("<div>").appendTo(that.$node);
  921. return new Dataset(oDataset, www);
  922. }
  923. }
  924. _.mixin(Menu.prototype, EventEmitter, {
  925. _onSelectableClick: function onSelectableClick($e) {
  926. this.trigger("selectableClicked", $($e.currentTarget));
  927. },
  928. _onRendered: function onRendered(type, dataset, suggestions, async) {
  929. this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty());
  930. this.trigger("datasetRendered", dataset, suggestions, async);
  931. },
  932. _onCleared: function onCleared() {
  933. this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty());
  934. this.trigger("datasetCleared");
  935. },
  936. _propagate: function propagate() {
  937. this.trigger.apply(this, arguments);
  938. },
  939. _allDatasetsEmpty: function allDatasetsEmpty() {
  940. return _.every(this.datasets, _.bind(function isDatasetEmpty(dataset) {
  941. var isEmpty = dataset.isEmpty();
  942. this.$node.attr("aria-expanded", !isEmpty);
  943. return isEmpty;
  944. }, this));
  945. },
  946. _getSelectables: function getSelectables() {
  947. return this.$node.find(this.selectors.selectable);
  948. },
  949. _removeCursor: function _removeCursor() {
  950. var $selectable = this.getActiveSelectable();
  951. $selectable && $selectable.removeClass(this.classes.cursor);
  952. },
  953. _ensureVisible: function ensureVisible($el) {
  954. var elTop, elBottom, nodeScrollTop, nodeHeight;
  955. elTop = $el.position().top;
  956. elBottom = elTop + $el.outerHeight(true);
  957. nodeScrollTop = this.$node.scrollTop();
  958. nodeHeight = this.$node.height() + parseInt(this.$node.css("paddingTop"), 10) + parseInt(this.$node.css("paddingBottom"), 10);
  959. if (elTop < 0) {
  960. this.$node.scrollTop(nodeScrollTop + elTop);
  961. } else if (nodeHeight < elBottom) {
  962. this.$node.scrollTop(nodeScrollTop + (elBottom - nodeHeight));
  963. }
  964. },
  965. bind: function() {
  966. var that = this, onSelectableClick;
  967. onSelectableClick = _.bind(this._onSelectableClick, this);
  968. this.$node.on("click.tt", this.selectors.selectable, onSelectableClick);
  969. this.$node.on("mouseover", this.selectors.selectable, function() {
  970. that.setCursor($(this));
  971. });
  972. this.$node.on("mouseleave", function() {
  973. that._removeCursor();
  974. });
  975. _.each(this.datasets, function(dataset) {
  976. dataset.onSync("asyncRequested", that._propagate, that).onSync("asyncCanceled", that._propagate, that).onSync("asyncReceived", that._propagate, that).onSync("rendered", that._onRendered, that).onSync("cleared", that._onCleared, that);
  977. });
  978. return this;
  979. },
  980. isOpen: function isOpen() {
  981. return this.$node.hasClass(this.classes.open);
  982. },
  983. open: function open() {
  984. this.$node.scrollTop(0);
  985. this.$node.addClass(this.classes.open);
  986. },
  987. close: function close() {
  988. this.$node.attr("aria-expanded", false);
  989. this.$node.removeClass(this.classes.open);
  990. this._removeCursor();
  991. },
  992. setLanguageDirection: function setLanguageDirection(dir) {
  993. this.$node.attr("dir", dir);
  994. },
  995. selectableRelativeToCursor: function selectableRelativeToCursor(delta) {
  996. var $selectables, $oldCursor, oldIndex, newIndex;
  997. $oldCursor = this.getActiveSelectable();
  998. $selectables = this._getSelectables();
  999. oldIndex = $oldCursor ? $selectables.index($oldCursor) : -1;
  1000. newIndex = oldIndex + delta;
  1001. newIndex = (newIndex + 1) % ($selectables.length + 1) - 1;
  1002. newIndex = newIndex < -1 ? $selectables.length - 1 : newIndex;
  1003. return newIndex === -1 ? null : $selectables.eq(newIndex);
  1004. },
  1005. setCursor: function setCursor($selectable) {
  1006. this._removeCursor();
  1007. if ($selectable = $selectable && $selectable.first()) {
  1008. $selectable.addClass(this.classes.cursor);
  1009. this._ensureVisible($selectable);
  1010. }
  1011. },
  1012. getSelectableData: function getSelectableData($el) {
  1013. return $el && $el.length ? Dataset.extractData($el) : null;
  1014. },
  1015. getActiveSelectable: function getActiveSelectable() {
  1016. var $selectable = this._getSelectables().filter(this.selectors.cursor).first();
  1017. return $selectable.length ? $selectable : null;
  1018. },
  1019. getTopSelectable: function getTopSelectable() {
  1020. var $selectable = this._getSelectables().first();
  1021. return $selectable.length ? $selectable : null;
  1022. },
  1023. update: function update(query) {
  1024. var isValidUpdate = query !== this.query;
  1025. if (isValidUpdate) {
  1026. this.query = query;
  1027. _.each(this.datasets, updateDataset);
  1028. }
  1029. return isValidUpdate;
  1030. function updateDataset(dataset) {
  1031. dataset.update(query);
  1032. }
  1033. },
  1034. empty: function empty() {
  1035. _.each(this.datasets, clearDataset);
  1036. this.query = null;
  1037. this.$node.addClass(this.classes.empty);
  1038. function clearDataset(dataset) {
  1039. dataset.clear();
  1040. }
  1041. },
  1042. destroy: function destroy() {
  1043. this.$node.off(".tt");
  1044. this.$node = $("<div>");
  1045. _.each(this.datasets, destroyDataset);
  1046. function destroyDataset(dataset) {
  1047. dataset.destroy();
  1048. }
  1049. }
  1050. });
  1051. return Menu;
  1052. }();
  1053. var Status = function() {
  1054. "use strict";
  1055. function Status(options) {
  1056. this.$el = $("<span></span>", {
  1057. role: "status",
  1058. "aria-live": "polite"
  1059. }).css({
  1060. position: "absolute",
  1061. padding: "0",
  1062. border: "0",
  1063. height: "1px",
  1064. width: "1px",
  1065. "margin-bottom": "-1px",
  1066. "margin-right": "-1px",
  1067. overflow: "hidden",
  1068. clip: "rect(0 0 0 0)",
  1069. "white-space": "nowrap"
  1070. });
  1071. options.$input.after(this.$el);
  1072. _.each(options.menu.datasets, _.bind(function(dataset) {
  1073. if (dataset.onSync) {
  1074. dataset.onSync("rendered", _.bind(this.update, this));
  1075. dataset.onSync("cleared", _.bind(this.cleared, this));
  1076. }
  1077. }, this));
  1078. }
  1079. _.mixin(Status.prototype, {
  1080. update: function update(event, suggestions) {
  1081. var length = suggestions.length;
  1082. var words;
  1083. if (length === 1) {
  1084. words = {
  1085. result: "result",
  1086. is: "is"
  1087. };
  1088. } else {
  1089. words = {
  1090. result: "results",
  1091. is: "are"
  1092. };
  1093. }
  1094. this.$el.text(length + " " + words.result + " " + words.is + " available, use up and down arrow keys to navigate.");
  1095. },
  1096. cleared: function() {
  1097. this.$el.text("");
  1098. }
  1099. });
  1100. return Status;
  1101. }();
  1102. var DefaultMenu = function() {
  1103. "use strict";
  1104. var s = Menu.prototype;
  1105. function DefaultMenu() {
  1106. Menu.apply(this, [].slice.call(arguments, 0));
  1107. }
  1108. _.mixin(DefaultMenu.prototype, Menu.prototype, {
  1109. open: function open() {
  1110. !this._allDatasetsEmpty() && this._show();
  1111. return s.open.apply(this, [].slice.call(arguments, 0));
  1112. },
  1113. close: function close() {
  1114. this._hide();
  1115. return s.close.apply(this, [].slice.call(arguments, 0));
  1116. },
  1117. _onRendered: function onRendered() {
  1118. if (this._allDatasetsEmpty()) {
  1119. this._hide();
  1120. } else {
  1121. this.isOpen() && this._show();
  1122. }
  1123. return s._onRendered.apply(this, [].slice.call(arguments, 0));
  1124. },
  1125. _onCleared: function onCleared() {
  1126. if (this._allDatasetsEmpty()) {
  1127. this._hide();
  1128. } else {
  1129. this.isOpen() && this._show();
  1130. }
  1131. return s._onCleared.apply(this, [].slice.call(arguments, 0));
  1132. },
  1133. setLanguageDirection: function setLanguageDirection(dir) {
  1134. this.$node.css(dir === "ltr" ? this.css.ltr : this.css.rtl);
  1135. return s.setLanguageDirection.apply(this, [].slice.call(arguments, 0));
  1136. },
  1137. _hide: function hide() {
  1138. this.$node.hide();
  1139. },
  1140. _show: function show() {
  1141. this.$node.css("display", "block");
  1142. }
  1143. });
  1144. return DefaultMenu;
  1145. }();
  1146. var Typeahead = function() {
  1147. "use strict";
  1148. function Typeahead(o, www) {
  1149. var onFocused, onBlurred, onEnterKeyed, onTabKeyed, onEscKeyed, onUpKeyed, onDownKeyed, onLeftKeyed, onRightKeyed, onQueryChanged, onWhitespaceChanged;
  1150. o = o || {};
  1151. if (!o.input) {
  1152. $.error("missing input");
  1153. }
  1154. if (!o.menu) {
  1155. $.error("missing menu");
  1156. }
  1157. if (!o.eventBus) {
  1158. $.error("missing event bus");
  1159. }
  1160. www.mixin(this);
  1161. this.eventBus = o.eventBus;
  1162. this.minLength = _.isNumber(o.minLength) ? o.minLength : 1;
  1163. this.input = o.input;
  1164. this.menu = o.menu;
  1165. this.enabled = true;
  1166. this.autoselect = !!o.autoselect;
  1167. this.active = false;
  1168. this.input.hasFocus() && this.activate();
  1169. this.dir = this.input.getLangDir();
  1170. this._hacks();
  1171. this.menu.bind().onSync("selectableClicked", this._onSelectableClicked, this).onSync("asyncRequested", this._onAsyncRequested, this).onSync("asyncCanceled", this._onAsyncCanceled, this).onSync("asyncReceived", this._onAsyncReceived, this).onSync("datasetRendered", this._onDatasetRendered, this).onSync("datasetCleared", this._onDatasetCleared, this);
  1172. onFocused = c(this, "activate", "open", "_onFocused");
  1173. onBlurred = c(this, "deactivate", "_onBlurred");
  1174. onEnterKeyed = c(this, "isActive", "isOpen", "_onEnterKeyed");
  1175. onTabKeyed = c(this, "isActive", "isOpen", "_onTabKeyed");
  1176. onEscKeyed = c(this, "isActive", "_onEscKeyed");
  1177. onUpKeyed = c(this, "isActive", "open", "_onUpKeyed");
  1178. onDownKeyed = c(this, "isActive", "open", "_onDownKeyed");
  1179. onLeftKeyed = c(this, "isActive", "isOpen", "_onLeftKeyed");
  1180. onRightKeyed = c(this, "isActive", "isOpen", "_onRightKeyed");
  1181. onQueryChanged = c(this, "_openIfActive", "_onQueryChanged");
  1182. onWhitespaceChanged = c(this, "_openIfActive", "_onWhitespaceChanged");
  1183. this.input.bind().onSync("focused", onFocused, this).onSync("blurred", onBlurred, this).onSync("enterKeyed", onEnterKeyed, this).onSync("tabKeyed", onTabKeyed, this).onSync("escKeyed", onEscKeyed, this).onSync("upKeyed", onUpKeyed, this).onSync("downKeyed", onDownKeyed, this).onSync("leftKeyed", onLeftKeyed, this).onSync("rightKeyed", onRightKeyed, this).onSync("queryChanged", onQueryChanged, this).onSync("whitespaceChanged", onWhitespaceChanged, this).onSync("langDirChanged", this._onLangDirChanged, this);
  1184. }
  1185. _.mixin(Typeahead.prototype, {
  1186. _hacks: function hacks() {
  1187. var $input, $menu;
  1188. $input = this.input.$input || $("<div>");
  1189. $menu = this.menu.$node || $("<div>");
  1190. $input.on("blur.tt", function($e) {
  1191. var active, isActive, hasActive;
  1192. active = document.activeElement;
  1193. isActive = $menu.is(active);
  1194. hasActive = $menu.has(active).length > 0;
  1195. if (_.isMsie() && (isActive || hasActive)) {
  1196. $e.preventDefault();
  1197. $e.stopImmediatePropagation();
  1198. _.defer(function() {
  1199. $input.focus();
  1200. });
  1201. }
  1202. });
  1203. $menu.on("mousedown.tt", function($e) {
  1204. $e.preventDefault();
  1205. });
  1206. },
  1207. _onSelectableClicked: function onSelectableClicked(type, $el) {
  1208. this.select($el);
  1209. },
  1210. _onDatasetCleared: function onDatasetCleared() {
  1211. this._updateHint();
  1212. },
  1213. _onDatasetRendered: function onDatasetRendered(type, suggestions, async, dataset) {
  1214. this._updateHint();
  1215. if (this.autoselect) {
  1216. var cursorClass = this.selectors.cursor.substr(1);
  1217. this.menu.$node.find(this.selectors.suggestion).first().addClass(cursorClass);
  1218. }
  1219. this.eventBus.trigger("render", suggestions, async, dataset);
  1220. },
  1221. _onAsyncRequested: function onAsyncRequested(type, dataset, query) {
  1222. this.eventBus.trigger("asyncrequest", query, dataset);
  1223. },
  1224. _onAsyncCanceled: function onAsyncCanceled(type, dataset, query) {
  1225. this.eventBus.trigger("asynccancel", query, dataset);
  1226. },
  1227. _onAsyncReceived: function onAsyncReceived(type, dataset, query) {
  1228. this.eventBus.trigger("asyncreceive", query, dataset);
  1229. },
  1230. _onFocused: function onFocused() {
  1231. this._minLengthMet() && this.menu.update(this.input.getQuery());
  1232. },
  1233. _onBlurred: function onBlurred() {
  1234. if (this.input.hasQueryChangedSinceLastFocus()) {
  1235. this.eventBus.trigger("change", this.input.getQuery());
  1236. }
  1237. },
  1238. _onEnterKeyed: function onEnterKeyed(type, $e) {
  1239. var $selectable;
  1240. if ($selectable = this.menu.getActiveSelectable()) {
  1241. if (this.select($selectable)) {
  1242. $e.preventDefault();
  1243. $e.stopPropagation();
  1244. }
  1245. } else if (this.autoselect) {
  1246. if (this.select(this.menu.getTopSelectable())) {
  1247. $e.preventDefault();
  1248. $e.stopPropagation();
  1249. }
  1250. }
  1251. },
  1252. _onTabKeyed: function onTabKeyed(type, $e) {
  1253. var $selectable;
  1254. if ($selectable = this.menu.getActiveSelectable()) {
  1255. this.select($selectable) && $e.preventDefault();
  1256. } else if ($selectable = this.menu.getTopSelectable()) {
  1257. this.autocomplete($selectable) && $e.preventDefault();
  1258. }
  1259. },
  1260. _onEscKeyed: function onEscKeyed() {
  1261. this.close();
  1262. },
  1263. _onUpKeyed: function onUpKeyed() {
  1264. this.moveCursor(-1);
  1265. },
  1266. _onDownKeyed: function onDownKeyed() {
  1267. this.moveCursor(+1);
  1268. },
  1269. _onLeftKeyed: function onLeftKeyed() {
  1270. if (this.dir === "rtl" && this.input.isCursorAtEnd()) {
  1271. this.autocomplete(this.menu.getActiveSelectable() || this.menu.getTopSelectable());
  1272. }
  1273. },
  1274. _onRightKeyed: function onRightKeyed() {
  1275. if (this.dir === "ltr" && this.input.isCursorAtEnd()) {
  1276. this.autocomplete(this.menu.getActiveSelectable() || this.menu.getTopSelectable());
  1277. }
  1278. },
  1279. _onQueryChanged: function onQueryChanged(e, query) {
  1280. this._minLengthMet(query) ? this.menu.update(query) : this.menu.empty();
  1281. },
  1282. _onWhitespaceChanged: function onWhitespaceChanged() {
  1283. this._updateHint();
  1284. },
  1285. _onLangDirChanged: function onLangDirChanged(e, dir) {
  1286. if (this.dir !== dir) {
  1287. this.dir = dir;
  1288. this.menu.setLanguageDirection(dir);
  1289. }
  1290. },
  1291. _openIfActive: function openIfActive() {
  1292. this.isActive() && this.open();
  1293. },
  1294. _minLengthMet: function minLengthMet(query) {
  1295. query = _.isString(query) ? query : this.input.getQuery() || "";
  1296. return query.length >= this.minLength;
  1297. },
  1298. _updateHint: function updateHint() {
  1299. var $selectable, data, val, query, escapedQuery, frontMatchRegEx, match;
  1300. $selectable = this.menu.getTopSelectable();
  1301. data = this.menu.getSelectableData($selectable);
  1302. val = this.input.getInputValue();
  1303. if (data && !_.isBlankString(val) && !this.input.hasOverflow()) {
  1304. query = Input.normalizeQuery(val);
  1305. escapedQuery = _.escapeRegExChars(query);
  1306. frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i");
  1307. match = frontMatchRegEx.exec(data.val);
  1308. match && this.input.setHint(val + match[1]);
  1309. } else {
  1310. this.input.clearHint();
  1311. }
  1312. },
  1313. isEnabled: function isEnabled() {
  1314. return this.enabled;
  1315. },
  1316. enable: function enable() {
  1317. this.enabled = true;
  1318. },
  1319. disable: function disable() {
  1320. this.enabled = false;
  1321. },
  1322. isActive: function isActive() {
  1323. return this.active;
  1324. },
  1325. activate: function activate() {
  1326. if (this.isActive()) {
  1327. return true;
  1328. } else if (!this.isEnabled() || this.eventBus.before("active")) {
  1329. return false;
  1330. } else {
  1331. this.active = true;
  1332. this.eventBus.trigger("active");
  1333. return true;
  1334. }
  1335. },
  1336. deactivate: function deactivate() {
  1337. if (!this.isActive()) {
  1338. return true;
  1339. } else if (this.eventBus.before("idle")) {
  1340. return false;
  1341. } else {
  1342. this.active = false;
  1343. this.close();
  1344. this.eventBus.trigger("idle");
  1345. return true;
  1346. }
  1347. },
  1348. isOpen: function isOpen() {
  1349. return this.menu.isOpen();
  1350. },
  1351. open: function open() {
  1352. if (!this.isOpen() && !this.eventBus.before("open")) {
  1353. this.menu.open();
  1354. this._updateHint();
  1355. this.eventBus.trigger("open");
  1356. }
  1357. return this.isOpen();
  1358. },
  1359. close: function close() {
  1360. if (this.isOpen() && !this.eventBus.before("close")) {
  1361. this.menu.close();
  1362. this.input.clearHint();
  1363. this.input.resetInputValue();
  1364. this.eventBus.trigger("close");
  1365. }
  1366. return !this.isOpen();
  1367. },
  1368. setVal: function setVal(val) {
  1369. this.input.setQuery(_.toStr(val));
  1370. },
  1371. getVal: function getVal() {
  1372. return this.input.getQuery();
  1373. },
  1374. select: function select($selectable) {
  1375. var data = this.menu.getSelectableData($selectable);
  1376. if (data && !this.eventBus.before("select", data.obj, data.dataset)) {
  1377. this.input.setQuery(data.val, true);
  1378. this.eventBus.trigger("select", data.obj, data.dataset);
  1379. this.close();
  1380. return true;
  1381. }
  1382. return false;
  1383. },
  1384. autocomplete: function autocomplete($selectable) {
  1385. var query, data, isValid;
  1386. query = this.input.getQuery();
  1387. data = this.menu.getSelectableData($selectable);
  1388. isValid = data && query !== data.val;
  1389. if (isValid && !this.eventBus.before("autocomplete", data.obj, data.dataset)) {
  1390. this.input.setQuery(data.val);
  1391. this.eventBus.trigger("autocomplete", data.obj, data.dataset);
  1392. return true;
  1393. }
  1394. return false;
  1395. },
  1396. moveCursor: function moveCursor(delta) {
  1397. var query, $candidate, data, suggestion, datasetName, cancelMove, id;
  1398. query = this.input.getQuery();
  1399. $candidate = this.menu.selectableRelativeToCursor(delta);
  1400. data = this.menu.getSelectableData($candidate);
  1401. suggestion = data ? data.obj : null;
  1402. datasetName = data ? data.dataset : null;
  1403. id = $candidate ? $candidate.attr("id") : null;
  1404. this.input.trigger("cursorchange", id);
  1405. cancelMove = this._minLengthMet() && this.menu.update(query);
  1406. if (!cancelMove && !this.eventBus.before("cursorchange", suggestion, datasetName)) {
  1407. this.menu.setCursor($candidate);
  1408. if (data) {
  1409. this.input.setInputValue(data.val);
  1410. } else {
  1411. this.input.resetInputValue();
  1412. this._updateHint();
  1413. }
  1414. this.eventBus.trigger("cursorchange", suggestion, datasetName);
  1415. return true;
  1416. }
  1417. return false;
  1418. },
  1419. destroy: function destroy() {
  1420. this.input.destroy();
  1421. this.menu.destroy();
  1422. }
  1423. });
  1424. return Typeahead;
  1425. function c(ctx) {
  1426. var methods = [].slice.call(arguments, 1);
  1427. return function() {
  1428. var args = [].slice.call(arguments);
  1429. _.each(methods, function(method) {
  1430. return ctx[method].apply(ctx, args);
  1431. });
  1432. };
  1433. }
  1434. }();
  1435. (function() {
  1436. "use strict";
  1437. var old, keys, methods;
  1438. old = $.fn.typeahead;
  1439. keys = {
  1440. www: "tt-www",
  1441. attrs: "tt-attrs",
  1442. typeahead: "tt-typeahead"
  1443. };
  1444. methods = {
  1445. initialize: function initialize(o, datasets) {
  1446. var www;
  1447. datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1);
  1448. o = o || {};
  1449. www = WWW(o.classNames);
  1450. return this.each(attach);
  1451. function attach() {
  1452. var $input, $wrapper, $hint, $menu, defaultHint, defaultMenu, eventBus, input, menu, status, typeahead, MenuConstructor;
  1453. _.each(datasets, function(d) {
  1454. d.highlight = !!o.highlight;
  1455. });
  1456. $input = $(this);
  1457. $wrapper = $(www.html.wrapper);
  1458. $hint = $elOrNull(o.hint);
  1459. $menu = $elOrNull(o.menu);
  1460. defaultHint = o.hint !== false && !$hint;
  1461. defaultMenu = o.menu !== false && !$menu;
  1462. defaultHint && ($hint = buildHintFromInput($input, www));
  1463. defaultMenu && ($menu = $(www.html.menu).css(www.css.menu));
  1464. $hint && $hint.val("");
  1465. $input = prepInput($input, www);
  1466. if (defaultHint || defaultMenu) {
  1467. $wrapper.css(www.css.wrapper);
  1468. $input.css(defaultHint ? www.css.input : www.css.inputWithNoHint);
  1469. $input.wrap($wrapper).parent().prepend(defaultHint ? $hint : null).append(defaultMenu ? $menu : null);
  1470. }
  1471. MenuConstructor = defaultMenu ? DefaultMenu : Menu;
  1472. eventBus = new EventBus({
  1473. el: $input
  1474. });
  1475. input = new Input({
  1476. hint: $hint,
  1477. input: $input
  1478. }, www);
  1479. menu = new MenuConstructor({
  1480. node: $menu,
  1481. datasets: datasets
  1482. }, www);
  1483. status = new Status({
  1484. $input: $input,
  1485. menu: menu
  1486. });
  1487. typeahead = new Typeahead({
  1488. input: input,
  1489. menu: menu,
  1490. eventBus: eventBus,
  1491. minLength: o.minLength,
  1492. autoselect: o.autoselect
  1493. }, www);
  1494. $input.data(keys.www, www);
  1495. $input.data(keys.typeahead, typeahead);
  1496. }
  1497. },
  1498. isEnabled: function isEnabled() {
  1499. var enabled;
  1500. ttEach(this.first(), function(t) {
  1501. enabled = t.isEnabled();
  1502. });
  1503. return enabled;
  1504. },
  1505. enable: function enable() {
  1506. ttEach(this, function(t) {
  1507. t.enable();
  1508. });
  1509. return this;
  1510. },
  1511. disable: function disable() {
  1512. ttEach(this, function(t) {
  1513. t.disable();
  1514. });
  1515. return this;
  1516. },
  1517. isActive: function isActive() {
  1518. var active;
  1519. ttEach(this.first(), function(t) {
  1520. active = t.isActive();
  1521. });
  1522. return active;
  1523. },
  1524. activate: function activate() {
  1525. ttEach(this, function(t) {
  1526. t.activate();
  1527. });
  1528. return this;
  1529. },
  1530. deactivate: function deactivate() {
  1531. ttEach(this, function(t) {
  1532. t.deactivate();
  1533. });
  1534. return this;
  1535. },
  1536. isOpen: function isOpen() {
  1537. var open;
  1538. ttEach(this.first(), function(t) {
  1539. open = t.isOpen();
  1540. });
  1541. return open;
  1542. },
  1543. open: function open() {
  1544. ttEach(this, function(t) {
  1545. t.open();
  1546. });
  1547. return this;
  1548. },
  1549. close: function close() {
  1550. ttEach(this, function(t) {
  1551. t.close();
  1552. });
  1553. return this;
  1554. },
  1555. select: function select(el) {
  1556. var success = false, $el = $(el);
  1557. ttEach(this.first(), function(t) {
  1558. success = t.select($el);
  1559. });
  1560. return success;
  1561. },
  1562. autocomplete: function autocomplete(el) {
  1563. var success = false, $el = $(el);
  1564. ttEach(this.first(), function(t) {
  1565. success = t.autocomplete($el);
  1566. });
  1567. return success;
  1568. },
  1569. moveCursor: function moveCursoe(delta) {
  1570. var success = false;
  1571. ttEach(this.first(), function(t) {
  1572. success = t.moveCursor(delta);
  1573. });
  1574. return success;
  1575. },
  1576. val: function val(newVal) {
  1577. var query;
  1578. if (!arguments.length) {
  1579. ttEach(this.first(), function(t) {
  1580. query = t.getVal();
  1581. });
  1582. return query;
  1583. } else {
  1584. ttEach(this, function(t) {
  1585. t.setVal(_.toStr(newVal));
  1586. });
  1587. return this;
  1588. }
  1589. },
  1590. destroy: function destroy() {
  1591. ttEach(this, function(typeahead, $input) {
  1592. revert($input);
  1593. typeahead.destroy();
  1594. });
  1595. return this;
  1596. }
  1597. };
  1598. $.fn.typeahead = function(method) {
  1599. if (methods[method]) {
  1600. return methods[method].apply(this, [].slice.call(arguments, 1));
  1601. } else {
  1602. return methods.initialize.apply(this, arguments);
  1603. }
  1604. };
  1605. $.fn.typeahead.noConflict = function noConflict() {
  1606. $.fn.typeahead = old;
  1607. return this;
  1608. };
  1609. function ttEach($els, fn) {
  1610. $els.each(function() {
  1611. var $input = $(this), typeahead;
  1612. (typeahead = $input.data(keys.typeahead)) && fn(typeahead, $input);
  1613. });
  1614. }
  1615. function buildHintFromInput($input, www) {
  1616. return $input.clone().addClass(www.classes.hint).removeData().css(www.css.hint).css(getBackgroundStyles($input)).prop({
  1617. readonly: true,
  1618. required: false
  1619. }).removeAttr("id name placeholder").removeClass("required").attr({
  1620. spellcheck: "false",
  1621. tabindex: -1
  1622. });
  1623. }
  1624. function prepInput($input, www) {
  1625. $input.data(keys.attrs, {
  1626. dir: $input.attr("dir"),
  1627. autocomplete: $input.attr("autocomplete"),
  1628. spellcheck: $input.attr("spellcheck"),
  1629. style: $input.attr("style")
  1630. });
  1631. $input.addClass(www.classes.input).attr({
  1632. spellcheck: false
  1633. });
  1634. try {
  1635. !$input.attr("dir") && $input.attr("dir", "auto");
  1636. } catch (e) {}
  1637. return $input;
  1638. }
  1639. function getBackgroundStyles($el) {
  1640. return {
  1641. backgroundAttachment: $el.css("background-attachment"),
  1642. backgroundClip: $el.css("background-clip"),
  1643. backgroundColor: $el.css("background-color"),
  1644. backgroundImage: $el.css("background-image"),
  1645. backgroundOrigin: $el.css("background-origin"),
  1646. backgroundPosition: $el.css("background-position"),
  1647. backgroundRepeat: $el.css("background-repeat"),
  1648. backgroundSize: $el.css("background-size")
  1649. };
  1650. }
  1651. function revert($input) {
  1652. var www, $wrapper;
  1653. www = $input.data(keys.www);
  1654. $wrapper = $input.parent().filter(www.selectors.wrapper);
  1655. _.each($input.data(keys.attrs), function(val, key) {
  1656. _.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val);
  1657. });
  1658. $input.removeData(keys.typeahead).removeData(keys.www).removeData(keys.attr).removeClass(www.classes.input);
  1659. if ($wrapper.length) {
  1660. $input.detach().insertAfter($wrapper);
  1661. $wrapper.remove();
  1662. }
  1663. }
  1664. function $elOrNull(obj) {
  1665. var isValid, $el;
  1666. isValid = _.isJQuery(obj) || _.isElement(obj);
  1667. $el = isValid ? $(obj).first() : [];
  1668. return $el.length ? $el : null;
  1669. }
  1670. })();
  1671. });