typeahead.jquery.js 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695
  1. /*!
  2. * typeahead.js 1.3.3
  3. * https://github.com/corejavascript/typeahead.js
  4. * Copyright 2013-2024 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 module === "object" && module.exports) {
  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. var id;
  485. o = o || {};
  486. if (!o.input) {
  487. $.error("input is missing");
  488. }
  489. www.mixin(this);
  490. this.$hint = $(o.hint);
  491. this.$input = $(o.input);
  492. this.$menu = $(o.menu);
  493. id = this.$input.attr("id") || _.guid();
  494. this.$menu.attr("id", id + "_listbox");
  495. this.$hint.attr({
  496. "aria-hidden": true
  497. });
  498. this.$input.attr({
  499. "aria-owns": id + "_listbox",
  500. "aria-controls": id + "_listbox",
  501. role: "combobox",
  502. "aria-autocomplete": "list",
  503. "aria-expanded": false
  504. });
  505. this.query = this.$input.val();
  506. this.queryWhenFocused = this.hasFocus() ? this.query : null;
  507. this.$overflowHelper = buildOverflowHelper(this.$input);
  508. this._checkLanguageDirection();
  509. if (this.$hint.length === 0) {
  510. this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop;
  511. }
  512. this.onSync("cursorchange", this._updateDescendent);
  513. }
  514. Input.normalizeQuery = function(str) {
  515. return _.toStr(str).replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
  516. };
  517. _.mixin(Input.prototype, EventEmitter, {
  518. _onBlur: function onBlur() {
  519. this.resetInputValue();
  520. this.trigger("blurred");
  521. },
  522. _onFocus: function onFocus() {
  523. this.queryWhenFocused = this.query;
  524. this.trigger("focused");
  525. },
  526. _onKeydown: function onKeydown($e) {
  527. var keyName = specialKeyCodeMap[$e.which || $e.keyCode];
  528. this._managePreventDefault(keyName, $e);
  529. if (keyName && this._shouldTrigger(keyName, $e)) {
  530. this.trigger(keyName + "Keyed", $e);
  531. }
  532. },
  533. _onInput: function onInput() {
  534. this._setQuery(this.getInputValue());
  535. this.clearHintIfInvalid();
  536. this._checkLanguageDirection();
  537. },
  538. _managePreventDefault: function managePreventDefault(keyName, $e) {
  539. var preventDefault;
  540. switch (keyName) {
  541. case "up":
  542. case "down":
  543. preventDefault = !withModifier($e);
  544. break;
  545. default:
  546. preventDefault = false;
  547. }
  548. preventDefault && $e.preventDefault();
  549. },
  550. _shouldTrigger: function shouldTrigger(keyName, $e) {
  551. var trigger;
  552. switch (keyName) {
  553. case "tab":
  554. trigger = !withModifier($e);
  555. break;
  556. default:
  557. trigger = true;
  558. }
  559. return trigger;
  560. },
  561. _checkLanguageDirection: function checkLanguageDirection() {
  562. var dir = (this.$input.css("direction") || "ltr").toLowerCase();
  563. if (this.dir !== dir) {
  564. this.dir = dir;
  565. this.$hint.attr("dir", dir);
  566. this.trigger("langDirChanged", dir);
  567. }
  568. },
  569. _setQuery: function setQuery(val, silent) {
  570. var areEquivalent, hasDifferentWhitespace;
  571. areEquivalent = areQueriesEquivalent(val, this.query);
  572. hasDifferentWhitespace = areEquivalent ? this.query.length !== val.length : false;
  573. this.query = val;
  574. if (!silent && !areEquivalent) {
  575. this.trigger("queryChanged", this.query);
  576. } else if (!silent && hasDifferentWhitespace) {
  577. this.trigger("whitespaceChanged", this.query);
  578. }
  579. },
  580. _updateDescendent: function updateDescendent(event, id) {
  581. this.$input.attr("aria-activedescendant", id);
  582. },
  583. bind: function() {
  584. var that = this, onBlur, onFocus, onKeydown, onInput;
  585. onBlur = _.bind(this._onBlur, this);
  586. onFocus = _.bind(this._onFocus, this);
  587. onKeydown = _.bind(this._onKeydown, this);
  588. onInput = _.bind(this._onInput, this);
  589. this.$input.on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown);
  590. if (!_.isMsie() || _.isMsie() > 9) {
  591. this.$input.on("input.tt", onInput);
  592. } else {
  593. this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) {
  594. if (specialKeyCodeMap[$e.which || $e.keyCode]) {
  595. return;
  596. }
  597. _.defer(_.bind(that._onInput, that, $e));
  598. });
  599. }
  600. return this;
  601. },
  602. focus: function focus() {
  603. this.$input.focus();
  604. },
  605. blur: function blur() {
  606. this.$input.blur();
  607. },
  608. getLangDir: function getLangDir() {
  609. return this.dir;
  610. },
  611. getQuery: function getQuery() {
  612. return this.query || "";
  613. },
  614. setQuery: function setQuery(val, silent) {
  615. this.setInputValue(val);
  616. this._setQuery(val, silent);
  617. },
  618. hasQueryChangedSinceLastFocus: function hasQueryChangedSinceLastFocus() {
  619. return this.query !== this.queryWhenFocused;
  620. },
  621. getInputValue: function getInputValue() {
  622. return this.$input.val();
  623. },
  624. setInputValue: function setInputValue(value) {
  625. this.$input.val(value);
  626. this.clearHintIfInvalid();
  627. this._checkLanguageDirection();
  628. },
  629. resetInputValue: function resetInputValue() {
  630. this.setInputValue(this.query);
  631. },
  632. getHint: function getHint() {
  633. return this.$hint.val();
  634. },
  635. setHint: function setHint(value) {
  636. this.$hint.val(value);
  637. },
  638. clearHint: function clearHint() {
  639. this.setHint("");
  640. },
  641. clearHintIfInvalid: function clearHintIfInvalid() {
  642. var val, hint, valIsPrefixOfHint, isValid;
  643. val = this.getInputValue();
  644. hint = this.getHint();
  645. valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0;
  646. isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow();
  647. !isValid && this.clearHint();
  648. },
  649. hasFocus: function hasFocus() {
  650. return this.$input.is(":focus");
  651. },
  652. hasOverflow: function hasOverflow() {
  653. var constraint = this.$input.width() - 2;
  654. this.$overflowHelper.text(this.getInputValue());
  655. return this.$overflowHelper.width() >= constraint;
  656. },
  657. isCursorAtEnd: function() {
  658. var valueLength, selectionStart, range;
  659. valueLength = this.$input.val().length;
  660. selectionStart = this.$input[0].selectionStart;
  661. if (_.isNumber(selectionStart)) {
  662. return selectionStart === valueLength;
  663. } else if (document.selection) {
  664. range = document.selection.createRange();
  665. range.moveStart("character", -valueLength);
  666. return valueLength === range.text.length;
  667. }
  668. return true;
  669. },
  670. destroy: function destroy() {
  671. this.$hint.off(".tt");
  672. this.$input.off(".tt");
  673. this.$overflowHelper.remove();
  674. this.$hint = this.$input = this.$overflowHelper = $("<div>");
  675. },
  676. setAriaExpanded: function setAriaExpanded(value) {
  677. this.$input.attr("aria-expanded", value);
  678. }
  679. });
  680. return Input;
  681. function buildOverflowHelper($input) {
  682. return $('<pre aria-hidden="true"></pre>').css({
  683. position: "absolute",
  684. visibility: "hidden",
  685. whiteSpace: "pre",
  686. fontFamily: $input.css("font-family"),
  687. fontSize: $input.css("font-size"),
  688. fontStyle: $input.css("font-style"),
  689. fontVariant: $input.css("font-variant"),
  690. fontWeight: $input.css("font-weight"),
  691. wordSpacing: $input.css("word-spacing"),
  692. letterSpacing: $input.css("letter-spacing"),
  693. textIndent: $input.css("text-indent"),
  694. textRendering: $input.css("text-rendering"),
  695. textTransform: $input.css("text-transform")
  696. }).insertAfter($input);
  697. }
  698. function areQueriesEquivalent(a, b) {
  699. return Input.normalizeQuery(a) === Input.normalizeQuery(b);
  700. }
  701. function withModifier($e) {
  702. return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey;
  703. }
  704. }();
  705. var Dataset = function() {
  706. "use strict";
  707. var keys, nameGenerator;
  708. keys = {
  709. dataset: "tt-selectable-dataset",
  710. val: "tt-selectable-display",
  711. obj: "tt-selectable-object"
  712. };
  713. nameGenerator = _.getIdGenerator();
  714. function Dataset(o, www) {
  715. o = o || {};
  716. o.templates = o.templates || {};
  717. o.templates.notFound = o.templates.notFound || o.templates.empty;
  718. if (!o.source) {
  719. $.error("missing source");
  720. }
  721. if (!o.node) {
  722. $.error("missing node");
  723. }
  724. if (o.name && !isValidName(o.name)) {
  725. $.error("invalid dataset name: " + o.name);
  726. }
  727. www.mixin(this);
  728. this.highlight = !!o.highlight;
  729. this.name = _.toStr(o.name || nameGenerator());
  730. this.limit = o.limit || 5;
  731. this.displayFn = getDisplayFn(o.display || o.displayKey);
  732. this.templates = getTemplates(o.templates, this.displayFn);
  733. this.source = o.source.__ttAdapter ? o.source.__ttAdapter() : o.source;
  734. this.async = _.isUndefined(o.async) ? this.source.length > 2 : !!o.async;
  735. this._resetLastSuggestion();
  736. this.$el = $(o.node).attr("role", "presentation").addClass(this.classes.dataset).addClass(this.classes.dataset + "-" + this.name);
  737. }
  738. Dataset.extractData = function extractData(el) {
  739. var $el = $(el);
  740. if ($el.data(keys.obj)) {
  741. return {
  742. dataset: $el.data(keys.dataset) || "",
  743. val: $el.data(keys.val) || "",
  744. obj: $el.data(keys.obj) || null
  745. };
  746. }
  747. return null;
  748. };
  749. _.mixin(Dataset.prototype, EventEmitter, {
  750. _overwrite: function overwrite(query, suggestions) {
  751. suggestions = suggestions || [];
  752. if (suggestions.length) {
  753. this._renderSuggestions(query, suggestions);
  754. } else if (this.async && this.templates.pending) {
  755. this._renderPending(query);
  756. } else if (!this.async && this.templates.notFound) {
  757. this._renderNotFound(query);
  758. } else {
  759. this._empty();
  760. }
  761. this.trigger("rendered", suggestions, false, this.name);
  762. },
  763. _append: function append(query, suggestions) {
  764. suggestions = suggestions || [];
  765. if (suggestions.length && this.$lastSuggestion.length) {
  766. this._appendSuggestions(query, suggestions);
  767. } else if (suggestions.length) {
  768. this._renderSuggestions(query, suggestions);
  769. } else if (!this.$lastSuggestion.length && this.templates.notFound) {
  770. this._renderNotFound(query);
  771. }
  772. this.trigger("rendered", suggestions, true, this.name);
  773. },
  774. _renderSuggestions: function renderSuggestions(query, suggestions) {
  775. var $fragment;
  776. $fragment = this._getSuggestionsFragment(query, suggestions);
  777. this.$lastSuggestion = $fragment.children().last();
  778. this.$el.html($fragment).prepend(this._getHeader(query, suggestions)).append(this._getFooter(query, suggestions));
  779. },
  780. _appendSuggestions: function appendSuggestions(query, suggestions) {
  781. var $fragment, $lastSuggestion;
  782. $fragment = this._getSuggestionsFragment(query, suggestions);
  783. $lastSuggestion = $fragment.children().last();
  784. this.$lastSuggestion.after($fragment);
  785. this.$lastSuggestion = $lastSuggestion;
  786. },
  787. _renderPending: function renderPending(query) {
  788. var template = this.templates.pending;
  789. this._resetLastSuggestion();
  790. template && this.$el.html(template({
  791. query: query,
  792. dataset: this.name
  793. }));
  794. },
  795. _renderNotFound: function renderNotFound(query) {
  796. var template = this.templates.notFound;
  797. this._resetLastSuggestion();
  798. template && this.$el.html(template({
  799. query: query,
  800. dataset: this.name
  801. }));
  802. },
  803. _empty: function empty() {
  804. this.$el.empty();
  805. this._resetLastSuggestion();
  806. },
  807. _getSuggestionsFragment: function getSuggestionsFragment(query, suggestions) {
  808. var that = this, fragment;
  809. fragment = document.createDocumentFragment();
  810. _.each(suggestions, function getSuggestionNode(suggestion) {
  811. var $el, context;
  812. context = that._injectQuery(query, suggestion);
  813. $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);
  814. fragment.appendChild($el[0]);
  815. });
  816. this.highlight && highlight({
  817. className: this.classes.highlight,
  818. node: fragment,
  819. pattern: query
  820. });
  821. return $(fragment);
  822. },
  823. _getFooter: function getFooter(query, suggestions) {
  824. return this.templates.footer ? this.templates.footer({
  825. query: query,
  826. suggestions: suggestions,
  827. dataset: this.name
  828. }) : null;
  829. },
  830. _getHeader: function getHeader(query, suggestions) {
  831. return this.templates.header ? this.templates.header({
  832. query: query,
  833. suggestions: suggestions,
  834. dataset: this.name
  835. }) : null;
  836. },
  837. _resetLastSuggestion: function resetLastSuggestion() {
  838. this.$lastSuggestion = $();
  839. },
  840. _injectQuery: function injectQuery(query, obj) {
  841. return _.isObject(obj) ? _.mixin({
  842. _query: query
  843. }, obj) : obj;
  844. },
  845. update: function update(query) {
  846. var that = this, canceled = false, syncCalled = false, rendered = 0;
  847. this.cancel();
  848. this.cancel = function cancel() {
  849. canceled = true;
  850. that.cancel = $.noop;
  851. that.async && that.trigger("asyncCanceled", query, that.name);
  852. };
  853. this.source(query, sync, async);
  854. !syncCalled && sync([]);
  855. function sync(suggestions) {
  856. if (syncCalled) {
  857. return;
  858. }
  859. syncCalled = true;
  860. suggestions = (suggestions || []).slice(0, that.limit);
  861. rendered = suggestions.length;
  862. that._overwrite(query, suggestions);
  863. if (rendered < that.limit && that.async) {
  864. that.trigger("asyncRequested", query, that.name);
  865. }
  866. }
  867. function async(suggestions) {
  868. suggestions = suggestions || [];
  869. if (!canceled && rendered < that.limit) {
  870. that.cancel = $.noop;
  871. var idx = Math.abs(rendered - that.limit);
  872. rendered += idx;
  873. that._append(query, suggestions.slice(0, idx));
  874. that.async && that.trigger("asyncReceived", query, that.name);
  875. }
  876. }
  877. },
  878. cancel: $.noop,
  879. clear: function clear() {
  880. this._empty();
  881. this.cancel();
  882. this.trigger("cleared");
  883. },
  884. isEmpty: function isEmpty() {
  885. return this.$el.is(":empty");
  886. },
  887. destroy: function destroy() {
  888. this.$el = $("<div>");
  889. }
  890. });
  891. return Dataset;
  892. function getDisplayFn(display) {
  893. display = display || _.stringify;
  894. return _.isFunction(display) ? display : displayFn;
  895. function displayFn(obj) {
  896. return obj[display];
  897. }
  898. }
  899. function getTemplates(templates, displayFn) {
  900. return {
  901. notFound: templates.notFound && _.templatify(templates.notFound),
  902. pending: templates.pending && _.templatify(templates.pending),
  903. header: templates.header && _.templatify(templates.header),
  904. footer: templates.footer && _.templatify(templates.footer),
  905. suggestion: templates.suggestion ? userSuggestionTemplate : suggestionTemplate
  906. };
  907. function userSuggestionTemplate(context) {
  908. var template = templates.suggestion;
  909. return $(template(context)).attr("id", _.guid());
  910. }
  911. function suggestionTemplate(context) {
  912. return $('<div role="option">').attr("id", _.guid()).text(displayFn(context));
  913. }
  914. }
  915. function isValidName(str) {
  916. return /^[_a-zA-Z0-9-]+$/.test(str);
  917. }
  918. }();
  919. var Menu = function() {
  920. "use strict";
  921. function Menu(o, www) {
  922. var that = this;
  923. o = o || {};
  924. if (!o.node) {
  925. $.error("node is required");
  926. }
  927. www.mixin(this);
  928. this.$node = $(o.node);
  929. this.query = null;
  930. this.datasets = _.map(o.datasets, initializeDataset);
  931. function initializeDataset(oDataset) {
  932. var node = that.$node.find(oDataset.node).first();
  933. oDataset.node = node.length ? node : $("<div>").appendTo(that.$node);
  934. return new Dataset(oDataset, www);
  935. }
  936. }
  937. _.mixin(Menu.prototype, EventEmitter, {
  938. _onSelectableClick: function onSelectableClick($e) {
  939. this.trigger("selectableClicked", $($e.currentTarget));
  940. },
  941. _onRendered: function onRendered(type, dataset, suggestions, async) {
  942. this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty());
  943. this.trigger("datasetRendered", dataset, suggestions, async);
  944. },
  945. _onCleared: function onCleared() {
  946. this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty());
  947. this.trigger("datasetCleared");
  948. },
  949. _propagate: function propagate() {
  950. this.trigger.apply(this, arguments);
  951. },
  952. _allDatasetsEmpty: function allDatasetsEmpty() {
  953. return _.every(this.datasets, _.bind(function isDatasetEmpty(dataset) {
  954. var isEmpty = dataset.isEmpty();
  955. this.$node.attr("aria-expanded", !isEmpty);
  956. return isEmpty;
  957. }, this));
  958. },
  959. _getSelectables: function getSelectables() {
  960. return this.$node.find(this.selectors.selectable);
  961. },
  962. _removeCursor: function _removeCursor() {
  963. var $selectable = this.getActiveSelectable();
  964. $selectable && $selectable.removeClass(this.classes.cursor);
  965. },
  966. _ensureVisible: function ensureVisible($el) {
  967. var elTop, elBottom, nodeScrollTop, nodeHeight;
  968. elTop = $el.position().top;
  969. elBottom = elTop + $el.outerHeight(true);
  970. nodeScrollTop = this.$node.scrollTop();
  971. nodeHeight = this.$node.height() + parseInt(this.$node.css("paddingTop"), 10) + parseInt(this.$node.css("paddingBottom"), 10);
  972. if (elTop < 0) {
  973. this.$node.scrollTop(nodeScrollTop + elTop);
  974. } else if (nodeHeight < elBottom) {
  975. this.$node.scrollTop(nodeScrollTop + (elBottom - nodeHeight));
  976. }
  977. },
  978. bind: function() {
  979. var that = this, onSelectableClick;
  980. onSelectableClick = _.bind(this._onSelectableClick, this);
  981. this.$node.on("click.tt", this.selectors.selectable, onSelectableClick);
  982. this.$node.on("mouseover", this.selectors.selectable, function() {
  983. that.setCursor($(this));
  984. });
  985. this.$node.on("mouseleave", function() {
  986. that._removeCursor();
  987. });
  988. _.each(this.datasets, function(dataset) {
  989. 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);
  990. });
  991. return this;
  992. },
  993. isOpen: function isOpen() {
  994. return this.$node.hasClass(this.classes.open);
  995. },
  996. open: function open() {
  997. this.$node.scrollTop(0);
  998. this.$node.addClass(this.classes.open);
  999. },
  1000. close: function close() {
  1001. this.$node.attr("aria-expanded", false);
  1002. this.$node.removeClass(this.classes.open);
  1003. this._removeCursor();
  1004. },
  1005. setLanguageDirection: function setLanguageDirection(dir) {
  1006. this.$node.attr("dir", dir);
  1007. },
  1008. selectableRelativeToCursor: function selectableRelativeToCursor(delta) {
  1009. var $selectables, $oldCursor, oldIndex, newIndex;
  1010. $oldCursor = this.getActiveSelectable();
  1011. $selectables = this._getSelectables();
  1012. oldIndex = $oldCursor ? $selectables.index($oldCursor) : -1;
  1013. newIndex = oldIndex + delta;
  1014. newIndex = (newIndex + 1) % ($selectables.length + 1) - 1;
  1015. newIndex = newIndex < -1 ? $selectables.length - 1 : newIndex;
  1016. return newIndex === -1 ? null : $selectables.eq(newIndex);
  1017. },
  1018. setCursor: function setCursor($selectable) {
  1019. this._removeCursor();
  1020. if ($selectable = $selectable && $selectable.first()) {
  1021. $selectable.addClass(this.classes.cursor);
  1022. this._ensureVisible($selectable);
  1023. }
  1024. },
  1025. getSelectableData: function getSelectableData($el) {
  1026. return $el && $el.length ? Dataset.extractData($el) : null;
  1027. },
  1028. getActiveSelectable: function getActiveSelectable() {
  1029. var $selectable = this._getSelectables().filter(this.selectors.cursor).first();
  1030. return $selectable.length ? $selectable : null;
  1031. },
  1032. getTopSelectable: function getTopSelectable() {
  1033. var $selectable = this._getSelectables().first();
  1034. return $selectable.length ? $selectable : null;
  1035. },
  1036. update: function update(query) {
  1037. var isValidUpdate = query !== this.query;
  1038. if (isValidUpdate) {
  1039. this.query = query;
  1040. _.each(this.datasets, updateDataset);
  1041. }
  1042. return isValidUpdate;
  1043. function updateDataset(dataset) {
  1044. dataset.update(query);
  1045. }
  1046. },
  1047. empty: function empty() {
  1048. _.each(this.datasets, clearDataset);
  1049. this.query = null;
  1050. this.$node.addClass(this.classes.empty);
  1051. function clearDataset(dataset) {
  1052. dataset.clear();
  1053. }
  1054. },
  1055. destroy: function destroy() {
  1056. this.$node.off(".tt");
  1057. this.$node = $("<div>");
  1058. _.each(this.datasets, destroyDataset);
  1059. function destroyDataset(dataset) {
  1060. dataset.destroy();
  1061. }
  1062. }
  1063. });
  1064. return Menu;
  1065. }();
  1066. var Status = function() {
  1067. "use strict";
  1068. function Status(options) {
  1069. this.$el = $("<span></span>", {
  1070. role: "status",
  1071. "aria-live": "polite"
  1072. }).css({
  1073. position: "absolute",
  1074. padding: "0",
  1075. border: "0",
  1076. height: "1px",
  1077. width: "1px",
  1078. "margin-bottom": "-1px",
  1079. "margin-right": "-1px",
  1080. overflow: "hidden",
  1081. clip: "rect(0 0 0 0)",
  1082. "white-space": "nowrap"
  1083. });
  1084. options.$input.after(this.$el);
  1085. _.each(options.menu.datasets, _.bind(function(dataset) {
  1086. if (dataset.onSync) {
  1087. dataset.onSync("rendered", _.bind(this.update, this));
  1088. dataset.onSync("cleared", _.bind(this.cleared, this));
  1089. }
  1090. }, this));
  1091. }
  1092. _.mixin(Status.prototype, {
  1093. update: function update(event, suggestions) {
  1094. var length = suggestions.length;
  1095. var words;
  1096. if (length === 1) {
  1097. words = {
  1098. result: "result",
  1099. is: "is"
  1100. };
  1101. } else {
  1102. words = {
  1103. result: "results",
  1104. is: "are"
  1105. };
  1106. }
  1107. this.$el.text(length + " " + words.result + " " + words.is + " available, use up and down arrow keys to navigate.");
  1108. },
  1109. cleared: function() {
  1110. this.$el.text("");
  1111. }
  1112. });
  1113. return Status;
  1114. }();
  1115. var DefaultMenu = function() {
  1116. "use strict";
  1117. var s = Menu.prototype;
  1118. function DefaultMenu() {
  1119. Menu.apply(this, [].slice.call(arguments, 0));
  1120. }
  1121. _.mixin(DefaultMenu.prototype, Menu.prototype, {
  1122. open: function open() {
  1123. !this._allDatasetsEmpty() && this._show();
  1124. return s.open.apply(this, [].slice.call(arguments, 0));
  1125. },
  1126. close: function close() {
  1127. this._hide();
  1128. return s.close.apply(this, [].slice.call(arguments, 0));
  1129. },
  1130. _onRendered: function onRendered() {
  1131. if (this._allDatasetsEmpty()) {
  1132. this._hide();
  1133. } else {
  1134. this.isOpen() && this._show();
  1135. }
  1136. return s._onRendered.apply(this, [].slice.call(arguments, 0));
  1137. },
  1138. _onCleared: function onCleared() {
  1139. if (this._allDatasetsEmpty()) {
  1140. this._hide();
  1141. } else {
  1142. this.isOpen() && this._show();
  1143. }
  1144. return s._onCleared.apply(this, [].slice.call(arguments, 0));
  1145. },
  1146. setLanguageDirection: function setLanguageDirection(dir) {
  1147. this.$node.css(dir === "ltr" ? this.css.ltr : this.css.rtl);
  1148. return s.setLanguageDirection.apply(this, [].slice.call(arguments, 0));
  1149. },
  1150. _hide: function hide() {
  1151. this.$node.hide();
  1152. },
  1153. _show: function show() {
  1154. this.$node.css("display", "block");
  1155. }
  1156. });
  1157. return DefaultMenu;
  1158. }();
  1159. var Typeahead = function() {
  1160. "use strict";
  1161. function Typeahead(o, www) {
  1162. var onFocused, onBlurred, onEnterKeyed, onTabKeyed, onEscKeyed, onUpKeyed, onDownKeyed, onLeftKeyed, onRightKeyed, onQueryChanged, onWhitespaceChanged;
  1163. o = o || {};
  1164. if (!o.input) {
  1165. $.error("missing input");
  1166. }
  1167. if (!o.menu) {
  1168. $.error("missing menu");
  1169. }
  1170. if (!o.eventBus) {
  1171. $.error("missing event bus");
  1172. }
  1173. www.mixin(this);
  1174. this.eventBus = o.eventBus;
  1175. this.minLength = _.isNumber(o.minLength) ? o.minLength : 1;
  1176. this.input = o.input;
  1177. this.menu = o.menu;
  1178. this.enabled = true;
  1179. this.autoselect = !!o.autoselect;
  1180. this.active = false;
  1181. this.input.hasFocus() && this.activate();
  1182. this.dir = this.input.getLangDir();
  1183. this._hacks();
  1184. 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);
  1185. onFocused = c(this, "activate", "open", "_onFocused");
  1186. onBlurred = c(this, "deactivate", "_onBlurred");
  1187. onEnterKeyed = c(this, "isActive", "isOpen", "_onEnterKeyed");
  1188. onTabKeyed = c(this, "isActive", "isOpen", "_onTabKeyed");
  1189. onEscKeyed = c(this, "isActive", "_onEscKeyed");
  1190. onUpKeyed = c(this, "isActive", "open", "_onUpKeyed");
  1191. onDownKeyed = c(this, "isActive", "open", "_onDownKeyed");
  1192. onLeftKeyed = c(this, "isActive", "isOpen", "_onLeftKeyed");
  1193. onRightKeyed = c(this, "isActive", "isOpen", "_onRightKeyed");
  1194. onQueryChanged = c(this, "_openIfActive", "_onQueryChanged");
  1195. onWhitespaceChanged = c(this, "_openIfActive", "_onWhitespaceChanged");
  1196. 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);
  1197. }
  1198. _.mixin(Typeahead.prototype, {
  1199. _hacks: function hacks() {
  1200. var $input, $menu;
  1201. $input = this.input.$input || $("<div>");
  1202. $menu = this.menu.$node || $("<div>");
  1203. $input.on("blur.tt", function($e) {
  1204. var active, isActive, hasActive;
  1205. active = document.activeElement;
  1206. isActive = $menu.is(active);
  1207. hasActive = $menu.has(active).length > 0;
  1208. if (_.isMsie() && (isActive || hasActive)) {
  1209. $e.preventDefault();
  1210. $e.stopImmediatePropagation();
  1211. _.defer(function() {
  1212. $input.focus();
  1213. });
  1214. }
  1215. });
  1216. $menu.on("mousedown.tt", function($e) {
  1217. $e.preventDefault();
  1218. });
  1219. },
  1220. _onSelectableClicked: function onSelectableClicked(type, $el) {
  1221. this.select($el);
  1222. },
  1223. _onDatasetCleared: function onDatasetCleared() {
  1224. this._updateHint();
  1225. },
  1226. _onDatasetRendered: function onDatasetRendered(type, suggestions, async, dataset) {
  1227. this._updateHint();
  1228. if (this.autoselect) {
  1229. var cursorClass = this.selectors.cursor.substr(1);
  1230. this.menu.$node.find(this.selectors.suggestion).first().addClass(cursorClass);
  1231. }
  1232. this.eventBus.trigger("render", suggestions, async, dataset);
  1233. },
  1234. _onAsyncRequested: function onAsyncRequested(type, dataset, query) {
  1235. this.eventBus.trigger("asyncrequest", query, dataset);
  1236. },
  1237. _onAsyncCanceled: function onAsyncCanceled(type, dataset, query) {
  1238. this.eventBus.trigger("asynccancel", query, dataset);
  1239. },
  1240. _onAsyncReceived: function onAsyncReceived(type, dataset, query) {
  1241. this.eventBus.trigger("asyncreceive", query, dataset);
  1242. },
  1243. _onFocused: function onFocused() {
  1244. this._minLengthMet() && this.menu.update(this.input.getQuery());
  1245. },
  1246. _onBlurred: function onBlurred() {
  1247. if (this.input.hasQueryChangedSinceLastFocus()) {
  1248. this.eventBus.trigger("change", this.input.getQuery());
  1249. }
  1250. },
  1251. _onEnterKeyed: function onEnterKeyed(type, $e) {
  1252. var $selectable;
  1253. if ($selectable = this.menu.getActiveSelectable()) {
  1254. if (this.select($selectable)) {
  1255. $e.preventDefault();
  1256. $e.stopPropagation();
  1257. }
  1258. } else if (this.autoselect) {
  1259. if (this.select(this.menu.getTopSelectable())) {
  1260. $e.preventDefault();
  1261. $e.stopPropagation();
  1262. }
  1263. }
  1264. },
  1265. _onTabKeyed: function onTabKeyed(type, $e) {
  1266. var $selectable;
  1267. if ($selectable = this.menu.getActiveSelectable()) {
  1268. this.select($selectable) && $e.preventDefault();
  1269. } else if (this.autoselect) {
  1270. if ($selectable = this.menu.getTopSelectable()) {
  1271. this.autocomplete($selectable) && $e.preventDefault();
  1272. }
  1273. }
  1274. },
  1275. _onEscKeyed: function onEscKeyed() {
  1276. this.close();
  1277. },
  1278. _onUpKeyed: function onUpKeyed() {
  1279. this.moveCursor(-1);
  1280. },
  1281. _onDownKeyed: function onDownKeyed() {
  1282. this.moveCursor(+1);
  1283. },
  1284. _onLeftKeyed: function onLeftKeyed() {
  1285. if (this.dir === "rtl" && this.input.isCursorAtEnd()) {
  1286. this.autocomplete(this.menu.getActiveSelectable() || this.menu.getTopSelectable());
  1287. }
  1288. },
  1289. _onRightKeyed: function onRightKeyed() {
  1290. if (this.dir === "ltr" && this.input.isCursorAtEnd()) {
  1291. this.autocomplete(this.menu.getActiveSelectable() || this.menu.getTopSelectable());
  1292. }
  1293. },
  1294. _onQueryChanged: function onQueryChanged(e, query) {
  1295. this._minLengthMet(query) ? this.menu.update(query) : this.menu.empty();
  1296. },
  1297. _onWhitespaceChanged: function onWhitespaceChanged() {
  1298. this._updateHint();
  1299. },
  1300. _onLangDirChanged: function onLangDirChanged(e, dir) {
  1301. if (this.dir !== dir) {
  1302. this.dir = dir;
  1303. this.menu.setLanguageDirection(dir);
  1304. }
  1305. },
  1306. _openIfActive: function openIfActive() {
  1307. this.isActive() && this.open();
  1308. },
  1309. _minLengthMet: function minLengthMet(query) {
  1310. query = _.isString(query) ? query : this.input.getQuery() || "";
  1311. return query.length >= this.minLength;
  1312. },
  1313. _updateHint: function updateHint() {
  1314. var $selectable, data, val, query, escapedQuery, frontMatchRegEx, match;
  1315. $selectable = this.menu.getTopSelectable();
  1316. data = this.menu.getSelectableData($selectable);
  1317. val = this.input.getInputValue();
  1318. if (data && !_.isBlankString(val) && !this.input.hasOverflow()) {
  1319. query = Input.normalizeQuery(val);
  1320. escapedQuery = _.escapeRegExChars(query);
  1321. frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i");
  1322. match = frontMatchRegEx.exec(data.val);
  1323. match && this.input.setHint(val + match[1]);
  1324. } else {
  1325. this.input.clearHint();
  1326. }
  1327. },
  1328. isEnabled: function isEnabled() {
  1329. return this.enabled;
  1330. },
  1331. enable: function enable() {
  1332. this.enabled = true;
  1333. },
  1334. disable: function disable() {
  1335. this.enabled = false;
  1336. },
  1337. isActive: function isActive() {
  1338. return this.active;
  1339. },
  1340. activate: function activate() {
  1341. if (this.isActive()) {
  1342. return true;
  1343. } else if (!this.isEnabled() || this.eventBus.before("active")) {
  1344. return false;
  1345. } else {
  1346. this.active = true;
  1347. this.eventBus.trigger("active");
  1348. return true;
  1349. }
  1350. },
  1351. deactivate: function deactivate() {
  1352. if (!this.isActive()) {
  1353. return true;
  1354. } else if (this.eventBus.before("idle")) {
  1355. return false;
  1356. } else {
  1357. this.active = false;
  1358. this.close();
  1359. this.eventBus.trigger("idle");
  1360. return true;
  1361. }
  1362. },
  1363. isOpen: function isOpen() {
  1364. return this.menu.isOpen();
  1365. },
  1366. open: function open() {
  1367. if (!this.isOpen() && !this.eventBus.before("open")) {
  1368. this.input.setAriaExpanded(true);
  1369. this.menu.open();
  1370. this._updateHint();
  1371. this.eventBus.trigger("open");
  1372. }
  1373. return this.isOpen();
  1374. },
  1375. close: function close() {
  1376. if (this.isOpen() && !this.eventBus.before("close")) {
  1377. this.input.setAriaExpanded(false);
  1378. this.menu.close();
  1379. this.input.clearHint();
  1380. this.input.resetInputValue();
  1381. this.eventBus.trigger("close");
  1382. }
  1383. return !this.isOpen();
  1384. },
  1385. setVal: function setVal(val) {
  1386. this.input.setQuery(_.toStr(val));
  1387. },
  1388. getVal: function getVal() {
  1389. return this.input.getQuery();
  1390. },
  1391. select: function select($selectable) {
  1392. var data = this.menu.getSelectableData($selectable);
  1393. if (data && !this.eventBus.before("select", data.obj, data.dataset)) {
  1394. this.input.setQuery(data.val, true);
  1395. this.eventBus.trigger("select", data.obj, data.dataset);
  1396. this.close();
  1397. return true;
  1398. }
  1399. return false;
  1400. },
  1401. autocomplete: function autocomplete($selectable) {
  1402. var query, data, isValid;
  1403. query = this.input.getQuery();
  1404. data = this.menu.getSelectableData($selectable);
  1405. isValid = data && query !== data.val;
  1406. if (isValid && !this.eventBus.before("autocomplete", data.obj, data.dataset)) {
  1407. this.input.setQuery(data.val);
  1408. this.eventBus.trigger("autocomplete", data.obj, data.dataset);
  1409. return true;
  1410. }
  1411. return false;
  1412. },
  1413. moveCursor: function moveCursor(delta) {
  1414. var query, $candidate, data, suggestion, datasetName, cancelMove, id;
  1415. query = this.input.getQuery();
  1416. $candidate = this.menu.selectableRelativeToCursor(delta);
  1417. data = this.menu.getSelectableData($candidate);
  1418. suggestion = data ? data.obj : null;
  1419. datasetName = data ? data.dataset : null;
  1420. id = $candidate ? $candidate.attr("id") : null;
  1421. this.input.trigger("cursorchange", id);
  1422. cancelMove = this._minLengthMet() && this.menu.update(query);
  1423. if (!cancelMove && !this.eventBus.before("cursorchange", suggestion, datasetName)) {
  1424. this.menu.setCursor($candidate);
  1425. if (data) {
  1426. if (typeof data.val === "string") {
  1427. this.input.setInputValue(data.val);
  1428. }
  1429. } else {
  1430. this.input.resetInputValue();
  1431. this._updateHint();
  1432. }
  1433. this.eventBus.trigger("cursorchange", suggestion, datasetName);
  1434. return true;
  1435. }
  1436. return false;
  1437. },
  1438. destroy: function destroy() {
  1439. this.input.destroy();
  1440. this.menu.destroy();
  1441. }
  1442. });
  1443. return Typeahead;
  1444. function c(ctx) {
  1445. var methods = [].slice.call(arguments, 1);
  1446. return function() {
  1447. var args = [].slice.call(arguments);
  1448. _.each(methods, function(method) {
  1449. return ctx[method].apply(ctx, args);
  1450. });
  1451. };
  1452. }
  1453. }();
  1454. (function() {
  1455. "use strict";
  1456. var old, keys, methods;
  1457. old = $.fn.typeahead;
  1458. keys = {
  1459. www: "tt-www",
  1460. attrs: "tt-attrs",
  1461. typeahead: "tt-typeahead"
  1462. };
  1463. methods = {
  1464. initialize: function initialize(o, datasets) {
  1465. var www;
  1466. datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1);
  1467. o = o || {};
  1468. www = WWW(o.classNames);
  1469. return this.each(attach);
  1470. function attach() {
  1471. var $input, $wrapper, $hint, $menu, defaultHint, defaultMenu, eventBus, input, menu, status, typeahead, MenuConstructor;
  1472. _.each(datasets, function(d) {
  1473. d.highlight = !!o.highlight;
  1474. });
  1475. $input = $(this);
  1476. $wrapper = $(www.html.wrapper);
  1477. $hint = $elOrNull(o.hint);
  1478. $menu = $elOrNull(o.menu);
  1479. defaultHint = o.hint !== false && !$hint;
  1480. defaultMenu = o.menu !== false && !$menu;
  1481. defaultHint && ($hint = buildHintFromInput($input, www));
  1482. defaultMenu && ($menu = $(www.html.menu).css(www.css.menu));
  1483. $hint && $hint.val("");
  1484. $input = prepInput($input, www);
  1485. if (defaultHint || defaultMenu) {
  1486. $wrapper.css(www.css.wrapper);
  1487. $input.css(defaultHint ? www.css.input : www.css.inputWithNoHint);
  1488. $input.wrap($wrapper).parent().prepend(defaultHint ? $hint : null).append(defaultMenu ? $menu : null);
  1489. }
  1490. MenuConstructor = defaultMenu ? DefaultMenu : Menu;
  1491. eventBus = new EventBus({
  1492. el: $input
  1493. });
  1494. input = new Input({
  1495. hint: $hint,
  1496. input: $input,
  1497. menu: $menu
  1498. }, www);
  1499. menu = new MenuConstructor({
  1500. node: $menu,
  1501. datasets: datasets
  1502. }, www);
  1503. status = new Status({
  1504. $input: $input,
  1505. menu: menu
  1506. });
  1507. typeahead = new Typeahead({
  1508. input: input,
  1509. menu: menu,
  1510. eventBus: eventBus,
  1511. minLength: o.minLength,
  1512. autoselect: o.autoselect
  1513. }, www);
  1514. $input.data(keys.www, www);
  1515. $input.data(keys.typeahead, typeahead);
  1516. }
  1517. },
  1518. isEnabled: function isEnabled() {
  1519. var enabled;
  1520. ttEach(this.first(), function(t) {
  1521. enabled = t.isEnabled();
  1522. });
  1523. return enabled;
  1524. },
  1525. enable: function enable() {
  1526. ttEach(this, function(t) {
  1527. t.enable();
  1528. });
  1529. return this;
  1530. },
  1531. disable: function disable() {
  1532. ttEach(this, function(t) {
  1533. t.disable();
  1534. });
  1535. return this;
  1536. },
  1537. isActive: function isActive() {
  1538. var active;
  1539. ttEach(this.first(), function(t) {
  1540. active = t.isActive();
  1541. });
  1542. return active;
  1543. },
  1544. activate: function activate() {
  1545. ttEach(this, function(t) {
  1546. t.activate();
  1547. });
  1548. return this;
  1549. },
  1550. deactivate: function deactivate() {
  1551. ttEach(this, function(t) {
  1552. t.deactivate();
  1553. });
  1554. return this;
  1555. },
  1556. isOpen: function isOpen() {
  1557. var open;
  1558. ttEach(this.first(), function(t) {
  1559. open = t.isOpen();
  1560. });
  1561. return open;
  1562. },
  1563. open: function open() {
  1564. ttEach(this, function(t) {
  1565. t.open();
  1566. });
  1567. return this;
  1568. },
  1569. close: function close() {
  1570. ttEach(this, function(t) {
  1571. t.close();
  1572. });
  1573. return this;
  1574. },
  1575. select: function select(el) {
  1576. var success = false, $el = $(el);
  1577. ttEach(this.first(), function(t) {
  1578. success = t.select($el);
  1579. });
  1580. return success;
  1581. },
  1582. autocomplete: function autocomplete(el) {
  1583. var success = false, $el = $(el);
  1584. ttEach(this.first(), function(t) {
  1585. success = t.autocomplete($el);
  1586. });
  1587. return success;
  1588. },
  1589. moveCursor: function moveCursoe(delta) {
  1590. var success = false;
  1591. ttEach(this.first(), function(t) {
  1592. success = t.moveCursor(delta);
  1593. });
  1594. return success;
  1595. },
  1596. val: function val(newVal) {
  1597. var query;
  1598. if (!arguments.length) {
  1599. ttEach(this.first(), function(t) {
  1600. query = t.getVal();
  1601. });
  1602. return query;
  1603. } else {
  1604. ttEach(this, function(t) {
  1605. t.setVal(_.toStr(newVal));
  1606. });
  1607. return this;
  1608. }
  1609. },
  1610. destroy: function destroy() {
  1611. ttEach(this, function(typeahead, $input) {
  1612. revert($input);
  1613. typeahead.destroy();
  1614. });
  1615. return this;
  1616. }
  1617. };
  1618. $.fn.typeahead = function(method) {
  1619. if (methods[method]) {
  1620. return methods[method].apply(this, [].slice.call(arguments, 1));
  1621. } else {
  1622. return methods.initialize.apply(this, arguments);
  1623. }
  1624. };
  1625. $.fn.typeahead.noConflict = function noConflict() {
  1626. $.fn.typeahead = old;
  1627. return this;
  1628. };
  1629. function ttEach($els, fn) {
  1630. $els.each(function() {
  1631. var $input = $(this), typeahead;
  1632. (typeahead = $input.data(keys.typeahead)) && fn(typeahead, $input);
  1633. });
  1634. }
  1635. function buildHintFromInput($input, www) {
  1636. return $input.clone().addClass(www.classes.hint).removeData().css(www.css.hint).css(getBackgroundStyles($input)).prop({
  1637. readonly: true,
  1638. required: false
  1639. }).removeAttr("id name placeholder").removeClass("required").attr({
  1640. spellcheck: "false",
  1641. tabindex: -1
  1642. });
  1643. }
  1644. function prepInput($input, www) {
  1645. $input.data(keys.attrs, {
  1646. dir: $input.attr("dir"),
  1647. autocomplete: $input.attr("autocomplete"),
  1648. spellcheck: $input.attr("spellcheck"),
  1649. style: $input.attr("style")
  1650. });
  1651. $input.addClass(www.classes.input).attr({
  1652. spellcheck: false
  1653. });
  1654. try {
  1655. !$input.attr("dir") && $input.attr("dir", "auto");
  1656. } catch (e) {}
  1657. return $input;
  1658. }
  1659. function getBackgroundStyles($el) {
  1660. return {
  1661. backgroundAttachment: $el.css("background-attachment"),
  1662. backgroundClip: $el.css("background-clip"),
  1663. backgroundColor: $el.css("background-color"),
  1664. backgroundImage: $el.css("background-image"),
  1665. backgroundOrigin: $el.css("background-origin"),
  1666. backgroundPosition: $el.css("background-position"),
  1667. backgroundRepeat: $el.css("background-repeat"),
  1668. backgroundSize: $el.css("background-size")
  1669. };
  1670. }
  1671. function revert($input) {
  1672. var www, $wrapper;
  1673. www = $input.data(keys.www);
  1674. $wrapper = $input.parent().filter(www.selectors.wrapper);
  1675. _.each($input.data(keys.attrs), function(val, key) {
  1676. _.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val);
  1677. });
  1678. $input.removeData(keys.typeahead).removeData(keys.www).removeData(keys.attr).removeClass(www.classes.input);
  1679. if ($wrapper.length) {
  1680. $input.detach().insertAfter($wrapper);
  1681. $wrapper.remove();
  1682. }
  1683. }
  1684. function $elOrNull(obj) {
  1685. var isValid, $el;
  1686. isValid = _.isJQuery(obj) || _.isElement(obj);
  1687. $el = isValid ? $(obj).first() : [];
  1688. return $el.length ? $el : null;
  1689. }
  1690. })();
  1691. });