web: update typeahead.js to 0.10.4

This commit is contained in:
Simon Michael 2014-07-29 10:50:23 -07:00
parent 3ce34b145c
commit 50ef6d52dd
2 changed files with 274 additions and 232 deletions

View File

@ -1,127 +1,134 @@
/*! /*!
* typeahead.js 0.10.2 * typeahead.js 0.10.4
* https://github.com/twitter/typeahead.js * https://github.com/twitter/typeahead.js
* Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT * Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
*/ */
(function($) { (function($) {
var _ = { var _ = function() {
isMsie: function() { "use strict";
return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false; return {
}, isMsie: function() {
isBlankString: function(str) { return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false;
return !str || /^\s*$/.test(str); },
}, isBlankString: function(str) {
escapeRegExChars: function(str) { return !str || /^\s*$/.test(str);
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); },
}, escapeRegExChars: function(str) {
isString: function(obj) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
return typeof obj === "string"; },
}, isString: function(obj) {
isNumber: function(obj) { return typeof obj === "string";
return typeof obj === "number"; },
}, isNumber: function(obj) {
isArray: $.isArray, return typeof obj === "number";
isFunction: $.isFunction, },
isObject: $.isPlainObject, isArray: $.isArray,
isUndefined: function(obj) { isFunction: $.isFunction,
return typeof obj === "undefined"; isObject: $.isPlainObject,
}, isUndefined: function(obj) {
bind: $.proxy, return typeof obj === "undefined";
each: function(collection, cb) { },
$.each(collection, reverseArgs); toStr: function toStr(s) {
function reverseArgs(index, value) { return _.isUndefined(s) || s === null ? "" : s + "";
return cb(value, index); },
} bind: $.proxy,
}, each: function(collection, cb) {
map: $.map, $.each(collection, reverseArgs);
filter: $.grep, function reverseArgs(index, value) {
every: function(obj, test) { return cb(value, index);
var result = true;
if (!obj) {
return result;
}
$.each(obj, function(key, val) {
if (!(result = test.call(null, val, key, obj))) {
return false;
} }
}); },
return !!result; map: $.map,
}, filter: $.grep,
some: function(obj, test) { every: function(obj, test) {
var result = false; var result = true;
if (!obj) { if (!obj) {
return result; return result;
}
$.each(obj, function(key, val) {
if (result = test.call(null, val, key, obj)) {
return false;
} }
}); $.each(obj, function(key, val) {
return !!result; if (!(result = test.call(null, val, key, obj))) {
}, return false;
mixin: $.extend, }
getUniqueId: function() { });
var counter = 0; return !!result;
return function() { },
return counter++; some: function(obj, test) {
}; var result = false;
}(), if (!obj) {
templatify: function templatify(obj) { return result;
return $.isFunction(obj) ? obj : template; }
function template() { $.each(obj, function(key, val) {
return String(obj); if (result = test.call(null, val, key, obj)) {
} return false;
}, }
defer: function(fn) { });
setTimeout(fn, 0); return !!result;
}, },
debounce: function(func, wait, immediate) { mixin: $.extend,
var timeout, result; getUniqueId: function() {
return function() { var counter = 0;
var context = this, args = arguments, later, callNow; return function() {
later = function() { return counter++;
timeout = null; };
if (!immediate) { }(),
templatify: function templatify(obj) {
return $.isFunction(obj) ? obj : template;
function template() {
return String(obj);
}
},
defer: function(fn) {
setTimeout(fn, 0);
},
debounce: function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments, later, callNow;
later = function() {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args); result = func.apply(context, args);
} }
return result;
}; };
callNow = immediate && !timeout; },
clearTimeout(timeout); throttle: function(func, wait) {
timeout = setTimeout(later, wait); var context, args, timeout, result, previous, later;
if (callNow) { previous = 0;
result = func.apply(context, args); later = function() {
} previous = new Date();
return result;
};
},
throttle: function(func, wait) {
var context, args, timeout, result, previous, later;
previous = 0;
later = function() {
previous = new Date();
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date(), remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null; timeout = null;
previous = now;
result = func.apply(context, args); result = func.apply(context, args);
} else if (!timeout) { };
timeout = setTimeout(later, remaining); return function() {
} var now = new Date(), remaining = wait - (now - previous);
return result; context = this;
}; args = arguments;
}, if (remaining <= 0) {
noop: function() {} clearTimeout(timeout);
}; timeout = null;
var VERSION = "0.10.2"; previous = now;
var tokenizers = function(root) { result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
},
noop: function() {}
};
}();
var VERSION = "0.10.4";
var tokenizers = function() {
"use strict";
return { return {
nonword: nonword, nonword: nonword,
whitespace: whitespace, whitespace: whitespace,
@ -130,26 +137,35 @@
whitespace: getObjTokenizer(whitespace) whitespace: getObjTokenizer(whitespace)
} }
}; };
function whitespace(s) { function whitespace(str) {
return s.split(/\s+/); str = _.toStr(str);
return str ? str.split(/\s+/) : [];
} }
function nonword(s) { function nonword(str) {
return s.split(/\W+/); str = _.toStr(str);
return str ? str.split(/\W+/) : [];
} }
function getObjTokenizer(tokenizer) { function getObjTokenizer(tokenizer) {
return function setKey(key) { return function setKey() {
var args = [].slice.call(arguments, 0);
return function tokenize(o) { return function tokenize(o) {
return tokenizer(o[key]); var tokens = [];
_.each(args, function(k) {
tokens = tokens.concat(tokenizer(_.toStr(o[k])));
});
return tokens;
}; };
}; };
} }
}(); }();
var LruCache = function() { var LruCache = function() {
"use strict";
function LruCache(maxSize) { function LruCache(maxSize) {
this.maxSize = maxSize || 100; this.maxSize = _.isNumber(maxSize) ? maxSize : 100;
this.size = 0; this.reset();
this.hash = {}; if (this.maxSize <= 0) {
this.list = new List(); this.set = this.get = $.noop;
}
} }
_.mixin(LruCache.prototype, { _.mixin(LruCache.prototype, {
set: function set(key, val) { set: function set(key, val) {
@ -174,6 +190,11 @@
this.list.moveToFront(node); this.list.moveToFront(node);
return node.val; return node.val;
} }
},
reset: function reset() {
this.size = 0;
this.hash = {};
this.list = new List();
} }
}); });
function List() { function List() {
@ -205,6 +226,7 @@
return LruCache; return LruCache;
}(); }();
var PersistentStorage = function() { var PersistentStorage = function() {
"use strict";
var ls, methods; var ls, methods;
try { try {
ls = window.localStorage; ls = window.localStorage;
@ -216,7 +238,7 @@
function PersistentStorage(namespace) { function PersistentStorage(namespace) {
this.prefix = [ "__", namespace, "__" ].join(""); this.prefix = [ "__", namespace, "__" ].join("");
this.ttlKey = "__ttl__"; this.ttlKey = "__ttl__";
this.keyMatcher = new RegExp("^" + this.prefix); this.keyMatcher = new RegExp("^" + _.escapeRegExChars(this.prefix));
} }
if (ls && window.JSON) { if (ls && window.JSON) {
methods = { methods = {
@ -284,21 +306,28 @@
} }
}(); }();
var Transport = function() { var Transport = function() {
var pendingRequestsCount = 0, pendingRequests = {}, maxPendingRequests = 6, requestCache = new LruCache(10); "use strict";
var pendingRequestsCount = 0, pendingRequests = {}, maxPendingRequests = 6, sharedCache = new LruCache(10);
function Transport(o) { function Transport(o) {
o = o || {}; o = o || {};
this.cancelled = false;
this.lastUrl = null;
this._send = o.transport ? callbackToDeferred(o.transport) : $.ajax; this._send = o.transport ? callbackToDeferred(o.transport) : $.ajax;
this._get = o.rateLimiter ? o.rateLimiter(this._get) : this._get; this._get = o.rateLimiter ? o.rateLimiter(this._get) : this._get;
this._cache = o.cache === false ? new LruCache(0) : sharedCache;
} }
Transport.setMaxPendingRequests = function setMaxPendingRequests(num) { Transport.setMaxPendingRequests = function setMaxPendingRequests(num) {
maxPendingRequests = num; maxPendingRequests = num;
}; };
Transport.resetCache = function clearCache() { Transport.resetCache = function resetCache() {
requestCache = new LruCache(10); sharedCache.reset();
}; };
_.mixin(Transport.prototype, { _.mixin(Transport.prototype, {
_get: function(url, o, cb) { _get: function(url, o, cb) {
var that = this, jqXhr; var that = this, jqXhr;
if (this.cancelled || url !== this.lastUrl) {
return;
}
if (jqXhr = pendingRequests[url]) { if (jqXhr = pendingRequests[url]) {
jqXhr.done(done).fail(fail); jqXhr.done(done).fail(fail);
} else if (pendingRequestsCount < maxPendingRequests) { } else if (pendingRequestsCount < maxPendingRequests) {
@ -309,7 +338,7 @@
} }
function done(resp) { function done(resp) {
cb && cb(null, resp); cb && cb(null, resp);
requestCache.set(url, resp); that._cache.set(url, resp);
} }
function fail() { function fail() {
cb && cb(true); cb && cb(true);
@ -329,7 +358,9 @@
cb = o; cb = o;
o = {}; o = {};
} }
if (resp = requestCache.get(url)) { this.cancelled = false;
this.lastUrl = url;
if (resp = this._cache.get(url)) {
_.defer(function() { _.defer(function() {
cb && cb(null, resp); cb && cb(null, resp);
}); });
@ -337,6 +368,9 @@
this._get(url, o, cb); this._get(url, o, cb);
} }
return !!resp; return !!resp;
},
cancel: function() {
this.cancelled = true;
} }
}); });
return Transport; return Transport;
@ -359,6 +393,7 @@
} }
}(); }();
var SearchIndex = function() { var SearchIndex = function() {
"use strict";
function SearchIndex(o) { function SearchIndex(o) {
o = o || {}; o = o || {};
if (!o.datumTokenizer || !o.queryTokenizer) { if (!o.datumTokenizer || !o.queryTokenizer) {
@ -370,12 +405,10 @@
} }
_.mixin(SearchIndex.prototype, { _.mixin(SearchIndex.prototype, {
bootstrap: function bootstrap(o) { bootstrap: function bootstrap(o) {
console.log('bootstrap',o);
this.datums = o.datums; this.datums = o.datums;
this.trie = o.trie; this.trie = o.trie;
}, },
add: function(data) { add: function(data) {
console.log('add',data);
var that = this; var that = this;
data = _.isArray(data) ? data : [ data ]; data = _.isArray(data) ? data : [ data ];
_.each(data, function(datum) { _.each(data, function(datum) {
@ -394,32 +427,18 @@
}); });
}, },
get: function get(query) { get: function get(query) {
console.log('trie',this.trie);
var that = this, tokens, matches; var that = this, tokens, matches;
tokens = normalizeTokens(this.queryTokenizer(query)); tokens = normalizeTokens(this.queryTokenizer(query));
// console.log('query',query);
// console.log('tokens',tokens);
_.each(tokens, function(token) { _.each(tokens, function(token) {
var node, chars, ch, ids; var node, chars, ch, ids;
if (matches && matches.length === 0) { if (matches && matches.length === 0) {
return false; return false;
} }
node = that.trie; node = that.trie;
// console.log('token',token);
// console.log('token split',token.split(""));
//whatever variable is used in the following while loop is losing the first character sometimes
chars = token.split(""); chars = token.split("");
// console.log('pre node',node);
// console.log('pre chars',chars);
// console.log('ch1',ch = chars.shift());
// console.log('node1',node = node.children[ch]);
// console.log('ch2',ch = chars.shift());
// console.log('node2',node = node.children[ch]);
while (node && (ch = chars.shift())) { while (node && (ch = chars.shift())) {
node = node.children[ch]; node = node.children[ch];
} }
// console.log('final node',node);
// console.log('final chars',chars);
if (node && chars.length === 0) { if (node && chars.length === 0) {
ids = node.ids.slice(0); ids = node.ids.slice(0);
matches = matches ? getIntersection(matches, ids) : ids; matches = matches ? getIntersection(matches, ids) : ids;
@ -428,7 +447,6 @@
return false; return false;
} }
}); });
// console.log('matches',matches);
return matches ? _.map(unique(matches), function(id) { return matches ? _.map(unique(matches), function(id) {
return that.datums[id]; return that.datums[id];
}) : []; }) : [];
@ -462,7 +480,7 @@
} }
function unique(array) { function unique(array) {
var seen = {}, uniques = []; var seen = {}, uniques = [];
for (var i = 0; i < array.length; i++) { for (var i = 0, len = array.length; i < len; i++) {
if (!seen[array[i]]) { if (!seen[array[i]]) {
seen[array[i]] = true; seen[array[i]] = true;
uniques.push(array[i]); uniques.push(array[i]);
@ -474,7 +492,8 @@
var ai = 0, bi = 0, intersection = []; var ai = 0, bi = 0, intersection = [];
arrayA = arrayA.sort(compare); arrayA = arrayA.sort(compare);
arrayB = arrayB.sort(compare); arrayB = arrayB.sort(compare);
while (ai < arrayA.length && bi < arrayB.length) { var lenArrayA = arrayA.length, lenArrayB = arrayB.length;
while (ai < lenArrayA && bi < lenArrayB) {
if (arrayA[ai] < arrayB[bi]) { if (arrayA[ai] < arrayB[bi]) {
ai++; ai++;
} else if (arrayA[ai] > arrayB[bi]) { } else if (arrayA[ai] > arrayB[bi]) {
@ -492,6 +511,7 @@
} }
}(); }();
var oParser = function() { var oParser = function() {
"use strict";
return { return {
local: getLocal, local: getLocal,
prefetch: getPrefetch, prefetch: getPrefetch,
@ -525,6 +545,7 @@
var remote, defaults; var remote, defaults;
defaults = { defaults = {
url: null, url: null,
cache: true,
wildcard: "%QUERY", wildcard: "%QUERY",
replace: null, replace: null,
rateLimitBy: "debounce", rateLimitBy: "debounce",
@ -559,6 +580,7 @@
} }
}(); }();
(function(root) { (function(root) {
"use strict";
var old, keys; var old, keys;
old = root.Bloodhound; old = root.Bloodhound;
keys = { keys = {
@ -607,6 +629,9 @@
}, },
_getFromRemote: function getFromRemote(query, cb) { _getFromRemote: function getFromRemote(query, cb) {
var that = this, url, uriEncodedQuery; var that = this, url, uriEncodedQuery;
if (!this.transport) {
return;
}
query = query || ""; query = query || "";
uriEncodedQuery = encodeURIComponent(query); uriEncodedQuery = encodeURIComponent(query);
url = this.remote.replace ? this.remote.replace(this.remote.url, query) : this.remote.url.replace(this.remote.wildcard, uriEncodedQuery); url = this.remote.replace ? this.remote.replace(this.remote.url, query) : this.remote.url.replace(this.remote.wildcard, uriEncodedQuery);
@ -615,6 +640,9 @@
err ? cb([]) : cb(that.remote.filter ? that.remote.filter(resp) : resp); err ? cb([]) : cb(that.remote.filter ? that.remote.filter(resp) : resp);
} }
}, },
_cancelLastRemoteRequest: function cancelLastRemoteRequest() {
this.transport && this.transport.cancel();
},
_saveToStorage: function saveToStorage(data, thumbprint, ttl) { _saveToStorage: function saveToStorage(data, thumbprint, ttl) {
if (this.storage) { if (this.storage) {
this.storage.set(keys.data, data, ttl); this.storage.set(keys.data, data, ttl);
@ -652,9 +680,7 @@
var that = this, matches = [], cacheHit = false; var that = this, matches = [], cacheHit = false;
matches = this.index.get(query); matches = this.index.get(query);
matches = this.sorter(matches).slice(0, this.limit); matches = this.sorter(matches).slice(0, this.limit);
if (matches.length < this.limit && this.transport) { matches.length < this.limit ? cacheHit = this._getFromRemote(query, returnRemoteMatches) : this._cancelLastRemoteRequest();
cacheHit = this._getFromRemote(query, returnRemoteMatches);
}
if (!cacheHit) { if (!cacheHit) {
(matches.length > 0 || !this.transport) && cb && cb(matches); (matches.length > 0 || !this.transport) && cb && cb(matches);
} }
@ -698,71 +724,79 @@
return false; return false;
} }
})(this); })(this);
var html = { var html = function() {
wrapper: '<span class="twitter-typeahead"></span>', return {
dropdown: '<span class="tt-dropdown-menu"></span>', wrapper: '<span class="twitter-typeahead"></span>',
dataset: '<div class="tt-dataset-%CLASS%"></div>', dropdown: '<span class="tt-dropdown-menu"></span>',
suggestions: '<span class="tt-suggestions"></span>', dataset: '<div class="tt-dataset-%CLASS%"></div>',
suggestion: '<div class="tt-suggestion"></div>' suggestions: '<span class="tt-suggestions"></span>',
}; suggestion: '<div class="tt-suggestion"></div>'
var css = { };
wrapper: { }();
position: "relative", var css = function() {
display: "inline-block" "use strict";
}, var css = {
hint: { wrapper: {
position: "absolute", position: "relative",
top: "0", display: "inline-block"
left: "0", },
borderColor: "transparent", hint: {
boxShadow: "none" position: "absolute",
}, top: "0",
input: { left: "0",
position: "relative", borderColor: "transparent",
verticalAlign: "top", boxShadow: "none",
backgroundColor: "transparent" opacity: "1"
}, },
inputWithNoHint: { input: {
position: "relative", position: "relative",
verticalAlign: "top" verticalAlign: "top",
}, backgroundColor: "transparent"
dropdown: { },
position: "absolute", inputWithNoHint: {
top: "100%", position: "relative",
left: "0", verticalAlign: "top"
zIndex: "100", },
display: "none" dropdown: {
}, position: "absolute",
suggestions: { top: "100%",
display: "block" left: "0",
}, zIndex: "100",
suggestion: { display: "none"
whiteSpace: "nowrap", },
cursor: "pointer" suggestions: {
}, display: "block"
suggestionChild: { },
whiteSpace: "normal" suggestion: {
}, whiteSpace: "nowrap",
ltr: { cursor: "pointer"
left: "0", },
right: "auto" suggestionChild: {
}, whiteSpace: "normal"
rtl: { },
left: "auto", ltr: {
right: " 0" left: "0",
right: "auto"
},
rtl: {
left: "auto",
right: " 0"
}
};
if (_.isMsie()) {
_.mixin(css.input, {
backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
});
} }
}; if (_.isMsie() && _.isMsie() <= 7) {
if (_.isMsie()) { _.mixin(css.input, {
_.mixin(css.input, { marginTop: "-1px"
backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)" });
}); }
} return css;
if (_.isMsie() && _.isMsie() <= 7) { }();
_.mixin(css.input, {
marginTop: "-1px"
});
}
var EventBus = function() { var EventBus = function() {
"use strict";
var namespace = "typeahead:"; var namespace = "typeahead:";
function EventBus(o) { function EventBus(o) {
if (!o || !o.el) { if (!o || !o.el) {
@ -779,6 +813,7 @@
return EventBus; return EventBus;
}(); }();
var EventEmitter = function() { var EventEmitter = function() {
"use strict";
var splitter = /\s+/, nextTick = getNextTick(); var splitter = /\s+/, nextTick = getNextTick();
return { return {
onSync: onSync, onSync: onSync,
@ -838,7 +873,7 @@
return flush; return flush;
function flush() { function flush() {
var cancelled; var cancelled;
for (var i = 0; !cancelled && i < callbacks.length; i += 1) { for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) {
cancelled = callbacks[i].apply(context, args) === false; cancelled = callbacks[i].apply(context, args) === false;
} }
return !cancelled; return !cancelled;
@ -868,6 +903,7 @@
} }
}(); }();
var highlight = function(doc) { var highlight = function(doc) {
"use strict";
var defaults = { var defaults = {
node: null, node: null,
pattern: null, pattern: null,
@ -886,7 +922,7 @@
regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly); regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly);
traverse(o.node, hightlightTextNode); traverse(o.node, hightlightTextNode);
function hightlightTextNode(textNode) { function hightlightTextNode(textNode) {
var match, patternNode; var match, patternNode, wrapperNode;
if (match = regex.exec(textNode.data)) { if (match = regex.exec(textNode.data)) {
wrapperNode = doc.createElement(o.tagName); wrapperNode = doc.createElement(o.tagName);
o.className && (wrapperNode.className = o.className); o.className && (wrapperNode.className = o.className);
@ -911,7 +947,7 @@
}; };
function getRegex(patterns, caseSensitive, wordsOnly) { function getRegex(patterns, caseSensitive, wordsOnly) {
var escapedPatterns = [], regexStr; var escapedPatterns = [], regexStr;
for (var i = 0; i < patterns.length; i++) { for (var i = 0, len = patterns.length; i < len; i++) {
escapedPatterns.push(_.escapeRegExChars(patterns[i])); escapedPatterns.push(_.escapeRegExChars(patterns[i]));
} }
regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")"; regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")";
@ -919,6 +955,7 @@
} }
}(window.document); }(window.document);
var Input = function() { var Input = function() {
"use strict";
var specialKeyCodeMap; var specialKeyCodeMap;
specialKeyCodeMap = { specialKeyCodeMap = {
9: "tab", 9: "tab",
@ -1014,8 +1051,9 @@
inputValue = this.getInputValue(); inputValue = this.getInputValue();
areEquivalent = areQueriesEquivalent(inputValue, this.query); areEquivalent = areQueriesEquivalent(inputValue, this.query);
hasDifferentWhitespace = areEquivalent ? this.query.length !== inputValue.length : false; hasDifferentWhitespace = areEquivalent ? this.query.length !== inputValue.length : false;
this.query = inputValue;
if (!areEquivalent) { if (!areEquivalent) {
this.trigger("queryChanged", this.query = inputValue); this.trigger("queryChanged", this.query);
} else if (hasDifferentWhitespace) { } else if (hasDifferentWhitespace) {
this.trigger("whitespaceChanged", this.query); this.trigger("whitespaceChanged", this.query);
} }
@ -1112,6 +1150,7 @@
} }
}(); }();
var Dataset = function() { var Dataset = function() {
"use strict";
var datasetKey = "ttDataset", valueKey = "ttValue", datumKey = "ttDatum"; var datasetKey = "ttDataset", valueKey = "ttValue", datumKey = "ttDatum";
function Dataset(o) { function Dataset(o) {
o = o || {}; o = o || {};
@ -1165,19 +1204,13 @@
nodes = _.map(suggestions, getSuggestionNode); nodes = _.map(suggestions, getSuggestionNode);
$suggestions.append.apply($suggestions, nodes); $suggestions.append.apply($suggestions, nodes);
that.highlight && highlight({ that.highlight && highlight({
className: "tt-highlight",
node: $suggestions[0], node: $suggestions[0],
pattern: query pattern: query
}); });
return $suggestions; return $suggestions;
function getSuggestionNode(suggestion) { function getSuggestionNode(suggestion) {
var $el; var $el;
// console.log(that.templates.suggestion(suggestion));
// console.log(datasetKey);
// console.log(that.name);
// console.log(valueKey);
// console.log(that.displayFn(suggestion));
// console.log(datumKey);
// console.log(suggestion);
$el = $(html.suggestion).append(that.templates.suggestion(suggestion)).data(datasetKey, that.name).data(valueKey, that.displayFn(suggestion)).data(datumKey, suggestion); $el = $(html.suggestion).append(that.templates.suggestion(suggestion)).data(datasetKey, that.name).data(valueKey, that.displayFn(suggestion)).data(datumKey, suggestion);
$el.children().each(function() { $el.children().each(function() {
$(this).css(css.suggestionChild); $(this).css(css.suggestionChild);
@ -1251,6 +1284,7 @@
} }
}(); }();
var Dropdown = function() { var Dropdown = function() {
"use strict";
function Dropdown(o) { function Dropdown(o) {
var that = this, onSuggestionClick, onSuggestionMouseEnter, onSuggestionMouseLeave; var that = this, onSuggestionClick, onSuggestionMouseEnter, onSuggestionMouseLeave;
o = o || {}; o = o || {};
@ -1410,6 +1444,7 @@
} }
}(); }();
var Typeahead = function() { var Typeahead = function() {
"use strict";
var attrsKey = "ttAttrs"; var attrsKey = "ttAttrs";
function Typeahead(o) { function Typeahead(o) {
var $menu, $input, $hint; var $menu, $input, $hint;
@ -1420,7 +1455,7 @@
this.isActivated = false; this.isActivated = false;
this.autoselect = !!o.autoselect; this.autoselect = !!o.autoselect;
this.minLength = _.isNumber(o.minLength) ? o.minLength : 1; this.minLength = _.isNumber(o.minLength) ? o.minLength : 1;
this.$node = buildDomStructure(o.input, o.withHint); this.$node = buildDom(o.input, o.withHint);
$menu = this.$node.find(".tt-dropdown-menu"); $menu = this.$node.find(".tt-dropdown-menu");
$input = this.$node.find(".tt-input"); $input = this.$node.find(".tt-input");
$hint = this.$node.find(".tt-hint"); $hint = this.$node.find(".tt-hint");
@ -1588,6 +1623,7 @@
this.dropdown.close(); this.dropdown.close();
}, },
setVal: function setVal(val) { setVal: function setVal(val) {
val = _.toStr(val);
if (this.isActivated) { if (this.isActivated) {
this.input.setInputValue(val); this.input.setInputValue(val);
} else { } else {
@ -1607,15 +1643,16 @@
} }
}); });
return Typeahead; return Typeahead;
function buildDomStructure(input, withHint) { function buildDom(input, withHint) {
var $input, $wrapper, $dropdown, $hint; var $input, $wrapper, $dropdown, $hint;
$input = $(input); $input = $(input);
$wrapper = $(html.wrapper).css(css.wrapper); $wrapper = $(html.wrapper).css(css.wrapper);
$dropdown = $(html.dropdown).css(css.dropdown); $dropdown = $(html.dropdown).css(css.dropdown);
$hint = $input.clone().css(css.hint).css(getBackgroundStyles($input)); $hint = $input.clone().css(css.hint).css(getBackgroundStyles($input));
$hint.val("").removeData().addClass("tt-hint").removeAttr("id name placeholder").prop("disabled", true).attr({ $hint.val("").removeData().addClass("tt-hint").removeAttr("id name placeholder required").prop("readonly", true).attr({
autocomplete: "off", autocomplete: "off",
spellcheck: "false" spellcheck: "false",
tabindex: -1
}); });
$input.data(attrsKey, { $input.data(attrsKey, {
dir: $input.attr("dir"), dir: $input.attr("dir"),
@ -1654,6 +1691,7 @@
} }
}(); }();
(function() { (function() {
"use strict";
var old, typeaheadKey, methods; var old, typeaheadKey, methods;
old = $.fn.typeahead; old = $.fn.typeahead;
typeaheadKey = "ttTypeahead"; typeaheadKey = "ttTypeahead";
@ -1726,8 +1764,12 @@
} }
}; };
$.fn.typeahead = function(method) { $.fn.typeahead = function(method) {
if (methods[method]) { var tts;
return methods[method].apply(this, [].slice.call(arguments, 1)); if (methods[method] && method !== "initialize") {
tts = this.filter(function() {
return !!$(this).data(typeaheadKey);
});
return methods[method].apply(tts, [].slice.call(arguments, 1));
} else { } else {
return methods.initialize.apply(this, arguments); return methods.initialize.apply(this, arguments);
} }
@ -1737,4 +1779,4 @@
return this; return this;
}; };
})(); })();
})(window.jQuery); })(window.jQuery);

File diff suppressed because one or more lines are too long