algoliasearch-rails 1.3.8 → 1.3.9

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 57c6cdf65eca1ff620c98d4e0c51c1fa69a95bd4
4
- data.tar.gz: c50e514b3c08c3789cbbb93b01181da8ea4570b9
3
+ metadata.gz: 03836856b81a8239c981587044d7f4d5886955ac
4
+ data.tar.gz: 4cf7e5902c2dfe67f96ec7f58f4f18fc6d2b9fe1
5
5
  SHA512:
6
- metadata.gz: 28ec5247fb088b3df20968d864ea8c7e144f5700de578f7119ca170ed58dc50fb37ff0c6698d3532a3e0296cedd3ee24af380f2ac0bb4a5018f980ffe81f437b
7
- data.tar.gz: 48a3d1d5ac96a56602cbf423ff57e60120e2279caeaf71894853ad8c02e968abd26f429fcacee925e1b688a567df9e20b52fa494b1458e89fad4cb3813e1ce3f
6
+ metadata.gz: e5ccdec94cc597a27ae970c0f39f30fde902329d6806bc178d0971282e3d1921851e7dbc8d2863e436219c241ca549413cad2c44b2eb32f97930fda7cbe626bd
7
+ data.tar.gz: d4e3017106bd09e87e63f2fb9d990ded70ca17aec174394aeea07518426d040ee6ba0223a81baca94a01502a0d9ba3e4914190de05bfd8ad7d8c24b4a7ed4a5a
data/ChangeLog CHANGED
@@ -1,5 +1,9 @@
1
1
  CHANGELOG
2
2
 
3
+ 2013-11-21 1.3.9
4
+
5
+ * updated custom typeahead.js (merged https://github.com/twitter/typeahead.js/pull/390)
6
+
3
7
  2013-11-21 1.3.8
4
8
 
5
9
  * expose new index settings: separatorsToIndex and optionalWords
data/VERSION CHANGED
@@ -1 +1 @@
1
- 1.3.8
1
+ 1.3.9
@@ -5,7 +5,7 @@
5
5
 
6
6
  Gem::Specification.new do |s|
7
7
  s.name = "algoliasearch-rails"
8
- s.version = "1.3.8"
8
+ s.version = "1.3.9"
9
9
 
10
10
  s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
11
  s.authors = ["Algolia"]
@@ -41,6 +41,7 @@ Gem::Specification.new do |s|
41
41
  "spec/utilities_spec.rb",
42
42
  "vendor/assets/javascripts/algolia/algoliasearch.js",
43
43
  "vendor/assets/javascripts/algolia/algoliasearch.min.js",
44
+ "vendor/assets/javascripts/algolia/typeahead.js",
44
45
  "vendor/assets/javascripts/algolia/typeahead.min.js"
45
46
  ]
46
47
  s.homepage = "http://github.com/algolia/algoliasearch-rails"
@@ -0,0 +1,1183 @@
1
+ /*!
2
+ * typeahead.js 0.9.3
3
+ * https://github.com/twitter/typeahead
4
+ * Copyright 2013 Twitter, Inc. and other contributors; Licensed MIT
5
+ */
6
+
7
+ (function($) {
8
+ var VERSION = "0.9.3";
9
+ var utils = {
10
+ isMsie: function() {
11
+ var match = /(msie) ([\w.]+)/i.exec(navigator.userAgent);
12
+ return match ? parseInt(match[2], 10) : false;
13
+ },
14
+ isBlankString: function(str) {
15
+ return !str || /^\s*$/.test(str);
16
+ },
17
+ escapeRegExChars: function(str) {
18
+ return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
19
+ },
20
+ isString: function(obj) {
21
+ return typeof obj === "string";
22
+ },
23
+ isNumber: function(obj) {
24
+ return typeof obj === "number";
25
+ },
26
+ isArray: $.isArray,
27
+ isFunction: $.isFunction,
28
+ isObject: $.isPlainObject,
29
+ isUndefined: function(obj) {
30
+ return typeof obj === "undefined";
31
+ },
32
+ bind: $.proxy,
33
+ bindAll: function(obj) {
34
+ var val;
35
+ for (var key in obj) {
36
+ $.isFunction(val = obj[key]) && (obj[key] = $.proxy(val, obj));
37
+ }
38
+ },
39
+ indexOf: function(haystack, needle) {
40
+ for (var i = 0; i < haystack.length; i++) {
41
+ if (haystack[i] === needle) {
42
+ return i;
43
+ }
44
+ }
45
+ return -1;
46
+ },
47
+ each: $.each,
48
+ map: $.map,
49
+ filter: $.grep,
50
+ every: function(obj, test) {
51
+ var result = true;
52
+ if (!obj) {
53
+ return result;
54
+ }
55
+ $.each(obj, function(key, val) {
56
+ if (!(result = test.call(null, val, key, obj))) {
57
+ return false;
58
+ }
59
+ });
60
+ return !!result;
61
+ },
62
+ some: function(obj, test) {
63
+ var result = false;
64
+ if (!obj) {
65
+ return result;
66
+ }
67
+ $.each(obj, function(key, val) {
68
+ if (result = test.call(null, val, key, obj)) {
69
+ return false;
70
+ }
71
+ });
72
+ return !!result;
73
+ },
74
+ mixin: $.extend,
75
+ getUniqueId: function() {
76
+ var counter = 0;
77
+ return function() {
78
+ return counter++;
79
+ };
80
+ }(),
81
+ defer: function(fn) {
82
+ setTimeout(fn, 0);
83
+ },
84
+ debounce: function(func, wait, immediate) {
85
+ var timeout, result;
86
+ return function() {
87
+ var context = this, args = arguments, later, callNow;
88
+ later = function() {
89
+ timeout = null;
90
+ if (!immediate) {
91
+ result = func.apply(context, args);
92
+ }
93
+ };
94
+ callNow = immediate && !timeout;
95
+ clearTimeout(timeout);
96
+ timeout = setTimeout(later, wait);
97
+ if (callNow) {
98
+ result = func.apply(context, args);
99
+ }
100
+ return result;
101
+ };
102
+ },
103
+ throttle: function(func, wait) {
104
+ var context, args, timeout, result, previous, later;
105
+ previous = 0;
106
+ later = function() {
107
+ previous = new Date();
108
+ timeout = null;
109
+ result = func.apply(context, args);
110
+ };
111
+ return function() {
112
+ var now = new Date(), remaining = wait - (now - previous);
113
+ context = this;
114
+ args = arguments;
115
+ if (remaining <= 0) {
116
+ clearTimeout(timeout);
117
+ timeout = null;
118
+ previous = now;
119
+ result = func.apply(context, args);
120
+ } else if (!timeout) {
121
+ timeout = setTimeout(later, remaining);
122
+ }
123
+ return result;
124
+ };
125
+ },
126
+ tokenizeQuery: function(str) {
127
+ return $.trim(str).toLowerCase().split(/[\s]+/);
128
+ },
129
+ tokenizeText: function(str) {
130
+ return $.trim(str).toLowerCase().split(/[\s\-_]+/);
131
+ },
132
+ getProtocol: function() {
133
+ return location.protocol;
134
+ },
135
+ noop: function() {}
136
+ };
137
+ var EventTarget = function() {
138
+ var eventSplitter = /\s+/;
139
+ return {
140
+ on: function(events, callback) {
141
+ var event;
142
+ if (!callback) {
143
+ return this;
144
+ }
145
+ this._callbacks = this._callbacks || {};
146
+ events = events.split(eventSplitter);
147
+ while (event = events.shift()) {
148
+ this._callbacks[event] = this._callbacks[event] || [];
149
+ this._callbacks[event].push(callback);
150
+ }
151
+ return this;
152
+ },
153
+ trigger: function(events, data) {
154
+ var event, callbacks;
155
+ if (!this._callbacks) {
156
+ return this;
157
+ }
158
+ events = events.split(eventSplitter);
159
+ while (event = events.shift()) {
160
+ if (callbacks = this._callbacks[event]) {
161
+ for (var i = 0; i < callbacks.length; i += 1) {
162
+ callbacks[i].call(this, {
163
+ type: event,
164
+ data: data
165
+ });
166
+ }
167
+ }
168
+ }
169
+ return this;
170
+ }
171
+ };
172
+ }();
173
+ var EventBus = function() {
174
+ var namespace = "typeahead:";
175
+ function EventBus(o) {
176
+ if (!o || !o.el) {
177
+ $.error("EventBus initialized without el");
178
+ }
179
+ this.$el = $(o.el);
180
+ }
181
+ utils.mixin(EventBus.prototype, {
182
+ trigger: function(type) {
183
+ var args = [].slice.call(arguments, 1);
184
+ this.$el.trigger(namespace + type, args);
185
+ }
186
+ });
187
+ return EventBus;
188
+ }();
189
+ var PersistentStorage = function() {
190
+ var ls, methods;
191
+ try {
192
+ ls = window.localStorage;
193
+ ls.setItem("~~~", "!");
194
+ ls.removeItem("~~~");
195
+ } catch (err) {
196
+ ls = null;
197
+ }
198
+ function PersistentStorage(namespace) {
199
+ this.prefix = [ "__", namespace, "__" ].join("");
200
+ this.ttlKey = "__ttl__";
201
+ this.keyMatcher = new RegExp("^" + this.prefix);
202
+ }
203
+ if (ls && window.JSON) {
204
+ methods = {
205
+ _prefix: function(key) {
206
+ return this.prefix + key;
207
+ },
208
+ _ttlKey: function(key) {
209
+ return this._prefix(key) + this.ttlKey;
210
+ },
211
+ get: function(key) {
212
+ if (this.isExpired(key)) {
213
+ this.remove(key);
214
+ }
215
+ return decode(ls.getItem(this._prefix(key)));
216
+ },
217
+ set: function(key, val, ttl) {
218
+ if (utils.isNumber(ttl)) {
219
+ ls.setItem(this._ttlKey(key), encode(now() + ttl));
220
+ } else {
221
+ ls.removeItem(this._ttlKey(key));
222
+ }
223
+ return ls.setItem(this._prefix(key), encode(val));
224
+ },
225
+ remove: function(key) {
226
+ ls.removeItem(this._ttlKey(key));
227
+ ls.removeItem(this._prefix(key));
228
+ return this;
229
+ },
230
+ clear: function() {
231
+ var i, key, keys = [], len = ls.length;
232
+ for (i = 0; i < len; i++) {
233
+ if ((key = ls.key(i)).match(this.keyMatcher)) {
234
+ keys.push(key.replace(this.keyMatcher, ""));
235
+ }
236
+ }
237
+ for (i = keys.length; i--; ) {
238
+ this.remove(keys[i]);
239
+ }
240
+ return this;
241
+ },
242
+ isExpired: function(key) {
243
+ var ttl = decode(ls.getItem(this._ttlKey(key)));
244
+ return utils.isNumber(ttl) && now() > ttl ? true : false;
245
+ }
246
+ };
247
+ } else {
248
+ methods = {
249
+ get: utils.noop,
250
+ set: utils.noop,
251
+ remove: utils.noop,
252
+ clear: utils.noop,
253
+ isExpired: utils.noop
254
+ };
255
+ }
256
+ utils.mixin(PersistentStorage.prototype, methods);
257
+ return PersistentStorage;
258
+ function now() {
259
+ return new Date().getTime();
260
+ }
261
+ function encode(val) {
262
+ return JSON.stringify(utils.isUndefined(val) ? null : val);
263
+ }
264
+ function decode(val) {
265
+ return JSON.parse(val);
266
+ }
267
+ }();
268
+ var RequestCache = function() {
269
+ function RequestCache(o) {
270
+ utils.bindAll(this);
271
+ o = o || {};
272
+ this.sizeLimit = o.sizeLimit || 10;
273
+ this.cache = {};
274
+ this.cachedKeysByAge = [];
275
+ }
276
+ utils.mixin(RequestCache.prototype, {
277
+ get: function(url) {
278
+ return this.cache[url];
279
+ },
280
+ set: function(url, resp) {
281
+ var requestToEvict;
282
+ if (this.cachedKeysByAge.length === this.sizeLimit) {
283
+ requestToEvict = this.cachedKeysByAge.shift();
284
+ delete this.cache[requestToEvict];
285
+ }
286
+ this.cache[url] = resp;
287
+ this.cachedKeysByAge.push(url);
288
+ }
289
+ });
290
+ return RequestCache;
291
+ }();
292
+ var Transport = function() {
293
+ var pendingRequestsCount = 0, pendingRequests = {}, maxPendingRequests, requestCache;
294
+ function Transport(o) {
295
+ utils.bindAll(this);
296
+ o = utils.isString(o) ? {
297
+ url: o
298
+ } : o;
299
+ requestCache = requestCache || new RequestCache();
300
+ maxPendingRequests = utils.isNumber(o.maxParallelRequests) ? o.maxParallelRequests : maxPendingRequests || 6;
301
+ this.url = o.url;
302
+ this.wildcard = o.wildcard || "%QUERY";
303
+ this.filter = o.filter;
304
+ this.replace = o.replace;
305
+ this.ajaxSettings = {
306
+ type: "get",
307
+ cache: o.cache,
308
+ timeout: o.timeout,
309
+ dataType: o.dataType || "json",
310
+ beforeSend: o.beforeSend
311
+ };
312
+ this._get = (/^throttle$/i.test(o.rateLimitFn) ? utils.throttle : utils.debounce)(this._get, o.rateLimitWait || 300);
313
+ }
314
+ utils.mixin(Transport.prototype, {
315
+ _get: function(url, cb) {
316
+ var that = this;
317
+ if (belowPendingRequestsThreshold()) {
318
+ this._sendRequest(url).done(done);
319
+ } else {
320
+ this.onDeckRequestArgs = [].slice.call(arguments, 0);
321
+ }
322
+ function done(resp) {
323
+ var data = that.filter ? that.filter(resp) : resp;
324
+ cb && cb(data);
325
+ requestCache.set(url, resp);
326
+ }
327
+ },
328
+ _sendRequest: function(url) {
329
+ var that = this, jqXhr = pendingRequests[url];
330
+ if (!jqXhr) {
331
+ incrementPendingRequests();
332
+ jqXhr = pendingRequests[url] = $.ajax(url, this.ajaxSettings).always(always);
333
+ }
334
+ return jqXhr;
335
+ function always() {
336
+ decrementPendingRequests();
337
+ pendingRequests[url] = null;
338
+ if (that.onDeckRequestArgs) {
339
+ that._get.apply(that, that.onDeckRequestArgs);
340
+ that.onDeckRequestArgs = null;
341
+ }
342
+ }
343
+ },
344
+ get: function(query, cb) {
345
+ var that = this, encodedQuery = encodeURIComponent(query || ""), url, resp;
346
+ cb = cb || utils.noop;
347
+ url = this.replace ? this.replace(this.url, encodedQuery) : this.url.replace(this.wildcard, encodedQuery);
348
+ if (resp = requestCache.get(url)) {
349
+ utils.defer(function() {
350
+ cb(that.filter ? that.filter(resp) : resp);
351
+ });
352
+ } else {
353
+ this._get(url, cb);
354
+ }
355
+ return !!resp;
356
+ }
357
+ });
358
+ return Transport;
359
+ function incrementPendingRequests() {
360
+ pendingRequestsCount++;
361
+ }
362
+ function decrementPendingRequests() {
363
+ pendingRequestsCount--;
364
+ }
365
+ function belowPendingRequestsThreshold() {
366
+ return pendingRequestsCount < maxPendingRequests;
367
+ }
368
+ }();
369
+ var Dataset = function() {
370
+ var keys = {
371
+ thumbprint: "thumbprint",
372
+ protocol: "protocol",
373
+ itemHash: "itemHash",
374
+ adjacencyList: "adjacencyList"
375
+ };
376
+ function Dataset(o) {
377
+ utils.bindAll(this);
378
+ if (utils.isString(o.template) && !o.engine) {
379
+ $.error("no template engine specified");
380
+ }
381
+ if (!o.local && !o.prefetch && !o.remote) {
382
+ $.error("one of local, prefetch, or remote is required");
383
+ }
384
+ if (o.minLength === 0 && !(o.local || o.prefetch)) {
385
+ $.error("local or prefetch required to use default suggestions");
386
+ }
387
+ this.name = o.name || utils.getUniqueId();
388
+ this.limit = o.limit || 5;
389
+ this.minLength = o.minLength == null ? 1 : o.minLength;
390
+ this.header = o.header;
391
+ this.footer = o.footer;
392
+ this.valueKey = o.valueKey || "value";
393
+ this.template = compileTemplate(o.template, o.engine, this.valueKey);
394
+ this.defaultSort = o.defaultSort;
395
+ this.local = o.local;
396
+ this.prefetch = o.prefetch;
397
+ this.remote = o.remote;
398
+ this.itemHash = {};
399
+ this.adjacencyList = {};
400
+ this.defaultOrder = [];
401
+ this.storage = o.name ? new PersistentStorage(o.name) : null;
402
+ }
403
+ utils.mixin(Dataset.prototype, {
404
+ _processLocalData: function(data) {
405
+ this._mergeProcessedData(this._processData(data));
406
+ },
407
+ _loadPrefetchData: function(o) {
408
+ var that = this, thumbprint = VERSION + (o.thumbprint || ""), storedThumbprint, storedProtocol, storedItemHash, storedAdjacencyList, isExpired, deferred;
409
+ if (this.storage) {
410
+ storedThumbprint = this.storage.get(keys.thumbprint);
411
+ storedProtocol = this.storage.get(keys.protocol);
412
+ storedItemHash = this.storage.get(keys.itemHash);
413
+ storedAdjacencyList = this.storage.get(keys.adjacencyList);
414
+ }
415
+ isExpired = storedThumbprint !== thumbprint || storedProtocol !== utils.getProtocol();
416
+ o = utils.isString(o) ? {
417
+ url: o
418
+ } : o;
419
+ o.ttl = utils.isNumber(o.ttl) ? o.ttl : 24 * 60 * 60 * 1e3;
420
+ if (storedItemHash && storedAdjacencyList && !isExpired) {
421
+ this._mergeProcessedData({
422
+ itemHash: storedItemHash,
423
+ adjacencyList: storedAdjacencyList
424
+ });
425
+ deferred = $.Deferred().resolve();
426
+ } else {
427
+ deferred = $.getJSON(o.url).done(processPrefetchData);
428
+ }
429
+ return deferred;
430
+ function processPrefetchData(data) {
431
+ var filteredData = o.filter ? o.filter(data) : data, processedData = that._processData(filteredData), itemHash = processedData.itemHash, adjacencyList = processedData.adjacencyList;
432
+ if (that.storage) {
433
+ that.storage.set(keys.itemHash, itemHash, o.ttl);
434
+ that.storage.set(keys.adjacencyList, adjacencyList, o.ttl);
435
+ that.storage.set(keys.thumbprint, thumbprint, o.ttl);
436
+ that.storage.set(keys.protocol, utils.getProtocol(), o.ttl);
437
+ }
438
+ that._mergeProcessedData(processedData);
439
+ }
440
+ },
441
+ _transformDatum: function(datum) {
442
+ var value = utils.isString(datum) ? datum : datum[this.valueKey], tokens = datum.tokens || utils.tokenizeText(value), item = {
443
+ value: value,
444
+ tokens: tokens
445
+ };
446
+ if (utils.isString(datum)) {
447
+ item.datum = {};
448
+ item.datum[this.valueKey] = datum;
449
+ } else {
450
+ item.datum = datum;
451
+ }
452
+ item.tokens = utils.filter(item.tokens, function(token) {
453
+ return !utils.isBlankString(token);
454
+ });
455
+ item.tokens = utils.map(item.tokens, function(token) {
456
+ return token.toLowerCase();
457
+ });
458
+ return item;
459
+ },
460
+ _processData: function(data) {
461
+ var that = this, itemHash = {}, adjacencyList = {};
462
+ utils.each(data, function(i, datum) {
463
+ var item = that._transformDatum(datum), id = utils.getUniqueId(item.value);
464
+ itemHash[id] = item;
465
+ utils.each(item.tokens, function(i, token) {
466
+ var character = token.charAt(0), adjacency = adjacencyList[character] || (adjacencyList[character] = [ id ]);
467
+ !~utils.indexOf(adjacency, id) && adjacency.push(id);
468
+ });
469
+ });
470
+ return {
471
+ itemHash: itemHash,
472
+ adjacencyList: adjacencyList
473
+ };
474
+ },
475
+ _mergeProcessedData: function(processedData) {
476
+ var that = this;
477
+ utils.mixin(this.itemHash, processedData.itemHash);
478
+ utils.each(processedData.adjacencyList, function(character, adjacency) {
479
+ var masterAdjacency = that.adjacencyList[character];
480
+ that.adjacencyList[character] = masterAdjacency ? masterAdjacency.concat(adjacency) : adjacency;
481
+ });
482
+ if (this.minLength === 0) {
483
+ for (var hashKey in processedData.itemHash) {
484
+ this.defaultOrder.push(hashKey);
485
+ }
486
+ if (utils.isFunction(this.defaultSort)) {
487
+ this.defaultOrder.sort(function(a, b) {
488
+ return that.defaultSort(that.itemHash[a], that.itemHash[b]);
489
+ });
490
+ }
491
+ }
492
+ },
493
+ _getDefaultList: function() {
494
+ var defaultList = [];
495
+ for (var i = 0; i < Math.min(this.limit, this.defaultOrder.length); i++) {
496
+ defaultList.push(this.itemHash[this.defaultOrder[i]]);
497
+ }
498
+ return defaultList;
499
+ },
500
+ _getLocalSuggestions: function(terms) {
501
+ var that = this, firstChars = [], lists = [], shortestList, suggestions = [];
502
+ utils.each(terms, function(i, term) {
503
+ var firstChar = term.charAt(0);
504
+ !~utils.indexOf(firstChars, firstChar) && firstChars.push(firstChar);
505
+ });
506
+ utils.each(firstChars, function(i, firstChar) {
507
+ var list = that.adjacencyList[firstChar];
508
+ if (!list) {
509
+ return false;
510
+ }
511
+ lists.push(list);
512
+ if (!shortestList || list.length < shortestList.length) {
513
+ shortestList = list;
514
+ }
515
+ });
516
+ if (lists.length < firstChars.length) {
517
+ return [];
518
+ }
519
+ utils.each(shortestList, function(i, id) {
520
+ var item = that.itemHash[id], isCandidate, isMatch;
521
+ isCandidate = utils.every(lists, function(list) {
522
+ return ~utils.indexOf(list, id);
523
+ });
524
+ isMatch = isCandidate && utils.every(terms, function(term) {
525
+ return utils.some(item.tokens, function(token) {
526
+ return token.indexOf(term) === 0;
527
+ });
528
+ });
529
+ isMatch && suggestions.push(item);
530
+ });
531
+ return suggestions;
532
+ },
533
+ initialize: function() {
534
+ var deferred;
535
+ this.local && this._processLocalData(this.local);
536
+ if (typeof this.remote === "undefined") {
537
+ this.transport = null;
538
+ } else if (typeof this.remote === "string") {
539
+ this.transport = new Transport(this.remote);
540
+ } else {
541
+ this.transport = this.remote;
542
+ }
543
+ deferred = this.prefetch ? this._loadPrefetchData(this.prefetch) : $.Deferred().resolve();
544
+ this.local = this.prefetch = this.remote = null;
545
+ this.initialize = function() {
546
+ return deferred;
547
+ };
548
+ return deferred;
549
+ },
550
+ getSuggestions: function(query, cb) {
551
+ var that = this, terms, suggestions, cacheHit = false;
552
+ if (query.length < this.minLength) {
553
+ return;
554
+ }
555
+ if (query.length == 0) return cb(this._getDefaultList());
556
+ terms = utils.tokenizeQuery(query);
557
+ suggestions = this._getLocalSuggestions(terms).slice(0, this.limit);
558
+ if (suggestions.length < this.limit && this.transport) {
559
+ cacheHit = this.transport.get(query, processRemoteData, that, cb, suggestions);
560
+ }
561
+ !cacheHit && cb && cb(suggestions);
562
+ function processRemoteData(data) {
563
+ suggestions = suggestions.slice(0);
564
+ utils.each(data, function(i, datum) {
565
+ var item = that._transformDatum(datum), isDuplicate;
566
+ isDuplicate = utils.some(suggestions, function(suggestion) {
567
+ return item.value === suggestion.value;
568
+ });
569
+ !isDuplicate && suggestions.push(item);
570
+ return suggestions.length < that.limit;
571
+ });
572
+ cb && cb(suggestions);
573
+ }
574
+ }
575
+ });
576
+ return Dataset;
577
+ function compileTemplate(template, engine, valueKey) {
578
+ var renderFn, compiledTemplate;
579
+ if (utils.isFunction(template)) {
580
+ renderFn = template;
581
+ } else if (utils.isString(template)) {
582
+ compiledTemplate = engine.compile(template);
583
+ renderFn = utils.bind(compiledTemplate.render, compiledTemplate);
584
+ } else {
585
+ renderFn = function(context) {
586
+ return "<p>" + context[valueKey] + "</p>";
587
+ };
588
+ }
589
+ return renderFn;
590
+ }
591
+ }();
592
+ var InputView = function() {
593
+ function InputView(o) {
594
+ var that = this;
595
+ utils.bindAll(this);
596
+ this.specialKeyCodeMap = {
597
+ 9: "tab",
598
+ 27: "esc",
599
+ 37: "left",
600
+ 39: "right",
601
+ 13: "enter",
602
+ 38: "up",
603
+ 40: "down"
604
+ };
605
+ this.$hint = $(o.hint);
606
+ this.$input = $(o.input).on("blur.tt", this._handleBlur).on("focus.tt", this._handleFocus).on("keydown.tt", this._handleSpecialKeyEvent);
607
+ if (!utils.isMsie()) {
608
+ this.$input.on("input.tt", this._compareQueryToInputValue);
609
+ } else {
610
+ this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) {
611
+ if (that.specialKeyCodeMap[$e.which || $e.keyCode]) {
612
+ return;
613
+ }
614
+ utils.defer(that._compareQueryToInputValue);
615
+ });
616
+ }
617
+ this.query = this.$input.val();
618
+ this.$overflowHelper = buildOverflowHelper(this.$input);
619
+ }
620
+ utils.mixin(InputView.prototype, EventTarget, {
621
+ _handleFocus: function() {
622
+ this.trigger("focused");
623
+ },
624
+ _handleBlur: function() {
625
+ this.trigger("blured");
626
+ },
627
+ _handleSpecialKeyEvent: function($e) {
628
+ var keyName = this.specialKeyCodeMap[$e.which || $e.keyCode];
629
+ keyName && this.trigger(keyName + "Keyed", $e);
630
+ },
631
+ _compareQueryToInputValue: function() {
632
+ var inputValue = this.getInputValue(), isSameQuery = compareQueries(this.query, inputValue), isSameQueryExceptWhitespace = isSameQuery ? this.query.length !== inputValue.length : false;
633
+ if (isSameQueryExceptWhitespace) {
634
+ this.trigger("whitespaceChanged", {
635
+ value: this.query
636
+ });
637
+ } else if (!isSameQuery) {
638
+ this.trigger("queryChanged", {
639
+ value: this.query = inputValue
640
+ });
641
+ }
642
+ },
643
+ destroy: function() {
644
+ this.$hint.off(".tt");
645
+ this.$input.off(".tt");
646
+ this.$hint = this.$input = this.$overflowHelper = null;
647
+ },
648
+ focus: function() {
649
+ this.$input.focus();
650
+ },
651
+ blur: function() {
652
+ this.$input.blur();
653
+ },
654
+ getQuery: function() {
655
+ return this.query;
656
+ },
657
+ setQuery: function(query) {
658
+ this.query = query;
659
+ },
660
+ getInputValue: function() {
661
+ return this.$input.val();
662
+ },
663
+ setInputValue: function(value, silent) {
664
+ this.$input.val(value);
665
+ !silent && this._compareQueryToInputValue();
666
+ },
667
+ getHintValue: function() {
668
+ return this.$hint.val();
669
+ },
670
+ setHintValue: function(value) {
671
+ this.$hint.val(value);
672
+ },
673
+ getLanguageDirection: function() {
674
+ return (this.$input.css("direction") || "ltr").toLowerCase();
675
+ },
676
+ isOverflow: function() {
677
+ this.$overflowHelper.text(this.getInputValue());
678
+ return this.$overflowHelper.width() > this.$input.width();
679
+ },
680
+ isCursorAtEnd: function() {
681
+ var valueLength = this.$input.val().length, selectionStart = this.$input[0].selectionStart, range;
682
+ if (utils.isNumber(selectionStart)) {
683
+ return selectionStart === valueLength;
684
+ } else if (document.selection) {
685
+ range = document.selection.createRange();
686
+ range.moveStart("character", -valueLength);
687
+ return valueLength === range.text.length;
688
+ }
689
+ return true;
690
+ }
691
+ });
692
+ return InputView;
693
+ function buildOverflowHelper($input) {
694
+ return $("<span></span>").css({
695
+ position: "absolute",
696
+ left: "-9999px",
697
+ visibility: "hidden",
698
+ whiteSpace: "nowrap",
699
+ fontFamily: $input.css("font-family"),
700
+ fontSize: $input.css("font-size"),
701
+ fontStyle: $input.css("font-style"),
702
+ fontVariant: $input.css("font-variant"),
703
+ fontWeight: $input.css("font-weight"),
704
+ wordSpacing: $input.css("word-spacing"),
705
+ letterSpacing: $input.css("letter-spacing"),
706
+ textIndent: $input.css("text-indent"),
707
+ textRendering: $input.css("text-rendering"),
708
+ textTransform: $input.css("text-transform")
709
+ }).insertAfter($input);
710
+ }
711
+ function compareQueries(a, b) {
712
+ a = (a || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
713
+ b = (b || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
714
+ return a === b;
715
+ }
716
+ }();
717
+ var DropdownView = function() {
718
+ var html = {
719
+ suggestionsList: '<span class="tt-suggestions"></span>'
720
+ }, css = {
721
+ suggestionsList: {
722
+ display: "block"
723
+ },
724
+ suggestion: {
725
+ whiteSpace: "nowrap",
726
+ cursor: "pointer"
727
+ },
728
+ suggestionChild: {
729
+ whiteSpace: "normal"
730
+ }
731
+ };
732
+ function DropdownView(o) {
733
+ utils.bindAll(this);
734
+ this.isOpen = false;
735
+ this.isEmpty = true;
736
+ this.isMouseOverDropdown = false;
737
+ this.showDefaultSuggestions = o.showDefaultSuggestions;
738
+ this.$menu = $(o.menu).on("mouseenter.tt", this._handleMouseenter).on("mouseleave.tt", this._handleMouseleave).on("click.tt", ".tt-suggestion", this._handleSelection).on("mouseover.tt", ".tt-suggestion", this._handleMouseover);
739
+ }
740
+ utils.mixin(DropdownView.prototype, EventTarget, {
741
+ _handleMouseenter: function() {
742
+ this.isMouseOverDropdown = true;
743
+ },
744
+ _handleMouseleave: function() {
745
+ this.isMouseOverDropdown = false;
746
+ },
747
+ _handleMouseover: function($e) {
748
+ var $suggestion = $($e.currentTarget);
749
+ this._getSuggestions().removeClass("tt-is-under-cursor");
750
+ $suggestion.addClass("tt-is-under-cursor");
751
+ },
752
+ _handleSelection: function($e) {
753
+ var $suggestion = $($e.currentTarget);
754
+ this.trigger("suggestionSelected", extractSuggestion($suggestion));
755
+ },
756
+ _show: function() {
757
+ this.$menu.css("display", "block");
758
+ },
759
+ _hide: function() {
760
+ this.$menu.hide();
761
+ },
762
+ _moveCursor: function(increment) {
763
+ var $suggestions, $cur, nextIndex, $underCursor;
764
+ if (!this.isVisible()) {
765
+ return;
766
+ }
767
+ $suggestions = this._getSuggestions();
768
+ $cur = $suggestions.filter(".tt-is-under-cursor");
769
+ $cur.removeClass("tt-is-under-cursor");
770
+ nextIndex = $suggestions.index($cur) + increment;
771
+ nextIndex = (nextIndex + 1) % ($suggestions.length + 1) - 1;
772
+ if (nextIndex === -1) {
773
+ this.trigger("cursorRemoved");
774
+ return;
775
+ } else if (nextIndex < -1) {
776
+ nextIndex = $suggestions.length - 1;
777
+ }
778
+ $underCursor = $suggestions.eq(nextIndex).addClass("tt-is-under-cursor");
779
+ this._ensureVisibility($underCursor);
780
+ this.trigger("cursorMoved", extractSuggestion($underCursor));
781
+ },
782
+ _getSuggestions: function() {
783
+ return this.$menu.find(".tt-suggestions > .tt-suggestion");
784
+ },
785
+ _ensureVisibility: function($el) {
786
+ var menuHeight = this.$menu.height() + parseInt(this.$menu.css("paddingTop"), 10) + parseInt(this.$menu.css("paddingBottom"), 10), menuScrollTop = this.$menu.scrollTop(), elTop = $el.position().top, elBottom = elTop + $el.outerHeight(true);
787
+ if (elTop < 0) {
788
+ this.$menu.scrollTop(menuScrollTop + elTop);
789
+ } else if (menuHeight < elBottom) {
790
+ this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight));
791
+ }
792
+ },
793
+ destroy: function() {
794
+ this.$menu.off(".tt");
795
+ this.$menu = null;
796
+ },
797
+ isVisible: function() {
798
+ return this.isOpen && !this.isEmpty;
799
+ },
800
+ closeUnlessMouseIsOverDropdown: function() {
801
+ if (!this.isMouseOverDropdown) {
802
+ this.close();
803
+ }
804
+ },
805
+ close: function() {
806
+ if (this.isOpen) {
807
+ this.isOpen = false;
808
+ this.isMouseOverDropdown = false;
809
+ this._hide();
810
+ this.$menu.find(".tt-suggestions > .tt-suggestion").removeClass("tt-is-under-cursor");
811
+ this.trigger("closed");
812
+ }
813
+ },
814
+ open: function() {
815
+ if (!this.isOpen) {
816
+ this.isOpen = true;
817
+ if (this.showDefaultSuggestions || !this.isEmpty) {
818
+ this._show();
819
+ }
820
+ this.trigger("opened");
821
+ }
822
+ },
823
+ setLanguageDirection: function(dir) {
824
+ var ltrCss = {
825
+ left: "0",
826
+ right: "auto"
827
+ }, rtlCss = {
828
+ left: "auto",
829
+ right: " 0"
830
+ };
831
+ dir === "ltr" ? this.$menu.css(ltrCss) : this.$menu.css(rtlCss);
832
+ },
833
+ moveCursorUp: function() {
834
+ this._moveCursor(-1);
835
+ },
836
+ moveCursorDown: function() {
837
+ this._moveCursor(+1);
838
+ },
839
+ getSuggestionUnderCursor: function() {
840
+ var $suggestion = this._getSuggestions().filter(".tt-is-under-cursor").first();
841
+ return $suggestion.length > 0 ? extractSuggestion($suggestion) : null;
842
+ },
843
+ getFirstSuggestion: function() {
844
+ var $suggestion = this._getSuggestions().first();
845
+ return $suggestion.length > 0 ? extractSuggestion($suggestion) : null;
846
+ },
847
+ renderSuggestions: function(dataset, suggestions) {
848
+ var datasetClassName = "tt-dataset-" + dataset.name, wrapper = '<div class="tt-suggestion">%body</div>', compiledHtml, $suggestionsList, $dataset = this.$menu.find("." + datasetClassName), elBuilder, fragment, $el;
849
+ if ($dataset.length === 0) {
850
+ $suggestionsList = $(html.suggestionsList).css(css.suggestionsList);
851
+ $dataset = $("<div></div>").addClass(datasetClassName).append(dataset.header).append($suggestionsList).append(dataset.footer).appendTo(this.$menu);
852
+ }
853
+ if (suggestions.length > 0) {
854
+ this.isEmpty = false;
855
+ this.isOpen && this._show();
856
+ elBuilder = document.createElement("div");
857
+ fragment = document.createDocumentFragment();
858
+ utils.each(suggestions, function(i, suggestion) {
859
+ suggestion.dataset = dataset.name;
860
+ compiledHtml = dataset.template(suggestion.datum);
861
+ elBuilder.innerHTML = wrapper.replace("%body", compiledHtml);
862
+ $el = $(elBuilder.firstChild).css(css.suggestion).data("suggestion", suggestion);
863
+ $el.children().each(function() {
864
+ $(this).css(css.suggestionChild);
865
+ });
866
+ fragment.appendChild($el[0]);
867
+ });
868
+ $dataset.show().find(".tt-suggestions").html(fragment);
869
+ } else {
870
+ this.clearSuggestions(dataset.name);
871
+ }
872
+ this.trigger("suggestionsRendered");
873
+ },
874
+ clearSuggestions: function(datasetName) {
875
+ var $datasets = datasetName ? this.$menu.find(".tt-dataset-" + datasetName) : this.$menu.find('[class^="tt-dataset-"]'), $suggestions = $datasets.find(".tt-suggestions");
876
+ $datasets.hide();
877
+ $suggestions.empty();
878
+ if (this._getSuggestions().length === 0) {
879
+ this.isEmpty = true;
880
+ this._hide();
881
+ }
882
+ }
883
+ });
884
+ return DropdownView;
885
+ function extractSuggestion($el) {
886
+ return $el.data("suggestion");
887
+ }
888
+ }();
889
+ var TypeaheadView = function() {
890
+ var html = {
891
+ wrapper: '<span class="twitter-typeahead"></span>',
892
+ hint: '<input class="tt-hint" type="text" autocomplete="off" spellcheck="off" disabled>',
893
+ dropdown: '<span class="tt-dropdown-menu"></span>'
894
+ }, css = {
895
+ wrapper: {
896
+ position: "relative",
897
+ display: "inline-block"
898
+ },
899
+ hint: {
900
+ position: "absolute",
901
+ top: "0",
902
+ left: "0",
903
+ borderColor: "transparent",
904
+ boxShadow: "none"
905
+ },
906
+ query: {
907
+ position: "relative",
908
+ verticalAlign: "top",
909
+ backgroundColor: "transparent"
910
+ },
911
+ dropdown: {
912
+ position: "absolute",
913
+ top: "100%",
914
+ left: "0",
915
+ zIndex: "100",
916
+ display: "none"
917
+ }
918
+ };
919
+ if (utils.isMsie()) {
920
+ utils.mixin(css.query, {
921
+ backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
922
+ });
923
+ }
924
+ if (utils.isMsie() && utils.isMsie() <= 7) {
925
+ utils.mixin(css.wrapper, {
926
+ display: "inline",
927
+ zoom: "1"
928
+ });
929
+ utils.mixin(css.query, {
930
+ marginTop: "-1px"
931
+ });
932
+ }
933
+ function TypeaheadView(o) {
934
+ var $menu, $input, $hint;
935
+ utils.bindAll(this);
936
+ this.$node = buildDomStructure(o.input);
937
+ this.datasets = o.datasets;
938
+ this.dir = null;
939
+ this.showDefaultSuggestions = false;
940
+ this.eventBus = o.eventBus;
941
+ $menu = this.$node.find(".tt-dropdown-menu");
942
+ $input = this.$node.find(".tt-query");
943
+ $hint = this.$node.find(".tt-hint");
944
+ for (var i = 0; i < this.datasets.length; i++) {
945
+ if (this.datasets[i].minLength === 0) this.showDefaultSuggestions = true;
946
+ }
947
+ this.dropdownView = new DropdownView({
948
+ menu: $menu,
949
+ showDefaultSuggestions: this.showDefaultSuggestions
950
+ }).on("suggestionSelected", this._handleSelection).on("cursorMoved", this._clearHint).on("cursorMoved", this._setInputValueToSuggestionUnderCursor).on("cursorRemoved", this._setInputValueToQuery).on("cursorRemoved", this._updateHint).on("suggestionsRendered", this._updateHint).on("opened", this._updateHint).on("closed", this._clearHint).on("opened closed", this._propagateEvent);
951
+ this.inputView = new InputView({
952
+ input: $input,
953
+ hint: $hint
954
+ }).on("focused", this._handleFocus).on("blured", this._closeDropdown).on("blured", this._setInputValueToQuery).on("enterKeyed tabKeyed", this._handleSelection).on("queryChanged", this._clearHint).on("queryChanged", this._clearSuggestions).on("queryChanged", this._getSuggestions).on("whitespaceChanged", this._updateHint).on("queryChanged whitespaceChanged", this._openDropdown).on("queryChanged whitespaceChanged", this._setLanguageDirection).on("escKeyed", this._closeDropdown).on("escKeyed", this._setInputValueToQuery).on("tabKeyed upKeyed downKeyed", this._managePreventDefault).on("upKeyed downKeyed", this._moveDropdownCursor).on("upKeyed downKeyed", this._openDropdown).on("tabKeyed leftKeyed rightKeyed", this._autocomplete);
955
+ }
956
+ utils.mixin(TypeaheadView.prototype, EventTarget, {
957
+ _managePreventDefault: function(e) {
958
+ var $e = e.data, hint, inputValue, preventDefault = false;
959
+ switch (e.type) {
960
+ case "tabKeyed":
961
+ hint = this.inputView.getHintValue();
962
+ inputValue = this.inputView.getInputValue();
963
+ preventDefault = hint && hint !== inputValue;
964
+ break;
965
+
966
+ case "upKeyed":
967
+ case "downKeyed":
968
+ preventDefault = !$e.shiftKey && !$e.ctrlKey && !$e.metaKey;
969
+ break;
970
+ }
971
+ preventDefault && $e.preventDefault();
972
+ },
973
+ _setLanguageDirection: function() {
974
+ var dir = this.inputView.getLanguageDirection();
975
+ if (dir !== this.dir) {
976
+ this.dir = dir;
977
+ this.$node.css("direction", dir);
978
+ this.dropdownView.setLanguageDirection(dir);
979
+ }
980
+ },
981
+ _updateHint: function() {
982
+ var suggestion = this.dropdownView.getFirstSuggestion(), hint = suggestion ? suggestion.value : null, dropdownIsVisible = this.dropdownView.isVisible(), inputHasOverflow = this.inputView.isOverflow(), inputValue, query, escapedQuery, beginsWithQuery, match;
983
+ if (hint && dropdownIsVisible && !inputHasOverflow) {
984
+ inputValue = this.inputView.getInputValue();
985
+ if (!inputValue) return;
986
+ query = inputValue.replace(/\s{2,}/g, " ").replace(/^\s+/g, "");
987
+ escapedQuery = utils.escapeRegExChars(query);
988
+ beginsWithQuery = new RegExp("^(?:" + escapedQuery + ")(.*$)", "i");
989
+ match = beginsWithQuery.exec(hint);
990
+ this.inputView.setHintValue(inputValue + (match ? match[1] : ""));
991
+ }
992
+ },
993
+ _clearHint: function() {
994
+ this.inputView.setHintValue("");
995
+ },
996
+ _clearSuggestions: function() {
997
+ this.dropdownView.clearSuggestions();
998
+ },
999
+ _setInputValueToQuery: function() {
1000
+ this.inputView.setInputValue(this.inputView.getQuery());
1001
+ },
1002
+ _setInputValueToSuggestionUnderCursor: function(e) {
1003
+ var suggestion = e.data;
1004
+ this.inputView.setInputValue(suggestion.value, true);
1005
+ },
1006
+ _handleFocus: function() {
1007
+ if (this.showDefaultSuggestions) {
1008
+ this._getSuggestions();
1009
+ }
1010
+ this._openDropdown();
1011
+ },
1012
+ _openDropdown: function() {
1013
+ this.dropdownView.open();
1014
+ },
1015
+ _closeDropdown: function(e) {
1016
+ this.dropdownView[e.type === "blured" ? "closeUnlessMouseIsOverDropdown" : "close"]();
1017
+ },
1018
+ _moveDropdownCursor: function(e) {
1019
+ var $e = e.data;
1020
+ if (!$e.shiftKey && !$e.ctrlKey && !$e.metaKey) {
1021
+ this.dropdownView[e.type === "upKeyed" ? "moveCursorUp" : "moveCursorDown"]();
1022
+ }
1023
+ },
1024
+ _handleSelection: function(e) {
1025
+ var byClick = e.type === "suggestionSelected", suggestion = byClick ? e.data : this.dropdownView.getSuggestionUnderCursor();
1026
+ if (suggestion) {
1027
+ this.inputView.setInputValue(suggestion.value);
1028
+ byClick ? this.inputView.focus() : e.data.preventDefault();
1029
+ byClick && utils.isMsie() ? utils.defer(this.dropdownView.close) : this.dropdownView.close();
1030
+ this.eventBus.trigger("selected", suggestion.datum, suggestion.dataset);
1031
+ }
1032
+ },
1033
+ _getSuggestions: function() {
1034
+ var that = this, query = this.inputView.getQuery();
1035
+ if (utils.isBlankString(query) && !this.showDefaultSuggestions) {
1036
+ return;
1037
+ }
1038
+ utils.each(this.datasets, function(i, dataset) {
1039
+ dataset.getSuggestions(query, function(suggestions) {
1040
+ if (query === that.inputView.getQuery()) {
1041
+ that.dropdownView.renderSuggestions(dataset, suggestions);
1042
+ }
1043
+ });
1044
+ });
1045
+ },
1046
+ _autocomplete: function(e) {
1047
+ var isCursorAtEnd, ignoreEvent, query, hint, suggestion;
1048
+ if (e.type === "rightKeyed" || e.type === "leftKeyed") {
1049
+ isCursorAtEnd = this.inputView.isCursorAtEnd();
1050
+ ignoreEvent = this.inputView.getLanguageDirection() === "ltr" ? e.type === "leftKeyed" : e.type === "rightKeyed";
1051
+ if (!isCursorAtEnd || ignoreEvent) {
1052
+ return;
1053
+ }
1054
+ }
1055
+ query = this.inputView.getQuery();
1056
+ hint = this.inputView.getHintValue();
1057
+ if (hint !== "" && query !== hint) {
1058
+ suggestion = this.dropdownView.getFirstSuggestion();
1059
+ this.inputView.setInputValue(suggestion.value);
1060
+ this.eventBus.trigger("autocompleted", suggestion.datum, suggestion.dataset);
1061
+ }
1062
+ },
1063
+ _propagateEvent: function(e) {
1064
+ this.eventBus.trigger(e.type);
1065
+ },
1066
+ destroy: function() {
1067
+ this.inputView.destroy();
1068
+ this.dropdownView.destroy();
1069
+ destroyDomStructure(this.$node);
1070
+ this.$node = null;
1071
+ },
1072
+ setQuery: function(query) {
1073
+ this.inputView.setQuery(query);
1074
+ this.inputView.setInputValue(query);
1075
+ this._clearHint();
1076
+ this._clearSuggestions();
1077
+ this._getSuggestions();
1078
+ }
1079
+ });
1080
+ return TypeaheadView;
1081
+ function buildDomStructure(input) {
1082
+ var $wrapper = $(html.wrapper), $dropdown = $(html.dropdown), $input = $(input), $hint = $(html.hint);
1083
+ $wrapper = $wrapper.css(css.wrapper);
1084
+ $dropdown = $dropdown.css(css.dropdown);
1085
+ $hint.css(css.hint).css({
1086
+ backgroundAttachment: $input.css("background-attachment"),
1087
+ backgroundClip: $input.css("background-clip"),
1088
+ backgroundColor: $input.css("background-color"),
1089
+ backgroundImage: $input.css("background-image"),
1090
+ backgroundOrigin: $input.css("background-origin"),
1091
+ backgroundPosition: $input.css("background-position"),
1092
+ backgroundRepeat: $input.css("background-repeat"),
1093
+ backgroundSize: $input.css("background-size")
1094
+ });
1095
+ $input.data("ttAttrs", {
1096
+ dir: $input.attr("dir"),
1097
+ autocomplete: $input.attr("autocomplete"),
1098
+ spellcheck: $input.attr("spellcheck"),
1099
+ style: $input.attr("style")
1100
+ });
1101
+ $input.addClass("tt-query").attr({
1102
+ autocomplete: "off",
1103
+ spellcheck: false
1104
+ }).css(css.query);
1105
+ try {
1106
+ !$input.attr("dir") && $input.attr("dir", "auto");
1107
+ } catch (e) {}
1108
+ return $input.wrap($wrapper).parent().prepend($hint).append($dropdown);
1109
+ }
1110
+ function destroyDomStructure($node) {
1111
+ var $input = $node.find(".tt-query");
1112
+ utils.each($input.data("ttAttrs"), function(key, val) {
1113
+ utils.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val);
1114
+ });
1115
+ $input.detach().removeData("ttAttrs").removeClass("tt-query").insertAfter($node);
1116
+ $node.remove();
1117
+ }
1118
+ }();
1119
+ (function() {
1120
+ var cache = {}, viewKey = "ttView", methods;
1121
+ methods = {
1122
+ initialize: function(datasetDefs) {
1123
+ var datasets;
1124
+ datasetDefs = utils.isArray(datasetDefs) ? datasetDefs : [ datasetDefs ];
1125
+ if (datasetDefs.length === 0) {
1126
+ $.error("no datasets provided");
1127
+ }
1128
+ datasets = utils.map(datasetDefs, function(o) {
1129
+ var dataset = cache[o.name] ? cache[o.name] : new Dataset(o);
1130
+ if (o.name) {
1131
+ cache[o.name] = dataset;
1132
+ }
1133
+ return dataset;
1134
+ });
1135
+ return this.each(initialize);
1136
+ function initialize() {
1137
+ var $input = $(this), deferreds, eventBus = new EventBus({
1138
+ el: $input
1139
+ });
1140
+ deferreds = utils.map(datasets, function(dataset) {
1141
+ return dataset.initialize();
1142
+ });
1143
+ $input.data(viewKey, new TypeaheadView({
1144
+ input: $input,
1145
+ eventBus: eventBus = new EventBus({
1146
+ el: $input
1147
+ }),
1148
+ datasets: datasets
1149
+ }));
1150
+ $.when.apply($, deferreds).always(function() {
1151
+ utils.defer(function() {
1152
+ eventBus.trigger("initialized");
1153
+ });
1154
+ });
1155
+ }
1156
+ },
1157
+ destroy: function() {
1158
+ return this.each(destroy);
1159
+ function destroy() {
1160
+ var $this = $(this), view = $this.data(viewKey);
1161
+ if (view) {
1162
+ view.destroy();
1163
+ $this.removeData(viewKey);
1164
+ }
1165
+ }
1166
+ },
1167
+ setQuery: function(query) {
1168
+ return this.each(setQuery);
1169
+ function setQuery() {
1170
+ var view = $(this).data(viewKey);
1171
+ view && view.setQuery(query);
1172
+ }
1173
+ }
1174
+ };
1175
+ jQuery.fn.typeahead = function(method) {
1176
+ if (methods[method]) {
1177
+ return methods[method].apply(this, [].slice.call(arguments, 1));
1178
+ } else {
1179
+ return methods.initialize.apply(this, arguments);
1180
+ }
1181
+ };
1182
+ })();
1183
+ })(window.jQuery);