This repository has been archived by the owner on May 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaddycomplete.min.js
12 lines (10 loc) · 19.6 KB
/
addycomplete.min.js
1
2
3
4
5
6
7
8
9
10
11
12
// Awesomplete - Lea Verou - MIT license
!function(){function t(t){var e=Array.isArray(t)?{label:t[0],value:t[1]}:"object"==typeof t&&"label"in t&&"value"in t?t:{label:t,value:t};this.label=e.label||e.value,this.value=e.value}function e(t,e,i){for(var n in e){var s=e[n],r=t.input.getAttribute("data-"+n.toLowerCase());"number"==typeof s?t[n]=parseInt(r):!1===s?t[n]=null!==r:s instanceof Function?t[n]=null:t[n]=r,t[n]||0===t[n]||(t[n]=n in i?i[n]:s)}}function i(t,e){return"string"==typeof t?(e||document).querySelector(t):t||null}function n(t,e){return o.call((e||document).querySelectorAll(t))}function s(){n("input.awesomplete").forEach(function(t){new r(t)})}var r=function(t,n){var s=this;this.isOpened=!1,this.input=i(t),this.input.setAttribute("autocomplete","off"),this.input.setAttribute("aria-autocomplete","list"),n=n||{},e(this,{minChars:2,maxItems:10,autoFirst:!1,data:r.DATA,filter:r.FILTER_CONTAINS,sort:!1!==n.sort&&r.SORT_BYLENGTH,item:r.ITEM,replace:r.REPLACE},n),this.index=-1,this.container=i.create("div",{className:"awesomplete",around:t}),this.ul=i.create("ul",{hidden:"hidden",inside:this.container}),this.status=i.create("span",{className:"visually-hidden",role:"status","aria-live":"assertive","aria-relevant":"additions",inside:this.container}),this._events={input:{input:this.evaluate.bind(this),blur:this.close.bind(this,{reason:"blur"}),keydown:function(t){var e=t.keyCode;s.opened&&(13===e&&s.selected?(t.preventDefault(),s.select()):27===e?s.close({reason:"esc"}):38!==e&&40!==e||(t.preventDefault(),s[38===e?"previous":"next"]()))}},form:{submit:this.close.bind(this,{reason:"submit"})},ul:{mousedown:function(t){var e=t.target;if(e!==this){for(;e&&!/li/i.test(e.nodeName);)e=e.parentNode;e&&0===t.button&&(t.preventDefault(),s.select(e,t.target))}}}},i.bind(this.input,this._events.input),i.bind(this.input.form,this._events.form),i.bind(this.ul,this._events.ul),this.input.hasAttribute("list")?(this.list="#"+this.input.getAttribute("list"),this.input.removeAttribute("list")):this.list=this.input.getAttribute("data-list")||n.list||[],r.all.push(this)};r.prototype={set list(t){if(Array.isArray(t))this._list=t;else if("string"==typeof t&&t.indexOf(",")>-1)this._list=t.split(/\s*,\s*/);else if((t=i(t))&&t.children){var e=[];o.apply(t.children).forEach(function(t){if(!t.disabled){var i=t.textContent.trim(),n=t.value||i,s=t.label||i;""!==n&&e.push({label:s,value:n})}}),this._list=e}document.activeElement===this.input&&this.evaluate()},get selected(){return this.index>-1},get opened(){return this.isOpened},close:function(t){this.opened&&(this.ul.setAttribute("hidden",""),this.isOpened=!1,this.index=-1,i.fire(this.input,"awesomplete-close",t||{}))},open:function(){this.ul.removeAttribute("hidden"),this.isOpened=!0,this.autoFirst&&-1===this.index&&this["goto"](0),i.fire(this.input,"awesomplete-open")},destroy:function(){i.unbind(this.input,this._events.input),i.unbind(this.input.form,this._events.form);var t=this.container.parentNode;t.insertBefore(this.input,this.container),t.removeChild(this.container),this.input.removeAttribute("autocomplete"),this.input.removeAttribute("aria-autocomplete");var e=r.all.indexOf(this);-1!==e&&r.all.splice(e,1)},next:function(){var t=this.ul.children.length;this["goto"](this.index<t-1?this.index+1:t?0:-1)},previous:function(){var t=this.ul.children.length,e=this.index-1;this["goto"](this.selected&&-1!==e?e:t-1)},"goto":function(t){var e=this.ul.children;this.selected&&e[this.index].setAttribute("aria-selected","false"),this.index=t,t>-1&&e.length>0&&(e[t].setAttribute("aria-selected","true"),this.status.textContent=e[t].textContent,this.ul.scrollTop=e[t].offsetTop-this.ul.clientHeight+e[t].clientHeight,i.fire(this.input,"awesomplete-highlight",{text:this.suggestions[this.index]}))},select:function(t,e){if(t?this.index=i.siblingIndex(t):t=this.ul.children[this.index],t){var n=this.suggestions[this.index];i.fire(this.input,"awesomplete-select",{text:n,origin:e||t})&&(this.replace(n),this.close({reason:"select"}),i.fire(this.input,"awesomplete-selectcomplete",{text:n}))}},evaluate:function(){var e=this,i=this.input.value;i.length>=this.minChars&&this._list.length>0?(this.index=-1,this.ul.innerHTML="",this.suggestions=this._list.map(function(n){return new t(e.data(n,i))}).filter(function(t){return e.filter(t,i)}),!1!==this.sort&&(this.suggestions=this.suggestions.sort(this.sort)),this.suggestions=this.suggestions.slice(0,this.maxItems),this.suggestions.forEach(function(t){e.ul.appendChild(e.item(t,i))}),0===this.ul.children.length?this.close({reason:"nomatches"}):this.open()):this.close({reason:"nomatches"})}},r.all=[],r.FILTER_CONTAINS=function(t,e){return RegExp(i.regExpEscape(e.trim()),"i").test(t)},r.FILTER_STARTSWITH=function(t,e){return RegExp("^"+i.regExpEscape(e.trim()),"i").test(t)},r.SORT_BYLENGTH=function(t,e){return t.length!==e.length?t.length-e.length:e>t?-1:1},r.ITEM=function(t,e){return i.create("li",{innerHTML:""===e.trim()?t:t.replace(RegExp(i.regExpEscape(e.trim()),"gi"),"<mark>$&</mark>"),"aria-selected":"false"})},r.REPLACE=function(t){this.input.value=t.value},r.DATA=function(t){return t},Object.defineProperty(t.prototype=Object.create(String.prototype),"length",{get:function(){return this.label.length}}),t.prototype.toString=t.prototype.valueOf=function(){return""+this.label};var o=Array.prototype.slice;i.create=function(t,e){var n=document.createElement(t);for(var s in e){var r=e[s];if("inside"===s)i(r).appendChild(n);else if("around"===s){var o=i(r);o.parentNode.insertBefore(n,o),n.appendChild(o)}else s in n?n[s]=r:n.setAttribute(s,r)}return n},i.bind=function(t,e){if(t)for(var i in e){var n=e[i];i.split(/\s+/).forEach(function(e){t.addEventListener(e,n)})}},i.unbind=function(t,e){if(t)for(var i in e){var n=e[i];i.split(/\s+/).forEach(function(e){t.removeEventListener(e,n)})}},i.fire=function(t,e,i){var n=document.createEvent("HTMLEvents");n.initEvent(e,!0,!0);for(var s in i)n[s]=i[s];return t.dispatchEvent(n)},i.regExpEscape=function(t){return t.replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&")},i.siblingIndex=function(t){for(var e=0;t=t.previousElementSibling;e++);return e},"undefined"!=typeof Document&&("loading"!==document.readyState?s():document.addEventListener("DOMContentLoaded",s)),r.$=i,r.$$=n,"undefined"!=typeof self&&(self.Awesomplete=r),"object"==typeof module&&module.exports&&(module.exports=r)}();
/*!
* Reqwest! A general purpose XHR connection manager
* license MIT (c) Dustin Diaz 2015
* https://github.com/ded/reqwest
*/
!function(e,t,r){"undefined"!=typeof module&&module.exports?module.exports=r():"function"==typeof define&&define.amd?define(r):t[e]=r()}("reqwest",this,function(){function succeed(e){var t=protocolRe.exec(e.url);return t=t&&t[1]||context.location.protocol,httpsRe.test(t)?twoHundo.test(e.request.status):!!e.request.response}function handleReadyState(e,t,r){return function(){return e._aborted?r(e.request):e._timedOut?r(e.request,"Request is aborted: timeout"):void(e.request&&4==e.request[readyState]&&(e.request.onreadystatechange=noop,succeed(e)?t(e.request):r(e.request)))}}function setHeaders(e,t){var r,s=t.headers||{};s.Accept=s.Accept||defaultHeaders.accept[t.type]||defaultHeaders.accept["*"];var n="undefined"!=typeof FormData&&t.data instanceof FormData;!t.crossOrigin&&!s[requestedWith]&&(s[requestedWith]=defaultHeaders.requestedWith),!s[contentType]&&!n&&(s[contentType]=t.contentType||defaultHeaders.contentType);for(r in s)s.hasOwnProperty(r)&&"setRequestHeader"in e&&e.setRequestHeader(r,s[r])}function setCredentials(e,t){"undefined"!=typeof t.withCredentials&&"undefined"!=typeof e.withCredentials&&(e.withCredentials=!!t.withCredentials)}function generalCallback(e){lastValue=e}function urlappend(e,t){return e+(/\?/.test(e)?"&":"?")+t}function handleJsonp(e,t,r,s){var n=uniqid++,a=e.jsonpCallback||"callback",o=e.jsonpCallbackName||reqwest.getcallbackPrefix(n),i=new RegExp("((^|\\?|&)"+a+")=([^&]+)"),l=s.match(i),u=doc.createElement("script"),p=0,c=-1!==navigator.userAgent.indexOf("MSIE 10.0");return l?"?"===l[3]?s=s.replace(i,"$1="+o):o=l[3]:s=urlappend(s,a+"="+o),context[o]=generalCallback,u.type="text/javascript",u.src=s,u.async=!0,"undefined"!=typeof u.onreadystatechange&&!c&&(u.htmlFor=u.id="_reqwest_"+n),u.onload=u.onreadystatechange=function(){return u[readyState]&&"complete"!==u[readyState]&&"loaded"!==u[readyState]||p?!1:(u.onload=u.onreadystatechange=null,u.onclick&&u.onclick(),t(lastValue),lastValue=void 0,head.removeChild(u),p=1,void 0)},head.appendChild(u),{abort:function(){u.onload=u.onreadystatechange=null,r({},"Request is aborted: timeout",{}),lastValue=void 0,head.removeChild(u),p=1}}}function getRequest(e,t){var r,s=this.o,n=(s.method||"GET").toUpperCase(),a="string"==typeof s?s:s.url,o=s.processData!==!1&&s.data&&"string"!=typeof s.data?reqwest.toQueryString(s.data):s.data||null,i=!1;return("jsonp"==s.type||"GET"==n)&&o&&(a=urlappend(a,o),o=null),"jsonp"==s.type?handleJsonp(s,e,t,a):(r=s.xhr&&s.xhr(s)||xhr(s),r.open(n,a,s.async===!1?!1:!0),setHeaders(r,s),setCredentials(r,s),context[xDomainRequest]&&r instanceof context[xDomainRequest]?(r.onload=e,r.onerror=t,r.onprogress=function(){},i=!0):r.onreadystatechange=handleReadyState(this,e,t),s.before&&s.before(r),i?setTimeout(function(){r.send(o)},200):r.send(o),r)}function Reqwest(e,t){this.o=e,this.fn=t,init.apply(this,arguments)}function setType(e){return null===e?void 0:e.match("json")?"json":e.match("javascript")?"js":e.match("text")?"html":e.match("xml")?"xml":void 0}function init(o,fn){function complete(e){for(o.timeout&&clearTimeout(self.timeout),self.timeout=null;self._completeHandlers.length>0;)self._completeHandlers.shift()(e)}function success(resp){var type=o.type||resp&&setType(resp.getResponseHeader("Content-Type"));resp="jsonp"!==type?self.request:resp;var filteredResponse=globalSetupOptions.dataFilter(resp.responseText,type),r=filteredResponse;try{resp.responseText=r}catch(e){}if(r)switch(type){case"json":try{resp=context.JSON?context.JSON.parse(r):eval("("+r+")")}catch(err){return error(resp,"Could not parse JSON in response",err)}break;case"js":resp=eval(r);break;case"html":resp=r;break;case"xml":resp=resp.responseXML&&resp.responseXML.parseError&&resp.responseXML.parseError.errorCode&&resp.responseXML.parseError.reason?null:resp.responseXML}for(self._responseArgs.resp=resp,self._fulfilled=!0,fn(resp),self._successHandler(resp);self._fulfillmentHandlers.length>0;)resp=self._fulfillmentHandlers.shift()(resp);complete(resp)}function timedOut(){self._timedOut=!0,self.request.abort()}function error(e,t,r){for(e=self.request,self._responseArgs.resp=e,self._responseArgs.msg=t,self._responseArgs.t=r,self._erred=!0;self._errorHandlers.length>0;)self._errorHandlers.shift()(e,t,r);complete(e)}this.url="string"==typeof o?o:o.url,this.timeout=null,this._fulfilled=!1,this._successHandler=function(){},this._fulfillmentHandlers=[],this._errorHandlers=[],this._completeHandlers=[],this._erred=!1,this._responseArgs={};var self=this;fn=fn||function(){},o.timeout&&(this.timeout=setTimeout(function(){timedOut()},o.timeout)),o.success&&(this._successHandler=function(){o.success.apply(o,arguments)}),o.error&&this._errorHandlers.push(function(){o.error.apply(o,arguments)}),o.complete&&this._completeHandlers.push(function(){o.complete.apply(o,arguments)}),this.request=getRequest.call(this,success,error)}function reqwest(e,t){return new Reqwest(e,t)}function normalize(e){return e?e.replace(/\r?\n/g,"\r\n"):""}function serial(e,t){var r,s,n,a,o=e.name,i=e.tagName.toLowerCase(),l=function(e){e&&!e.disabled&&t(o,normalize(e.attributes.value&&e.attributes.value.specified?e.value:e.text))};if(!e.disabled&&o)switch(i){case"input":/reset|button|image|file/i.test(e.type)||(r=/checkbox/i.test(e.type),s=/radio/i.test(e.type),n=e.value,(!r&&!s||e.checked)&&t(o,normalize(r&&""===n?"on":n)));break;case"textarea":t(o,normalize(e.value));break;case"select":if("select-one"===e.type.toLowerCase())l(e.selectedIndex>=0?e.options[e.selectedIndex]:null);else for(a=0;e.length&&a<e.length;a++)e.options[a].selected&&l(e.options[a])}}function eachFormElement(){var e,t,r=this,s=function(e,t){var s,n,a;for(s=0;s<t.length;s++)for(a=e[byTag](t[s]),n=0;n<a.length;n++)serial(a[n],r)};for(t=0;t<arguments.length;t++)e=arguments[t],/input|select|textarea/i.test(e.tagName)&&serial(e,r),s(e,["input","select","textarea"])}function serializeQueryString(){return reqwest.toQueryString(reqwest.serializeArray.apply(null,arguments))}function serializeHash(){var e={};return eachFormElement.apply(function(t,r){t in e?(e[t]&&!isArray(e[t])&&(e[t]=[e[t]]),e[t].push(r)):e[t]=r},arguments),e}function buildParams(e,t,r,s){var n,a,o,i=/\[\]$/;if(isArray(t))for(a=0;t&&a<t.length;a++)o=t[a],r||i.test(e)?s(e,o):buildParams(e+"["+("object"==typeof o?a:"")+"]",o,r,s);else if(t&&"[object Object]"===t.toString())for(n in t)buildParams(e+"["+n+"]",t[n],r,s);else s(e,t)}var context=this;if("window"in context)var doc=document,byTag="getElementsByTagName",head=doc[byTag]("head")[0];else{var XHR2;try{XHR2=require("xhr2")}catch(ex){throw new Error("Peer dependency `xhr2` required! Please npm install xhr2")}}var httpsRe=/^http/,protocolRe=/(^\w+):\/\//,twoHundo=/^(20\d|1223)$/,readyState="readyState",contentType="Content-Type",requestedWith="X-Requested-With",uniqid=0,callbackPrefix="reqwest_"+ +new Date,lastValue,xmlHttpRequest="XMLHttpRequest",xDomainRequest="XDomainRequest",noop=function(){},isArray="function"==typeof Array.isArray?Array.isArray:function(e){return e instanceof Array},defaultHeaders={contentType:"application/x-www-form-urlencoded",requestedWith:xmlHttpRequest,accept:{"*":"text/javascript, text/html, application/xml, text/xml, */*",xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript",js:"application/javascript, text/javascript"}},xhr=function(e){if(e.crossOrigin===!0){var t=context[xmlHttpRequest]?new XMLHttpRequest:null;if(t&&"withCredentials"in t)return t;if(context[xDomainRequest])return new XDomainRequest;throw new Error("Browser does not support cross-origin requests")}return context[xmlHttpRequest]?new XMLHttpRequest:XHR2?new XHR2:new ActiveXObject("Microsoft.XMLHTTP")},globalSetupOptions={dataFilter:function(e){return e}};return Reqwest.prototype={abort:function(){this._aborted=!0,this.request.abort()},retry:function(){init.call(this,this.o,this.fn)},then:function(e,t){return e=e||function(){},t=t||function(){},this._fulfilled?this._responseArgs.resp=e(this._responseArgs.resp):this._erred?t(this._responseArgs.resp,this._responseArgs.msg,this._responseArgs.t):(this._fulfillmentHandlers.push(e),this._errorHandlers.push(t)),this},always:function(e){return this._fulfilled||this._erred?e(this._responseArgs.resp):this._completeHandlers.push(e),this},fail:function(e){return this._erred?e(this._responseArgs.resp,this._responseArgs.msg,this._responseArgs.t):this._errorHandlers.push(e),this},"catch":function(e){return this.fail(e)}},reqwest.serializeArray=function(){var e=[];return eachFormElement.apply(function(t,r){e.push({name:t,value:r})},arguments),e},reqwest.serialize=function(){if(0===arguments.length)return"";var e,t,r=Array.prototype.slice.call(arguments,0);return e=r.pop(),e&&e.nodeType&&r.push(e)&&(e=null),e&&(e=e.type),t="map"==e?serializeHash:"array"==e?reqwest.serializeArray:serializeQueryString,t.apply(null,r)},reqwest.toQueryString=function(e,t){var r,s,n=t||!1,a=[],o=encodeURIComponent,i=function(e,t){t="function"==typeof t?t():null==t?"":t,a[a.length]=o(e)+"="+o(t)};if(isArray(e))for(s=0;e&&s<e.length;s++)i(e[s].name,e[s].value);else for(r in e)e.hasOwnProperty(r)&&buildParams(r,e[r],n,i);return a.join("&").replace(/%20/g,"+")},reqwest.getcallbackPrefix=function(){return callbackPrefix},reqwest.compat=function(e,t){return e&&(e.type&&(e.method=e.type)&&delete e.type,e.dataType&&(e.type=e.dataType),e.jsonpCallback&&(e.jsonpCallbackName=e.jsonpCallback)&&delete e.jsonpCallback,e.jsonp&&(e.jsonpCallback=e.jsonp)),new Reqwest(e,t)},reqwest.ajaxSetup=function(e){e=e||{};for(var t in e)globalSetupOptions[t]=e[t]},reqwest});
// AddyComplete v2.1.2 - https://www.addy.co.nz
function AddyUrlSettingFactory(e){function s(e){e=e.replace(/[\[\]]/g,"\\$&");var s=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)"),i=s.exec(n);return i?i[2]?decodeURIComponent(i[2].replace(/\+/g," ")):"":null}function i(){var s=document.getElementsByTagName("script");e=e.toLowerCase();for(var i=0;i<s.length;i++)if(s[i].src&&-1!==s[i].src.toLowerCase().indexOf(e))return s[i].src;return console.warn("Script source not found. Name: ",e),""}this.createOptions=function(){var e={};return e.ignoreKeys=[38,40,13],e.excludePostBox=s("excludePostBox")||!1,e.nzCountryValue=s("nzCountryValue")||"NZL",e},this.createConfig=function(){var e={};return e.key=s("key"),e.key&&""!=e.key||console.warn("The API key is missing"),e.maxItems=s("maxItems")||10,e.debounceMs=s("debounceMs")||250,e},this.createCallback=function(){var e=s("callback");return e&&"function"==typeof window[e]?e:null};var n=i(e)}function AddyComplete(e,s){function i(e,s){var i;return function(){var n=this,t=arguments,a=function(){i=null,e.apply(n,t)};clearTimeout(i),i=setTimeout(a,s),i||e.apply(n,t)}}function n(e,s){reqwest({url:e,type:"jsonp",success:function(e){s(e)}})}if(!e)return void console.warn("Input field is missing");var t=this;t.urlBase="https://www.addy.co.nz/",t.fields=s?s:{},t.options=addySettingsFactory.createOptions(),t.config=addySettingsFactory.createConfig(),t.awesomplete=new Awesomplete(e,{maxItems:t.config.maxItems,minChars:3,autoFirst:!0,sort:!1}),t.awesomplete.filter=function(){return!0},this.setAddress=function(e){t.fields.address&&(t.fields.address.value=e.displayline),t.fields.suburb&&(t.fields.suburb.value=e.suburb),t.fields.city&&(t.fields.city.value=e.city),t.fields.postcode&&(t.fields.postcode.value=e.postcode),t.fields.line1&&(t.fields.line1.value=e.address1),t.fields.line2&&(t.fields.line2.value=e.address2),t.fields.line3&&(t.fields.line3.value=e.address3),t.fields.line4&&(t.fields.line4.value=e.address4),!t.fields.city&&t.fields.suburb&&""===e.suburb&&""!==e.city&&(t.fields.suburb.value=e.city),t.fields.address1&&t.fields.address2?(e.address4||0===e.address2.indexOf("RD ")?(t.fields.address1.value=e.address1,t.fields.address2.value=e.address2):(t.fields.address1.value=e.displayline,t.fields.address2.value=""),!t.fields.suburb&&e.suburb&&""!==e.suburb&&(""!==t.fields.address2.value&&(t.fields.address1.value+=", "+t.fields.address2.value),t.fields.address2.value=e.suburb)):t.fields.address1&&!t.fields.address2&&(t.fields.address1.value=e.displayline);var s=t.fields.region;if(s)if(s.options){e.region=e.region.toUpperCase();var i=[e.region,e.region.replace("'",""),e.region.replace("-"," - "),e.region.replace("-"," / "),e.region.replace("-","/")];console.log(i);for(var n=0;n<s.options.length;n++)if(i.indexOf(s.options[n].text.toUpperCase())>-1||i.indexOf(s.options[n].value.toUpperCase())>-1){s.selectedIndex=n;break}}else s.value=e.region};var a=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var s=16*Math.random()|0,i="x"==e?s:3&s|8;return i.toString(16)})},d=a();e.onkeyup=i(function(e){return-1!==t.options.ignoreKeys.indexOf(e.keyCode)||this.value.length<t.awesomplete.minChars?void 0:t.fields.country&&this.fields.country.options[t.fields.country.selectedIndex].value!==t.options.nzCountryValue?void(t.awesomplete.list=[]):void n(t.urlBase+"api/search?key="+t.config.key+"&session="+d+"&expostbox="+t.options.excludePostBox+"&max="+t.awesomplete.maxItems+"&s="+this.value,function(e){t.awesomplete.list=e.addresses.map(function(e){return{label:e.a,value:e.id}})})},t.config.debounceMs),e.addEventListener("awesomplete-selectcomplete",function(e){n(t.urlBase+"api/address/"+e.text.value+"?key="+t.config.key+"&session="+d,function(e){this.setAddress(e)}.bind(this))}.bind(this),!1)}var addySettingsFactory=new AddyUrlSettingFactory("addycomplete"),addyInitCallback=addySettingsFactory.createCallback();addyInitCallback&&window[addyInitCallback]();