@dylmye/mui-google-places-autocomplete
Version:
Google places autocomplete input for MUI library in React.
17 lines (14 loc) • 10.7 kB
JavaScript
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("@mui/material");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=n(e);
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */function r(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}function i(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}l((o=o.apply(e,t||[])).next())}))}var s=function e(t,n){if(t===n)return!0;if(t&&n&&"object"==typeof t&&"object"==typeof n){if(t.constructor!==n.constructor)return!1;var o,r,i;if(Array.isArray(t)){if((o=t.length)!=n.length)return!1;for(r=o;0!=r--;)if(!e(t[r],n[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if((o=(i=Object.keys(t)).length)!==Object.keys(n).length)return!1;for(r=o;0!=r--;)if(!Object.prototype.hasOwnProperty.call(n,i[r]))return!1;for(r=o;0!=r--;){var s=i[r];if(!e(t[s],n[s]))return!1}return!0}return t!=t&&n!=n};var a;!function(e){e[e.INITIALIZED=0]="INITIALIZED",e[e.LOADING=1]="LOADING",e[e.SUCCESS=2]="SUCCESS",e[e.FAILURE=3]="FAILURE"}(a||(a={}));class l{constructor({apiKey:e,channel:t,client:n,id:o="__googleMapsScriptId",libraries:r=[],language:i,region:a,version:c,mapIds:u,nonce:d,retries:p=3,url:g="https://maps.googleapis.com/maps/api/js"}){if(this.CALLBACK="__googleMapsCallback",this.callbacks=[],this.done=!1,this.loading=!1,this.errors=[],this.version=c,this.apiKey=e,this.channel=t,this.client=n,this.id=o||"__googleMapsScriptId",this.libraries=r,this.language=i,this.region=a,this.mapIds=u,this.nonce=d,this.retries=p,this.url=g,l.instance){if(!s(this.options,l.instance.options))throw new Error(`Loader must not be called again with different options. ${JSON.stringify(this.options)} !== ${JSON.stringify(l.instance.options)}`);return l.instance}l.instance=this}get options(){return{version:this.version,apiKey:this.apiKey,channel:this.channel,client:this.client,id:this.id,libraries:this.libraries,language:this.language,region:this.region,mapIds:this.mapIds,nonce:this.nonce,url:this.url}}get status(){return this.errors.length?a.FAILURE:this.done?a.SUCCESS:this.loading?a.LOADING:a.INITIALIZED}get failed(){return this.done&&!this.loading&&this.errors.length>=this.retries+1}createUrl(){let e=this.url;return e+=`?callback=${this.CALLBACK}`,this.apiKey&&(e+=`&key=${this.apiKey}`),this.channel&&(e+=`&channel=${this.channel}`),this.client&&(e+=`&client=${this.client}`),this.libraries.length>0&&(e+=`&libraries=${this.libraries.join(",")}`),this.language&&(e+=`&language=${this.language}`),this.region&&(e+=`®ion=${this.region}`),this.version&&(e+=`&v=${this.version}`),this.mapIds&&(e+=`&map_ids=${this.mapIds.join(",")}`),e}deleteScript(){const e=document.getElementById(this.id);e&&e.remove()}load(){return this.loadPromise()}loadPromise(){return new Promise(((e,t)=>{this.loadCallback((n=>{n?t(n.error):e(window.google)}))}))}loadCallback(e){this.callbacks.push(e),this.execute()}setScript(){if(document.getElementById(this.id))return void this.callback();const e=this.createUrl(),t=document.createElement("script");t.id=this.id,t.type="text/javascript",t.src=e,t.onerror=this.loadErrorCallback.bind(this),t.defer=!0,t.async=!0,this.nonce&&(t.nonce=this.nonce),document.head.appendChild(t)}reset(){this.deleteScript(),this.done=!1,this.loading=!1,this.errors=[],this.onerrorEvent=null}resetIfRetryingFailed(){this.failed&&this.reset()}loadErrorCallback(e){if(this.errors.push(e),this.errors.length<=this.retries){const e=this.errors.length*Math.pow(2,this.errors.length);console.log(`Failed to load Google Maps script, retrying in ${e} ms.`),setTimeout((()=>{this.deleteScript(),this.setScript()}),e)}else this.onerrorEvent=e,this.callback()}setCallback(){window.__googleMapsCallback=this.callback.bind(this)}callback(){this.done=!0,this.loading=!1,this.callbacks.forEach((e=>{e(this.onerrorEvent)})),this.callbacks=[]}execute(){if(this.resetIfRetryingFailed(),this.done)this.callback();else{if(window.google&&window.google.maps&&window.google.maps.version)return console.warn("Google Maps already loaded outside @googlemaps/js-api-loader.This may result in undesirable behavior as options and script parameters may not match."),void this.callback();this.loading||(this.loading=!0,this.setCallback(),this.setScript())}}}var c=e.forwardRef(((n,s)=>{var{inputValue:a,setInputValue:c,value:u,setValue:d,apiKey:p="",apiOptions:g={},autocompletionRequest:h={},debounce:f=300,minLengthAutocomplete:m=0,onLoadFailed:b=console.error,withSessionToken:w=!1,label:y,inputProps:v={}}=n,O=r(n,["inputValue","setInputValue","value","setValue","apiKey","apiOptions","autocompletionRequest","debounce","minLengthAutocomplete","onLoadFailed","withSessionToken","label","inputProps"]);const[S,I]=e.useState(void 0),[E,k]=e.useState(void 0),[x,L]=e.useState([]),[j,C]=e.useState(!1),[A,_]=e.useState(null),[T]=function(t,n,o){void 0===o&&(o={});var r=o.maxWait,i=e.useRef(null),s=e.useRef([]),a=o.leading,l=void 0===o.trailing||o.trailing,c=e.useRef(!1),u=e.useRef(null),d=e.useRef(!1),p=e.useRef(t);p.current=t;var g=e.useCallback((function(){clearTimeout(u.current),clearTimeout(i.current),i.current=null,s.current=[],u.current=null,c.current=!1}),[]);e.useEffect((function(){return d.current=!1,function(){d.current=!0}}),[]);var h=e.useCallback((function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];s.current=e,clearTimeout(u.current),c.current&&(c.current=!1),u.current||!a||c.current||(p.current.apply(p,e),c.current=!0),u.current=setTimeout((function(){var t=!0;a&&c.current&&(t=!1),g(),!d.current&&l&&t&&p.current.apply(p,e)}),n),r&&!i.current&&l&&(i.current=setTimeout((function(){var e=s.current;g(),d.current||p.current.apply(null,e)}),r))}),[r,n,g,a,l]),f=e.useCallback((function(){u.current&&(p.current.apply(null,s.current),g())}),[g]);return[h,g,f]}(((e,t)=>{if(!S||e.length<m)return t([]);C(!0);const n=Object.assign({},h);S.getPlacePredictions(((e,t,n)=>{const{bounds:o,location:i}=e,s=r(e,["bounds","location"]),a=Object.assign({input:t},s);return n&&(a.sessionToken=n),o&&(a.bounds=new google.maps.LatLngBounds(...o)),i&&(a.location=new google.maps.LatLng(i)),a})(n,e,w&&E),(e=>{t(e||[]),C(!1)}))}),f),P=()=>{if(!window.google)throw new Error("[mui-google-places-autocomplete]: Google script not loaded");if(!window.google.maps)throw new Error("[mui-google-places-autocomplete]: Google maps script not loaded");if(!window.google.maps.places)throw new Error("[mui-google-places-autocomplete]: Google maps places script not loaded");I(new window.google.maps.places.AutocompleteService),k(new google.maps.places.AutocompleteSessionToken)};return e.useImperativeHandle(s,(()=>({getSessionToken:()=>E,refreshSessionToken:()=>{k(new google.maps.places.AutocompleteSessionToken)}})),[E]),e.useEffect((()=>{p?i(void 0,void 0,void 0,(function*(){try{window.google&&window.google.maps&&window.google.maps.places||(yield new l(Object.assign({apiKey:p},Object.assign({libraries:["places"]},g))).load()),P()}catch(e){b(e)}})):P()}),[]),e.useEffect((()=>{S&&T(a,L)}),[a]),o.default.createElement(t.Autocomplete,Object.assign({autoComplete:!0,includeInputInList:!0,filterSelectedOptions:!0,noOptionsText:"Nothing found",onChange:(e,t)=>{t&&L([t,...x]),d?d(t):_(t)},onInputChange:(e,t)=>{c(t)},loading:j},O,{options:x,value:null!=u?u:A,renderInput:e=>o.default.createElement(t.TextField,Object.assign({},e,v,{label:y,fullWidth:!0})),renderOption:(e,n)=>{const r=[{text:n.structured_formatting.main_text}];return o.default.createElement("li",Object.assign({},e),o.default.createElement(t.Grid,{container:!0,alignItems:"center"},o.default.createElement(t.Grid,{item:!0,sx:{width:"calc(100%)",wordWrap:"break-word"}},r.map(((e,n)=>o.default.createElement(t.Box,{key:n,component:"span"},e.text))),o.default.createElement(t.Typography,{variant:"body2",color:"text.secondary"},n.structured_formatting.secondary_text))))},getOptionLabel:e=>"string"==typeof e?e:e.description,isOptionEqualToValue:(e,t)=>!!t&&e.description===(null==t?void 0:t.description)}))}));exports.GooglePlacesAutocompleteField=t=>{var{field:n,form:{setFieldValue:i,isSubmitting:s}}=t,a=r(t,["field","form"]);const[l,u]=e.useState((null==n?void 0:n.value)?{description:n.value,matched_substrings:[],place_id:"",structured_formatting:{main_text:"",main_text_matched_substrings:[],secondary_text:""},terms:[],types:[]}:null);return o.default.createElement(c,Object.assign({inputValue:n.value,setInputValue:e=>i(n.name,e),value:null!=l?l:null,setValue:e=>u(null!=e?e:null),disabled:s},a))},exports.default=c,exports.geocodeByAddress=e=>{const t=new window.google.maps.Geocoder,{OK:n}=window.google.maps.GeocoderStatus;return new Promise(((o,r)=>{t.geocode({address:e},((e,t)=>t!==n?r(t):o(e)))}))},exports.geocodeByLatLng=e=>{const t=new window.google.maps.Geocoder,{OK:n}=window.google.maps.GeocoderStatus;return new Promise(((o,r)=>{t.geocode({location:e},((e,t)=>t!==n?r(t):o(e)))}))},exports.geocodeByPlaceId=e=>{const t=new window.google.maps.Geocoder,{OK:n}=window.google.maps.GeocoderStatus;return new Promise(((o,r)=>{t.geocode({placeId:e},((e,t)=>t!==n?r(t):o(e)))}))},exports.getLatLng=e=>new Promise(((t,n)=>{try{return t({lat:e.geometry.location.lat(),lng:e.geometry.location.lng()})}catch(e){return n(e)}}));
//# sourceMappingURL=index.js.map