Skip to content

Instantly share code, notes, and snippets.

@KatrinaHoffert
Created February 22, 2015 21:36
Show Gist options
  • Save KatrinaHoffert/da5145a9b6441886f083 to your computer and use it in GitHub Desktop.
Save KatrinaHoffert/da5145a9b6441886f083 to your computer and use it in GitHub Desktop.
/**
* jQuery Typeahead
* Copyright (C) 2014 RunningCoder.org
* Licensed under the MIT license
*
* @author Tom Bertrand
* @version 1.7.6 (2015-01-17)
*
* @link
* http://www.runningcoder.org/jquerytypeahead/
*/
(function(e,t,n,r){e.Typeahead={source:{}};if(typeof Object.preventExtensions!=="function"){Object.preventExtensions=function(e){return e}}var i={input:null,minLength:2,maxItem:8,dynamic:false,delay:300,order:null,offset:false,hint:false,accent:false,highlight:true,list:false,group:false,groupMaxItem:false,filter:false,backdrop:false,cache:false,ttl:36e5,compression:false,selector:{container:"typeahead-container",group:"typeahead-group",result:"typeahead-result",list:"typeahead-list",display:"typeahead-display",query:"typeahead-query",filter:"typeahead-filter",filterButton:"typeahead-filter-button",filterValue:"typeahead-filter-value",dropdown:"typeahead-dropdown",button:"typeahead-button",backdrop:"typeahead-backdrop",hint:"typeahead-hint"},display:"display",template:null,source:null,callback:{onInit:null,onResult:null,onMouseEnter:null,onMouseLeave:null,onClick:null,onSubmit:null},debug:false};var s={dynamic:[true,false],order:["asc","desc"],offset:[true,false],accent:[true,false],cache:[true,false],compression:[true,false],debug:[true,false]};var o=".typeahead.input";var u={from:"ãàáäâẽèéëêìíïîõòóöôùúüûñç",to:"aaaaaeeeeeiiiiooooouuuunc"};var a=function(r,a){function x(){for(var t in a){if(!a.hasOwnProperty(t)){continue}if(t==="source"){for(var r in a[t]){if(!a[t].hasOwnProperty(r)){continue}if(!(a[t][r]instanceof Object)||r==="data"){r="group";a[t]={group:a[t]}}}}else if(s[t]&&n.inArray(a[t],s[t])===-1){delete a[t]}}if(a.dynamic){a.cache=false;a.compression=false}if(a.cache){a.cache=function(){var t=typeof e.localStorage!=="undefined";if(t){try{localStorage.setItem("typeahead","typeahead");localStorage.removeItem("typeahead")}catch(n){t=false}}return t}()}a=n.extend(true,Object.preventExtensions(n.extend(true,{},i)),a)}function T(){R(a.callback.onInit,[r]);m=r.closest("."+a.selector.container);var e=["focus"+o,"input"+o,"propertychange"+o,"keydown"+o,"dynamic"+o];n("html").on("click"+o,function(e){L()});m.on("click"+o,function(e){e.stopPropagation();if(a.filter){m.find("."+a.selector.dropdown.replace(" ",".")).hide()}});r.closest("form").on("submit",function(e){if(R(a.callback.onSubmit,[r,this,d,e])){return false}});r.on(e.join(" "),function(e){switch(e.type){case"keydown":if(e.keyCode&&~[9,13,27,38,39,40].indexOf(e.keyCode)){k(e)}break;case"focus":if(l===null){if(!a.dynamic){A()}}break;case"input":case"propertychange":if(!l){if(a.dynamic){f=n.trim(n(this).val());q(function(){if(f.length>=a.minLength&&f!==""){A()}},a.delay)}return};case"dynamic":default:f=n.trim(n(this).val());L();if(f.length>=a.minLength&&f!==""){N();C()}if(e.type==="dynamic"&&a.dynamic){l=false;E=0}break}})}function N(){if(f===""){return false}d=null;if(v&&!a.source[v]){v=false}var e,t=f,n=0,i=/\d/.test(a.groupMaxItem)&&a.groupMaxItem,s;if(a.accent){t=j(f)}for(var o in h){if(!h.hasOwnProperty(o)||v&&o!==v){continue}if(i){s=0}for(var u in h[o]){if(!h[o].hasOwnProperty(u)){continue}if((p.length>=a.maxItem||i&&s>=i)&&!a.callback.onResult){break}if(a.source[o]&&a.source[o].display){h[o][u].display=h[o][u][a.source[o].display]}else{h[o][u].display=h[o][u][a.display]}e=h[o][u].display.toString();if(!e){continue}if(a.accent){e=j(e)}if(e.toLowerCase().indexOf(t.toLowerCase())!==-1&&(!a.offset||e.toLowerCase().indexOf(t.toLowerCase())===0)){if(a.source[o].ignore&&~a.source[o].ignore.indexOf(e)){continue}n++;if(a.callback.onResult&&(p.length>=a.maxItem||i&&s>=i)){continue}h[o][u].group=o;p.push(h[o][u]);if(i){s++}}}}if(a.order){p.sort(B("display",a.order==="asc",function(e){return e.toString().toUpperCase()}))}if(a.group){var l=[];for(var o in h){for(var c in p){if(p[c].group===o){l.push(p[c])}}}p=l}R(a.callback.onResult,[r,f,p,n]);return true}function C(){if(f===""||p.length===0){return false}var e=n("<div/>",{"class":a.selector.result,html:n("<ul/>",{"class":a.selector.list,html:function(){for(var e in p){if(!p.hasOwnProperty(e)){continue}(function(e,t){if(typeof e.display!=="string"){e.display+=""}var i,s,o,u,l,c,h,p,v;if(a.group){i=e.group;if(typeof a.group!=="boolean"&&e[a.group]){i=e[a.group]}}if(a.list){s=e.group;if(typeof a.list!=="boolean"&&e[a.list]){s=e[a.list]}}if(a.group&&!n(t).find('li[data-search-group="'+i+'"]')[0]){n(t).append(n("<li/>",{"class":a.selector.group,html:n("<a/>",{html:i}),"data-search-group":i}))}l=e.display.toLowerCase();h=f.toLowerCase();if(a.accent){l=j(l);h=j(h)}if(a.highlight){l=I(l,h)}o=n("<li/>",{html:n("<a/>",{href:"javascript:;123","data-group":i,html:function(){v=e.group&&a.source[e.group].template||a.template;if(v){c=a.source[e.group]&&a.source[e.group].display||a.display;u=v.replace(/\{\{([a-z0-9_\-]+)\}\}/gi,function(t,n,r){if(n===c){return l}return e[n]||"null"})}else{u='<span class="'+a.selector.display+'">'+l+"</span>"+(s?"<small>"+s+"</small>":"")}n(this).append(u)},click:({result:e},function(t){t.preventDefault();f=e.display;r.val(f).focus();L();d=e;R(a.callback.onClick,[r,this,e,t])}),mouseenter:function(t){n(this).closest("li").siblings("li.active").removeClass("active");n(this).closest("li").addClass("active");R(a.callback.onMouseEnter,[r,this,e,t])},mouseleave:function(t){n(this).closest("li").removeClass("active");R(a.callback.onMouseLeave,[r,this,e,t])}})});if(a.group){p=n(t).find('a[data-group="'+i+'"]:last').closest("li");if(!p[0]){p=n(t).find('li[data-search-group="'+i+'"]')}n(o).insertAfter(p)}else{n(t).append(o)}})(p[e],this)}}})});m.addClass("result").append(e);if(a.backdrop){if(g.container){g.container.show()}else{g.css=n.extend({opacity:.6,filter:"alpha(opacity=60)",position:"fixed",top:0,right:0,bottom:0,left:0,"z-index":1040,"background-color":"#000"},a.backdrop);g.container=n("<div/>",{"class":a.selector.backdrop,css:g.css,click:function(){L()}}).insertAfter(m)}m.addClass("backdrop").css({"z-index":g.css["z-index"]+1,position:"relative"})}if(a.hint){if(!y.container){y.css=n.extend({"border-color":"transparent",position:"absolute","z-index":1,"-webkit-text-fill-color":"silver",color:"silver","background-color":"transparent","user-select":"none","box-shadow":"none"},a.hint);y.container=r.clone(true).attr({"class":a.selector.hint,readonly:true,tabindex:-1}).removeAttr("id placeholder name").css(y.css).insertBefore(r);r.css({position:"relative","z-index":2,"background-color":"transparent"}).parent().css({position:"relative"})}var t,i=typeof a.group==="string"&&p[0][a.group]||p[0].group;for(var s in p){if(!p.hasOwnProperty(s)){continue}if(p[s].group!==i){if(!t){i=p[s].group}else{break}}if(p[s].display.toLowerCase().indexOf(f.toLowerCase())===0){t=p[s].display;break}}if(t){y.container.val(f+t.substring(f.length)).show()}}return true}function k(e){if(p.length===0&&e.keyCode!==13){return false}var t=m.find("."+a.selector.result).find("li:not([data-search-group])"),i=t.siblings(".active");if(e.keyCode===13){if(t.filter(".active")[0]){e.preventDefault();e.stopPropagation();t.filter(".active").find("a").click()}L()}else{e.preventDefault();if(t.length>1){i.removeClass("active")}if(e.keyCode===40){if(i[0]){i.next().addClass("active")}else{n(t[0]).toggleClass("active")}}else if(e.keyCode===38){if(i[0]){i.prev().addClass("active")}else{n(t[p.length-1]).toggleClass("active")}}else if(e.keyCode===39){if(a.hint&&!i[0]){r.val(y.container.val())}if(i[0]){i.find("a").click()}else{t.filter(".active").find("a").click()}f=r.val();L();return true}if(a.group){var s=t.siblings(".active");if(s.attr("data-search-group")){s.removeClass("active");if(e.keyCode===40){s.next().addClass("active")}else if(e.keyCode===38){s.prev().addClass("active")}}}}if(a.hint){if(t.filter(".active")[0]){y.container.hide()}else{y.container.show()}}r.val(t.filter(".active").find("."+a.selector.display).text()||f);return true}function L(){p=[];if(a.filter){m.removeClass("filter").find("."+a.selector.dropdown.replace(" ",".")).hide()}if(a.hint){m.removeClass("hint");if(y.container){y.container.val("")}}if(a.backdrop||f===""){m.removeClass("backdrop").removeAttr("style");if(g.container){g.container.hide()}}m.removeClass("result").find("."+a.selector.result).remove();R(a.callback.onResult,[r,"",[],0])}function A(){l=false;b=(new Date).getTime();if(S===0){for(var t in a.source){if(a.source.hasOwnProperty(t)){++S}}}var i;for(var s in a.source){if(!a.source.hasOwnProperty(s)){continue}if(!a.dynamic&&h[s]&&h[s].length!==0){H();continue}if(a.cache){h[s]=localStorage.getItem(r.selector+":"+s);if(h[s]){if(a.compression){h[s]=W(h[s])}i=JSON.parse(h[s]);if(i&&i.data&&i.ttl&&i.ttl>(new Date).getTime()){h[s]=i.data;H();continue}}}if(!a.source[s].data&&!a.source[s].url){if(typeof a.source[s]==="string"||a.source[s]instanceof Array){a.source[s]={url:a.source[s]}}else{}}h[s]=[];if(a.source[s].data&&a.source[s].data instanceof Array){for(var o in a.source[s].data){if(!a.source[s].data.hasOwnProperty(o)){continue}if(a.source[s].data[o]instanceof Object){break}var u={};u[a.display]=a.source[s].data[o];a.source[s].data[o]=u}h[s]=h[s].concat(a.source[s].data);if(!a.source[s].url){D(s);H();continue}}if(a.source[s].url){var c=a.source[s].url instanceof Array&&a.source[s].url[0]||a.source[s].url,p=a.source[s].url instanceof Array&&a.source[s].url[1]||null,d={};if(typeof c==="object"){d=n.extend(true,{},c);c=JSON.stringify(c)}var v=P.get(c);if(/https?:\/\//.test(c)&&!~c.indexOf(e.location.host)&&!!~c.indexOf("{callback}")){U.fetch(c.replace("{callback}",encodeURIComponent(w)),function(e){})}else{if(typeof v==="undefined"){P.set(c,[])}else if(v instanceof Array&&v.length===0){P.queue(c,s,p);continue}else{_(v,s,p);H();continue}if(d&&d.data){for(var m in d.data){if(d.data[m]==="{{query}}"){d.data[m]=f;break}}}n.ajax(n.extend({async:true,url:c,dataType:"json",ajaxGroup:s,ajaxPath:p,ajaxTimestamp:b},d)).done(function(e){if(this.ajaxTimestamp!==b){return false}if(typeof this.process==="function"){e=this.process(e)}P.set(c,e);P.processQueue(c);_(e,this.ajaxGroup,this.ajaxPath)}).fail(function(){}).complete(function(){if(this.ajaxTimestamp===b){H()}})}}}}function O(){function e(e){v=e;m.find("."+a.selector.filterValue).text(v||a.filter);m.find("."+a.selector.dropdown.replace(" ",".")).hide();L();N();C();r.focus()}if(!a.filter){return false}n("<span/>",{"class":a.selector.filter,html:function(){n(this).append(n("<button/>",{type:"button","class":a.selector.filterButton,html:"<span class='"+a.selector.filterValue+"'>"+a.filter+"</span> <span class='caret'></span>",click:function(e){e.stopPropagation();var t=m.find("."+a.selector.dropdown.replace(" ","."));if(!t.is(":visible")){m.addClass("filter");t.show()}else{m.removeClass("filter");t.hide()}}}));n(this).append(n("<ul/>",{"class":a.selector.dropdown,html:function(){for(var t in a.source){if(!a.source.hasOwnProperty(t)){continue}(function(t,r){var i=n("<li/>",{html:n("<a/>",{href:"javascript:;",html:t,click:({i:t},function(n){n.preventDefault();e(t)})})});n(r).append(i)})(t,this)}n(this).append(n("<li/>",{"class":"divider"}));n(this).append(n("<li/>",{html:n("<a/>",{href:"javascript:;",html:a.filter,click:function(t){t.preventDefault();e()}})}))}}))}}).insertAfter(m.find("."+a.selector.query))}function M(e){if(!e||!e.group){return false}var t=e.group||"group",n=a.source[t].url instanceof Array?a.source[t].url[1]:null;_(e,t,n);H()}function H(){E++;if(E===S){l=true;c=[];if(a.dynamic){r.trigger("dynamic.typeahead.input")}}}var f="",l=null,c=[],h=[],p=[],d=null,v,m,g={},y={},b=null,w="window.Typeahead.source['"+r.selector+"'].populate",E=0,S=0;var _=function(e,t,n){var r=true;if(n){var i=n.split("."),s=0;while(s<i.length){if(typeof e!=="undefined"){e=e[i[s++]]}else{r=false;break}}}if(r){for(var o in e){if(!e.hasOwnProperty(o)){continue}if(e[o]instanceof Object){break}var u={};u[a.display]=e[o];e[o]=u}h[t]=h[t].concat(e);D(t)}};var D=function(e){if(!a.cache){return false}var t={ttl:(new Date).getTime()+a.ttl,data:h[e]};t=JSON.stringify(t);if(a.compression){t=z(t)}localStorage.setItem(r.selector+":"+e,t)};var P={_queue:[],get:function(e){return c[e]},set:function(e,t){c[e]=t},queue:function(e,t,n){this._queue.push({url:e,group:t,path:n})},processQueue:function(e){for(var t in this._queue){if(this._queue[t].url!==e){continue}_(c[e],this._queue[t].group,this._queue[t].path);H();delete this._queue[t]}}};var B=function(e,t,n){var r=n?function(t){return n(t[e])}:function(t){return t[e]};t=[-1,1][+!!t];return function(e,n){return e=r(e),n=r(n),t*((e>n)-(n>e))}};var j=function(e){if(!e||typeof e!=="string"){return false}e=e.toLowerCase();for(var t=0,n=u.from.length;t<n;t++){e=e.replace(new RegExp(u.from.charAt(t),"g"),u.to.charAt(t))}return e};var F=function(e,t,n,r){return e.substring(0,t)+r+e.substring(t+n)};var I=function(e,t){var n=e.indexOf(t);if(n===-1){return e}return F(e,n,t.length,"<strong>"+e.substr(n,t.length)+"</strong>")};var q=function(){var e=0;return function(t,n){clearTimeout(e);e=setTimeout(t,n)}}();var R=function(t,r){if(!t){return false}var i;if(typeof t==="function"){i=t}else if(typeof t==="string"||t instanceof Array){i=e;if(typeof t==="string"){t=[t,[]]}var s=t[0].split("."),o=t[1],u=true,a=0;while(a<s.length){if(typeof i!=="undefined"){i=i[s[a++]]}else{u=false;break}}if(!u||typeof i!=="function"){return false}}i.apply(this,n.merge(o||[],r?r:[]));return true};var U={fetch:function(n,r){var i=encodeURIComponent(w);e[i]=this.evalJSONP(r);n=n.replace("="+w,"="+i);var s=t.createElement("SCRIPT");s.src=n;t.getElementsByTagName("HEAD")[0].appendChild(s)},evalJSONP:function(e){return function(t){var n=false;if(typeof t==="string"){try{n=JSON.parse(t)}catch(r){}}else{n=JSON.parse(JSON.stringify(t))}if(n){e(n)}else{throw"JSONP call returned invalid or empty JSON"}}}};var z=function(e){var t={},n=(e+"").split(""),r=[],i,s=n[0],o=256;for(var u=1;u<n.length;u++){i=n[u];if(t[s+i]!=null){s+=i}else{r.push(s.length>1?t[s]:s.charCodeAt(0));t[s+i]=o;o++;s=i}}r.push(s.length>1?t[s]:s.charCodeAt(0));for(var u=0;u<r.length;u++){r[u]=String.fromCharCode(r[u])}return r.join("")};var W=function(e){var t={},n=(e+"").split(""),r=n[0],i=r,s=[r],o=256,u;for(var a=1;a<n.length;a++){var f=n[a].charCodeAt(0);if(f<256){u=n[a]}else{u=t[f]?t[f]:i+r}s.push(u);r=u.charAt(0);t[o]=i+r;o++;i=u}return s.join("")};this.__construct=function(){x();T();O()}();return{populate:M}};n.fn.typeahead=n.typeahead=function(e){return f.typeahead(this,e)};var f={typeahead:function(t,r){if(!r||!r.source){return}if(typeof t==="function"){if(!r.input){return}t=n(r.input);if(!t[0]||t.length>1){return}}else if(typeof t[0]==="undefined"||t.length>1){return}return e.Typeahead.source[t.selector]=new a(t,r)}};if(!Array.prototype.indexOf){Array.prototype.indexOf=function(e){var t=this.length>>>0;var n=Number(arguments[1])||0;n=n<0?Math.ceil(n):Math.floor(n);if(n<0)n+=t;for(;n<t;n++){if(n in this&&this[n]===e)return n}return-1}}})(window,document,window.jQuery)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment