diff --git a/Gruntfile.js b/Gruntfile.js index e90abec60f..938927078b 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -2,42 +2,41 @@ var semver = require('semver'), f = require('util').format, files = { common: [ - 'src/common/utils.js' + 'src/common/utils.js' ], bloodhound: [ - 'src/bloodhound/version.js', - 'src/bloodhound/tokenizers.js', - 'src/bloodhound/lru_cache.js', - 'src/bloodhound/persistent_storage.js', - 'src/bloodhound/transport.js', - 'src/bloodhound/search_index.js', - 'src/bloodhound/prefetch.js', - 'src/bloodhound/remote.js', - 'src/bloodhound/options_parser.js', - 'src/bloodhound/bloodhound.js' + 'src/bloodhound/version.js', + 'src/bloodhound/deferred.js', + 'src/bloodhound/tokenizers.js', + 'src/bloodhound/lru_cache.js', + 'src/bloodhound/persistent_storage.js', + 'src/bloodhound/transport.js', + 'src/bloodhound/search_index.js', + 'src/bloodhound/prefetch.js', + 'src/bloodhound/remote.js', + 'src/bloodhound/options_parser.js', + 'src/bloodhound/bloodhound.js' ], typeahead: [ - 'src/typeahead/www.js', - 'src/typeahead/event_bus.js', - 'src/typeahead/event_emitter.js', - 'src/typeahead/highlight.js', - 'src/typeahead/input.js', - 'src/typeahead/dataset.js', - 'src/typeahead/menu.js', - 'src/typeahead/status.js', - 'src/typeahead/default_menu.js', - 'src/typeahead/typeahead.js', - 'src/typeahead/plugin.js' + 'src/typeahead/www.js', + 'src/typeahead/event_bus.js', + 'src/typeahead/event_emitter.js', + 'src/typeahead/highlight.js', + 'src/typeahead/input.js', + 'src/typeahead/dataset.js', + 'src/typeahead/menu.js', + 'src/typeahead/status.js', + 'src/typeahead/default_menu.js', + 'src/typeahead/typeahead.js', + 'src/typeahead/plugin.js' ] }; module.exports = function(grunt) { grunt.initConfig({ version: grunt.file.readJSON('package.json').version, - tempDir: 'dist_temp', buildDir: 'dist', - banner: [ '/*!', ' * typeahead.js <%= version %>', @@ -45,12 +44,10 @@ module.exports = function(grunt) { ' * Copyright 2013-<%= grunt.template.today("yyyy") %> Twitter, Inc. and other contributors; Licensed MIT', ' */\n\n' ].join('\n'), - uglify: { options: { banner: '<%= banner %>' }, - concatBloodhound: { options: { mangle: false, @@ -71,7 +68,6 @@ module.exports = function(grunt) { src: files.common.concat(files.typeahead), dest: '<%= tempDir %>/typeahead.jquery.js' }, - bloodhound: { options: { mangle: false, @@ -131,16 +127,15 @@ module.exports = function(grunt) { dest: '<%= buildDir %>/typeahead.bundle.min.js' } }, - umd: { bloodhound: { src: '<%= tempDir %>/bloodhound.js', objectToExport: 'Bloodhound', deps: { - default: ['$'], - amd: ['jquery'], - cjs: ['jquery'], - global: ['jQuery'] + default: [], + amd: [], + cjs: [], + global: [] } }, typeahead: { @@ -153,7 +148,6 @@ module.exports = function(grunt) { } } }, - replace: { version: { options: { @@ -175,7 +169,6 @@ module.exports = function(grunt) { ] } }, - jshint: { options: { jshintrc: '.jshintrc' @@ -184,14 +177,12 @@ module.exports = function(grunt) { test: ['test/**/*_spec.js', 'test/integration/test.js'], gruntfile: ['Gruntfile.js'] }, - watch: { js: { files: 'src/**/*', tasks: 'build' } }, - exec: { npm_publish: 'npm publish', git_is_clean: 'test -z "$(git status --porcelain)"', @@ -220,22 +211,18 @@ module.exports = function(grunt) { 'rm -rf typeahead.js' ].join(' && ') }, - clean: { dist: 'dist' }, - connect: { server: { options: { port: 8888, keepalive: true } } }, - concurrent: { options: { logConcurrentOutput: true }, dev: ['server', 'watch'] }, - step: { options: { option: false @@ -245,7 +232,6 @@ module.exports = function(grunt) { grunt.registerTask('release', '#shipit', function(version) { var curVersion = grunt.config.get('version'); - version = semver.inc(curVersion, version) || version; if (!semver.valid(version) || semver.lte(version, curVersion)) { diff --git a/dist/bloodhound.js b/dist/bloodhound.js index 3cb1c4e5fa..5672c2748b 100644 --- a/dist/bloodhound.js +++ b/dist/bloodhound.js @@ -1,20 +1,21 @@ /*! - * typeahead.js 1.2.0 + * typeahead.js 1.2.1 * https://github.com/twitter/typeahead.js * Copyright 2013-2017 Twitter, Inc. and other contributors; Licensed MIT */ + (function(root, factory) { if (typeof define === "function" && define.amd) { - define([ "jquery" ], function(a0) { - return root["Bloodhound"] = factory(a0); + define([], function() { + return root["Bloodhound"] = factory(); }); - } else if (typeof exports === "object") { - module.exports = factory(require("jquery")); + } else if (typeof module === "object" && module.exports) { + module.exports = factory(); } else { - root["Bloodhound"] = factory(root["jQuery"]); + root["Bloodhound"] = factory(); } -})(this, function($) { +})(this, function() { var _ = function() { "use strict"; return { @@ -33,9 +34,24 @@ isNumber: function(obj) { return typeof obj === "number"; }, - isArray: $.isArray, - isFunction: $.isFunction, - isObject: $.isPlainObject, + isArray: function(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }, + isFunction: function(obj) { + return typeof obj === "function"; + }, + isObject: function(obj) { + var proto, Ctor, hasOwn = {}.hasOwnProperty; + if (!obj || {}.toString.call(obj) !== "[object Object]") { + return false; + } + proto = Object.getPrototypeOf(obj); + if (!proto) { + return true; + } + Ctor = hasOwn.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && hasOwn.toString.call(Ctor) === hasOwn.toString.call(Object); + }, isUndefined: function(obj) { return typeof obj === "undefined"; }, @@ -48,21 +64,81 @@ toStr: function toStr(s) { return _.isUndefined(s) || s === null ? "" : s + ""; }, - bind: $.proxy, + bind: function(fn, context) { + var tmp, args, proxy; + if (typeof context === "string") { + tmp = fn[context]; + context = fn; + fn = tmp; + } + if (!_.isFunction(fn)) { + return undefined; + } + args = [].slice.call(arguments, 2); + proxy = function() { + return fn.apply(context || _, args.concat([].slice.call(arguments))); + }; + proxy.guid = fn.guid = fn.guid || _.guid(); + return proxy; + }, each: function(collection, cb) { - $.each(collection, reverseArgs); - function reverseArgs(index, value) { + (function(obj, callback) { + var length, i = 0; + if (_.isArray(obj)) { + length = obj.length; + for (;i < length; i++) { + if (callback.call(obj[i], i, obj[i]) === false) { + break; + } + } + } else { + for (i in obj) { + if (callback.call(obj[i], i, obj[i]) === false) { + break; + } + } + } + return obj; + })(collection, function(index, value) { return cb(value, index); + }); + }, + map: function(elems, callback, arg) { + var length, value, i = 0, ret = []; + if (_.isArray(elems)) { + length = elems.length; + for (;i < length; i++) { + value = callback(elems[i], i, arg); + if (value != null) { + ret.push(value); + } + } + } else { + for (i in elems) { + value = callback(elems[i], i, arg); + if (value != null) { + ret.push(value); + } + } + } + return [].concat.apply([], ret); + }, + filter: function(elems, callback, invert) { + var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; + for (;i < length; i++) { + callbackInverse = !callback(elems[i], i); + if (callbackInverse !== callbackExpect) { + matches.push(elems[i]); + } } + return matches; }, - map: $.map, - filter: $.grep, every: function(obj, test) { var result = true; if (!obj) { return result; } - $.each(obj, function(key, val) { + _.each(obj, function(val, key) { if (!(result = test.call(null, val, key, obj))) { return false; } @@ -74,19 +150,56 @@ if (!obj) { return result; } - $.each(obj, function(key, val) { + _.each(obj, function(val, key) { if (result = test.call(null, val, key, obj)) { return false; } }); return !!result; }, - mixin: $.extend, + mixin: function() { + var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; + if (typeof target === "boolean") { + deep = target; + target = arguments[i] || {}; + i++; + } + if (typeof target !== "object" && !_.isFunction(target)) { + target = {}; + } + if (i === length) { + target = _; + i--; + } + for (;i < length; i++) { + if ((options = arguments[i]) != null) { + for (name in options) { + src = target[name]; + copy = options[name]; + if (target === copy) { + continue; + } + if (deep && copy && (_.isObject(copy) || (copyIsArray = _.isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && _.isArray(src) ? src : []; + } else { + clone = src && _.isObject(src) ? src : {}; + } + target[name] = _.mixin(deep, clone, copy); + } else if (copy !== undefined) { + target[name] = copy; + } + } + } + } + return target; + }, identity: function(x) { return x; }, clone: function(obj) { - return $.extend(true, {}, obj); + return _.mixin(true, {}, obj); }, getIdGenerator: function() { var counter = 0; @@ -95,7 +208,7 @@ }; }, templatify: function templatify(obj) { - return $.isFunction(obj) ? obj : template; + return _.isFunction(obj) ? obj : template; function template() { return String(obj); } @@ -148,6 +261,81 @@ stringify: function(val) { return _.isString(val) ? val : JSON.stringify(val); }, + ajax: function(opts, onSuccess, onFailure) { + var url; + if (_.isObject(opts)) { + url = opts.url; + } else { + url = opts; + opts = {}; + } + var deferred = Deferred(); + (function(onSuccess, onFailure) { + var req = new XMLHttpRequest(); + req.open(opts.type || "GET", url); + req.responseType = opts.responseType || opts.dataType || "json"; + opts.headers && function(req, headers) { + for (var key in headers) { + req.setRequestHeader(key, headers[key]); + } + }(req, opts.headers); + opts.listeners && function(req, listeners) { + for (var key in listeners) { + req.addEventListener(key, listeners[key], false); + } + }(req, opts.listeners); + req.onload = function() { + if (req.status == 200) { + onSuccess(req.response); + } else { + onFailure(req.statusText); + } + }; + req.onerror = function() { + onFailure("Network Error"); + }; + req.send(); + return req; + })(function(resp) { + _.defer(function() { + onSuccess(resp); + deferred.resolve(resp); + }); + }, function(err) { + _.defer(function() { + onFailure(err); + deferred.reject(err); + }); + }); + return deferred; + }, + param: function(a) { + var prefix, s = [], buildParams = function(prefix, obj, add) { + var name; + if (_.isArray(obj)) { + _.each(obj, function(v, i) { + if (/\[\]$/.test(prefix)) { + add(prefix, v); + } else { + buildParams(prefix + "[" + (typeof v === "object" && v != null ? i : "") + "]", v, add); + } + }); + } else if (_.type(obj) === "object") { + for (name in obj) { + buildParams(prefix + "[" + name + "]", obj[name], add); + } + } else { + add(prefix, obj); + } + }, add = function(key, valueOrFunction) { + var value = _.isFunction(valueOrFunction) ? valueOrFunction() : valueOrFunction; + s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value == null ? "" : value); + }; + for (prefix in a) { + buildParams(prefix, a[prefix], add); + } + return s.join("&"); + }, guid: function() { function _p8(s) { var p = (Math.random().toString(16) + "000000000").substr(2, 8); @@ -158,7 +346,200 @@ noop: function() {} }; }(); - var VERSION = "1.2.0"; + var VERSION = "1.2.1"; + var Deferred = function() { + var Deferred, PENDING, REJECTED, RESOLVED, VERSION, _when, after, execute, flatten, has, isArguments, isPromise, d, slice = [].slice; + VERSION = "3.1.0"; + PENDING = "pending"; + RESOLVED = "resolved"; + REJECTED = "rejected"; + has = function(obj, prop) { + return obj != null ? obj.hasOwnProperty(prop) : void 0; + }; + isArguments = function(obj) { + return has(obj, "length") && has(obj, "callee"); + }; + isPromise = function(obj) { + return has(obj, "promise") && typeof (obj != null ? obj.promise : void 0) === "function"; + }; + flatten = function(array) { + if (isArguments(array)) { + return flatten(Array.prototype.slice.call(array)); + } + if (!_.isArray(array)) { + return [ array ]; + } + return array.reduce(function(memo, value) { + if (_.isArray(value)) { + return memo.concat(flatten(value)); + } + memo.push(value); + return memo; + }, []); + }; + after = function(times, func) { + if (times <= 0) { + return func(); + } + return function() { + if (--times < 1) { + return func.apply(this, arguments); + } + }; + }; + execute = function(callbacks, args, context) { + var callback, i, len, ref, results; + ref = flatten(callbacks); + results = []; + for (i = 0, len = ref.length; i < len; i++) { + callback = ref[i]; + results.push(callback.call.apply(callback, [ context ].concat(slice.call(args)))); + } + return results; + }; + Deferred = function() { + var candidate, close, closingArguments, doneCallbacks, failCallbacks, progressCallbacks, state; + state = PENDING; + doneCallbacks = []; + failCallbacks = []; + progressCallbacks = []; + closingArguments = { + resolved: {}, + rejected: {}, + pending: {} + }; + this.promise = function(candidate) { + var pipe, storeCallbacks; + candidate = candidate || {}; + candidate.state = function() { + return state; + }; + storeCallbacks = function(shouldExecuteImmediately, holder, holderState) { + return function() { + if (state === PENDING) { + holder.push.apply(holder, flatten(arguments)); + } + if (shouldExecuteImmediately()) { + execute(arguments, closingArguments[holderState]); + } + return candidate; + }; + }; + candidate.done = storeCallbacks(function() { + return state === RESOLVED; + }, doneCallbacks, RESOLVED); + candidate.fail = storeCallbacks(function() { + return state === REJECTED; + }, failCallbacks, REJECTED); + candidate.progress = storeCallbacks(function() { + return state !== PENDING; + }, progressCallbacks, PENDING); + candidate.always = function() { + var ref; + return (ref = candidate.done.apply(candidate, arguments)).fail.apply(ref, arguments); + }; + pipe = function(doneFilter, failFilter, progressFilter) { + var filter, master; + master = new Deferred(); + filter = function(source, funnel, callback) { + if (!callback) { + return candidate[source](master[funnel]); + } + return candidate[source](function() { + var args, value; + args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + value = callback.apply(null, args); + if (isPromise(value)) { + return value.done(master.resolve).fail(master.reject).progress(master.notify); + } else { + return master[funnel](value); + } + }); + }; + filter("done", "resolve", doneFilter); + filter("fail", "reject", failFilter); + filter("progress", "notify", progressFilter); + return master; + }; + candidate.pipe = pipe; + candidate.then = pipe; + if (candidate.promise == null) { + candidate.promise = function() { + return candidate; + }; + } + return candidate; + }; + this.promise(this); + candidate = this; + close = function(finalState, callbacks, context) { + return function() { + if (state === PENDING) { + state = finalState; + closingArguments[finalState] = arguments; + execute(callbacks, closingArguments[finalState], context); + return candidate; + } + return this; + }; + }; + this.resolve = close(RESOLVED, doneCallbacks); + this.reject = close(REJECTED, failCallbacks); + this.notify = close(PENDING, progressCallbacks); + this.resolveWith = function(context, args) { + return close(RESOLVED, doneCallbacks, context).apply(null, args); + }; + this.rejectWith = function(context, args) { + return close(REJECTED, failCallbacks, context).apply(null, args); + }; + this.notifyWith = function(context, args) { + return close(PENDING, progressCallbacks, context).apply(null, args); + }; + return this; + }; + _when = function() { + var def, defs, finish, i, len, resolutionArgs, trigger; + defs = slice.apply(arguments); + if (defs.length === 1) { + if (isPromise(defs[0])) { + return defs[0]; + } else { + return new Deferred().resolve(defs[0]).promise(); + } + } + trigger = new Deferred(); + if (!defs.length) { + return trigger.resolve().promise(); + } + resolutionArgs = []; + finish = after(defs.length, function() { + return trigger.resolve.apply(trigger, resolutionArgs); + }); + defs.forEach(function(def, index) { + if (isPromise(def)) { + return def.done(function() { + var args; + args = 1 <= arguments.length ? slice.call(arguments, 0) : []; + resolutionArgs[index] = args.length > 1 ? args : args[0]; + return finish(); + }); + } else { + resolutionArgs[index] = def; + return finish(); + } + }); + for (i = 0, len = defs.length; i < len; i++) { + def = defs[i]; + isPromise(def) && def.fail(trigger.reject); + } + return trigger.promise(); + }; + var d = function() { + return new Deferred(); + }; + d.when = _when; + return d; + }(); var tokenizers = function() { "use strict"; return { @@ -211,7 +592,7 @@ this.maxSize = _.isNumber(maxSize) ? maxSize : 100; this.reset(); if (this.maxSize <= 0) { - this.set = this.get = $.noop; + this.set = this.get = _.noop; } } _.mixin(LruCache.prototype, { @@ -349,7 +730,7 @@ return JSON.stringify(_.isUndefined(val) ? null : val); } function decode(val) { - return $.parseJSON(val); + return JSON.parse(val); } function gatherMatchingKeys(keyMatcher) { var i, key, keys = [], len = LOCAL_STORAGE.length; @@ -382,7 +763,7 @@ _.mixin(Transport.prototype, { _fingerprint: function fingerprint(o) { o = o || {}; - return o.url + o.type + $.param(o.data || {}); + return o.url + o.type + _.param(o.data || {}); }, _get: function(o, cb) { var that = this, fingerprint, jqXhr; @@ -416,7 +797,7 @@ }, get: function(o, cb) { var resp, fingerprint; - cb = cb || $.noop; + cb = cb || _.noop; o = _.isString(o) ? { url: o } : o || {}; @@ -441,7 +822,7 @@ function SearchIndex(o) { o = o || {}; if (!o.datumTokenizer || !o.queryTokenizer) { - $.error("datumTokenizer and queryTokenizer are both required"); + throw new Error("datumTokenizer and queryTokenizer are both required"); } this.identify = o.identify || _.stringify; this.datumTokenizer = o.datumTokenizer; @@ -692,8 +1073,12 @@ remote: null }; o = _.mixin(defaults, o || {}); - !o.datumTokenizer && $.error("datumTokenizer is required"); - !o.queryTokenizer && $.error("queryTokenizer is required"); + if (!o.datumTokenizer) { + throw new Error("datumTokenizer is required"); + } + if (!o.queryTokenizer) { + throw new Error("queryTokenizer is required"); + } sorter = o.sorter; o.sorter = sorter ? function(x) { return x.sort(sorter); @@ -722,11 +1107,13 @@ url: o } : o; o = _.mixin(defaults, o); - !o.url && $.error("prefetch requires url to be set"); + if (!o.url) { + throw new Error("prefetch requires url to be set"); + } o.transform = o.filter || o.transform; o.cacheKey = o.cacheKey || o.url; o.thumbprint = VERSION + o.thumbprint; - o.transport = o.transport ? callbackToDeferred(o.transport) : $.ajax; + o.transport = o.transport ? callbackToDeferred(o.transport) : _.ajax; return o; } function parseRemote(o) { @@ -750,11 +1137,13 @@ url: o } : o; o = _.mixin(defaults, o); - !o.url && $.error("remote requires url to be set"); + if (!o.url) { + throw new Error("remote requires url to be set"); + } o.transform = o.filter || o.transform; o.prepare = toRemotePrepare(o); o.limiter = toLimiter(o); - o.transport = o.transport ? callbackToDeferred(o.transport) : $.ajax; + o.transport = o.transport ? callbackToDeferred(o.transport) : _.ajax; delete o.replace; delete o.wildcard; delete o.rateLimitBy; @@ -811,7 +1200,7 @@ } function callbackToDeferred(fn) { return function wrapper(o) { - var deferred = $.Deferred(); + var deferred = Deferred(); fn(o, onSuccess, onError); return deferred; function onSuccess(resp) { @@ -865,7 +1254,7 @@ }, _loadPrefetch: function loadPrefetch() { var that = this, deferred, serialized; - deferred = $.Deferred(); + deferred = Deferred(); if (!this.prefetch) { deferred.resolve(); } else if (serialized = this.prefetch.fromCache()) { diff --git a/dist/bloodhound.min.js b/dist/bloodhound.min.js index d83a6e53c8..044d53db66 100644 --- a/dist/bloodhound.min.js +++ b/dist/bloodhound.min.js @@ -1,7 +1,8 @@ /*! - * typeahead.js 1.2.0 + * typeahead.js 1.2.1 * https://github.com/twitter/typeahead.js * Copyright 2013-2017 Twitter, Inc. and other contributors; Licensed MIT */ -!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(c){return a.Bloodhound=b(c)}):"object"==typeof exports?module.exports=b(require("jquery")):a.Bloodhound=b(a.jQuery)}(this,function(a){var b=function(){"use strict";return{isMsie:function(){return!!/(msie|trident)/i.test(navigator.userAgent)&&navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2]},isBlankString:function(a){return!a||/^\s*$/.test(a)},escapeRegExChars:function(a){return a.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isString:function(a){return"string"==typeof a},isNumber:function(a){return"number"==typeof a},isArray:a.isArray,isFunction:a.isFunction,isObject:a.isPlainObject,isUndefined:function(a){return"undefined"==typeof a},isElement:function(a){return!(!a||1!==a.nodeType)},isJQuery:function(b){return b instanceof a},toStr:function(a){return b.isUndefined(a)||null===a?"":a+""},bind:a.proxy,each:function(b,c){function d(a,b){return c(b,a)}a.each(b,d)},map:a.map,filter:a.grep,every:function(b,c){var d=!0;return b?(a.each(b,function(a,e){if(!(d=c.call(null,e,a,b)))return!1}),!!d):d},some:function(b,c){var d=!1;return b?(a.each(b,function(a,e){if(d=c.call(null,e,a,b))return!1}),!!d):d},mixin:a.extend,identity:function(a){return a},clone:function(b){return a.extend(!0,{},b)},getIdGenerator:function(){var a=0;return function(){return a++}},templatify:function(b){function c(){return String(b)}return a.isFunction(b)?b:c},defer:function(a){setTimeout(a,0)},debounce:function(a,b,c){var d,e;return function(){var f,g,h=this,i=arguments;return f=function(){d=null,c||(e=a.apply(h,i))},g=c&&!d,clearTimeout(d),d=setTimeout(f,b),g&&(e=a.apply(h,i)),e}},throttle:function(a,b){var c,d,e,f,g,h;return g=0,h=function(){g=new Date,e=null,f=a.apply(c,d)},function(){var i=new Date,j=b-(i-g);return c=this,d=arguments,j<=0?(clearTimeout(e),e=null,g=i,f=a.apply(c,d)):e||(e=setTimeout(h,j)),f}},stringify:function(a){return b.isString(a)?a:JSON.stringify(a)},guid:function(){function a(a){var b=(Math.random().toString(16)+"000000000").substr(2,8);return a?"-"+b.substr(0,4)+"-"+b.substr(4,4):b}return"tt-"+a()+a(!0)+a(!0)+a()},noop:function(){}}}(),c="1.2.0",d=function(){"use strict";function a(a){return a=b.toStr(a),a?a.split(/\s+/):[]}function c(a){return a=b.toStr(a),a?a.split(/\W+/):[]}function d(a){a=b.toStr(a);var c=[],d="";return b.each(a.split(""),function(a){a.match(/\s+/)?d="":(c.push(d+a),d+=a)}),c}function e(a){return function(c){return c=b.isArray(c)?c:[].slice.call(arguments,0),function(d){var e=[];return b.each(c,function(c){e=e.concat(a(b.toStr(d[c])))}),e}}}return{nonword:c,whitespace:a,ngram:d,obj:{nonword:e(c),whitespace:e(a),ngram:e(d)}}}(),e=function(){"use strict";function c(c){this.maxSize=b.isNumber(c)?c:100,this.reset(),this.maxSize<=0&&(this.set=this.get=a.noop)}function d(){this.head=this.tail=null}function e(a,b){this.key=a,this.val=b,this.prev=this.next=null}return b.mixin(c.prototype,{set:function(a,b){var c,d=this.list.tail;this.size>=this.maxSize&&(this.list.remove(d),delete this.hash[d.key],this.size--),(c=this.hash[a])?(c.val=b,this.list.moveToFront(c)):(c=new e(a,b),this.list.add(c),this.hash[a]=c,this.size++)},get:function(a){var b=this.hash[a];if(b)return this.list.moveToFront(b),b.val},reset:function(){this.size=0,this.hash={},this.list=new d}}),b.mixin(d.prototype,{add:function(a){this.head&&(a.next=this.head,this.head.prev=a),this.head=a,this.tail=this.tail||a},remove:function(a){a.prev?a.prev.next=a.next:this.head=a.next,a.next?a.next.prev=a.prev:this.tail=a.prev},moveToFront:function(a){this.remove(a),this.add(a)}}),c}(),f=function(){"use strict";function c(a,c){this.prefix=["__",a,"__"].join(""),this.ttlKey="__ttl__",this.keyMatcher=new RegExp("^"+b.escapeRegExChars(this.prefix)),this.ls=c||h,!this.ls&&this._noop()}function d(){return(new Date).getTime()}function e(a){return JSON.stringify(b.isUndefined(a)?null:a)}function f(b){return a.parseJSON(b)}function g(a){var b,c,d=[],e=h.length;for(b=0;bc)}}),c}(),g=function(){"use strict";function c(a){a=a||{},this.maxPendingRequests=a.maxPendingRequests||6,this.cancelled=!1,this.lastReq=null,this._send=a.transport,this._get=a.limiter?a.limiter(this._get):this._get,this._cache=a.cache===!1?new e(0):g}var d=0,f={},g=new e(10);return c.setMaxPendingRequests=function(a){this.maxPendingRequests=a},c.resetCache=function(){g.reset()},b.mixin(c.prototype,{_fingerprint:function(b){return b=b||{},b.url+b.type+a.param(b.data||{})},_get:function(a,b){function c(a){b(null,a),j._cache.set(h,a)}function e(){b(!0)}function g(){d--,delete f[h],j.onDeckRequestArgs&&(j._get.apply(j,j.onDeckRequestArgs),j.onDeckRequestArgs=null)}var h,i,j=this;h=this._fingerprint(a),this.cancelled||h!==this.lastReq||((i=f[h])?i.done(c).fail(e):db[d]?d++:(e.push(a[c]),c++,d++);return e}var h="c",i="i";return b.mixin(c.prototype,{bootstrap:function(a){this.datums=a.datums,this.trie=a.trie},add:function(a){var c=this;a=b.isArray(a)?a:[a],b.each(a,function(a){var f,g;c.datums[f=c.identify(a)]=a,g=d(c.datumTokenizer(a)),b.each(g,function(a){var b,d,g;for(b=c.trie,d=a.split("");g=d.shift();)b=b[h][g]||(b[h][g]=e()),b[i].push(f)})})},get:function(a){var c=this;return b.map(a,function(a){return c.datums[a]})},search:function(a){var c,e,j=this;return c=d(this.queryTokenizer(a)),b.each(c,function(a){var b,c,d,f;if(e&&0===e.length&&!j.matchAnyQueryToken)return!1;for(b=j.trie,c=a.split("");b&&(d=c.shift());)b=b[h][d];if(b&&0===c.length)f=b[i].slice(0),e=e?g(e,f):f;else if(!j.matchAnyQueryToken)return e=[],!1}),e?b.map(f(e),function(a){return j.datums[a]}):[]},all:function(){var a=[];for(var b in this.datums)a.push(this.datums[b]);return a},reset:function(){this.datums={},this.trie=e()},serialize:function(){return{datums:this.datums,trie:this.trie}}}),c}(),i=function(){"use strict";function a(a){this.url=a.url,this.ttl=a.ttl,this.cache=a.cache,this.prepare=a.prepare,this.transform=a.transform,this.transport=a.transport,this.thumbprint=a.thumbprint,this.storage=new f(a.cacheKey)}var c;return c={data:"data",protocol:"protocol",thumbprint:"thumbprint"},b.mixin(a.prototype,{_settings:function(){return{url:this.url,type:"GET",dataType:"json"}},store:function(a){this.cache&&(this.storage.set(c.data,a,this.ttl),this.storage.set(c.protocol,location.protocol,this.ttl),this.storage.set(c.thumbprint,this.thumbprint,this.ttl))},fromCache:function(){var a,b={};return this.cache?(b.data=this.storage.get(c.data),b.protocol=this.storage.get(c.protocol),b.thumbprint=this.storage.get(c.thumbprint),a=b.thumbprint!==this.thumbprint||b.protocol!==location.protocol,b.data&&!a?b.data:null):null},fromNetwork:function(a){function b(){a(!0)}function c(b){a(null,e.transform(b))}var d,e=this;a&&(d=this.prepare(this._settings()),this.transport(d).fail(b).done(c))},clear:function(){return this.storage.clear(),this}}),a}(),j=function(){"use strict";function a(a){this.url=a.url,this.prepare=a.prepare,this.transform=a.transform,this.indexResponse=a.indexResponse,this.transport=new g({cache:a.cache,limiter:a.limiter,transport:a.transport,maxPendingRequests:a.maxPendingRequests})}return b.mixin(a.prototype,{_settings:function(){return{url:this.url,type:"GET",dataType:"json"}},get:function(a,b){function c(a,c){b(a?[]:e.transform(c))}var d,e=this;if(b)return a=a||"",d=this.prepare(a,this._settings()),this.transport.get(d,c)},cancelLastRequest:function(){this.transport.cancel()}}),a}(),k=function(){"use strict";function d(d){var e;return d?(e={url:null,ttl:864e5,cache:!0,cacheKey:null,thumbprint:"",prepare:b.identity,transform:b.identity,transport:null},d=b.isString(d)?{url:d}:d,d=b.mixin(e,d),!d.url&&a.error("prefetch requires url to be set"),d.transform=d.filter||d.transform,d.cacheKey=d.cacheKey||d.url,d.thumbprint=c+d.thumbprint,d.transport=d.transport?h(d.transport):a.ajax,d):null}function e(c){var d;if(c)return d={url:null,cache:!0,prepare:null,replace:null,wildcard:null,limiter:null,rateLimitBy:"debounce",rateLimitWait:300,transform:b.identity,transport:null},c=b.isString(c)?{url:c}:c,c=b.mixin(d,c),!c.url&&a.error("remote requires url to be set"),c.transform=c.filter||c.transform,c.prepare=f(c),c.limiter=g(c),c.transport=c.transport?h(c.transport):a.ajax,delete c.replace,delete c.wildcard,delete c.rateLimitBy,delete c.rateLimitWait,c}function f(a){function b(a,b){return b.url=f(b.url,a),b}function c(a,b){return b.url=b.url.replace(g,encodeURIComponent(a)),b}function d(a,b){return b}var e,f,g;return e=a.prepare,f=a.replace,g=a.wildcard,e?e:e=f?b:a.wildcard?c:d}function g(a){function c(a){return function(c){return b.debounce(c,a)}}function d(a){return function(c){return b.throttle(c,a)}}var e,f,g;return e=a.limiter,f=a.rateLimitBy,g=a.rateLimitWait,e||(e=/^throttle$/i.test(f)?d(g):c(g)),e}function h(c){return function(d){function e(a){b.defer(function(){g.resolve(a)})}function f(a){b.defer(function(){g.reject(a)})}var g=a.Deferred();return c(d,e,f),g}}return function(c){var f,g;return f={initialize:!0,identify:b.stringify,datumTokenizer:null,queryTokenizer:null,matchAnyQueryToken:!1,sufficient:5,indexRemote:!1,sorter:null,local:[],prefetch:null,remote:null},c=b.mixin(f,c||{}),!c.datumTokenizer&&a.error("datumTokenizer is required"),!c.queryTokenizer&&a.error("queryTokenizer is required"),g=c.sorter,c.sorter=g?function(a){return a.sort(g)}:b.identity,c.local=b.isFunction(c.local)?c.local():c.local,c.prefetch=d(c.prefetch),c.remote=e(c.remote),c}}(),l=function(){"use strict";function c(a){a=k(a),this.sorter=a.sorter,this.identify=a.identify,this.sufficient=a.sufficient,this.indexRemote=a.indexRemote,this.local=a.local,this.remote=a.remote?new j(a.remote):null,this.prefetch=a.prefetch?new i(a.prefetch):null,this.index=new h({identify:this.identify,datumTokenizer:a.datumTokenizer,queryTokenizer:a.queryTokenizer}),a.initialize!==!1&&this.initialize()}var e;return e=window&&window.Bloodhound,c.noConflict=function(){return window&&(window.Bloodhound=e),c},c.tokenizers=d,b.mixin(c.prototype,{__ttAdapter:function(){function a(a,b,d){return c.search(a,b,d)}function b(a,b){return c.search(a,b)}var c=this;return this.remote?a:b},_loadPrefetch:function(){function b(a,b){return a?c.reject():(e.add(b),e.prefetch.store(e.index.serialize()),void c.resolve())}var c,d,e=this;return c=a.Deferred(),this.prefetch?(d=this.prefetch.fromCache())?(this.index.bootstrap(d),c.resolve()):this.prefetch.fromNetwork(b):c.resolve(),c.promise()},_initialize:function(){function a(){b.add(b.local)}var b=this;return this.clear(),(this.initPromise=this._loadPrefetch()).done(a),this.initPromise},initialize:function(a){return!this.initPromise||a?this._initialize():this.initPromise},add:function(a){return this.index.add(a),this},get:function(a){return a=b.isArray(a)?a:[].slice.call(arguments),this.index.get(a)},search:function(a,c,d){function e(a){var c=[];b.each(a,function(a){!b.some(f,function(b){return g.identify(a)===g.identify(b)})&&c.push(a)}),g.indexRemote&&g.add(c),d(c)}var f,g=this;return c=c||b.noop,d=d||b.noop,f=this.sorter(this.index.search(a)),c(this.remote?f.slice():f),this.remote&&f.length1?a:a[0],d()}):(h[b]=a,d())}),e=0,f=c.length;e=this.maxSize&&(this.list.remove(e),delete this.hash[e.key],this.size--),(c=this.hash[a])?(c.val=b,this.list.moveToFront(c)):(c=new d(a,b),this.list.add(c),this.hash[a]=c,this.size++)},get:function(a){var b=this.hash[a];if(b)return this.list.moveToFront(b),b.val},reset:function(){this.size=0,this.hash={},this.list=new c}}),a.mixin(c.prototype,{add:function(a){this.head&&(a.next=this.head,this.head.prev=a),this.head=a,this.tail=this.tail||a},remove:function(a){a.prev?a.prev.next=a.next:this.head=a.next,a.next?a.next.prev=a.prev:this.tail=a.prev},moveToFront:function(a){this.remove(a),this.add(a)}}),b}(),f=function(){"use strict";function b(b,c){this.prefix=["__",b,"__"].join(""),this.ttlKey="__ttl__",this.keyMatcher=new RegExp("^"+a.escapeRegExChars(this.prefix)),this.ls=c||g,!this.ls&&this._noop()}function c(){return(new Date).getTime()}function d(b){return JSON.stringify(a.isUndefined(b)?null:b)}function e(a){return JSON.parse(a)}function f(a){var b,c,d=[],e=g.length;for(b=0;bd)}}),b}(),g=function(){"use strict";function b(a){a=a||{},this.maxPendingRequests=a.maxPendingRequests||6,this.cancelled=!1,this.lastReq=null,this._send=a.transport,this._get=a.limiter?a.limiter(this._get):this._get,this._cache=!1===a.cache?new e(0):f}var c=0,d={},f=new e(10);return b.setMaxPendingRequests=function(a){this.maxPendingRequests=a},b.resetCache=function(){f.reset()},a.mixin(b.prototype,{_fingerprint:function(b){return b=b||{},b.url+b.type+a.param(b.data||{})},_get:function(a,b){function e(a){b(null,a),j._cache.set(h,a)}function f(){b(!0)}function g(){c--,delete d[h],j.onDeckRequestArgs&&(j._get.apply(j,j.onDeckRequestArgs),j.onDeckRequestArgs=null)}var h,i,j=this;h=this._fingerprint(a),this.cancelled||h!==this.lastReq||((i=d[h])?i.done(e).fail(f):cb[d]?d++:(e.push(a[c]),c++,d++);return e}var g="c",h="i";return a.mixin(b.prototype,{bootstrap:function(a){this.datums=a.datums,this.trie=a.trie},add:function(b){var e=this;b=a.isArray(b)?b:[b],a.each(b,function(b){var f,i;e.datums[f=e.identify(b)]=b,i=c(e.datumTokenizer(b)),a.each(i,function(a){var b,c,i;for(b=e.trie,c=a.split("");i=c.shift();)b=b[g][i]||(b[g][i]=d()),b[h].push(f)})})},get:function(b){var c=this;return a.map(b,function(a){return c.datums[a]})},search:function(b){var d,i,j=this;return d=c(this.queryTokenizer(b)),a.each(d,function(a){var b,c,d,e;if(i&&0===i.length&&!j.matchAnyQueryToken)return!1;for(b=j.trie,c=a.split("");b&&(d=c.shift());)b=b[g][d];if(b&&0===c.length)e=b[h].slice(0),i=i?f(i,e):e;else if(!j.matchAnyQueryToken)return i=[],!1}),i?a.map(e(i),function(a){return j.datums[a]}):[]},all:function(){var a=[];for(var b in this.datums)a.push(this.datums[b]);return a},reset:function(){this.datums={},this.trie=d()},serialize:function(){return{datums:this.datums,trie:this.trie}}}),b}(),i=function(){"use strict";function b(a){this.url=a.url,this.ttl=a.ttl,this.cache=a.cache,this.prepare=a.prepare,this.transform=a.transform,this.transport=a.transport,this.thumbprint=a.thumbprint,this.storage=new f(a.cacheKey)}var c;return c={data:"data",protocol:"protocol",thumbprint:"thumbprint"},a.mixin(b.prototype,{_settings:function(){return{url:this.url,type:"GET",dataType:"json"}},store:function(a){this.cache&&(this.storage.set(c.data,a,this.ttl),this.storage.set(c.protocol,location.protocol,this.ttl),this.storage.set(c.thumbprint,this.thumbprint,this.ttl))},fromCache:function(){var a,b={};return this.cache?(b.data=this.storage.get(c.data),b.protocol=this.storage.get(c.protocol),b.thumbprint=this.storage.get(c.thumbprint),a=b.thumbprint!==this.thumbprint||b.protocol!==location.protocol,b.data&&!a?b.data:null):null},fromNetwork:function(a){function b(){a(!0)}function c(b){a(null,e.transform(b))}var d,e=this;a&&(d=this.prepare(this._settings()),this.transport(d).fail(b).done(c))},clear:function(){return this.storage.clear(),this}}),b}(),j=function(){"use strict";function b(a){this.url=a.url,this.prepare=a.prepare,this.transform=a.transform,this.indexResponse=a.indexResponse,this.transport=new g({cache:a.cache,limiter:a.limiter,transport:a.transport,maxPendingRequests:a.maxPendingRequests})}return a.mixin(b.prototype,{_settings:function(){return{url:this.url,type:"GET",dataType:"json"}},get:function(a,b){function c(a,c){b(a?[]:e.transform(c))}var d,e=this;if(b)return a=a||"",d=this.prepare(a,this._settings()),this.transport.get(d,c)},cancelLastRequest:function(){this.transport.cancel()}}),b}(),k=function(){"use strict";function d(c){var d;if(!c)return null;if(d={url:null,ttl:864e5,cache:!0,cacheKey:null,thumbprint:"",prepare:a.identity,transform:a.identity,transport:null},c=a.isString(c)?{url:c}:c,c=a.mixin(d,c),!c.url)throw new Error("prefetch requires url to be set");return c.transform=c.filter||c.transform,c.cacheKey=c.cacheKey||c.url,c.thumbprint=b+c.thumbprint,c.transport=c.transport?h(c.transport):a.ajax,c}function e(b){var c;if(b){if(c={url:null,cache:!0,prepare:null,replace:null,wildcard:null,limiter:null,rateLimitBy:"debounce",rateLimitWait:300,transform:a.identity,transport:null},b=a.isString(b)?{url:b}:b,b=a.mixin(c,b),!b.url)throw new Error("remote requires url to be set");return b.transform=b.filter||b.transform,b.prepare=f(b),b.limiter=g(b),b.transport=b.transport?h(b.transport):a.ajax,delete b.replace,delete b.wildcard,delete b.rateLimitBy,delete b.rateLimitWait,b}}function f(a){function b(a,b){return b.url=f(b.url,a),b}function c(a,b){return b.url=b.url.replace(g,encodeURIComponent(a)),b}function d(a,b){return b}var e,f,g;return e=a.prepare,f=a.replace,g=a.wildcard,e||(e=f?b:a.wildcard?c:d)}function g(b){var c,d,e;return c=b.limiter,d=b.rateLimitBy,e=b.rateLimitWait,c||(c=/^throttle$/i.test(d)?function(b){return function(c){return a.throttle(c,b)}}(e):function(b){return function(c){return a.debounce(c,b)}}(e)),c}function h(b){return function(d){function e(b){a.defer(function(){g.resolve(b)})}function f(b){a.defer(function(){g.reject(b)})}var g=c();return b(d,e,f),g}}return function(b){var c,f;if(c={initialize:!0,identify:a.stringify,datumTokenizer:null,queryTokenizer:null,matchAnyQueryToken:!1,sufficient:5,indexRemote:!1,sorter:null,local:[],prefetch:null,remote:null},b=a.mixin(c,b||{}),!b.datumTokenizer)throw new Error("datumTokenizer is required");if(!b.queryTokenizer)throw new Error("queryTokenizer is required");return f=b.sorter,b.sorter=f?function(a){return a.sort(f)}:a.identity,b.local=a.isFunction(b.local)?b.local():b.local,b.prefetch=d(b.prefetch),b.remote=e(b.remote),b}}();return function(){"use strict";function b(a){a=k(a),this.sorter=a.sorter,this.identify=a.identify,this.sufficient=a.sufficient,this.indexRemote=a.indexRemote,this.local=a.local,this.remote=a.remote?new j(a.remote):null,this.prefetch=a.prefetch?new i(a.prefetch):null,this.index=new h({identify:this.identify,datumTokenizer:a.datumTokenizer,queryTokenizer:a.queryTokenizer}),!1!==a.initialize&&this.initialize()}var e;return e=window&&window.Bloodhound,b.noConflict=function(){return window&&(window.Bloodhound=e),b},b.tokenizers=d,a.mixin(b.prototype,{__ttAdapter:function(){function a(a,b,d){return c.search(a,b,d)}function b(a,b){return c.search(a,b)}var c=this;return this.remote?a:b},_loadPrefetch:function(){function a(a,c){if(a)return b.reject();e.add(c),e.prefetch.store(e.index.serialize()),b.resolve()}var b,d,e=this;return b=c(),this.prefetch?(d=this.prefetch.fromCache())?(this.index.bootstrap(d),b.resolve()):this.prefetch.fromNetwork(a):b.resolve(),b.promise()},_initialize:function(){function a(){b.add(b.local)}var b=this;return this.clear(),(this.initPromise=this._loadPrefetch()).done(a),this.initPromise},initialize:function(a){return!this.initPromise||a?this._initialize():this.initPromise},add:function(a){return this.index.add(a),this},get:function(b){return b=a.isArray(b)?b:[].slice.call(arguments),this.index.get(b)},search:function(b,c,d){function e(b){var c=[];a.each(b,function(b){!a.some(f,function(a){return g.identify(b)===g.identify(a)})&&c.push(b)}),g.indexRemote&&g.add(c),d(c)}var f,g=this;return c=c||a.noop,d=d||a.noop,f=this.sorter(this.index.search(b)),c(this.remote?f.slice():f),this.remote&&f.length 1 ? args : args[0]; + return finish(); + }); + } else { + resolutionArgs[index] = def; + return finish(); + } + }); + for (i = 0, len = defs.length; i < len; i++) { + def = defs[i]; + isPromise(def) && def.fail(trigger.reject); + } + return trigger.promise(); + }; + var d = function() { + return new Deferred(); + }; + d.when = _when; + return d; + }(); var tokenizers = function() { "use strict"; return { @@ -211,7 +592,7 @@ this.maxSize = _.isNumber(maxSize) ? maxSize : 100; this.reset(); if (this.maxSize <= 0) { - this.set = this.get = $.noop; + this.set = this.get = _.noop; } } _.mixin(LruCache.prototype, { @@ -349,7 +730,7 @@ return JSON.stringify(_.isUndefined(val) ? null : val); } function decode(val) { - return $.parseJSON(val); + return JSON.parse(val); } function gatherMatchingKeys(keyMatcher) { var i, key, keys = [], len = LOCAL_STORAGE.length; @@ -382,7 +763,7 @@ _.mixin(Transport.prototype, { _fingerprint: function fingerprint(o) { o = o || {}; - return o.url + o.type + $.param(o.data || {}); + return o.url + o.type + _.param(o.data || {}); }, _get: function(o, cb) { var that = this, fingerprint, jqXhr; @@ -416,7 +797,7 @@ }, get: function(o, cb) { var resp, fingerprint; - cb = cb || $.noop; + cb = cb || _.noop; o = _.isString(o) ? { url: o } : o || {}; @@ -441,7 +822,7 @@ function SearchIndex(o) { o = o || {}; if (!o.datumTokenizer || !o.queryTokenizer) { - $.error("datumTokenizer and queryTokenizer are both required"); + throw new Error("datumTokenizer and queryTokenizer are both required"); } this.identify = o.identify || _.stringify; this.datumTokenizer = o.datumTokenizer; @@ -692,8 +1073,12 @@ remote: null }; o = _.mixin(defaults, o || {}); - !o.datumTokenizer && $.error("datumTokenizer is required"); - !o.queryTokenizer && $.error("queryTokenizer is required"); + if (!o.datumTokenizer) { + throw new Error("datumTokenizer is required"); + } + if (!o.queryTokenizer) { + throw new Error("queryTokenizer is required"); + } sorter = o.sorter; o.sorter = sorter ? function(x) { return x.sort(sorter); @@ -722,11 +1107,13 @@ url: o } : o; o = _.mixin(defaults, o); - !o.url && $.error("prefetch requires url to be set"); + if (!o.url) { + throw new Error("prefetch requires url to be set"); + } o.transform = o.filter || o.transform; o.cacheKey = o.cacheKey || o.url; o.thumbprint = VERSION + o.thumbprint; - o.transport = o.transport ? callbackToDeferred(o.transport) : $.ajax; + o.transport = o.transport ? callbackToDeferred(o.transport) : _.ajax; return o; } function parseRemote(o) { @@ -750,11 +1137,13 @@ url: o } : o; o = _.mixin(defaults, o); - !o.url && $.error("remote requires url to be set"); + if (!o.url) { + throw new Error("remote requires url to be set"); + } o.transform = o.filter || o.transform; o.prepare = toRemotePrepare(o); o.limiter = toLimiter(o); - o.transport = o.transport ? callbackToDeferred(o.transport) : $.ajax; + o.transport = o.transport ? callbackToDeferred(o.transport) : _.ajax; delete o.replace; delete o.wildcard; delete o.rateLimitBy; @@ -811,7 +1200,7 @@ } function callbackToDeferred(fn) { return function wrapper(o) { - var deferred = $.Deferred(); + var deferred = Deferred(); fn(o, onSuccess, onError); return deferred; function onSuccess(resp) { @@ -865,7 +1254,7 @@ }, _loadPrefetch: function loadPrefetch() { var that = this, deferred, serialized; - deferred = $.Deferred(); + deferred = Deferred(); if (!this.prefetch) { deferred.resolve(); } else if (serialized = this.prefetch.fromCache()) { @@ -956,7 +1345,7 @@ define([ "jquery" ], function(a0) { return factory(a0); }); - } else if (typeof exports === "object") { + } else if (typeof module === "object" && module.exports) { module.exports = factory(require("jquery")); } else { factory(root["jQuery"]); @@ -980,9 +1369,24 @@ isNumber: function(obj) { return typeof obj === "number"; }, - isArray: $.isArray, - isFunction: $.isFunction, - isObject: $.isPlainObject, + isArray: function(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }, + isFunction: function(obj) { + return typeof obj === "function"; + }, + isObject: function(obj) { + var proto, Ctor, hasOwn = {}.hasOwnProperty; + if (!obj || {}.toString.call(obj) !== "[object Object]") { + return false; + } + proto = Object.getPrototypeOf(obj); + if (!proto) { + return true; + } + Ctor = hasOwn.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && hasOwn.toString.call(Ctor) === hasOwn.toString.call(Object); + }, isUndefined: function(obj) { return typeof obj === "undefined"; }, @@ -995,21 +1399,81 @@ toStr: function toStr(s) { return _.isUndefined(s) || s === null ? "" : s + ""; }, - bind: $.proxy, + bind: function(fn, context) { + var tmp, args, proxy; + if (typeof context === "string") { + tmp = fn[context]; + context = fn; + fn = tmp; + } + if (!_.isFunction(fn)) { + return undefined; + } + args = [].slice.call(arguments, 2); + proxy = function() { + return fn.apply(context || _, args.concat([].slice.call(arguments))); + }; + proxy.guid = fn.guid = fn.guid || _.guid(); + return proxy; + }, each: function(collection, cb) { - $.each(collection, reverseArgs); - function reverseArgs(index, value) { + (function(obj, callback) { + var length, i = 0; + if (_.isArray(obj)) { + length = obj.length; + for (;i < length; i++) { + if (callback.call(obj[i], i, obj[i]) === false) { + break; + } + } + } else { + for (i in obj) { + if (callback.call(obj[i], i, obj[i]) === false) { + break; + } + } + } + return obj; + })(collection, function(index, value) { return cb(value, index); + }); + }, + map: function(elems, callback, arg) { + var length, value, i = 0, ret = []; + if (_.isArray(elems)) { + length = elems.length; + for (;i < length; i++) { + value = callback(elems[i], i, arg); + if (value != null) { + ret.push(value); + } + } + } else { + for (i in elems) { + value = callback(elems[i], i, arg); + if (value != null) { + ret.push(value); + } + } } + return [].concat.apply([], ret); + }, + filter: function(elems, callback, invert) { + var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; + for (;i < length; i++) { + callbackInverse = !callback(elems[i], i); + if (callbackInverse !== callbackExpect) { + matches.push(elems[i]); + } + } + return matches; }, - map: $.map, - filter: $.grep, every: function(obj, test) { var result = true; if (!obj) { return result; } - $.each(obj, function(key, val) { + _.each(obj, function(val, key) { if (!(result = test.call(null, val, key, obj))) { return false; } @@ -1021,19 +1485,56 @@ if (!obj) { return result; } - $.each(obj, function(key, val) { + _.each(obj, function(val, key) { if (result = test.call(null, val, key, obj)) { return false; } }); return !!result; }, - mixin: $.extend, + mixin: function() { + var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; + if (typeof target === "boolean") { + deep = target; + target = arguments[i] || {}; + i++; + } + if (typeof target !== "object" && !_.isFunction(target)) { + target = {}; + } + if (i === length) { + target = _; + i--; + } + for (;i < length; i++) { + if ((options = arguments[i]) != null) { + for (name in options) { + src = target[name]; + copy = options[name]; + if (target === copy) { + continue; + } + if (deep && copy && (_.isObject(copy) || (copyIsArray = _.isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && _.isArray(src) ? src : []; + } else { + clone = src && _.isObject(src) ? src : {}; + } + target[name] = _.mixin(deep, clone, copy); + } else if (copy !== undefined) { + target[name] = copy; + } + } + } + } + return target; + }, identity: function(x) { return x; }, clone: function(obj) { - return $.extend(true, {}, obj); + return _.mixin(true, {}, obj); }, getIdGenerator: function() { var counter = 0; @@ -1042,7 +1543,7 @@ }; }, templatify: function templatify(obj) { - return $.isFunction(obj) ? obj : template; + return _.isFunction(obj) ? obj : template; function template() { return String(obj); } @@ -1095,6 +1596,81 @@ stringify: function(val) { return _.isString(val) ? val : JSON.stringify(val); }, + ajax: function(opts, onSuccess, onFailure) { + var url; + if (_.isObject(opts)) { + url = opts.url; + } else { + url = opts; + opts = {}; + } + var deferred = Deferred(); + (function(onSuccess, onFailure) { + var req = new XMLHttpRequest(); + req.open(opts.type || "GET", url); + req.responseType = opts.responseType || opts.dataType || "json"; + opts.headers && function(req, headers) { + for (var key in headers) { + req.setRequestHeader(key, headers[key]); + } + }(req, opts.headers); + opts.listeners && function(req, listeners) { + for (var key in listeners) { + req.addEventListener(key, listeners[key], false); + } + }(req, opts.listeners); + req.onload = function() { + if (req.status == 200) { + onSuccess(req.response); + } else { + onFailure(req.statusText); + } + }; + req.onerror = function() { + onFailure("Network Error"); + }; + req.send(); + return req; + })(function(resp) { + _.defer(function() { + onSuccess(resp); + deferred.resolve(resp); + }); + }, function(err) { + _.defer(function() { + onFailure(err); + deferred.reject(err); + }); + }); + return deferred; + }, + param: function(a) { + var prefix, s = [], buildParams = function(prefix, obj, add) { + var name; + if (_.isArray(obj)) { + _.each(obj, function(v, i) { + if (/\[\]$/.test(prefix)) { + add(prefix, v); + } else { + buildParams(prefix + "[" + (typeof v === "object" && v != null ? i : "") + "]", v, add); + } + }); + } else if (_.type(obj) === "object") { + for (name in obj) { + buildParams(prefix + "[" + name + "]", obj[name], add); + } + } else { + add(prefix, obj); + } + }, add = function(key, valueOrFunction) { + var value = _.isFunction(valueOrFunction) ? valueOrFunction() : valueOrFunction; + s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value == null ? "" : value); + }; + for (prefix in a) { + buildParams(prefix, a[prefix], add); + } + return s.join("&"); + }, guid: function() { function _p8(s) { var p = (Math.random().toString(16) + "000000000").substr(2, 8); diff --git a/dist/typeahead.bundle.min.js b/dist/typeahead.bundle.min.js index 2d688c7b87..f1af4125d4 100644 --- a/dist/typeahead.bundle.min.js +++ b/dist/typeahead.bundle.min.js @@ -1,8 +1,9 @@ /*! - * typeahead.js 1.2.0 + * typeahead.js 1.2.1 * https://github.com/twitter/typeahead.js * Copyright 2013-2017 Twitter, Inc. and other contributors; Licensed MIT */ -!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(c){return a.Bloodhound=b(c)}):"object"==typeof exports?module.exports=b(require("jquery")):a.Bloodhound=b(a.jQuery)}(this,function(a){var b=function(){"use strict";return{isMsie:function(){return!!/(msie|trident)/i.test(navigator.userAgent)&&navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2]},isBlankString:function(a){return!a||/^\s*$/.test(a)},escapeRegExChars:function(a){return a.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isString:function(a){return"string"==typeof a},isNumber:function(a){return"number"==typeof a},isArray:a.isArray,isFunction:a.isFunction,isObject:a.isPlainObject,isUndefined:function(a){return"undefined"==typeof a},isElement:function(a){return!(!a||1!==a.nodeType)},isJQuery:function(b){return b instanceof a},toStr:function(a){return b.isUndefined(a)||null===a?"":a+""},bind:a.proxy,each:function(b,c){function d(a,b){return c(b,a)}a.each(b,d)},map:a.map,filter:a.grep,every:function(b,c){var d=!0;return b?(a.each(b,function(a,e){if(!(d=c.call(null,e,a,b)))return!1}),!!d):d},some:function(b,c){var d=!1;return b?(a.each(b,function(a,e){if(d=c.call(null,e,a,b))return!1}),!!d):d},mixin:a.extend,identity:function(a){return a},clone:function(b){return a.extend(!0,{},b)},getIdGenerator:function(){var a=0;return function(){return a++}},templatify:function(b){function c(){return String(b)}return a.isFunction(b)?b:c},defer:function(a){setTimeout(a,0)},debounce:function(a,b,c){var d,e;return function(){var f,g,h=this,i=arguments;return f=function(){d=null,c||(e=a.apply(h,i))},g=c&&!d,clearTimeout(d),d=setTimeout(f,b),g&&(e=a.apply(h,i)),e}},throttle:function(a,b){var c,d,e,f,g,h;return g=0,h=function(){g=new Date,e=null,f=a.apply(c,d)},function(){var i=new Date,j=b-(i-g);return c=this,d=arguments,j<=0?(clearTimeout(e),e=null,g=i,f=a.apply(c,d)):e||(e=setTimeout(h,j)),f}},stringify:function(a){return b.isString(a)?a:JSON.stringify(a)},guid:function(){function a(a){var b=(Math.random().toString(16)+"000000000").substr(2,8);return a?"-"+b.substr(0,4)+"-"+b.substr(4,4):b}return"tt-"+a()+a(!0)+a(!0)+a()},noop:function(){}}}(),c="1.2.0",d=function(){"use strict";function a(a){return a=b.toStr(a),a?a.split(/\s+/):[]}function c(a){return a=b.toStr(a),a?a.split(/\W+/):[]}function d(a){a=b.toStr(a);var c=[],d="";return b.each(a.split(""),function(a){a.match(/\s+/)?d="":(c.push(d+a),d+=a)}),c}function e(a){return function(c){return c=b.isArray(c)?c:[].slice.call(arguments,0),function(d){var e=[];return b.each(c,function(c){e=e.concat(a(b.toStr(d[c])))}),e}}}return{nonword:c,whitespace:a,ngram:d,obj:{nonword:e(c),whitespace:e(a),ngram:e(d)}}}(),e=function(){"use strict";function c(c){this.maxSize=b.isNumber(c)?c:100,this.reset(),this.maxSize<=0&&(this.set=this.get=a.noop)}function d(){this.head=this.tail=null}function e(a,b){this.key=a,this.val=b,this.prev=this.next=null}return b.mixin(c.prototype,{set:function(a,b){var c,d=this.list.tail;this.size>=this.maxSize&&(this.list.remove(d),delete this.hash[d.key],this.size--),(c=this.hash[a])?(c.val=b,this.list.moveToFront(c)):(c=new e(a,b),this.list.add(c),this.hash[a]=c,this.size++)},get:function(a){var b=this.hash[a];if(b)return this.list.moveToFront(b),b.val},reset:function(){this.size=0,this.hash={},this.list=new d}}),b.mixin(d.prototype,{add:function(a){this.head&&(a.next=this.head,this.head.prev=a),this.head=a,this.tail=this.tail||a},remove:function(a){a.prev?a.prev.next=a.next:this.head=a.next,a.next?a.next.prev=a.prev:this.tail=a.prev},moveToFront:function(a){this.remove(a),this.add(a)}}),c}(),f=function(){"use strict";function c(a,c){this.prefix=["__",a,"__"].join(""),this.ttlKey="__ttl__",this.keyMatcher=new RegExp("^"+b.escapeRegExChars(this.prefix)),this.ls=c||h,!this.ls&&this._noop()}function d(){return(new Date).getTime()}function e(a){return JSON.stringify(b.isUndefined(a)?null:a)}function f(b){return a.parseJSON(b)}function g(a){var b,c,d=[],e=h.length;for(b=0;bc)}}),c}(),g=function(){"use strict";function c(a){a=a||{},this.maxPendingRequests=a.maxPendingRequests||6,this.cancelled=!1,this.lastReq=null,this._send=a.transport,this._get=a.limiter?a.limiter(this._get):this._get,this._cache=a.cache===!1?new e(0):g}var d=0,f={},g=new e(10);return c.setMaxPendingRequests=function(a){this.maxPendingRequests=a},c.resetCache=function(){g.reset()},b.mixin(c.prototype,{_fingerprint:function(b){return b=b||{},b.url+b.type+a.param(b.data||{})},_get:function(a,b){function c(a){b(null,a),j._cache.set(h,a)}function e(){b(!0)}function g(){d--,delete f[h],j.onDeckRequestArgs&&(j._get.apply(j,j.onDeckRequestArgs),j.onDeckRequestArgs=null)}var h,i,j=this;h=this._fingerprint(a),this.cancelled||h!==this.lastReq||((i=f[h])?i.done(c).fail(e):db[d]?d++:(e.push(a[c]),c++,d++);return e}var h="c",i="i";return b.mixin(c.prototype,{bootstrap:function(a){this.datums=a.datums,this.trie=a.trie},add:function(a){var c=this;a=b.isArray(a)?a:[a],b.each(a,function(a){var f,g;c.datums[f=c.identify(a)]=a,g=d(c.datumTokenizer(a)),b.each(g,function(a){var b,d,g;for(b=c.trie,d=a.split("");g=d.shift();)b=b[h][g]||(b[h][g]=e()),b[i].push(f)})})},get:function(a){var c=this;return b.map(a,function(a){return c.datums[a]})},search:function(a){var c,e,j=this;return c=d(this.queryTokenizer(a)),b.each(c,function(a){var b,c,d,f;if(e&&0===e.length&&!j.matchAnyQueryToken)return!1;for(b=j.trie,c=a.split("");b&&(d=c.shift());)b=b[h][d];if(b&&0===c.length)f=b[i].slice(0),e=e?g(e,f):f;else if(!j.matchAnyQueryToken)return e=[],!1}),e?b.map(f(e),function(a){return j.datums[a]}):[]},all:function(){var a=[];for(var b in this.datums)a.push(this.datums[b]);return a},reset:function(){this.datums={},this.trie=e()},serialize:function(){return{datums:this.datums,trie:this.trie}}}),c}(),i=function(){"use strict";function a(a){this.url=a.url,this.ttl=a.ttl,this.cache=a.cache,this.prepare=a.prepare,this.transform=a.transform,this.transport=a.transport,this.thumbprint=a.thumbprint,this.storage=new f(a.cacheKey)}var c;return c={data:"data",protocol:"protocol",thumbprint:"thumbprint"},b.mixin(a.prototype,{_settings:function(){return{url:this.url,type:"GET",dataType:"json"}},store:function(a){this.cache&&(this.storage.set(c.data,a,this.ttl),this.storage.set(c.protocol,location.protocol,this.ttl),this.storage.set(c.thumbprint,this.thumbprint,this.ttl))},fromCache:function(){var a,b={};return this.cache?(b.data=this.storage.get(c.data),b.protocol=this.storage.get(c.protocol),b.thumbprint=this.storage.get(c.thumbprint),a=b.thumbprint!==this.thumbprint||b.protocol!==location.protocol,b.data&&!a?b.data:null):null},fromNetwork:function(a){function b(){a(!0)}function c(b){a(null,e.transform(b))}var d,e=this;a&&(d=this.prepare(this._settings()),this.transport(d).fail(b).done(c))},clear:function(){return this.storage.clear(),this}}),a}(),j=function(){"use strict";function a(a){this.url=a.url,this.prepare=a.prepare,this.transform=a.transform,this.indexResponse=a.indexResponse,this.transport=new g({cache:a.cache,limiter:a.limiter,transport:a.transport,maxPendingRequests:a.maxPendingRequests})}return b.mixin(a.prototype,{_settings:function(){return{url:this.url,type:"GET",dataType:"json"}},get:function(a,b){function c(a,c){b(a?[]:e.transform(c))}var d,e=this;if(b)return a=a||"",d=this.prepare(a,this._settings()),this.transport.get(d,c)},cancelLastRequest:function(){this.transport.cancel()}}),a}(),k=function(){"use strict";function d(d){var e;return d?(e={url:null,ttl:864e5,cache:!0,cacheKey:null,thumbprint:"",prepare:b.identity,transform:b.identity,transport:null},d=b.isString(d)?{url:d}:d,d=b.mixin(e,d),!d.url&&a.error("prefetch requires url to be set"),d.transform=d.filter||d.transform,d.cacheKey=d.cacheKey||d.url,d.thumbprint=c+d.thumbprint,d.transport=d.transport?h(d.transport):a.ajax,d):null}function e(c){var d;if(c)return d={url:null,cache:!0,prepare:null,replace:null,wildcard:null,limiter:null,rateLimitBy:"debounce",rateLimitWait:300,transform:b.identity,transport:null},c=b.isString(c)?{url:c}:c,c=b.mixin(d,c),!c.url&&a.error("remote requires url to be set"),c.transform=c.filter||c.transform,c.prepare=f(c),c.limiter=g(c),c.transport=c.transport?h(c.transport):a.ajax,delete c.replace,delete c.wildcard,delete c.rateLimitBy,delete c.rateLimitWait,c}function f(a){function b(a,b){return b.url=f(b.url,a),b}function c(a,b){return b.url=b.url.replace(g,encodeURIComponent(a)),b}function d(a,b){return b}var e,f,g;return e=a.prepare,f=a.replace,g=a.wildcard,e?e:e=f?b:a.wildcard?c:d}function g(a){function c(a){return function(c){return b.debounce(c,a)}}function d(a){return function(c){return b.throttle(c,a)}}var e,f,g;return e=a.limiter,f=a.rateLimitBy,g=a.rateLimitWait,e||(e=/^throttle$/i.test(f)?d(g):c(g)),e}function h(c){return function(d){function e(a){b.defer(function(){g.resolve(a)})}function f(a){b.defer(function(){g.reject(a)})}var g=a.Deferred();return c(d,e,f),g}}return function(c){var f,g;return f={initialize:!0,identify:b.stringify,datumTokenizer:null,queryTokenizer:null,matchAnyQueryToken:!1,sufficient:5,indexRemote:!1,sorter:null,local:[],prefetch:null,remote:null},c=b.mixin(f,c||{}),!c.datumTokenizer&&a.error("datumTokenizer is required"),!c.queryTokenizer&&a.error("queryTokenizer is required"),g=c.sorter,c.sorter=g?function(a){return a.sort(g)}:b.identity,c.local=b.isFunction(c.local)?c.local():c.local,c.prefetch=d(c.prefetch),c.remote=e(c.remote),c}}(),l=function(){"use strict";function c(a){a=k(a),this.sorter=a.sorter,this.identify=a.identify,this.sufficient=a.sufficient,this.indexRemote=a.indexRemote,this.local=a.local,this.remote=a.remote?new j(a.remote):null,this.prefetch=a.prefetch?new i(a.prefetch):null,this.index=new h({identify:this.identify,datumTokenizer:a.datumTokenizer,queryTokenizer:a.queryTokenizer}),a.initialize!==!1&&this.initialize()}var e;return e=window&&window.Bloodhound,c.noConflict=function(){return window&&(window.Bloodhound=e),c},c.tokenizers=d,b.mixin(c.prototype,{__ttAdapter:function(){function a(a,b,d){return c.search(a,b,d)}function b(a,b){return c.search(a,b)}var c=this;return this.remote?a:b},_loadPrefetch:function(){function b(a,b){return a?c.reject():(e.add(b),e.prefetch.store(e.index.serialize()),void c.resolve())}var c,d,e=this;return c=a.Deferred(),this.prefetch?(d=this.prefetch.fromCache())?(this.index.bootstrap(d),c.resolve()):this.prefetch.fromNetwork(b):c.resolve(),c.promise()},_initialize:function(){function a(){b.add(b.local)}var b=this;return this.clear(),(this.initPromise=this._loadPrefetch()).done(a),this.initPromise},initialize:function(a){return!this.initPromise||a?this._initialize():this.initPromise},add:function(a){return this.index.add(a),this},get:function(a){return a=b.isArray(a)?a:[].slice.call(arguments),this.index.get(a)},search:function(a,c,d){function e(a){var c=[];b.each(a,function(a){!b.some(f,function(b){return g.identify(a)===g.identify(b)})&&c.push(a)}),g.indexRemote&&g.add(c),d(c)}var f,g=this;return c=c||b.noop,d=d||b.noop,f=this.sorter(this.index.search(a)),c(this.remote?f.slice():f),this.remote&&f.length',menu:'
'}}function d(a){var c={};return b.each(a,function(a,b){c[b]="."+a}),c}function e(){var a={wrapper:{position:"relative",display:"inline-block"},hint:{position:"absolute",top:"0",left:"0",borderColor:"transparent",boxShadow:"none",opacity:"1"},input:{position:"relative",verticalAlign:"top",backgroundColor:"transparent"},inputWithNoHint:{position:"relative",verticalAlign:"top"},menu:{position:"absolute",top:"100%",left:"0",zIndex:"100",display:"none"},ltr:{left:"0",right:"auto"},rtl:{left:"auto",right:" 0"}};return b.isMsie()&&b.mixin(a.input,{backgroundImage:"url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"}),a}var f={wrapper:"twitter-typeahead",input:"tt-input",hint:"tt-hint",menu:"tt-menu",dataset:"tt-dataset",suggestion:"tt-suggestion",selectable:"tt-selectable",empty:"tt-empty",open:"tt-open",cursor:"tt-cursor",highlight:"tt-highlight"};return a}(),d=function(){"use strict";function c(b){b&&b.el||a.error("EventBus initialized without el"),this.$el=a(b.el)}var d,e;return d="typeahead:",e={render:"rendered",cursorchange:"cursorchanged",select:"selected",autocomplete:"autocompleted"},b.mixin(c.prototype,{_trigger:function(b,c){var e=a.Event(d+b);return this.$el.trigger.call(this.$el,e,c||[]),e},before:function(a){var b,c;return b=[].slice.call(arguments,1),c=this._trigger("before"+a,b),c.isDefaultPrevented()},trigger:function(a){var b;this._trigger(a,[].slice.call(arguments,1)),(b=e[a])&&this._trigger(b,[].slice.call(arguments,1))}}),c}(),e=function(){"use strict";function a(a,b,c,d){var e;if(!c)return this;for(b=b.split(i),c=d?h(c,d):c,this._callbacks=this._callbacks||{};e=b.shift();)this._callbacks[e]=this._callbacks[e]||{sync:[],async:[]},this._callbacks[e][a].push(c);return this}function b(b,c,d){return a.call(this,"async",b,c,d)}function c(b,c,d){return a.call(this,"sync",b,c,d)}function d(a){var b;if(!this._callbacks)return this;for(a=a.split(i);b=a.shift();)delete this._callbacks[b];return this}function e(a){var b,c,d,e,g;if(!this._callbacks)return this;for(a=a.split(i),d=[].slice.call(arguments,1);(b=a.shift())&&(c=this._callbacks[b]);)e=f(c.sync,this,[b].concat(d)),g=f(c.async,this,[b].concat(d)),e()&&j(g);return this}function f(a,b,c){function d(){for(var d,e=0,f=a.length;!d&&e