UNPKG

@shopgate/engage

Version:
20 lines 8.66 kB
import _isEqual from"lodash/isEqual";import _upperCase from"lodash/upperCase";import _camelCase from"lodash/camelCase";function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_nonIterableRest();}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance");}function _iterableToArrayLimit(arr,i){var _arr=[];var _n=true;var _d=false;var _e=undefined;try{for(var _i=arr[Symbol.iterator](),_s;!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"]!=null)_i["return"]();}finally{if(_d)throw _e;}}return _arr;}function _arrayWithHoles(arr){if(Array.isArray(arr))return arr;}import*as React from'react';import PropTypes from'prop-types';import classnames from'classnames';import{i18n}from'@shopgate/engage/core/helpers';import{parsePhoneNumber}from'react-phone-number-input';import PhoneInputCountrySelect from'react-phone-number-input/mobile';import PhoneInput from'react-phone-number-input/input-mobile';import{getCountries}from'react-phone-number-input/input';import en from'react-phone-number-input/locale/en';import de from'react-phone-number-input/locale/de';import es from'react-phone-number-input/locale/es';import fr from'react-phone-number-input/locale/fr';import pt from'react-phone-number-input/locale/pt';import flags from'react-phone-number-input/flags';import{useCountriesNames}from'@shopgate/engage/i18n';import{css}from'glamor';import{themeConfig}from'@shopgate/engage';import Label from'@shopgate/pwa-ui-shared/TextField/components/Label';import FormHelper from"./FormHelper";var variables=themeConfig.variables,colors=themeConfig.colors;var styles={formField:css({width:'100%',marginBottom:'0px !important'}).toString(),phoneField:css({position:'relative',width:'100%',paddingTop:variables.gap.big*0.75,paddingBottom:variables.gap.big*1.25,' input.PhoneInputInput':{outline:'none',fontSize:'1rem',lineHeight:'1.1875rem',borderRadius:0,paddingBottom:variables.gap.xsmall*1.5,borderBottom:"1px solid ".concat(colors.shade12),'&:focus':{borderBottom:"2px solid ".concat(colors.primary),paddingBottom:variables.gap.xsmall*1.5-1}}}),phoneFieldError:css({' input.PhoneInputInput':{borderBottom:"2px solid var(--color-state-alert, ".concat(colors.error,")"),paddingBottom:variables.gap.xsmall*1.5-1}}).toString(),phoneFieldErrorText:css({position:'absolute',width:'100%',bottom:'-10px',fontSize:'0.75rem',lineHeight:0.875,color:"var(--color-state-alert, ".concat(colors.error,")"),overflow:'hidden',whiteSpace:'nowrap',textOverflow:'ellipsis',marginLeft:'38px'})};var builtInCountries=getCountries();var locales={en:en,de:de,es:es,fr:fr,pt:pt};/** * Renders the reserve form phone input maybe with country selection. * @param {Object} props The component props. * @returns {JSX.Element} */var UnwrappedElementPhoneNumber=React.memo(function(props){var element=props.element,name=props.name,errorText=props.errorText,value=props.value,visible=props.visible,formName=props.formName;var label=element.label,handleChange=element.handleChange,_element$disabled=element.disabled,disabled=_element$disabled===void 0?false:_element$disabled,_element$required=element.required,required=_element$required===void 0?false:_element$required,_element$config=element.config,_element$config2=_element$config===void 0?{}:_element$config,_element$config2$supp=_element$config2.supportedCountries,supportedCountries=_element$config2$supp===void 0?[]:_element$config2$supp,_element$config2$coun=_element$config2.countrySortOrder,countrySortOrder=_element$config2$coun===void 0?[]:_element$config2$coun,_element$config2$user=_element$config2.userLocation,userLocation=_element$config2$user===void 0?{}:_element$config2$user;var _React$useState=React.useState(false),_React$useState2=_slicedToArray(_React$useState,2),isFocused=_React$useState2[0],setIsFocused=_React$useState2[1];// Maps available countries to correct format. var countries=React.useMemo(function(){if(supportedCountries.length===0){return builtInCountries;}return supportedCountries.map(function(country){var pieces=country.split('_');return _upperCase(pieces[0]);});},[supportedCountries]);var countriesNames=useCountriesNames(countries,locales);// Get labels for supported countries. var labels=React.useMemo(function(){var output={};if(!countries){return output;}countries.forEach(function(key){var pieces=key.split('_');output[pieces[0]]=countriesNames[key];});return output;},[countries,countriesNames]);var defaultCountry=React.useMemo(function(){var country;if(value){// Try to parse the value to determine a country var phoneNumber=parsePhoneNumber(value||'');if(phoneNumber&&phoneNumber.country){country=phoneNumber.country;}}if(!country&&userLocation){// Take the country from the user location if present country=userLocation.country;}if(!country){// If no country could be determined yet, take the country from the language var _i18n$getLang$split=i18n.getLang().split('-');var _i18n$getLang$split2=_slicedToArray(_i18n$getLang$split,2);country=_i18n$getLang$split2[1];}// Check if the determined country is included inside the available countries if(!countries.includes(country)){if((countrySortOrder===null||countrySortOrder===void 0?void 0:countrySortOrder.length)&&countries.includes(countrySortOrder[0])){// Take first country if the sort order list if present var _countrySortOrder=_slicedToArray(countrySortOrder,1);country=_countrySortOrder[0];}else{// Take first country from the list var _countries=_slicedToArray(countries,1);country=_countries[0];}}return country;},[countries,countrySortOrder,userLocation,value]);var countryOptionsOrder=React.useMemo(function(){/** * To avoid component errors remove countries from the sort order array that are not part * of the counties array. */var sanitizedCountrySortOrder=countrySortOrder.filter(function(countryCode){return countries.includes(countryCode);});var countryListsEqual=_isEqual([].concat(countries).sort(),[].concat(sanitizedCountrySortOrder).sort());/** * When list with supported countries has the same entries as the country sort order, we don't * need to add a separator to the countryOptionsOrder array since the country picker lists * will not show a section with unordered countries. */return sanitizedCountrySortOrder.length?[].concat(sanitizedCountrySortOrder,countryListsEqual?[]:['|']):[];},[countries,countrySortOrder]);var hasCountrySelect=React.useMemo(function(){return countries.length>1;},[countries.length]);var handleChangeWrapped=React.useCallback(function(phoneValue){handleChange(phoneValue,{target:{name:name}});},[handleChange,name]);var phoneClasses=classnames('textField',_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({simpleInput:!hasCountrySelect},_camelCase(name),true),"phonePicker",true),"phonePickerError",!!errorText),"validationError",!!errorText),"phonePickerFocused",isFocused),styles.phoneField,true),styles.phoneFieldError,!!errorText));if(!visible){return null;}var Component=hasCountrySelect?PhoneInputCountrySelect:PhoneInput;return React.createElement("div",{className:classnames('formBuilderField','engage__form-phone-number',{validationError:!!errorText})},React.createElement("div",{className:phoneClasses},React.createElement(Label,{label:label,isFocused:isFocused,isFloating:isFocused||!!value}),React.createElement(Component,_extends({defaultCountry:defaultCountry,name:name,value:value||'',onChange:handleChangeWrapped,onFocus:function onFocus(){return setIsFocused(true);},onBlur:function onBlur(){return setIsFocused(false);},disabled:disabled,required:required,"aria-invalid":!!errorText,"aria-describedby":errorText.length>0?"ariaError-".concat(name):null},hasCountrySelect?{countryOptionsOrder:countryOptionsOrder,addInternationalOption:false,flags:flags,countries:countries,labels:labels}:{className:'PhoneInputInput'}))),React.createElement(FormHelper,{errorText:errorText,element:element,formName:formName,elementName:name}));});UnwrappedElementPhoneNumber.defaultProps={value:'',visible:true};export default UnwrappedElementPhoneNumber;