typeahead.jquery.js 70 KB

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