@shopgate/engage 7.8.0-beta.1 → 7.8.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/account/components/Profile/Profile.config.js +8 -3
  2. package/account/components/Profile/Profile.js +1 -1
  3. package/account/components/Profile/Profile.provider.js +9 -8
  4. package/account/components/Profile/ProfileForm.js +2 -2
  5. package/account/helper/form.js +28 -8
  6. package/checkout/providers/CheckoutProvider.js +2 -2
  7. package/components/Form/Builder/Builder.js +4 -9
  8. package/components/Form/Builder/ElementCheckbox.js +2 -2
  9. package/components/Form/Builder/ElementMultiSelect.js +2 -2
  10. package/components/Form/Builder/ElementPhoneNumber.js +3 -3
  11. package/components/Form/Builder/ElementRadio.js +2 -2
  12. package/components/Form/Builder/ElementSelect.js +2 -2
  13. package/components/Form/Builder/ElementText.js +2 -2
  14. package/components/Form/Builder/FormHelper.js +5 -0
  15. package/components/Form/Builder/helpers/common.js +6 -0
  16. package/components/Form/Builder/stylePresets.js +1 -1
  17. package/core/hooks/useFormState.js +5 -1
  18. package/core/hooks/useScrollTo.js +2 -1
  19. package/package.json +7 -7
  20. package/registration/components/Registration/RegistrationFormExtra.config.js +2 -2
  21. package/registration/components/Registration/RegistrationFormExtra.js +1 -1
  22. package/registration/providers/GuestRegistrationProvider.actions.js +2 -2
  23. package/registration/providers/GuestRegistrationProvider.js +3 -3
  24. package/registration/providers/RegistrationProvider.actions.js +2 -2
  25. package/registration/providers/RegistrationProvider.constraints.js +2 -2
  26. package/registration/providers/RegistrationProvider.js +3 -3
  27. package/registration/components/Registration/RegisterFormBilling.config.js +0 -6
  28. package/registration/helpers/index.js +0 -5
@@ -1,5 +1,10 @@
1
- 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);}import{i18n}from'@shopgate/engage/core';import{generateFormFields}from'@shopgate/engage/account/helper/form';/**
1
+ 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);}import{i18n}from'@shopgate/engage/core';import{generateCustomerAttributesFields}from'@shopgate/engage/account/helper/form';/**
2
2
  * Generates form configuration.
3
- * @param {Array} customerAttributes List of customer attributes.
3
+ * @param {Object} additionalOptions Options for the customer attributes creation helper
4
+ * @param {Array} additionalOptions.customerAttributes Customer attributes.
5
+ * @param {Array} additionalOptions.supportedCountries A list of supported countries.
6
+ * @param {Object} additionalOptions.userLocation User location for better phone picker defaults.
7
+ * @param {boolean} [additionalOptions.allowPleaseChoose] Allows please choose option for required
8
+ * attributes.
4
9
  * @returns {Object}
5
- */var generateFormConfig=function generateFormConfig(customerAttributes){return{fields:_extends({firstName:{type:'text',label:"".concat(i18n.text('account.profile.form.firstName')," *")},middleName:{type:'text',label:"".concat(i18n.text('account.profile.form.middleName'))},lastName:{type:'text',label:"".concat(i18n.text('account.profile.form.lastName')," *")},emailAddress:{type:'email',label:"".concat(i18n.text('account.profile.form.emailAddress')," *"),disabled:true},marketingOptIn:{type:'checkbox',label:i18n.text('account.profile.form.marketing_opt_in_label')}},generateFormFields(customerAttributes,false))};};export default generateFormConfig;
10
+ */var generateFormConfig=function generateFormConfig(additionalOptions){return{fields:_extends({firstName:{type:'text',label:"".concat(i18n.text('account.profile.form.firstName')," *")},middleName:{type:'text',label:"".concat(i18n.text('account.profile.form.middleName'))},lastName:{type:'text',label:"".concat(i18n.text('account.profile.form.lastName')," *")},emailAddress:{type:'email',label:"".concat(i18n.text('account.profile.form.emailAddress')," *"),disabled:true},marketingOptIn:{type:'checkbox',label:i18n.text('account.profile.form.marketing_opt_in_label')}},generateCustomerAttributesFields(additionalOptions,false))};};export default generateFormConfig;
@@ -1 +1 @@
1
- import React from'react';import{css}from'glamor';import Provider from"./Profile.provider";import AddressBook from"./ProfileAddressBook";import Header from"./ProfileHeader";import Form from"./ProfileForm";var styles={root:css({padding:8}).toString()};/** @returns {JSX} */var Profile=function Profile(){return React.createElement(Provider,null,React.createElement("div",{className:styles.root},React.createElement(Header,null),React.createElement(Form,null),React.createElement(AddressBook,null)));};export default Profile;
1
+ import React,{useRef}from'react';import{css}from'glamor';import Provider from"./Profile.provider";import AddressBook from"./ProfileAddressBook";import Header from"./ProfileHeader";import Form from"./ProfileForm";var styles={root:css({padding:8}).toString()};/** @returns {JSX} */var Profile=function Profile(){var formContainerRef=useRef(null);return React.createElement(Provider,{formContainerRef:formContainerRef},React.createElement("div",{className:styles.root},React.createElement(Header,null),React.createElement(Form,{ref:formContainerRef}),React.createElement(AddressBook,null)));};export default Profile;
@@ -1,21 +1,22 @@
1
- import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}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);}import React,{createContext,useMemo,useEffect,useContext,useCallback}from'react';import PropTypes from'prop-types';import{connect}from'react-redux';import{useRoute,i18n,historyPush}from'@shopgate/engage/core';import{getMerchantCustomerAttributes}from'@shopgate/engage/core/selectors/merchantSettings';import{useFormState as useForm,convertValidationErrors}from'@shopgate/engage/core/hooks/useFormState';import showModal from'@shopgate/pwa-common/actions/modal/showModal';import{LoadingProvider,ToastProvider}from'@shopgate/pwa-common/providers';import UIEvents from'@shopgate/pwa-core/emitters/ui';import{CHECKOUT_ADDRESS_BOOK_CONTACT_PATTERN,useAddressBook}from'@shopgate/engage/checkout';import{PROFILE_ADDRESS_PATH}from"../../constants/routes";import{fetchCustomerContacts}from"../../actions/fetchContacts";import{fetchCustomerData}from"../../actions/fetchCustomer";import{updateCustomerData}from"../../actions/updateCustomer";import{deleteCustomerContact}from"../../actions/deleteContact";import{deleteCustomer as deleteCustomerAction}from"../../actions/deleteCustomer";import{getContacts}from"../../selectors/contacts";import{getCustomer}from"../../selectors/customer";import{extractAttributes,extractDefaultValues}from"../../helper/form";import createConstraints from"./Profile.constraints";var ProfileContext=createContext();/**
1
+ import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}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 _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 React,{createContext,useMemo,useEffect,useContext,useCallback,useState}from'react';import PropTypes from'prop-types';import{connect}from'react-redux';import{getShopSettings}from'@shopgate/engage/core/config';import{getPreferredLocationAddress}from'@shopgate/engage/locations/selectors';import{useRoute,i18n,historyPush,EVALIDATION}from'@shopgate/engage/core';import{getMerchantCustomerAttributes}from'@shopgate/engage/core/selectors/merchantSettings';import{useFormState as useForm,convertValidationErrors}from'@shopgate/engage/core/hooks/useFormState';import showModal from'@shopgate/pwa-common/actions/modal/showModal';import{LoadingProvider,ToastProvider}from'@shopgate/pwa-common/providers';import UIEvents from'@shopgate/pwa-core/emitters/ui';import{CHECKOUT_ADDRESS_BOOK_CONTACT_PATTERN,useAddressBook}from'@shopgate/engage/checkout';import{PROFILE_ADDRESS_PATH}from"../../constants/routes";import{fetchCustomerContacts}from"../../actions/fetchContacts";import{fetchCustomerData}from"../../actions/fetchCustomer";import{updateCustomerData}from"../../actions/updateCustomer";import{deleteCustomerContact}from"../../actions/deleteContact";import{deleteCustomer as deleteCustomerAction}from"../../actions/deleteCustomer";import{getContacts}from"../../selectors/contacts";import{getCustomer}from"../../selectors/customer";import{extractAttributes,extractDefaultValues,convertPipelineValidationErrors}from"../../helper/form";import createConstraints from"./Profile.constraints";var ProfileContext=createContext();/**
2
2
  * @returns {Array}
3
3
  */export var useProfileContext=function useProfileContext(){return useContext(ProfileContext);};/**
4
4
  * @param {Object} state State.
5
5
  * @returns {Object}
6
- */var mapStateToProps=function mapStateToProps(state){return{contacts:getContacts(state),customer:getCustomer(state),merchantCustomerAttributes:getMerchantCustomerAttributes(state)};};/**
6
+ */var mapStateToProps=function mapStateToProps(state){return{contacts:getContacts(state),customer:getCustomer(state),merchantCustomerAttributes:getMerchantCustomerAttributes(state),shopSettings:getShopSettings(state),userLocation:getPreferredLocationAddress(state)};};/**
7
7
  * @param {Function} dispatch Dispatch.
8
8
  * @returns {Object}
9
9
  */var mapDispatchToProps=function mapDispatchToProps(dispatch){return{fetchContacts:function fetchContacts(){return dispatch(fetchCustomerContacts());},deleteContact:function deleteContact(customerId){return dispatch(deleteCustomerContact(customerId));},deleteCustomer:function deleteCustomer(){return dispatch(deleteCustomerAction());},fetchCustomer:function fetchCustomer(){return dispatch(fetchCustomerData());},updateCustomer:function updateCustomer(customer){return dispatch(updateCustomerData(customer));},showDialog:function showDialog(props){return dispatch(showModal(props));},push:function push(props){return dispatch(historyPush(props));}};};/**
10
10
  * @returns {JSX}
11
- */var ProfileProvider=function ProfileProvider(_ref){var fetchContacts=_ref.fetchContacts,deleteContact=_ref.deleteContact,fetchCustomer=_ref.fetchCustomer,updateCustomer=_ref.updateCustomer,deleteCustomer=_ref.deleteCustomer,push=_ref.push,showDialog=_ref.showDialog,contacts=_ref.contacts,customer=_ref.customer,merchantCustomerAttributes=_ref.merchantCustomerAttributes,children=_ref.children;// Route
12
- var _useRoute=useRoute(),pathname=_useRoute.pathname;var _useAddressBook=useAddressBook(),isCheckout=_useAddressBook.isCheckout,type=_useAddressBook.type,deleteContactFromOrder=_useAddressBook.deleteContactFromOrder;// Default state.
11
+ */var ProfileProvider=function ProfileProvider(_ref){var fetchContacts=_ref.fetchContacts,deleteContact=_ref.deleteContact,fetchCustomer=_ref.fetchCustomer,updateCustomer=_ref.updateCustomer,deleteCustomer=_ref.deleteCustomer,push=_ref.push,showDialog=_ref.showDialog,contacts=_ref.contacts,customer=_ref.customer,merchantCustomerAttributes=_ref.merchantCustomerAttributes,children=_ref.children,shopSettings=_ref.shopSettings,userLocation=_ref.userLocation,formContainerRef=_ref.formContainerRef;// Route
12
+ var _useRoute=useRoute(),pathname=_useRoute.pathname;var _useAddressBook=useAddressBook(),isCheckout=_useAddressBook.isCheckout,type=_useAddressBook.type,deleteContactFromOrder=_useAddressBook.deleteContactFromOrder;var _useState=useState(null),_useState2=_slicedToArray(_useState,2),requestErrors=_useState2[0],setRequestErrors=_useState2[1];// Default state.
13
13
  var defaultState=useMemo(function(){return customer?_extends({},customer,{marketingOptIn:customer.settings.marketingOptIn||false},extractDefaultValues(customer.attributes)):null;},[customer]);// Saving the form.
14
- var saveForm=useCallback(/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(values){return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:LoadingProvider.setLoading(pathname);_context.prev=1;_context.next=4;return updateCustomer(_extends({firstName:values.firstName},values.middleName?{middleName:values.middleName}:{},{lastName:values.lastName,emailAddress:values.emailAddress,settings:{marketingOptIn:values.marketingOptIn},attributes:extractAttributes(merchantCustomerAttributes,values)}));case 4:_context.next=6;return fetchCustomer();case 6:UIEvents.emit(ToastProvider.ADD,{id:'account.profile.form.success',message:'account.profile.form.success'});_context.next=12;break;case 9:_context.prev=9;_context.t0=_context["catch"](1);UIEvents.emit(ToastProvider.ADD,{id:'account.profile.form.error',message:'account.profile.form.error'});case 12:LoadingProvider.unsetLoading(pathname);case 13:case"end":return _context.stop();}}},_callee,null,[[1,9]]);}));return function(_x){return _ref2.apply(this,arguments);};}(),[fetchCustomer,merchantCustomerAttributes,pathname,updateCustomer]);// Hold profile form state.
15
- var constraints=useMemo(function(){return createConstraints(merchantCustomerAttributes);},[merchantCustomerAttributes]);var formState=useForm(defaultState,saveForm,constraints);var validationErrors=useMemo(function(){return convertValidationErrors(formState.validationErrors||{});},[formState.validationErrors]);/**
14
+ var saveForm=useCallback(/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(values){var attributes,validationErrors,code,errors,converted,_converted$validation;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:LoadingProvider.setLoading(pathname);attributes=extractAttributes(merchantCustomerAttributes,values);_context.prev=2;_context.next=5;return updateCustomer(_extends({firstName:values.firstName},values.middleName?{middleName:values.middleName}:{},{lastName:values.lastName,emailAddress:values.emailAddress,settings:{marketingOptIn:values.marketingOptIn},attributes:attributes}));case 5:_context.next=7;return fetchCustomer();case 7:UIEvents.emit(ToastProvider.ADD,{id:'account.profile.form.success',message:'account.profile.form.success'});_context.next=15;break;case 10:_context.prev=10;_context.t0=_context["catch"](2);code=_context.t0.code,errors=_context.t0.errors;if(code===EVALIDATION){converted=convertPipelineValidationErrors(errors,attributes);if((converted===null||converted===void 0?void 0:converted.validation)&&Object.keys(converted.validation).length>0){validationErrors=converted===null||converted===void 0?void 0:(_converted$validation=converted.validation)===null||_converted$validation===void 0?void 0:_converted$validation.attributes;}}UIEvents.emit(ToastProvider.ADD,{id:'account.profile.form.error',message:'account.profile.form.error'});case 15:setRequestErrors(validationErrors||null);LoadingProvider.unsetLoading(pathname);case 17:case"end":return _context.stop();}}},_callee,null,[[2,10]]);}));return function(_x){return _ref2.apply(this,arguments);};}(),[fetchCustomer,merchantCustomerAttributes,pathname,updateCustomer]);// Hold profile form state.
15
+ var constraints=useMemo(function(){return createConstraints(merchantCustomerAttributes);},[merchantCustomerAttributes]);var formState=useForm(defaultState,saveForm,constraints,formContainerRef,120);var validationErrors=useMemo(function(){return convertValidationErrors(formState.validationErrors||requestErrors||{});},[formState.validationErrors,requestErrors]);useEffect(function(){formState.scrollToError();// eslint-disable-next-line react-hooks/exhaustive-deps
16
+ },[formState.scrollToError,requestErrors]);/**
16
17
  * Executes callback with confirmation beforehand.
17
18
  * @param {string} message String
18
19
  */var confirmation=/*#__PURE__*/function(){var _ref3=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(message){var confirmed;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:_context2.next=2;return showDialog({title:i18n.text('account.profile.confirm.title'),message:i18n.text(message),confirm:i18n.text('account.profile.confirm.confirm')});case 2:confirmed=_context2.sent;return _context2.abrupt("return",!!confirmed);case 4:case"end":return _context2.stop();}}},_callee2);}));return function confirmation(_x2){return _ref3.apply(this,arguments);};}();// Deletes a contact.
19
20
  /* eslint-disable react-hooks/exhaustive-deps */var deleteContactWrapper=useCallback(/*#__PURE__*/function(){var _ref4=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(contactId){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:_context3.next=2;return confirmation('account.profile.confirm.messageContact');case 2:if(_context3.sent){_context3.next=4;break;}return _context3.abrupt("return");case 4:LoadingProvider.setLoading(pathname);_context3.prev=5;_context3.next=8;return deleteContact(contactId);case 8:_context3.next=10;return fetchContacts();case 10:if(!deleteContactFromOrder){_context3.next=13;break;}_context3.next=13;return deleteContactFromOrder(contactId);case 13:_context3.next=17;break;case 15:_context3.prev=15;_context3.t0=_context3["catch"](5);case 17:LoadingProvider.unsetLoading(pathname);case 18:case"end":return _context3.stop();}}},_callee3,null,[[5,15]]);}));return function(_x3){return _ref4.apply(this,arguments);};}(),[deleteContact,fetchContacts,pathname]);var deleteCustomerWrapper=useCallback(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:_context4.next=2;return confirmation('account.profile.confirm.messageCustomer');case 2:if(_context4.sent){_context4.next=4;break;}return _context4.abrupt("return");case 4:LoadingProvider.setLoading(pathname);_context4.prev=5;_context4.next=8;return deleteCustomer();case 8:_context4.next=12;break;case 10:_context4.prev=10;_context4.t0=_context4["catch"](5);case 12:LoadingProvider.unsetLoading(pathname);case 13:case"end":return _context4.stop();}}},_callee4,null,[[5,10]]);})),[deleteContact,fetchContacts,pathname]);/* eslint-enable react-hooks/exhaustive-deps */var editContact=useCallback(function(contact){var editPathname=isCheckout?"".concat(CHECKOUT_ADDRESS_BOOK_CONTACT_PATTERN).replace(':type',type):PROFILE_ADDRESS_PATH;push({pathname:editPathname,state:{contact:contact}});},[isCheckout,push,type]);// Store context value.
20
- var contextValue=useMemo(function(){return{contacts:contacts,validationErrors:validationErrors,merchantCustomerAttributes:merchantCustomerAttributes,customer:defaultState,isCheckout:isCheckout,formState:formState,saveForm:formState.handleSubmit,editContact:editContact,deleteContact:deleteContactWrapper,deleteCustomer:deleteCustomerWrapper};},[contacts,merchantCustomerAttributes,isCheckout,defaultState,deleteContactWrapper,deleteCustomerWrapper,editContact,formState,validationErrors]);// Fetch all required data for the profile page.
21
- useEffect(function(){fetchContacts();fetchCustomer();},[fetchContacts,fetchCustomer]);if(!customer){return null;}return React.createElement(ProfileContext.Provider,{value:contextValue},children);};ProfileProvider.defaultProps={customer:null};export default connect(mapStateToProps,mapDispatchToProps)(ProfileProvider);
21
+ var contextValue=useMemo(function(){return{contacts:contacts,validationErrors:validationErrors,merchantCustomerAttributes:merchantCustomerAttributes,customer:defaultState,isCheckout:isCheckout,supportedCountries:shopSettings.supportedCountries,userLocation:userLocation,formState:formState,saveForm:formState.handleSubmit,editContact:editContact,deleteContact:deleteContactWrapper,deleteCustomer:deleteCustomerWrapper};},[userLocation,shopSettings.supportedCountries,contacts,merchantCustomerAttributes,isCheckout,defaultState,deleteContactWrapper,deleteCustomerWrapper,editContact,formState,validationErrors]);// Fetch all required data for the profile page.
22
+ useEffect(function(){fetchContacts();fetchCustomer();},[fetchContacts,fetchCustomer]);if(!customer){return null;}return React.createElement(ProfileContext.Provider,{value:contextValue},children);};ProfileProvider.defaultProps={customer:null,formContainerRef:null};export default connect(mapStateToProps,mapDispatchToProps)(ProfileProvider);
@@ -1,3 +1,3 @@
1
- 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 _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);}import React,{useMemo,useCallback}from'react';import{css}from'glamor';import{i18n}from'@shopgate/engage/core';import{responsiveMediaQuery}from'@shopgate/engage/styles';import{FormBuilder,RippleButton}from'@shopgate/engage/components';import{StylePresets}from'@shopgate/engage/components/Form';import{useProfileContext}from"./Profile.provider";import generateFormConfig from"./Profile.config";var styles={root:css({display:'flex',flexDirection:'column',marginBottom:16}).toString(),form:css(_extends({},StylePresets.OUTLINED_FORM_FIELDS,{},StylePresets.TWO_COLUMN_LAYOUT,{' .container-checkbox':_defineProperty({},responsiveMediaQuery('>=md',{webOnly:false}),{marginRight:'50%'})})).toString(),button:css({'&&':_defineProperty({marginTop:8,marginRight:16,backgroundColor:'var(--color-primary)',borderRadius:5,fontSize:14,textTransform:'none',padding:0},responsiveMediaQuery('<md',{webOnly:false}),{marginRight:0})}).toString(),buttonDelete:css({'&&':_defineProperty({marginTop:8,marginRight:16,border:'1px solid var(--color-state-alert)',backgroundColor:'#fff',color:'var(--color-state-alert)',borderRadius:5,fontSize:14,textTransform:'none',padding:0},responsiveMediaQuery('<md',{webOnly:false}),{marginRight:0})}).toString(),ripple:css({padding:'8px 16px'}).toString(),actions:css(_defineProperty({display:'flex',justifyContent:'flex-end',flexDirection:'row'},responsiveMediaQuery('<md',{webOnly:false}),{marginTop:8,flexDirection:'column-reverse'})).toString()};/**
1
+ 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 _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);}import React,{useMemo,useCallback,forwardRef}from'react';import{css}from'glamor';import{i18n}from'@shopgate/engage/core';import{responsiveMediaQuery}from'@shopgate/engage/styles';import{FormBuilder,RippleButton}from'@shopgate/engage/components';import{StylePresets}from'@shopgate/engage/components/Form';import{useProfileContext}from"./Profile.provider";import generateFormConfig from"./Profile.config";var styles={root:css({display:'flex',flexDirection:'column',marginBottom:16}).toString(),form:css(_extends({},StylePresets.OUTLINED_FORM_FIELDS,{},StylePresets.TWO_COLUMN_LAYOUT,{' .container-checkbox':_defineProperty({},responsiveMediaQuery('>=md',{webOnly:false}),{marginRight:'50%'})})).toString(),button:css({'&&':_defineProperty({marginTop:8,marginRight:16,backgroundColor:'var(--color-primary)',borderRadius:5,fontSize:14,textTransform:'none',padding:0},responsiveMediaQuery('<md',{webOnly:false}),{marginRight:0})}).toString(),buttonDelete:css({'&&':_defineProperty({marginTop:8,marginRight:16,border:'1px solid var(--color-state-alert)',backgroundColor:'#fff',color:'var(--color-state-alert)',borderRadius:5,fontSize:14,textTransform:'none',padding:0},responsiveMediaQuery('<md',{webOnly:false}),{marginRight:0})}).toString(),ripple:css({padding:'8px 16px'}).toString(),actions:css(_defineProperty({display:'flex',justifyContent:'flex-end',flexDirection:'row'},responsiveMediaQuery('<md',{webOnly:false}),{marginTop:8,flexDirection:'column-reverse'})).toString()};/**
2
2
  * @returns {JSX}
3
- */var ProfileForm=function ProfileForm(){var _useProfileContext=useProfileContext(),formState=_useProfileContext.formState,customer=_useProfileContext.customer,saveForm=_useProfileContext.saveForm,deleteCustomer=_useProfileContext.deleteCustomer,validationErrors=_useProfileContext.validationErrors,merchantCustomerAttributes=_useProfileContext.merchantCustomerAttributes;var formConfig=useMemo(function(){return generateFormConfig(merchantCustomerAttributes);},[merchantCustomerAttributes]);/* eslint-disable react-hooks/exhaustive-deps */var handleUpdate=useCallback(function(values){formState.setValues(values);},[formState.setValues]);/* eslint-enable react-hooks/exhaustive-deps */if(!customer){return null;}return React.createElement("div",{className:styles.root},React.createElement(FormBuilder,{name:"ProfileForm",className:styles.form,config:formConfig,defaults:customer,validationErrors:validationErrors,handleUpdate:handleUpdate}),React.createElement("div",{className:styles.actions},React.createElement(RippleButton,{className:styles.buttonDelete,rippleClassName:styles.ripple,type:"primary",onClick:deleteCustomer},i18n.text('account.profile.delete')),React.createElement(RippleButton,{className:styles.button,rippleClassName:styles.ripple,type:"primary",onClick:saveForm},i18n.text('account.profile.form.save'))));};export default ProfileForm;
3
+ */var ProfileForm=forwardRef(function(_,ref){var _useProfileContext=useProfileContext(),formState=_useProfileContext.formState,customer=_useProfileContext.customer,saveForm=_useProfileContext.saveForm,deleteCustomer=_useProfileContext.deleteCustomer,validationErrors=_useProfileContext.validationErrors,merchantCustomerAttributes=_useProfileContext.merchantCustomerAttributes,supportedCountries=_useProfileContext.supportedCountries,userLocation=_useProfileContext.userLocation;var formConfig=useMemo(function(){return generateFormConfig({customerAttributes:merchantCustomerAttributes,supportedCountries:supportedCountries,userLocation:userLocation});},[merchantCustomerAttributes,supportedCountries,userLocation]);/* eslint-disable react-hooks/exhaustive-deps */var handleUpdate=useCallback(function(values){formState.setValues(values);},[formState.setValues]);/* eslint-enable react-hooks/exhaustive-deps */if(!customer){return null;}return React.createElement("div",{className:styles.root,ref:ref},React.createElement(FormBuilder,{name:"ProfileForm",className:styles.form,config:formConfig,defaults:customer,validationErrors:validationErrors,handleUpdate:handleUpdate}),React.createElement("div",{className:styles.actions},React.createElement(RippleButton,{className:styles.buttonDelete,rippleClassName:styles.ripple,type:"primary",onClick:deleteCustomer},i18n.text('account.profile.delete')),React.createElement(RippleButton,{className:styles.button,rippleClassName:styles.ripple,type:"primary",onClick:saveForm},i18n.text('account.profile.form.save'))));});export default ProfileForm;
@@ -1,12 +1,15 @@
1
- function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}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 _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);}import sortBy from'lodash/sortBy';import{i18n}from'@shopgate/engage/core';/**
1
+ function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}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 _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);}import sortBy from'lodash/sortBy';import setWith from'lodash/setWith';import{i18n}from'@shopgate/engage/core';/**
2
2
  * @param {Object} attribute Customer attribute.
3
3
  * @returns {string}
4
- */var mapCustomerAttributeType=function mapCustomerAttributeType(attribute){if(attribute.values&&attribute.values.length){if(attribute.type==='collectionOfValues'){return'multiselect';}return'select';}switch(attribute.type){case'number':return'number';case'boolean':return'checkbox';case'date':return'date';default:return'text';}};/**
5
- * Generates form field config
6
- * @param {Object} customerAttributes Customer attributes.
7
- * @param {boolean} allowPleaseChoose Allows please choose option for required attributes.
4
+ */var mapCustomerAttributeType=function mapCustomerAttributeType(attribute){if(attribute.values&&attribute.values.length){if(attribute.type==='collectionOfValues'){return'multiselect';}return'select';}switch(attribute.type){case'number':return'number';case'boolean':return'checkbox';case'date':return'date';case'callingNumber':return'phone_picker';default:return'text';}};/**
5
+ * Generates customer attributes form field config
6
+ * @param {Object} options Options for the helper
7
+ * @param {Array} options.customerAttributes Customer attributes.
8
+ * @param {Array} options.supportedCountries A list of supported countries.
9
+ * @param {Object} options.userLocation User location for better phone picker defaults.
10
+ * @param {boolean} options.allowPleaseChoose Allows please choose option for required attributes.
8
11
  * @returns {Object}
9
- */export var generateFormFields=function generateFormFields(customerAttributes){var allowPleaseChoose=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;return _extends({},Object.assign.apply(Object,[{}].concat(sortBy(customerAttributes,['sequenceId']).map(function(attribute){return _defineProperty({},"attribute_".concat(attribute.code),_extends({type:mapCustomerAttributeType(attribute),label:"".concat(attribute.name," ").concat(attribute.isRequired?'*':'')},attribute.values?{options:_extends({},!attribute.isRequired?{'':''}:{},{},attribute.isRequired&&attribute.type!=='collectionOfValues'&&allowPleaseChoose?{'':i18n.text('common.please_choose')}:{},{},Object.assign.apply(Object,[{}].concat(sortBy(attribute.values,['sequenceId']).map(function(option){return _defineProperty({},option.code,option.name);}))))}:{}));}))));};/**
12
+ */export var generateCustomerAttributesFields=function generateCustomerAttributesFields(_ref){var customerAttributes=_ref.customerAttributes,supportedCountries=_ref.supportedCountries,userLocation=_ref.userLocation,_ref$allowPleaseChoos=_ref.allowPleaseChoose,allowPleaseChoose=_ref$allowPleaseChoos===void 0?true:_ref$allowPleaseChoos;return _extends({},Object.assign.apply(Object,[{}].concat(sortBy(customerAttributes,['sequenceId']).map(function(attribute){return _defineProperty({},"attribute_".concat(attribute.code),_extends({type:mapCustomerAttributeType(attribute),label:"".concat(attribute.name," ").concat(attribute.isRequired?'*':'')},attribute.values?{options:_extends({},!attribute.isRequired?{'':''}:{},{},attribute.isRequired&&attribute.type!=='collectionOfValues'&&allowPleaseChoose?{'':i18n.text('common.please_choose')}:{},{},Object.assign.apply(Object,[{}].concat(sortBy(attribute.values,['sequenceId']).map(function(option){return _defineProperty({},option.code,option.name);}))))}:{},{},attribute.type==='callingNumber'?{config:{supportedCountries:supportedCountries,userLocation:userLocation}}:null));}))));};/**
10
13
  * Generates form constraints for attributes.
11
14
  * @param {Object} customerAttributes Customer attributes.
12
15
  * @returns {Object}
@@ -24,7 +27,7 @@ if(attribute.type==='text'||attribute.type==='date'){return value!==null?value.t
24
27
  * @param {Object} customerAttributes Customer attributes.
25
28
  * @param {Object} formData Form data.
26
29
  * @returns {Object}
27
- */export var extractAttributes=function extractAttributes(customerAttributes,formData){return customerAttributes.map(function(attribute){return{code:attribute.code,value:mapAttributeType(formData["attribute_".concat(attribute.code)],attribute)};})// Removes wrong numbers (sometimes generated by the formbuilder when emptying the field)
30
+ */export var extractAttributes=function extractAttributes(customerAttributes,formData){return customerAttributes.map(function(attribute){return{code:attribute.code,value:mapAttributeType(formData["attribute_".concat(attribute.code)],attribute)};})// Removes wrong numbers (sometimes generated by the form builder when emptying the field)
28
31
  .filter(function(attribute){return!Number.isNaN(attribute.value);})// Removes all attributes that are empty / no longer set.
29
32
  .filter(function(attribute){var _attribute$value,_attribute$value2,_attribute$value2$cod,_attribute$value3,_attribute$value3$,_attribute$value3$$co;return(// Any number.
30
33
  typeof attribute.value==='number'||// Non-empty strings.
@@ -37,4 +40,21 @@ attribute.value===true||attribute.value===false||// Object containing the code.
37
40
  * @returns {Object}
38
41
  */export var extractDefaultValues=function extractDefaultValues(customerAttributes){return Object.assign.apply(Object,[{}].concat(customerAttributes.map(function(attribute){var value=attribute.value;if(value){if(Array.isArray(value)&&value[0]&&_typeof(value[0])==='object'){// Multi select L:95
39
42
  value=value.reduce(function(acc,val){return[].concat(acc,[val.code]);},[]);}else if(_typeof(value)==='object'){// Single select L:100
40
- value=value.code;}else if(value!==true&&value!==false){value=value.toString();}}return _defineProperty({},"attribute_".concat(attribute.code),value);})));};
43
+ value=value.code;}else if(value!==true&&value!==false){value=value.toString();}}return _defineProperty({},"attribute_".concat(attribute.code),value);})));};/**
44
+ * Converts pipeline validation errors
45
+ * @param {Array} errors The errors
46
+ * @param {Array} attributes Attributes that where sent with the register request. Used to retrieve
47
+ * extra form field for attribute validation errors.
48
+ * @returns {Object|null}
49
+ */export var convertPipelineValidationErrors=function convertPipelineValidationErrors(errors){var attributes=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];if(!Array.isArray(errors)||errors.length===0){return null;}var converted=errors.reduce(function(result,error){var _error$path=error.path,path=_error$path===void 0?[]:_error$path,code=error.code,_error$subentityPath=error.subentityPath,subentityPath=_error$subentityPath===void 0?[]:_error$subentityPath,displayMessage=error.displayMessage;var message=error.message;if(path.length===0&&subentityPath.length===0){result.general.push(error);return result;}var validationPath;if(path.length>0){message=i18n.text('validation.checkField');validationPath=path.slice(2).join('.');}else if(subentityPath.length>0&&subentityPath.includes('attributes')){/**
50
+ * Validation errors for customer attributes needs special handling. They are sent
51
+ * as an array to the server, which only includes the fields where an actual value was set.
52
+ * The subentityPath of attribute validation errors will only contain an array index which
53
+ * needs to be mapped to tha actual field id.
54
+ *
55
+ * So here in the first step, we search for the subentity path entry that comes after the
56
+ * "attributes" entry and convert it back to an integer which can be used to determine
57
+ * and entry within the attribute data that was used for the request.
58
+ */var attributeIndex=parseInt(subentityPath[subentityPath.indexOf('attributes')+1],10);message=i18n.text('validation.checkField');// Retrieve the attribute code to mock a validation path that can be used to find the correct
59
+ // form field.
60
+ validationPath="attributes.attribute_".concat(attributes[attributeIndex].code);}else if(subentityPath.length>0){var field=subentityPath[subentityPath.length-1];if(code===409&&field==='emailAddress'){message=i18n.text('validation.emailConflict');}else{message=i18n.text('validation.checkField');}validationPath=subentityPath.join('.');}if(validationPath){setWith(result.validation,validationPath,displayMessage||message,Object);}return result;},{validation:{},general:[]});return converted;};
@@ -1,4 +1,4 @@
1
- import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}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 _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;}/* eslint-disable no-unused-expressions */import React,{useCallback}from'react';import{isAvailable,InAppBrowser,Linking}from'@shopgate/native-modules';import{useFormState}from'@shopgate/engage/core/hooks/useFormState';import{i18n,useAsyncMemo,getUserAgent,LoadingProvider}from'@shopgate/engage/core';import{MARKETING_OPT_IN_DEFAULT}from'@shopgate/engage/registration/constants';import Context from"./CheckoutProvider.context";import connect from"./CheckoutProvider.connector";import{pickupConstraints,selfPickupConstraints}from"./CheckoutProvider.constraints";import{CHECKOUT_CONFIRMATION_PATTERN}from"../constants/routes";import{hasWebBridge}from"../../core";var defaultPickupPersonState={pickupPerson:'me',firstName:'',lastName:'',mobile:'',email:'',firstName2:'',lastName2:'',mobile2:'',email2:''};/**
1
+ import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}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 _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;}/* eslint-disable no-unused-expressions */import React,{useCallback}from'react';import{isAvailable,InAppBrowser,Linking}from'@shopgate/native-modules';import{useFormState}from'@shopgate/engage/core/hooks/useFormState';import{i18n,useAsyncMemo,getUserAgent,LoadingProvider}from'@shopgate/engage/core';import{MARKETING_OPT_IN_DEFAULT}from'@shopgate/engage/registration/constants';import Context from"./CheckoutProvider.context";import connect from"./CheckoutProvider.connector";import{pickupConstraints,selfPickupConstraints}from"./CheckoutProvider.constraints";import{CHECKOUT_CONFIRMATION_PATTERN}from"../constants/routes";var defaultPickupPersonState={pickupPerson:'me',firstName:'',lastName:'',mobile:'',email:'',firstName2:'',lastName2:'',mobile2:'',email2:''};/**
2
2
  * Converts validation errors into errors for form builder.
3
3
  * @param {Object} validationErrors The validation errors.
4
4
  * @returns {Array}
@@ -25,4 +25,4 @@ var value=React.useMemo(function(){return{setPaymentHandler:function setPaymentH
25
25
  React.useEffect(function(){if(!isAvailable())return undefined;/**
26
26
  * @param {Object} event Event
27
27
  */var listener=/*#__PURE__*/function(){var _ref9=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(event){var _ref10,_ref10$link,link,_link$match,_link$match2,_,_scheme,path,_ref11,_ref12,order;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:_ref10=(event===null||event===void 0?void 0:event.detail)||{},_ref10$link=_ref10.link,link=_ref10$link===void 0?'':_ref10$link;/* eslint-disable-next-line no-unused-vars */_link$match=link.match(/(.*):\/\/([a-zA-Z0-9-/]*)(.*)/),_link$match2=_slicedToArray(_link$match,3),_=_link$match2[0],_scheme=_link$match2[1],path=_link$match2[2];// Order is done, fetch again to retrieve infos for success page
28
- if(!(path==='payment/success')){_context4.next=11;break;}_context4.next=5;return Promise.all([fetchCheckoutOrder(),fetchCart()]);case 5:_ref11=_context4.sent;_ref12=_slicedToArray(_ref11,1);order=_ref12[0];historyReplace({pathname:CHECKOUT_CONFIRMATION_PATTERN,state:{order:order}});_context4.next=12;break;case 11:if(path==='payment/error'){showModal({title:null,confirm:null,dismiss:'modal.ok',message:'checkout.errors.payment.genericExternal'});}case 12:case"end":return _context4.stop();}}},_callee4);}));return function listener(_x3){return _ref9.apply(this,arguments);};}();Linking.addEventListener('deepLinkOpened',listener);return function(){Linking.removeEventListener('deepLinkOpened',listener);};},[fetchCart,fetchCheckoutOrder,historyReplace,showModal]);if(!isDataReady||!isCheckoutInitialized){return null;}return React.createElement(Context.Provider,{value:value},children);};CheckoutProvider.defaultProps={orderInitialized:false,orderReadOnly:false,orderReserveOnly:false,isShippingAddressSelectionEnabled:false,isPickupContactSelectionEnabled:false,isGuestCheckout:false};export default connect(CheckoutProvider);
28
+ if(!(path==='payment/success')){_context4.next=11;break;}_context4.next=5;return Promise.all([fetchCheckoutOrder(),fetchCart()]);case 5:_ref11=_context4.sent;_ref12=_slicedToArray(_ref11,1);order=_ref12[0];historyReplace({pathname:CHECKOUT_CONFIRMATION_PATTERN,state:{order:order}});_context4.next=12;break;case 11:if(path==='payment/error'){showModal({title:null,confirm:null,dismiss:'modal.ok',message:'checkout.errors.payment.genericExternal'});}case 12:case"end":return _context4.stop();}}},_callee4);}));return function listener(_x3){return _ref9.apply(this,arguments);};}();Linking.addEventListener('deepLinkOpened',listener);return function(){Linking.removeEventListener('deepLinkOpened',listener);};},[fetchCart,fetchCheckoutOrder,historyReplace,showModal]);if(!isDataReady||!isCheckoutInitialized){return null;}return React.createElement(Context.Provider,{value:value},children);};CheckoutProvider.defaultProps={orderInitialized:false,orderReadOnly:false,orderReserveOnly:false,isShippingAddressSelectionEnabled:false,isPickupContactSelectionEnabled:false,isGuestCheckout:false};export default connect(CheckoutProvider);/* eslint-enable no-unused-expressions */
@@ -1,9 +1,4 @@
1
- import _camelCase from"lodash/camelCase";var _defineProperty2;function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(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;}function _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded);var key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++){key=sourceSymbolKeys[i];if(excluded.indexOf(key)>=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key];}}return target;}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return{};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i<sourceKeys.length;i++){key=sourceKeys[i];if(excluded.indexOf(key)>=0)continue;target[key]=source[key];}return target;}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 _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}return _assertThisInitialized(self);}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function");}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}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;}import React,{Component,Fragment}from'react';import PropTypes from'prop-types';import{logger}from'@shopgate/pwa-core/helpers';import Portal from'@shopgate/pwa-common/components/Portal';import{BEFORE,AFTER}from'@shopgate/pwa-common/constants/Portals';import{Form}from'..';import ActionListener from"./classes/ActionListener";import{ELEMENT_TYPE_EMAIL,ELEMENT_TYPE_PASSWORD,ELEMENT_TYPE_TEXT,ELEMENT_TYPE_NUMBER,ELEMENT_TYPE_SELECT,ELEMENT_TYPE_COUNTRY,ELEMENT_TYPE_PROVINCE,ELEMENT_TYPE_CHECKBOX,ELEMENT_TYPE_RADIO,ELEMENT_TYPE_DATE,ELEMENT_TYPE_PHONE,ELEMENT_TYPE_PHONE_PICKER,ELEMENT_TYPE_MULTISELECT}from"./Builder.constants";import ElementText from"./ElementText";import ElementSelect from"./ElementSelect";import ElementMultiSelect from"./ElementMultiSelect";import ElementRadio from"./ElementRadio";import ElementCheckbox from"./ElementCheckbox";import ElementPhoneNumber from"./ElementPhoneNumber";import buildFormElements from"./helpers/buildFormElements";import buildFormDefaults from"./helpers/buildFormDefaults";import buildCountryList from"./helpers/buildCountryList";import buildProvinceList from"./helpers/buildProvinceList";import buildValidationErrorList from"./helpers/buildValidationErrorList";/**
2
- * Takes a string and converts it to a part to be used in a portal name
3
- * @package FormBuilder
4
- * @param {string} s The string to be sanitized
5
- * @return {string}
6
- */var sanitize=function sanitize(s){return s.replace(/[\\._]/,'-');};/**
1
+ import _camelCase from"lodash/camelCase";var _defineProperty2;function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(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;}function _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded);var key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++){key=sourceSymbolKeys[i];if(excluded.indexOf(key)>=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key];}}return target;}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return{};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i<sourceKeys.length;i++){key=sourceKeys[i];if(excluded.indexOf(key)>=0)continue;target[key]=source[key];}return target;}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 _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}return _assertThisInitialized(self);}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function");}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}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;}import React,{Component,Fragment}from'react';import PropTypes from'prop-types';import{logger}from'@shopgate/pwa-core/helpers';import Portal from'@shopgate/pwa-common/components/Portal';import{BEFORE,AFTER}from'@shopgate/pwa-common/constants/Portals';import{Form}from'..';import ActionListener from"./classes/ActionListener";import{ELEMENT_TYPE_EMAIL,ELEMENT_TYPE_PASSWORD,ELEMENT_TYPE_TEXT,ELEMENT_TYPE_NUMBER,ELEMENT_TYPE_SELECT,ELEMENT_TYPE_COUNTRY,ELEMENT_TYPE_PROVINCE,ELEMENT_TYPE_CHECKBOX,ELEMENT_TYPE_RADIO,ELEMENT_TYPE_DATE,ELEMENT_TYPE_PHONE,ELEMENT_TYPE_PHONE_PICKER,ELEMENT_TYPE_MULTISELECT}from"./Builder.constants";import ElementText from"./ElementText";import ElementSelect from"./ElementSelect";import ElementMultiSelect from"./ElementMultiSelect";import ElementRadio from"./ElementRadio";import ElementCheckbox from"./ElementCheckbox";import ElementPhoneNumber from"./ElementPhoneNumber";import buildFormElements from"./helpers/buildFormElements";import buildFormDefaults from"./helpers/buildFormDefaults";import buildCountryList from"./helpers/buildCountryList";import buildProvinceList from"./helpers/buildProvinceList";import buildValidationErrorList from"./helpers/buildValidationErrorList";import{sanitizePortalName}from"./helpers/common";/**
7
2
  * Optional select element
8
3
  * @type {Object}
9
4
  */var emptySelectOption={'':''};/**
@@ -22,11 +17,11 @@ _this.formElements.forEach(function(formElement){if(!finalState.elementVisibilit
22
17
  _this.setState(finalState);// Transform to external structure (unavailable ones will be set undefined)
23
18
  var updateData={};_this.formElements.forEach(function(el){if(el.custom){if(updateData.customAttributes===undefined){updateData.customAttributes={};}updateData.customAttributes[el.id]=finalState.formData[el.id];}else{updateData[el.id]=finalState.formData[el.id];}});// Trigger the given update action of the parent and provide all new validation errors to it
24
19
  _this.props.handleUpdate(updateData,hasErrors,// Output validation errors in the same structure (array) as the component takes them
25
- hasErrors?Object.keys(validationErrors).map(function(k){return{path:k,message:validationErrors[k]};}):[]);});_defineProperty(_assertThisInitialized(_this),"renderElement",function(element,elementErrorText){var elementName="".concat(_this.props.name,"_").concat(element.id);var elementValue=_this.state.formData[element.id];var elementVisible=_this.state.elementVisibility[element.id]||false;// Take a dynamic REACT element based on its type
20
+ hasErrors?Object.keys(validationErrors).map(function(k){return{path:k,message:validationErrors[k]};}):[]);});_defineProperty(_assertThisInitialized(_this),"renderElement",function(formName,element,elementErrorText){var elementName="".concat(_this.props.name,"_").concat(element.id);var elementValue=_this.state.formData[element.id];var elementVisible=_this.state.elementVisibility[element.id]||false;// Take a dynamic REACT element based on its type
26
21
  var Element=_this.getFormElementComponent(element.type);if(!Element){logger.error("Unknown form element type: ".concat(element.type));return null;}// Country and province elements have their data injected, if not already present
27
22
  var elementData=element;switch(element.type){case ELEMENT_TYPE_COUNTRY:{elementData.options=element.options||_this.countryList;break;}case ELEMENT_TYPE_PROVINCE:{// Province selection only makes sense with a country being selected, or from custom options
28
23
  var countryElement=_this.formElements.find(function(el){return el.type===ELEMENT_TYPE_COUNTRY;});elementData.options=countryElement&&_this.state.formData[countryElement.id]?buildProvinceList(_this.state.formData[countryElement.id],// Auto-select with "empty" when not required
29
- element.required?null:emptySelectOption):{};break;}default:break;}return React.createElement(Element,{name:elementName,element:elementData,errorText:elementErrorText,value:elementValue,visible:elementVisible});});_this.state={elementVisibility:{},formData:{}};// Reorganize form elements into a structure that can be easily rendered
24
+ element.required?null:emptySelectOption):{};break;}default:break;}return React.createElement(Element,{name:elementName,element:elementData,errorText:elementErrorText,value:elementValue,visible:elementVisible,formName:formName});});_this.state={elementVisibility:{},formData:{}};// Reorganize form elements into a structure that can be easily rendered
30
25
  var formElements=buildFormElements(props.config,_this.elementChangeHandler);// Compute defaults
31
26
  var formDefaults=buildFormDefaults(formElements,props.defaults);// Assign defaults to state
32
27
  _this.state.formData=formDefaults;// Handle fixed visibilities
@@ -43,7 +38,7 @@ var _newState=_this.state;_this.formElements.forEach(function(element){_newState
43
38
  * Renders the component based on the given config
44
39
  * @return {JSX}
45
40
  */value:function render(){var _this2=this;// Convert validation errors for easier handling
46
- var validationErrors=buildValidationErrorList(this.props.validationErrors);return React.createElement(Form,{className:_camelCase(this.props.name),onSubmit:this.props.onSubmit},React.createElement("div",{className:this.props.className},this.formElements.map(function(element){return React.createElement(Fragment,{key:"".concat(_this2.props.name,"_").concat(element.id)},React.createElement(Portal,{name:"".concat(sanitize(_this2.props.name),".").concat(sanitize(element.id),".").concat(BEFORE)}),React.createElement(Portal,{name:"".concat(sanitize(_this2.props.name),".").concat(sanitize(element.id))},_this2.renderElement(element,validationErrors[element.id]||'')),React.createElement(Portal,{name:"".concat(sanitize(_this2.props.name),".").concat(sanitize(element.id),".").concat(AFTER)}));})));}}]);return Builder;}(Component);_defineProperty(Builder,"defaultElements",(_defineProperty2={},_defineProperty(_defineProperty2,ELEMENT_TYPE_EMAIL,ElementText),_defineProperty(_defineProperty2,ELEMENT_TYPE_PASSWORD,ElementText),_defineProperty(_defineProperty2,ELEMENT_TYPE_TEXT,ElementText),_defineProperty(_defineProperty2,ELEMENT_TYPE_NUMBER,ElementText),_defineProperty(_defineProperty2,ELEMENT_TYPE_SELECT,ElementSelect),_defineProperty(_defineProperty2,ELEMENT_TYPE_MULTISELECT,ElementMultiSelect),_defineProperty(_defineProperty2,ELEMENT_TYPE_COUNTRY,ElementSelect),_defineProperty(_defineProperty2,ELEMENT_TYPE_PROVINCE,ElementSelect),_defineProperty(_defineProperty2,ELEMENT_TYPE_CHECKBOX,ElementCheckbox),_defineProperty(_defineProperty2,ELEMENT_TYPE_RADIO,ElementRadio),_defineProperty(_defineProperty2,ELEMENT_TYPE_DATE,ElementText),_defineProperty(_defineProperty2,ELEMENT_TYPE_PHONE,ElementText),_defineProperty(_defineProperty2,ELEMENT_TYPE_PHONE_PICKER,ElementPhoneNumber),_defineProperty2));_defineProperty(Builder,"defaultProps",{className:null,defaults:{},elements:Builder.defaultElements,onSubmit:function onSubmit(){},validationErrors:[]/**
41
+ var validationErrors=buildValidationErrorList(this.props.validationErrors);return React.createElement(Form,{className:_camelCase(this.props.name),onSubmit:this.props.onSubmit},React.createElement("div",{className:this.props.className},this.formElements.map(function(element){return React.createElement(Fragment,{key:"".concat(_this2.props.name,"_").concat(element.id)},React.createElement(Portal,{name:"".concat(sanitizePortalName(_this2.props.name),".").concat(sanitizePortalName(element.id),".").concat(BEFORE),props:{formName:_this2.props.name,errorText:validationErrors[element.id]||'',element:element}}),React.createElement(Portal,{name:"".concat(sanitizePortalName(_this2.props.name),".").concat(sanitizePortalName(element.id)),props:{formName:_this2.props.name,errorText:validationErrors[element.id]||'',element:element}},_this2.renderElement(_this2.props.name,element,validationErrors[element.id]||'')),React.createElement(Portal,{name:"".concat(sanitizePortalName(_this2.props.name),".").concat(sanitizePortalName(element.id),".").concat(AFTER),props:{formName:_this2.props.name,errorText:validationErrors[element.id]||'',element:element}}));})));}}]);return Builder;}(Component);_defineProperty(Builder,"defaultElements",(_defineProperty2={},_defineProperty(_defineProperty2,ELEMENT_TYPE_EMAIL,ElementText),_defineProperty(_defineProperty2,ELEMENT_TYPE_PASSWORD,ElementText),_defineProperty(_defineProperty2,ELEMENT_TYPE_TEXT,ElementText),_defineProperty(_defineProperty2,ELEMENT_TYPE_NUMBER,ElementText),_defineProperty(_defineProperty2,ELEMENT_TYPE_SELECT,ElementSelect),_defineProperty(_defineProperty2,ELEMENT_TYPE_MULTISELECT,ElementMultiSelect),_defineProperty(_defineProperty2,ELEMENT_TYPE_COUNTRY,ElementSelect),_defineProperty(_defineProperty2,ELEMENT_TYPE_PROVINCE,ElementSelect),_defineProperty(_defineProperty2,ELEMENT_TYPE_CHECKBOX,ElementCheckbox),_defineProperty(_defineProperty2,ELEMENT_TYPE_RADIO,ElementRadio),_defineProperty(_defineProperty2,ELEMENT_TYPE_DATE,ElementText),_defineProperty(_defineProperty2,ELEMENT_TYPE_PHONE,ElementText),_defineProperty(_defineProperty2,ELEMENT_TYPE_PHONE_PICKER,ElementPhoneNumber),_defineProperty2));_defineProperty(Builder,"defaultProps",{className:null,defaults:{},elements:Builder.defaultElements,onSubmit:function onSubmit(){},validationErrors:[]/**
47
42
  * Initializes the component.
48
43
  * @param {Object} props The components props.
49
44
  */});export default Builder;
@@ -1,6 +1,6 @@
1
- import _camelCase from"lodash/camelCase";import React,{memo}from'react';import PropTypes from'prop-types';import classNames from'classnames';import Checkbox from'@shopgate/pwa-ui-shared/Form/Checkbox';/**
1
+ import _camelCase from"lodash/camelCase";import React,{memo}from'react';import PropTypes from'prop-types';import classNames from'classnames';import Checkbox from'@shopgate/pwa-ui-shared/Form/Checkbox';import FormHelper from"./FormHelper";/**
2
2
  * Takes an element and renders it, if the type matches
3
3
  * @param {Object} props Component props.
4
4
  * @param {Object} props.element The data of the element to be rendered
5
5
  * @returns {JSX}
6
- */var ElementCheckbox=function ElementCheckbox(props){var element=props.element,errorText=props.errorText,value=props.value,name=props.name,visible=props.visible;if(!visible){return null;}return React.createElement("div",{className:classNames('container-checkbox',_camelCase(name),{validationError:!!errorText})},React.createElement(Checkbox,{name:name,errorText:errorText,checked:!!value,label:element.label,onChange:element.handleChange,translateErrorText:false,disabled:element.disabled}));};ElementCheckbox.defaultProps={value:false,visible:true};export default memo(ElementCheckbox);
6
+ */var ElementCheckbox=function ElementCheckbox(props){var element=props.element,errorText=props.errorText,value=props.value,name=props.name,visible=props.visible,formName=props.formName;if(!visible){return null;}return React.createElement("div",{className:classNames('container-checkbox',_camelCase(name),'formBuilderField',{validationError:!!errorText})},React.createElement(Checkbox,{name:name,errorText:errorText,checked:!!value,label:element.label,onChange:element.handleChange,translateErrorText:false,showErrorText:false,disabled:element.disabled}),React.createElement(FormHelper,{errorText:errorText,element:element,formName:formName}));};ElementCheckbox.defaultProps={value:false,visible:true};export default memo(ElementCheckbox);
@@ -1,6 +1,6 @@
1
- import _camelCase from"lodash/camelCase";import React,{memo}from'react';import PropTypes from'prop-types';import classNames from'classnames';import Select from'@shopgate/pwa-ui-shared/Form/Select';import SelectContextChoices from'@shopgate/pwa-ui-shared/Form/SelectContextChoices';import ResponsiveContainer from"../../ResponsiveContainer/ResponsiveContainer";/**
1
+ import _camelCase from"lodash/camelCase";import React,{memo}from'react';import PropTypes from'prop-types';import classNames from'classnames';import Select from'@shopgate/pwa-ui-shared/Form/Select';import SelectContextChoices from'@shopgate/pwa-ui-shared/Form/SelectContextChoices';import ResponsiveContainer from"../../ResponsiveContainer/ResponsiveContainer";import FormHelper from"./FormHelper";/**
2
2
  * Takes an element and renders it, if the type matches
3
3
  * @param {Object} props Component props.
4
4
  * @param {Object} props.element The data of the element to be rendered
5
5
  * @returns {JSX}
6
- */var ElementMultiSelect=function ElementMultiSelect(props){var element=props.element,errorText=props.errorText,name=props.name,value=props.value,visible=props.visible;if(!visible){return null;}var values=[].concat(value).filter(Boolean);return React.createElement("div",{className:classNames(_camelCase(name),{validationError:!!errorText})},React.createElement(ResponsiveContainer,{appAlways:true,breakpoint:"xs"},React.createElement(Select,{name:name,label:element.label,placeholder:element.placeholder,value:values,options:element.options,onChange:element.handleChange,errorText:errorText,isControlled:true,translateErrorText:false,disabled:element.disabled,multiple:true})),React.createElement(ResponsiveContainer,{webOnly:true,breakpoint:">xs"},React.createElement(SelectContextChoices,{label:element.label,placeholder:element.placeholder,value:values,options:element.options,onChange:element.handleChange,errorText:errorText})));};ElementMultiSelect.defaultProps={value:'',visible:true};export default memo(ElementMultiSelect);
6
+ */var ElementMultiSelect=function ElementMultiSelect(props){var element=props.element,errorText=props.errorText,name=props.name,value=props.value,visible=props.visible,formName=props.formName;if(!visible){return null;}var values=[].concat(value).filter(Boolean);return React.createElement("div",{className:classNames(_camelCase(name),'formBuilderField',{validationError:!!errorText})},React.createElement(ResponsiveContainer,{appAlways:true,breakpoint:"xs"},React.createElement(Select,{name:name,label:element.label,placeholder:element.placeholder,value:values,options:element.options,onChange:element.handleChange,errorText:errorText,isControlled:true,translateErrorText:false,showErrorText:false,disabled:element.disabled,multiple:true})),React.createElement(ResponsiveContainer,{webOnly:true,breakpoint:">xs"},React.createElement(SelectContextChoices,{label:element.label,placeholder:element.placeholder,value:values,options:element.options,onChange:element.handleChange,errorText:errorText,showErrorText:false})),React.createElement(FormHelper,{errorText:errorText,element:element,formName:formName}));};ElementMultiSelect.defaultProps={value:'',visible:true};export default memo(ElementMultiSelect);
@@ -1,8 +1,8 @@
1
- import _camelCase from"lodash/camelCase";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 classnames from'classnames';import{i18n}from'@shopgate/engage/core';import{parsePhoneNumber}from'react-phone-number-input';import PhoneInput from'react-phone-number-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 TextField from'@shopgate/pwa-ui-shared/TextField';import{useCountriesNames}from'@shopgate/engage/i18n';import{css}from'glamor';import{themeConfig}from'@shopgate/engage';var variables=themeConfig.variables,colors=themeConfig.colors;var styles={formField:css({width:'100%',paddingBottom:variables.gap.small}).toString(),phoneField:css({position:'relative',width:'100%',paddingTop:variables.gap.big*0.75,paddingBottom:variables.gap.big*1.25,marginBottom:variables.gap.small,' 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};/**
1
+ import _camelCase from"lodash/camelCase";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 classnames from'classnames';import{i18n}from'@shopgate/engage/core';import{parsePhoneNumber}from'react-phone-number-input';import PhoneInput from'react-phone-number-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 TextField from'@shopgate/pwa-ui-shared/TextField';import{useCountriesNames}from'@shopgate/engage/i18n';import{css}from'glamor';import{themeConfig}from'@shopgate/engage';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};/**
2
2
  * Renders the reserve form phone input maybe with country selection.
3
3
  * @param {Object} props The component props.
4
4
  * @returns {JSX.Element}
5
- */var UnwrappedElementPhoneNumber=React.memo(function(props){var _classnames;var element=props.element,name=props.name,errorText=props.errorText,value=props.value,visible=props.visible;var label=element.label,handleChange=element.handleChange,_element$default=element["default"],defaultValue=_element$default===void 0?'':_element$default,_element$disabled=element.disabled,disabled=_element$disabled===void 0?false:_element$disabled,_element$config=element.config;_element$config=_element$config===void 0?{}:_element$config;var _element$config$suppo=_element$config.supportedCountries,supportedCountries=_element$config$suppo===void 0?[]:_element$config$suppo,_element$config$userL=_element$config.userLocation,userLocation=_element$config$userL===void 0?{}:_element$config$userL;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.
5
+ */var UnwrappedElementPhoneNumber=React.memo(function(props){var _classnames;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$default=element["default"],defaultValue=_element$default===void 0?'':_element$default,_element$disabled=element.disabled,disabled=_element$disabled===void 0?false:_element$disabled,_element$config=element.config;_element$config=_element$config===void 0?{}:_element$config;var _element$config$suppo=_element$config.supportedCountries,supportedCountries=_element$config$suppo===void 0?[]:_element$config$suppo,_element$config$userL=_element$config.userLocation,userLocation=_element$config$userL===void 0?{}:_element$config$userL;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.
6
6
  var countries=React.useMemo(function(){if(!supportedCountries){return builtInCountries;}var sortedCountries=[].concat(builtInCountries);var sanitizedSupportedCountries=supportedCountries.map(function(country){var pieces=country.split('_');return pieces[0];});sanitizedSupportedCountries.forEach(function(country){sortedCountries.splice(sortedCountries.indexOf(country),1);});return[].concat(sanitizedSupportedCountries,sortedCountries);},[supportedCountries]);var countriesNames=useCountriesNames(supportedCountries,locales);// Get labels for supported countries.
7
7
  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]);// Sets the default country based on the users location.
8
- var defaultCountry=React.useMemo(function(){if(!defaultValue&&!value&&userLocation){return userLocation.country;}var phoneNumber=parsePhoneNumber(value||'');if(phoneNumber&&phoneNumber.country){return phoneNumber.country;}if(userLocation){return userLocation.country;}return i18n.getLang().split('-')[1];},[defaultValue,userLocation,value]);var handleChangeWrapped=React.useCallback(function(phoneValue){handleChange(phoneValue,{target:{name:name}});},[handleChange,name]);var phoneClasses=classnames((_classnames={},_defineProperty(_classnames,_camelCase(name),true),_defineProperty(_classnames,"phonePicker",true),_defineProperty(_classnames,"phonePickerError",!!errorText),_defineProperty(_classnames,"validationError",!!errorText),_defineProperty(_classnames,"phonePickerFocused",isFocused),_defineProperty(_classnames,styles.phoneField,true),_defineProperty(_classnames,styles.phoneFieldError,!!errorText),_classnames));if(!visible){return null;}if(!countries||countries.length===0){return React.createElement(TextField,{name:name,value:value,onChange:handleChange,onFocus:function onFocus(){return setIsFocused(true);},onBlur:function onBlur(){return setIsFocused(false);},label:label,className:classnames(styles.formField,{validationError:!!errorText}),errorText:errorText,disabled:disabled});}return React.createElement("div",{className:phoneClasses},React.createElement(PhoneInput,{defaultCountry:defaultCountry,addInternationalOption:false,flags:flags,name:name,value:value||'',onChange:handleChangeWrapped,onFocus:function onFocus(){return setIsFocused(true);},onBlur:function onBlur(){return setIsFocused(false);},placeholder:label,countries:countries,labels:labels,disabled:disabled}),!!errorText&&React.createElement("div",{className:"errorText ".concat(styles.phoneFieldErrorText)},errorText));});export default UnwrappedElementPhoneNumber;
8
+ var defaultCountry=React.useMemo(function(){if(!defaultValue&&!value&&userLocation){return userLocation.country;}var phoneNumber=parsePhoneNumber(value||'');if(phoneNumber&&phoneNumber.country){return phoneNumber.country;}if(userLocation){return userLocation.country;}return i18n.getLang().split('-')[1];},[defaultValue,userLocation,value]);var handleChangeWrapped=React.useCallback(function(phoneValue){handleChange(phoneValue,{target:{name:name}});},[handleChange,name]);var phoneClasses=classnames((_classnames={},_defineProperty(_classnames,_camelCase(name),true),_defineProperty(_classnames,"phonePicker",true),_defineProperty(_classnames,"phonePickerError",!!errorText),_defineProperty(_classnames,"validationError",!!errorText),_defineProperty(_classnames,"phonePickerFocused",isFocused),_defineProperty(_classnames,styles.phoneField,true),_defineProperty(_classnames,styles.phoneFieldError,!!errorText),_classnames));if(!visible){return null;}if(!countries||countries.length===0){return React.createElement(React.Fragment,null,React.createElement(TextField,{name:name,value:value,onChange:handleChange,onFocus:function onFocus(){return setIsFocused(true);},onBlur:function onBlur(){return setIsFocused(false);},label:label,className:classnames(styles.formField,{validationError:!!errorText}),disabled:disabled}),React.createElement(FormHelper,{errorText:errorText,element:element,formName:formName}));}return React.createElement("div",{className:"formBuilderField"},React.createElement("div",{className:phoneClasses},React.createElement(PhoneInput,{defaultCountry:defaultCountry,addInternationalOption:false,flags:flags,name:name,value:value||'',onChange:handleChangeWrapped,onFocus:function onFocus(){return setIsFocused(true);},onBlur:function onBlur(){return setIsFocused(false);},placeholder:label,countries:countries,labels:labels,disabled:disabled,countryOptionsOrder:supportedCountries.length?[].concat(supportedCountries,['|']):[]})),React.createElement(FormHelper,{errorText:errorText,element:element,formName:formName}));});export default UnwrappedElementPhoneNumber;
@@ -1,6 +1,6 @@
1
- import _camelCase from"lodash/camelCase";import React,{memo}from'react';import PropTypes from'prop-types';import classNames from'classnames';import RadioGroup from'@shopgate/pwa-ui-shared/Form/RadioGroup';import RadioItem from'@shopgate/pwa-ui-shared/Form/RadioGroup/components/Item';/**
1
+ import _camelCase from"lodash/camelCase";import React,{memo}from'react';import PropTypes from'prop-types';import classNames from'classnames';import RadioGroup from'@shopgate/pwa-ui-shared/Form/RadioGroup';import RadioItem from'@shopgate/pwa-ui-shared/Form/RadioGroup/components/Item';import FormHelper from"./FormHelper";/**
2
2
  * Takes an element and renders it, if the type matches
3
3
  * @param {Object} props Component props.
4
4
  * @param {Object} props.element The data of the element to be rendered
5
5
  * @returns {JSX}
6
- */var ElementRadio=function ElementRadio(props){var element=props.element,errorText=props.errorText,name=props.name,value=props.value,visible=props.visible;if(!visible){return null;}return React.createElement("div",{className:classNames(_camelCase(name),{validationError:!!errorText})},React.createElement(RadioGroup,{name:name,label:element.label,value:value,onChange:element.handleChange,errorText:errorText,isControlled:true,translateErrorText:false,disabled:element.disabled},Object.keys(element.options).map(function(itemName){return React.createElement(RadioItem,{key:"".concat(name,"_").concat(itemName),id:"".concat(name,"_").concat(_camelCase(itemName)),name:itemName,label:element.options[itemName]});})));};ElementRadio.defaultProps={value:'',visible:true};export default memo(ElementRadio);
6
+ */var ElementRadio=function ElementRadio(props){var element=props.element,errorText=props.errorText,name=props.name,value=props.value,visible=props.visible,formName=props.formName;if(!visible){return null;}return React.createElement("div",{className:classNames(_camelCase(name),'formBuilderField',{validationError:!!errorText})},React.createElement(RadioGroup,{name:name,label:element.label,value:value,onChange:element.handleChange,errorText:errorText,isControlled:true,translateErrorText:false,showErrorText:false,disabled:element.disabled},Object.keys(element.options).map(function(itemName){return React.createElement(RadioItem,{key:"".concat(name,"_").concat(itemName),id:"".concat(name,"_").concat(_camelCase(itemName)),name:itemName,label:element.options[itemName]});})),React.createElement(FormHelper,{errorText:errorText,element:element,formName:formName}));};ElementRadio.defaultProps={value:'',visible:true};export default memo(ElementRadio);
@@ -1,6 +1,6 @@
1
- import _camelCase from"lodash/camelCase";import React,{memo}from'react';import PropTypes from'prop-types';import classNames from'classnames';import Select from'@shopgate/pwa-ui-shared/Form/Select';/**
1
+ import _camelCase from"lodash/camelCase";import React,{memo}from'react';import PropTypes from'prop-types';import classNames from'classnames';import Select from'@shopgate/pwa-ui-shared/Form/Select';import FormHelper from"./FormHelper";/**
2
2
  * Takes an element and renders it, if the type matches
3
3
  * @param {Object} props Component props.
4
4
  * @param {Object} props.element The data of the element to be rendered
5
5
  * @returns {JSX}
6
- */var ElementSelect=function ElementSelect(props){var element=props.element,errorText=props.errorText,name=props.name,value=props.value,visible=props.visible;if(!visible){return null;}return React.createElement("div",{className:classNames(_camelCase(name),{validationError:!!errorText})},React.createElement(Select,{name:name,label:element.label,placeholder:element.placeholder,value:value,options:element.options,onChange:element.handleChange,errorText:errorText,isControlled:true,translateErrorText:false,disabled:element.disabled}));};ElementSelect.defaultProps={value:'',visible:true};export default memo(ElementSelect);
6
+ */var ElementSelect=function ElementSelect(props){var element=props.element,errorText=props.errorText,name=props.name,value=props.value,visible=props.visible,formName=props.formName;if(!visible){return null;}return React.createElement("div",{className:classNames(_camelCase(name),'formBuilderField',{validationError:!!errorText})},React.createElement(Select,{name:name,label:element.label,placeholder:element.placeholder,value:value,options:element.options,onChange:element.handleChange,errorText:errorText,isControlled:true,translateErrorText:false,showErrorText:false,disabled:element.disabled}),React.createElement(FormHelper,{errorText:errorText,element:element,formName:formName}));};ElementSelect.defaultProps={value:'',visible:true};export default memo(ElementSelect);
@@ -1,7 +1,7 @@
1
- import _camelCase from"lodash/camelCase";var _mapping;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;}import React,{memo}from'react';import PropTypes from'prop-types';import classNames from'classnames';import TextField from'@shopgate/pwa-ui-shared/TextField';import{ELEMENT_TYPE_TEXT,ELEMENT_TYPE_NUMBER,ELEMENT_TYPE_EMAIL,ELEMENT_TYPE_PASSWORD,ELEMENT_TYPE_DATE,ELEMENT_TYPE_PHONE}from"./Builder.constants";// Map element type to input type
1
+ import _camelCase from"lodash/camelCase";var _mapping;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;}import React,{memo}from'react';import PropTypes from'prop-types';import classNames from'classnames';import TextField from'@shopgate/pwa-ui-shared/TextField';import FormHelper from"./FormHelper";import{ELEMENT_TYPE_TEXT,ELEMENT_TYPE_NUMBER,ELEMENT_TYPE_EMAIL,ELEMENT_TYPE_PASSWORD,ELEMENT_TYPE_DATE,ELEMENT_TYPE_PHONE}from"./Builder.constants";// Map element type to input type
2
2
  var mapping=(_mapping={},_defineProperty(_mapping,ELEMENT_TYPE_TEXT,'text'),_defineProperty(_mapping,ELEMENT_TYPE_NUMBER,'number'),_defineProperty(_mapping,ELEMENT_TYPE_EMAIL,'email'),_defineProperty(_mapping,ELEMENT_TYPE_PASSWORD,'password'),_defineProperty(_mapping,ELEMENT_TYPE_DATE,'date'),_defineProperty(_mapping,ELEMENT_TYPE_PHONE,'tel'),_mapping);/**
3
3
  * Takes an element and renders it, if the type matches
4
4
  * @param {Object} props Component props.
5
5
  * @param {Object} props.element The data of the element to be rendered
6
6
  * @returns {JSX}
7
- */var ElementText=function ElementText(props){var element=props.element,errorText=props.errorText,name=props.name,value=props.value,visible=props.visible;if(!visible){return null;}var type=mapping[element.type];return React.createElement("div",{className:classNames(_camelCase(name),{validationError:!!errorText})},React.createElement(TextField,{type:type,name:name,label:element.label,value:value,onChange:element.handleChange,errorText:errorText,isControlled:true,translateErrorText:false,disabled:element.disabled}));};ElementText.defaultProps={value:'',visible:true};export default memo(ElementText);
7
+ */var ElementText=function ElementText(props){var element=props.element,errorText=props.errorText,name=props.name,value=props.value,visible=props.visible,formName=props.formName;if(!visible){return null;}var type=mapping[element.type];return React.createElement("div",{className:classNames(_camelCase(name),'formBuilderField',{validationError:!!errorText})},React.createElement(TextField,{type:type,name:name,label:element.label,value:value,onChange:element.handleChange,errorText:errorText,isControlled:true,translateErrorText:false,showErrorText:false,disabled:element.disabled}),React.createElement(FormHelper,{errorText:errorText,element:element,formName:formName}));};ElementText.defaultProps={value:'',visible:true};export default memo(ElementText);
@@ -0,0 +1,5 @@
1
+ import React from'react';import PropTypes from'prop-types';import ErrorTextCmp from'@shopgate/pwa-ui-shared/FormElement/components/ErrorText';import{SurroundPortals}from'@shopgate/engage/components';import{sanitizePortalName}from"./helpers/common";/**
2
+ * Component for error texts
3
+ * @param {Object} props Component props.
4
+ * @returns {JSX}
5
+ */var FormHelper=function FormHelper(_ref){var errorText=_ref.errorText,element=_ref.element,formName=_ref.formName;return React.createElement("div",{className:"formHelper"},React.createElement(SurroundPortals,{portalName:"".concat(sanitizePortalName(formName),".").concat(sanitizePortalName(element.id),".formHelper"),portalProps:{formName:formName,element:element,errorText:errorText}},!!errorText&&React.createElement(ErrorTextCmp,{errorText:errorText,translate:false})));};FormHelper.defaultProps={errorText:null};export default FormHelper;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Takes a string and converts it to a part to be used in a portal name
3
+ * @package FormBuilder
4
+ * @param {string} s The string to be sanitized
5
+ * @return {string}
6
+ */export var sanitizePortalName=function sanitizePortalName(s){return s.replace(/[\\._]/,'-');};
@@ -1 +1 @@
1
- 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;}import{isIOSTheme}from'@shopgate/engage/core';import{themeConfig}from'@shopgate/engage';import{responsiveMediaQuery}from'@shopgate/engage/styles';var colors=themeConfig.colors,variables=themeConfig.variables;export var TWO_COLUMN_LAYOUT=_defineProperty({},responsiveMediaQuery('>=md',{webOnly:false}),{display:'flex',flexDirection:'row',flexWrap:'wrap',margin:-8,marginTop:16,marginBottom:8,'>div':{flex:'1 1 50%',padding:'0 8px',maxWidth:'50%'},'>.phonePicker':{marginLeft:8,marginRight:8,flexBasis:'calc(50% - 16px)'}});export var OUTLINED_FORM_FIELDS={' .textField, .formElement:not(.radioGroup):not(.checkbox), .phonePicker':_extends({paddingBottom:8},!isIOSTheme()?{background:"var(--color-background-accent, ".concat(colors.shade8,")"),padding:0,marginBottom:32,borderTopLeftRadius:4,borderTopRightRadius:4,borderBottom:"1px solid ".concat(colors.shade12)}:{}),' .phonePickerError':_extends({},!isIOSTheme()?{borderBottom:"2px solid var(--color-state-alert, ".concat(colors.error,")")}:{}),' .phonePickerFocused:not(.phonePickerError)':_extends({},!isIOSTheme()?{borderBottom:'2px solid var(--color-primary)'}:{}),' .formElement:not(.radioGroup) label':_extends({},!isIOSTheme()?{paddingLeft:24,color:'var(--color-text-low-emphasis)',transform:'translate3d(0, -18px, 0) scale3d(0.75, 0.75, 0.75)'}:{}),' .textField label':_extends({},!isIOSTheme()?{paddingLeft:17,color:'var(--color-text-low-emphasis)','.floating':{transform:'translate3d(3px, -18px, 0) scale3d(0.75, 0.75, 0.75)'}}:{}),' .formElement:not(.radioGroup) select, .formElement .info-field':_extends({},!isIOSTheme()?{paddingLeft:16,color:'var(--color-text-high-emphasis)'}:{}),' .formElement:not(.radioGroup):not(.checkbox) svg':_extends({},!isIOSTheme()?{marginTop:8,right:8}:{}),' .formElement:not(.radioGroup) .placeholder':_extends({},!isIOSTheme()?{paddingLeft:20,color:'var(--color-text-low-emphasis)'}:{}),' .formElement.disabled, .textField.disabled':{' input, select, svg':{opacity:0.28},' .label':{opacity:0.6}},' .textField input':_extends({},!isIOSTheme()?{paddingLeft:16,color:'var(--color-text-high-emphasis)'}:{}),' .underline':_extends({},!isIOSTheme()?{marginBottom:0,borderBottom:'none'}:{}),' .errorText':_extends({},!isIOSTheme()?{bottom:-20,paddingLeft:16}:{bottom:0}),' .phonePicker':_extends({paddingTop:variables.gap.big},isIOSTheme()?{paddingBottom:2}:{paddingTop:23,paddingLeft:8}),' .phonePicker .PhoneInputInput':_extends({},!isIOSTheme()?{borderBottom:'none',color:'var(--color-text-high-emphasis)','&:focus':{borderBottom:'none'},'::placeholder':{color:'var(--color-text-low-emphasis)'}}:{}),' .phonePicker .errorText':_extends({},!isIOSTheme()?{marginLeft:-8}:{marginLeft:0,bottom:-11,overflow:'initial'}),' .PhoneInputCountryIcon':_extends({},!isIOSTheme()?{marginBottom:8,marginLeft:16}:{}),' .PhoneInputCountrySelectArrow':_extends({},!isIOSTheme()?{marginRight:6,marginLeft:10,marginBottom:8}:{}),' .placeholder':{color:colors.shade12}};
1
+ 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;}import{isIOSTheme}from'@shopgate/engage/core';import{themeConfig}from'@shopgate/engage';import{responsiveMediaQuery}from'@shopgate/engage/styles';var colors=themeConfig.colors,variables=themeConfig.variables;export var TWO_COLUMN_LAYOUT=_defineProperty({},responsiveMediaQuery('>=md',{webOnly:false}),{display:'flex',flexDirection:'row',flexWrap:'wrap',margin:-8,marginTop:16,marginBottom:8,'>div':{flex:'1 1 50%',padding:'0 8px',maxWidth:'50%'},'>.phonePicker':{marginLeft:8,marginRight:8,flexBasis:'calc(50% - 16px)'}});export var OUTLINED_FORM_FIELDS={' .formHelper':_extends({},!isIOSTheme()?{minHeight:32}:{minHeight:12},{' .errorText':_extends({position:'relative',textOverflow:'unset',whiteSpace:'unset',lineHeight:'15px',bottom:'unset'},!isIOSTheme()?{padding:'8px 8px 8px 16px'}:{})}),' .formBuilderField':{' .textField, .formElement:not(.radioGroup):not(.checkbox), .phonePicker':{marginBottom:'unset',paddingBottom:'unset'}},' .radioGroup + .formHelper, .checkbox + .formHelper':{minHeight:16},' .checkbox':{paddingBottom:0},' .textField, .formElement:not(.radioGroup):not(.checkbox), .phonePicker':_extends({paddingBottom:8},!isIOSTheme()?{background:"var(--color-background-accent, ".concat(colors.shade8,")"),padding:0,marginBottom:32,borderTopLeftRadius:4,borderTopRightRadius:4,borderBottom:"1px solid ".concat(colors.shade12)}:{}),' .phonePickerError':_extends({},!isIOSTheme()?{borderBottom:"2px solid var(--color-state-alert, ".concat(colors.error,")")}:{}),' .phonePickerFocused:not(.phonePickerError)':_extends({},!isIOSTheme()?{borderBottom:'2px solid var(--color-primary)'}:{}),' .formElement:not(.radioGroup) label':_extends({},!isIOSTheme()?{paddingLeft:24,color:'var(--color-text-low-emphasis)',transform:'translate3d(0, -18px, 0) scale3d(0.75, 0.75, 0.75)'}:{}),' .textField label':_extends({},!isIOSTheme()?{paddingLeft:17,color:'var(--color-text-low-emphasis)','.floating':{transform:'translate3d(3px, -18px, 0) scale3d(0.75, 0.75, 0.75)'}}:{}),' .formElement:not(.radioGroup) select, .formElement .info-field':_extends({},!isIOSTheme()?{paddingLeft:16,color:'var(--color-text-high-emphasis)'}:{}),' .formElement:not(.radioGroup):not(.checkbox) svg':_extends({},!isIOSTheme()?{marginTop:8,right:8}:{}),' .formElement:not(.radioGroup) .placeholder':_extends({},!isIOSTheme()?{paddingLeft:20,color:'var(--color-text-low-emphasis)'}:{}),' .formElement.disabled, .textField.disabled':{' input, select, svg':{opacity:0.28},' .label':{opacity:0.6}},' .textField input':_extends({},!isIOSTheme()?{paddingLeft:16,color:'var(--color-text-high-emphasis)'}:{}),' .underline':_extends({},!isIOSTheme()?{marginBottom:0,borderBottom:'none'}:{}),' .errorText':_extends({},!isIOSTheme()?{bottom:-20,paddingLeft:16}:{bottom:0}),' .phonePicker':_extends({paddingTop:variables.gap.big},isIOSTheme()?{paddingBottom:2}:{paddingTop:23,paddingLeft:8}),' .phonePicker .PhoneInputInput':_extends({},!isIOSTheme()?{borderBottom:'none',color:'var(--color-text-high-emphasis)','&:focus':{borderBottom:'none'},'::placeholder':{color:'var(--color-text-low-emphasis)'}}:{}),' .phonePicker .errorText':_extends({},!isIOSTheme()?{marginLeft:-8}:{marginLeft:0,bottom:-11,overflow:'initial'}),' .PhoneInputCountryIcon':_extends({},!isIOSTheme()?{marginBottom:8,marginLeft:16}:{}),' .PhoneInputCountrySelectArrow':_extends({},!isIOSTheme()?{marginRight:6,marginLeft:10,marginBottom:8}:{}),' .placeholder':{color:colors.shade12}};
@@ -7,8 +7,12 @@ import _regeneratorRuntime from"@babel/runtime/regenerator";import _debounce fro
7
7
  * @param {Function} complete The completion callback.
8
8
  * @param {Object} validationConstraints validationConstraints
9
9
  * @param {Object} [formContainerRef=null] A ref to a container with forms
10
+ * @param {number} [validationErrorScrollOffset=10] When a form container ref is passed with the
11
+ * parameters, whenever validation errors occur, the page will scroll to the first error. Depending
12
+ * on the page, the scroll logic might not be accurate. So this offset parameter can be used
13
+ * to influence scroll behavior.
10
14
  * @returns {{ handleChange, handleSubmit, values, valid, validationErrors: ?Object, isSubmitting }}
11
- */export function useFormState(initialState,complete){var validationConstraints=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var formContainerRef=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;var _useScrollTo=useScrollTo(formContainerRef),scrollTo=_useScrollTo.scrollTo;// Submit lock prevents the form from being submitted multiple times
15
+ */export function useFormState(initialState,complete){var validationConstraints=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var formContainerRef=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;var validationErrorScrollOffset=arguments.length>4&&arguments[4]!==undefined?arguments[4]:10;var _useScrollTo=useScrollTo(formContainerRef,validationErrorScrollOffset),scrollTo=_useScrollTo.scrollTo;// Submit lock prevents the form from being submitted multiple times
12
16
  var submitLock=useRef(false);var _useState=useState(initialState),_useState2=_slicedToArray(_useState,2),values=_useState2[0],setValues=_useState2[1];var _useState3=useState(false),_useState4=_slicedToArray(_useState3,2),isSubmitting=_useState4[0],setSubmitting=_useState4[1];var _useState5=useState(false),_useState6=_slicedToArray(_useState5,2),changed=_useState6[0],setChanged=_useState6[1];var _useState7=useState(false),_useState8=_slicedToArray(_useState7,2),ignoreErrors=_useState8[0],setIgnoreErrors=_useState8[1];var _useValidation=useValidation(validationConstraints),valid=_useValidation.valid,validationErrors=_useValidation.validationErrors,validate=_useValidation.validate,reset=_useValidation.reset;var scrollToError=useCallback(function(){scrollTo('.validationError');},[scrollTo]);// -- CHANGED ---------------
13
17
  useEffect(function(){var isEqual=JSON.stringify(values)===JSON.stringify(initialState);if(!isEqual&&!changed){setChanged(true);}else if(isEqual&&changed){setChanged(false);}},[changed,initialState,values]);// -- IS_SUBMITTING ---------
14
18
  /* eslint-disable react-hooks/exhaustive-deps */useEffect(function(){if(!isSubmitting){return;}var mounted=true;if((valid===true||ignoreErrors)&&!submitLock.current){submitLock.current=true;_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return complete(values);case 2:if(mounted){setSubmitting(false);setChanged(false);submitLock.current=false;}case 3:case"end":return _context.stop();}}},_callee);}))();}// eslint-disable-next-line consistent-return
@@ -1,4 +1,5 @@
1
1
  import{useCallback}from'react';import{getCSSCustomProp}from'@shopgate/engage/styles';import{hasWebBridge}from"../helpers/bridge";/**
2
2
  * @param {Object} ref A ref to the scroll container
3
+ * @param {number} [offset=10] Optional offset for the scroll operation
3
4
  * @returns {Object}
4
- */export var useScrollTo=function useScrollTo(ref){var scrollTo=useCallback(function(selector){if(!(ref===null||ref===void 0?void 0:ref.current)){return;}var firstElement=ref.current.querySelector(selector);if(firstElement){if(hasWebBridge()){var offset=10;var appBarHeight=getCSSCustomProp('--app-bar-height')||0;var _firstElement$getBoun=firstElement.getBoundingClientRect(),top=_firstElement$getBoun.top;var scrollTop=top+window.pageYOffset-parseInt(appBarHeight,10)-offset;window.scroll({top:scrollTop,behavior:'smooth'});}else{firstElement.scrollIntoView({behavior:'smooth'});}}},[ref]);return{scrollTo:scrollTo};};
5
+ */export var useScrollTo=function useScrollTo(ref){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;var scrollTo=useCallback(function(selector){if(!(ref===null||ref===void 0?void 0:ref.current)){return;}var firstElement=ref.current.querySelector(selector);if(firstElement){if(hasWebBridge()){var scrollOffset=offset;var appBarHeight=getCSSCustomProp('--app-bar-height')||0;var _firstElement$getBoun=firstElement.getBoundingClientRect(),top=_firstElement$getBoun.top;var scrollTop=top+window.pageYOffset-parseInt(appBarHeight,10)-scrollOffset;window.scroll({top:scrollTop,behavior:'smooth'});}else{firstElement.scrollIntoView({behavior:'smooth'});}}},[offset,ref]);return{scrollTo:scrollTo};};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shopgate/engage",
3
- "version": "7.8.0-beta.1",
3
+ "version": "7.8.0-beta.2",
4
4
  "description": "Shopgate's ENGAGE library.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Shopgate <support@shopgate.com>",
@@ -16,12 +16,12 @@
16
16
  ],
17
17
  "dependencies": {
18
18
  "@shopgate/native-modules": "1.0.0-beta.18",
19
- "@shopgate/pwa-common": "7.8.0-beta.1",
20
- "@shopgate/pwa-common-commerce": "7.8.0-beta.1",
21
- "@shopgate/pwa-core": "7.8.0-beta.1",
22
- "@shopgate/pwa-ui-ios": "7.8.0-beta.1",
23
- "@shopgate/pwa-ui-material": "7.8.0-beta.1",
24
- "@shopgate/pwa-ui-shared": "7.8.0-beta.1",
19
+ "@shopgate/pwa-common": "7.8.0-beta.2",
20
+ "@shopgate/pwa-common-commerce": "7.8.0-beta.2",
21
+ "@shopgate/pwa-core": "7.8.0-beta.2",
22
+ "@shopgate/pwa-ui-ios": "7.8.0-beta.2",
23
+ "@shopgate/pwa-ui-material": "7.8.0-beta.2",
24
+ "@shopgate/pwa-ui-shared": "7.8.0-beta.2",
25
25
  "@stripe/react-stripe-js": "^1.1.2",
26
26
  "@stripe/stripe-js": "^1.3.1",
27
27
  "@virtuous/conductor": "~2.5.0",
@@ -1,5 +1,5 @@
1
- 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);}import{i18n}from'@shopgate/engage/core';import{generateFormFields}from'@shopgate/engage/account/helper/form';/**
1
+ 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);}import{i18n}from'@shopgate/engage/core';import{generateCustomerAttributesFields}from'@shopgate/engage/account/helper/form';/**
2
2
  * Generates form configuration.
3
3
  * @param {Object} params Additional parameters
4
4
  * @returns {Object}
5
- */var generateFormConfig=function generateFormConfig(_ref){var customerAttributes=_ref.customerAttributes,isGuest=_ref.isGuest;return{fields:_extends({},!isGuest&&{marketingOptIn:{type:'checkbox',label:i18n.text('registration.marketing_opt_in_label')}},{},generateFormFields(customerAttributes))};};export default generateFormConfig;
5
+ */var generateFormConfig=function generateFormConfig(_ref){var customerAttributes=_ref.customerAttributes,isGuest=_ref.isGuest,supportedCountries=_ref.supportedCountries,userLocation=_ref.userLocation;return{fields:_extends({},!isGuest&&{marketingOptIn:{type:'checkbox',label:i18n.text('registration.marketing_opt_in_label')}},{},generateCustomerAttributesFields({customerAttributes:customerAttributes,supportedCountries:supportedCountries,userLocation:userLocation}))};};export default generateFormConfig;
@@ -2,4 +2,4 @@ import React,{useMemo,useCallback}from'react';import PropTypes from'prop-types';
2
2
  * The RegistrationFormExtra component.
3
3
  * @param {Object} props The component props
4
4
  * @returns {JSX}
5
- */var RegistrationFormExtra=function RegistrationFormExtra(_ref){var isGuest=_ref.isGuest;var _useRegistration=useRegistration(isGuest),defaultExtraFormState=_useRegistration.defaultExtraFormState,updateExtraForm=_useRegistration.updateExtraForm,customerAttributes=_useRegistration.customerAttributes,extraFormValidationErrors=_useRegistration.extraFormValidationErrors;var formConfig=useMemo(function(){return generateFormConfig({customerAttributes:customerAttributes,isGuest:isGuest});},[customerAttributes,isGuest]);var handleUpdate=useCallback(function(values){updateExtraForm(values);},[updateExtraForm]);return React.createElement(Section,{className:section,hasForm:true,id:ELEMENT_ID_CUSTOMER_ATTRIBUTES},React.createElement(FormBuilder,{className:form,name:"RegistrationExtra",config:formConfig,defaults:defaultExtraFormState,validationErrors:extraFormValidationErrors,handleUpdate:handleUpdate}));};RegistrationFormExtra.defaultProps={isGuest:false};export default RegistrationFormExtra;
5
+ */var RegistrationFormExtra=function RegistrationFormExtra(_ref){var isGuest=_ref.isGuest;var _useRegistration=useRegistration(isGuest),defaultExtraFormState=_useRegistration.defaultExtraFormState,updateExtraForm=_useRegistration.updateExtraForm,customerAttributes=_useRegistration.customerAttributes,extraFormValidationErrors=_useRegistration.extraFormValidationErrors,supportedCountries=_useRegistration.supportedCountries,userLocation=_useRegistration.userLocation;var formConfig=useMemo(function(){return generateFormConfig({customerAttributes:customerAttributes,isGuest:isGuest,supportedCountries:supportedCountries,userLocation:userLocation});},[customerAttributes,isGuest,supportedCountries,userLocation]);var handleUpdate=useCallback(function(values){updateExtraForm(values);},[updateExtraForm]);return React.createElement(Section,{className:section,hasForm:true,id:ELEMENT_ID_CUSTOMER_ATTRIBUTES},React.createElement(FormBuilder,{className:form,name:"RegistrationExtra",config:formConfig,defaults:defaultExtraFormState,validationErrors:extraFormValidationErrors,handleUpdate:handleUpdate}));};RegistrationFormExtra.defaultProps={isGuest:false};export default RegistrationFormExtra;
@@ -1,4 +1,4 @@
1
- import _regeneratorRuntime from"@babel/runtime/regenerator";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 _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded);var key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++){key=sourceSymbolKeys[i];if(excluded.indexOf(key)>=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key];}}return target;}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return{};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i<sourceKeys.length;i++){key=sourceKeys[i];if(excluded.indexOf(key)>=0)continue;target[key]=source[key];}return target;}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import{EVALIDATION}from'@shopgate/engage/core';import{updateCheckoutOrder}from'@shopgate/engage/checkout/actions';import{extractAttributes}from'@shopgate/engage/account/helper/form';import{getMerchantCustomerAttributes}from'@shopgate/engage/core/selectors/merchantSettings';import{convertSubmitRegistrationValidationErrors}from"../helpers";/**
1
+ import _regeneratorRuntime from"@babel/runtime/regenerator";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 _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded);var key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++){key=sourceSymbolKeys[i];if(excluded.indexOf(key)>=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key];}}return target;}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return{};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i<sourceKeys.length;i++){key=sourceKeys[i];if(excluded.indexOf(key)>=0)continue;target[key]=source[key];}return target;}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import{EVALIDATION}from'@shopgate/engage/core';import{updateCheckoutOrder}from'@shopgate/engage/checkout/actions';import{extractAttributes,convertPipelineValidationErrors}from'@shopgate/engage/account/helper/form';import{getMerchantCustomerAttributes}from'@shopgate/engage/core/selectors/merchantSettings';/**
2
2
  * Submits guest registration form data.
3
3
  * @returns {Function}
4
- */export var submitGuestRegistration=function submitGuestRegistration(_ref){var billingFormData=_ref.billingFormData,shippingFormData=_ref.shippingFormData,pickupFormData=_ref.pickupFormData,extraFormData=_ref.extraFormData,processShipping=_ref.processShipping;return(/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(dispatch,getState){var customerAttributes,marketingOptIn,attributeData,attributes,pickupPerson,restPickupFormData,_pickupFormData,shippingFormVisible,pickupFormVisible,addressSequences,order,errors,response,code,validationErrors,converted,_converted$validation,sequenceErrors,shippingIndex,pickupIndex,billing,shipping,pickup;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:customerAttributes=getMerchantCustomerAttributes(getState());marketingOptIn=extraFormData.marketingOptIn,attributeData=_objectWithoutProperties(extraFormData,["marketingOptIn"]);attributes=extractAttributes(customerAttributes,attributeData);restPickupFormData={};if(pickupFormData){_pickupFormData=pickupFormData;pickupPerson=_pickupFormData.pickupPerson;restPickupFormData=_objectWithoutPropertiesLoose(_pickupFormData,["pickupPerson"]);_pickupFormData;}shippingFormVisible=processShipping&&!!shippingFormData;pickupFormVisible=pickupFormData&&pickupPerson!=='me';addressSequences=[_extends({type:'billing'},billingFormData)].concat(processShipping?_extends({type:'shipping'},shippingFormData||billingFormData):[],pickupFormData?_extends({},pickupPerson==='me'?_extends({type:'pickup'},billingFormData):_extends({type:'pickup'},restPickupFormData)):[]);order=_extends({addressSequences:addressSequences,primaryBillToAddressSequenceIndex:0,primaryShipToAddressSequenceIndex:1},(attributes===null||attributes===void 0?void 0:attributes.length)?{customer:{attributes:attributes}}:{});_context.prev=9;_context.next=12;return dispatch(updateCheckoutOrder(order));case 12:response=_context.sent;_context.next=23;break;case 15:_context.prev=15;_context.t0=_context["catch"](9);code=_context.t0.code,validationErrors=_context.t0.errors;if(!(code===EVALIDATION)){_context.next=22;break;}errors=validationErrors;_context.next=23;break;case 22:throw _context.t0;case 23:converted=convertSubmitRegistrationValidationErrors(errors);if(!((converted===null||converted===void 0?void 0:converted.validation)&&Object.keys(converted.validation).length>0)){_context.next=32;break;}sequenceErrors=converted===null||converted===void 0?void 0:(_converted$validation=converted.validation)===null||_converted$validation===void 0?void 0:_converted$validation.addressSequences;shippingIndex=addressSequences.findIndex(function(item){return item.type==='shipping';});pickupIndex=addressSequences.findIndex(function(item){return item.type==='pickup';});billing=(sequenceErrors===null||sequenceErrors===void 0?void 0:sequenceErrors['0'])||{};shipping=shippingFormVisible?(sequenceErrors===null||sequenceErrors===void 0?void 0:sequenceErrors[shippingIndex])||{}:{};pickup=pickupFormVisible?(sequenceErrors===null||sequenceErrors===void 0?void 0:sequenceErrors[pickupIndex])||{}:{};return _context.abrupt("return",{response:response,errors:{billingFormData:_extends({},billing),shippingFormData:_extends({},shipping),pickupFormData:_extends({},pickup)}});case 32:return _context.abrupt("return",{response:response});case 33:case"end":return _context.stop();}}},_callee,null,[[9,15]]);}));return function(_x,_x2){return _ref2.apply(this,arguments);};}());};
4
+ */export var submitGuestRegistration=function submitGuestRegistration(_ref){var billingFormData=_ref.billingFormData,shippingFormData=_ref.shippingFormData,pickupFormData=_ref.pickupFormData,extraFormData=_ref.extraFormData,processShipping=_ref.processShipping;return(/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(dispatch,getState){var customerAttributes,marketingOptIn,attributeData,attributes,pickupPerson,restPickupFormData,_pickupFormData,shippingFormVisible,pickupFormVisible,addressSequences,order,errors,response,code,validationErrors,converted,_converted$validation,_converted$validation2,sequenceErrors,shippingIndex,pickupIndex,billing,shipping,pickup,extra;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:customerAttributes=getMerchantCustomerAttributes(getState());marketingOptIn=extraFormData.marketingOptIn,attributeData=_objectWithoutProperties(extraFormData,["marketingOptIn"]);attributes=extractAttributes(customerAttributes,attributeData);restPickupFormData={};if(pickupFormData){_pickupFormData=pickupFormData;pickupPerson=_pickupFormData.pickupPerson;restPickupFormData=_objectWithoutPropertiesLoose(_pickupFormData,["pickupPerson"]);_pickupFormData;}shippingFormVisible=processShipping&&!!shippingFormData;pickupFormVisible=pickupFormData&&pickupPerson!=='me';addressSequences=[_extends({type:'billing'},billingFormData)].concat(processShipping?_extends({type:'shipping'},shippingFormData||billingFormData):[],pickupFormData?_extends({},pickupPerson==='me'?_extends({type:'pickup'},billingFormData):_extends({type:'pickup'},restPickupFormData)):[]);order=_extends({addressSequences:addressSequences,primaryBillToAddressSequenceIndex:0,primaryShipToAddressSequenceIndex:1},(attributes===null||attributes===void 0?void 0:attributes.length)?{customer:{attributes:attributes}}:{});_context.prev=9;_context.next=12;return dispatch(updateCheckoutOrder(order));case 12:response=_context.sent;_context.next=23;break;case 15:_context.prev=15;_context.t0=_context["catch"](9);code=_context.t0.code,validationErrors=_context.t0.errors;if(!(code===EVALIDATION)){_context.next=22;break;}errors=validationErrors;_context.next=23;break;case 22:throw _context.t0;case 23:converted=convertPipelineValidationErrors(errors,attributes);if(!((converted===null||converted===void 0?void 0:converted.validation)&&Object.keys(converted.validation).length>0)){_context.next=33;break;}sequenceErrors=converted===null||converted===void 0?void 0:(_converted$validation=converted.validation)===null||_converted$validation===void 0?void 0:_converted$validation.addressSequences;shippingIndex=addressSequences.findIndex(function(item){return item.type==='shipping';});pickupIndex=addressSequences.findIndex(function(item){return item.type==='pickup';});billing=(sequenceErrors===null||sequenceErrors===void 0?void 0:sequenceErrors['0'])||{};shipping=shippingFormVisible?(sequenceErrors===null||sequenceErrors===void 0?void 0:sequenceErrors[shippingIndex])||{}:{};pickup=pickupFormVisible?(sequenceErrors===null||sequenceErrors===void 0?void 0:sequenceErrors[pickupIndex])||{}:{};extra=(converted===null||converted===void 0?void 0:(_converted$validation2=converted.validation)===null||_converted$validation2===void 0?void 0:_converted$validation2.attributes)||{};return _context.abrupt("return",{response:response,errors:{billingFormData:_extends({},billing),shippingFormData:_extends({},shipping),pickupFormData:_extends({},pickup),extraFormData:_extends({},extra)}});case 33:return _context.abrupt("return",{response:response});case 34:case"end":return _context.stop();}}},_callee,null,[[9,15]]);}));return function(_x,_x2){return _ref2.apply(this,arguments);};}());};
@@ -5,7 +5,7 @@ import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGenera
5
5
  */var convertValidationErrors=function convertValidationErrors(validationErrors){return Object.keys(validationErrors).map(function(key){return{path:key,message:i18n.text(validationErrors[key])};});};/**
6
6
  * @param {Object} props The provider props
7
7
  * @returns {JSX}
8
- */var GuestRegistrationProvider=function GuestRegistrationProvider(_ref){var children=_ref.children,formContainerRef=_ref.formContainerRef,isDataReady=_ref.isDataReady,userLocation=_ref.userLocation,customerAttributes=_ref.customerAttributes,billingAddress=_ref.billingAddress,shippingAddress=_ref.shippingAddress,pickupAddress=_ref.pickupAddress,customer=_ref.customer,billingPickupEquals=_ref.billingPickupEquals,billingShippingEquals=_ref.billingShippingEquals,numberOfAddressLines=_ref.numberOfAddressLines,cartHasDirectShipItems=_ref.cartHasDirectShipItems,orderReserveOnly=_ref.orderReserveOnly,orderNeedsPayment=_ref.orderNeedsPayment,isShippingAddressSelectionEnabled=_ref.isShippingAddressSelectionEnabled,isPickupContactSelectionEnabled=_ref.isPickupContactSelectionEnabled,shopSettings=_ref.shopSettings,submitGuestRegistration=_ref.submitGuestRegistration,prepareCheckout=_ref.prepareCheckout,isLastStackEntry=_ref.isLastStackEntry,historyPop=_ref.historyPop,historyPush=_ref.historyPush;var _useScrollTo=useScrollTo(formContainerRef),scrollTo=_useScrollTo.scrollTo;var isShippingFormEnabled=useMemo(function(){return cartHasDirectShipItems;},[cartHasDirectShipItems]);var getIsShippingFormVisible=useCallback(function(){return isShippingFormEnabled&&!!shippingAddress&&!billingShippingEquals;},[billingShippingEquals,isShippingFormEnabled,shippingAddress]);var _useState=useState(false),_useState2=_slicedToArray(_useState,2),isLocked=_useState2[0],setIsLocked=_useState2[1];var _useState3=useState(false),_useState4=_slicedToArray(_useState3,2),isBillingFormSubmitted=_useState4[0],setIsBillingFormSubmitted=_useState4[1];var _useState5=useState(false),_useState6=_slicedToArray(_useState5,2),isShippingFormSubmitted=_useState6[0],setIsShippingFormSubmitted=_useState6[1];var _useState7=useState(false),_useState8=_slicedToArray(_useState7,2),isExtraFormSubmitted=_useState8[0],setIsExtraFormSubmitted=_useState8[1];var _useState9=useState(false),_useState10=_slicedToArray(_useState9,2),isPickupFormSubmitted=_useState10[0],setIsPickupFormSubmitted=_useState10[1];var _useState11=useState(null),_useState12=_slicedToArray(_useState11,2),billingFormRequestErrors=_useState12[0],setBillingFormRequestErrors=_useState12[1];var _useState13=useState(null),_useState14=_slicedToArray(_useState13,2),shippingFormRequestErrors=_useState14[0],setShippingFormRequestErrors=_useState14[1];var _useState15=useState(null),_useState16=_slicedToArray(_useState15,2),pickupFormRequestErrors=_useState16[0],setPickupFormRequestErrors=_useState16[1];var _useState17=useState(getIsShippingFormVisible()),_useState18=_slicedToArray(_useState17,2),isShippingFormVisible=_useState18[0],setIsShippingFormVisible=_useState18[1];var _useState19=useState(generateSelfPickupConstraints()),_useState20=_slicedToArray(_useState19,2),pickupConstraints=_useState20[0],setPickupConstraints=_useState20[1];var _useRoute=useRoute(),_useRoute$query$edit=_useRoute.query.edit,guestRegistrationEditMode=_useRoute$query$edit===void 0?null:_useRoute$query$edit;// Initialize checkout process.
8
+ */var GuestRegistrationProvider=function GuestRegistrationProvider(_ref){var children=_ref.children,formContainerRef=_ref.formContainerRef,isDataReady=_ref.isDataReady,userLocation=_ref.userLocation,customerAttributes=_ref.customerAttributes,billingAddress=_ref.billingAddress,shippingAddress=_ref.shippingAddress,pickupAddress=_ref.pickupAddress,customer=_ref.customer,billingPickupEquals=_ref.billingPickupEquals,billingShippingEquals=_ref.billingShippingEquals,numberOfAddressLines=_ref.numberOfAddressLines,cartHasDirectShipItems=_ref.cartHasDirectShipItems,orderReserveOnly=_ref.orderReserveOnly,orderNeedsPayment=_ref.orderNeedsPayment,isShippingAddressSelectionEnabled=_ref.isShippingAddressSelectionEnabled,isPickupContactSelectionEnabled=_ref.isPickupContactSelectionEnabled,shopSettings=_ref.shopSettings,submitGuestRegistration=_ref.submitGuestRegistration,prepareCheckout=_ref.prepareCheckout,isLastStackEntry=_ref.isLastStackEntry,historyPop=_ref.historyPop,historyPush=_ref.historyPush;var _useScrollTo=useScrollTo(formContainerRef),scrollTo=_useScrollTo.scrollTo;var isShippingFormEnabled=useMemo(function(){return cartHasDirectShipItems;},[cartHasDirectShipItems]);var getIsShippingFormVisible=useCallback(function(){return isShippingFormEnabled&&!!shippingAddress&&!billingShippingEquals;},[billingShippingEquals,isShippingFormEnabled,shippingAddress]);var _useState=useState(false),_useState2=_slicedToArray(_useState,2),isLocked=_useState2[0],setIsLocked=_useState2[1];var _useState3=useState(false),_useState4=_slicedToArray(_useState3,2),isBillingFormSubmitted=_useState4[0],setIsBillingFormSubmitted=_useState4[1];var _useState5=useState(false),_useState6=_slicedToArray(_useState5,2),isShippingFormSubmitted=_useState6[0],setIsShippingFormSubmitted=_useState6[1];var _useState7=useState(false),_useState8=_slicedToArray(_useState7,2),isExtraFormSubmitted=_useState8[0],setIsExtraFormSubmitted=_useState8[1];var _useState9=useState(false),_useState10=_slicedToArray(_useState9,2),isPickupFormSubmitted=_useState10[0],setIsPickupFormSubmitted=_useState10[1];var _useState11=useState(null),_useState12=_slicedToArray(_useState11,2),billingFormRequestErrors=_useState12[0],setBillingFormRequestErrors=_useState12[1];var _useState13=useState(null),_useState14=_slicedToArray(_useState13,2),shippingFormRequestErrors=_useState14[0],setShippingFormRequestErrors=_useState14[1];var _useState15=useState(null),_useState16=_slicedToArray(_useState15,2),pickupFormRequestErrors=_useState16[0],setPickupFormRequestErrors=_useState16[1];var _useState17=useState(null),_useState18=_slicedToArray(_useState17,2),extraFormRequestErrors=_useState18[0],setExtraFormRequestErrors=_useState18[1];var _useState19=useState(getIsShippingFormVisible()),_useState20=_slicedToArray(_useState19,2),isShippingFormVisible=_useState20[0],setIsShippingFormVisible=_useState20[1];var _useState21=useState(generateSelfPickupConstraints()),_useState22=_slicedToArray(_useState21,2),pickupConstraints=_useState22[0],setPickupConstraints=_useState22[1];var _useRoute=useRoute(),_useRoute$query$edit=_useRoute.query.edit,guestRegistrationEditMode=_useRoute$query$edit===void 0?null:_useRoute$query$edit;// Initialize checkout process.
9
9
  var _useAsyncMemo=useAsyncMemo(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:if(!guestRegistrationEditMode){_context.next=2;break;}return _context.abrupt("return",true);case 2:_context.prev=2;setIsLocked(true);_context.next=6;return prepareCheckout({initializePayment:false,initializeOrder:!!isLastStackEntry});case 6:setIsLocked(false);return _context.abrupt("return",true);case 10:_context.prev=10;_context.t0=_context["catch"](2);setIsLocked(false);return _context.abrupt("return",false);case 14:case"end":return _context.stop();}}},_callee,null,[[2,10]]);})),[],false),_useAsyncMemo2=_slicedToArray(_useAsyncMemo,1),isInitialized=_useAsyncMemo2[0];useEffect(function(){setIsShippingFormVisible(getIsShippingFormVisible());},[getIsShippingFormVisible,setIsShippingFormVisible]);// Determine values to prefill some form fields
10
10
  var userCountry=useMemo(function(){return(userLocation===null||userLocation===void 0?void 0:userLocation.country)||(appConfig===null||appConfig===void 0?void 0:appConfig.marketId)||null;},[userLocation]);var userRegion=useMemo(function(){return(userLocation===null||userLocation===void 0?void 0:userLocation.region)||null;},[userLocation]);// ===== billing form =====
11
11
  var defaultBillingFormState=useMemo(function(){return _extends({},initialBillingFormState,{country:userCountry,region:userRegion},pickBy(billingAddress||{},identity));},[billingAddress,userCountry,userRegion]);var billingConstraints=useMemo(function(){return generateBillingConstraints(orderReserveOnly);},[orderReserveOnly]);var handleBillingFormSubmit=useCallback(function(){setIsBillingFormSubmitted(true);},[setIsBillingFormSubmitted]);var billingFormState=useFormState(defaultBillingFormState,handleBillingFormSubmit,billingConstraints,formContainerRef);// ===== shipping form =====
@@ -13,5 +13,5 @@ var defaultShippingFormState=useMemo(function(){return _extends({},initialShippi
13
13
  var defaultPickupFormState=useMemo(function(){return _extends({},initialPickupFormState,{},!billingPickupEquals?pickBy(pickupAddress||{},identity):{},{pickupPerson:billingPickupEquals?'me':'someoneElse'});},[billingPickupEquals,pickupAddress]);var handlePickupFormSubmit=useCallback(function(){setIsPickupFormSubmitted(true);},[]);var pickupFormState=useFormState(defaultPickupFormState,handlePickupFormSubmit,pickupConstraints,formContainerRef);useEffect(function(){setPickupConstraints(pickupFormState.values.pickupPerson==='me'?generateSelfPickupConstraints():generatePickupConstraints());},[pickupFormState.values.pickupPerson]);// ===== extra form =====
14
14
  var defaultExtraFormState=useMemo(function(){return _extends({},initialOptInFormState,{},extractDefaultValues((customer===null||customer===void 0?void 0:customer.attributes)||[]));},[customer]);var extraConstraints=useMemo(function(){return generateExtraConstraints(customerAttributes);},[customerAttributes]);var handleExtraFormSubmit=useCallback(function(){setIsExtraFormSubmitted(true);},[]);var extraFormState=useFormState(defaultExtraFormState,handleExtraFormSubmit,extraConstraints,formContainerRef);var handleSubmit=useCallback(function(){billingFormState.handleSubmit();shippingFormState.handleSubmit();pickupFormState.handleSubmit();extraFormState.handleSubmit();},[billingFormState,extraFormState,pickupFormState,shippingFormState]);useEffect(function(){if(!isBillingFormSubmitted||!isShippingFormSubmitted||!isPickupFormSubmitted||!isExtraFormSubmitted){return;}// Break the process when one of the forms has validation errors from the constraints
15
15
  if(!billingFormState.valid||!shippingFormState.valid||!pickupFormState.valid||!extraFormState.valid){setIsBillingFormSubmitted(false);setIsShippingFormSubmitted(false);setIsPickupFormSubmitted(false);setIsExtraFormSubmitted(false);}/** Async wrapper for submit registration */var fn=/*#__PURE__*/function(){var _ref3=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var response,_ref4,errors;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:setIsLocked(true);_context2.prev=1;_context2.next=4;return submitGuestRegistration(_extends({billingFormData:billingFormState.values},isShippingFormVisible?{shippingFormData:shippingFormState.values}:{},{},isPickupContactSelectionEnabled?{pickupFormData:pickupFormState.values}:{},{extraFormData:extraFormState.values,processShipping:isShippingAddressSelectionEnabled}));case 4:response=_context2.sent;_context2.next=11;break;case 7:_context2.prev=7;_context2.t0=_context2["catch"](1);setIsLocked(false);return _context2.abrupt("return");case 11:_ref4=response||{},errors=_ref4.errors;if(errors){_context2.next=17;break;}setIsLocked(false);LoadingProvider.setLoading(GUEST_CHECKOUT_PAYMENT_PATTERN);if(guestRegistrationEditMode){historyPop();}else{historyPush({pathname:GUEST_CHECKOUT_PAYMENT_PATTERN});}return _context2.abrupt("return");case 17:// Updated the request validation errors
16
- setBillingFormRequestErrors((errors===null||errors===void 0?void 0:errors.billingFormData)||null);setShippingFormRequestErrors((errors===null||errors===void 0?void 0:errors.shippingFormData)||null);setPickupFormRequestErrors((errors===null||errors===void 0?void 0:errors.pickupFormData)||null);// Release forms for additional submits
17
- setIsBillingFormSubmitted(false);setIsShippingFormSubmitted(false);setIsPickupFormSubmitted(false);setIsExtraFormSubmitted(false);setIsLocked(false);case 25:case"end":return _context2.stop();}}},_callee2,null,[[1,7]]);}));return function fn(){return _ref3.apply(this,arguments);};}();fn();/* eslint-disable react-hooks/exhaustive-deps */},[isBillingFormSubmitted,isShippingFormSubmitted,isPickupFormSubmitted,isExtraFormSubmitted]);/* eslint-enable react-hooks/exhaustive-deps */ /* eslint-disable react-hooks/exhaustive-deps */useEffect(function(){billingFormState.scrollToError();},[billingFormRequestErrors,shippingFormRequestErrors,pickupFormRequestErrors,billingFormState.scrollToError]);/* eslint-enable react-hooks/exhaustive-deps */useEffect(function(){if(isLocked){LoadingProvider.setLoading(GUEST_CHECKOUT_PATTERN);return;}LoadingProvider.unsetLoading(GUEST_CHECKOUT_PATTERN);},[isLocked]);useEffect(function(){var timer=setTimeout(function(){if(!guestRegistrationEditMode){return;}var scrollToElement;if(guestRegistrationEditMode===ADDRESS_TYPE_SHIPPING){if(isShippingFormVisible){scrollToElement=ELEMENT_ID_SHIPPING_CONTACT;}else{scrollToElement=ELEMENT_ID_SHIPPING_CONTACT_TOGGLE;}}else if(guestRegistrationEditMode===ADDRESS_TYPE_PICKUP){scrollToElement=ELEMENT_ID_PICKUP_CONTACT;}if(scrollToElement){scrollTo("#".concat(scrollToElement));}},500);return function(){return clearTimeout(timer);};/* eslint-disable react-hooks/exhaustive-deps */},[]);/* eslint-enable react-hooks/exhaustive-deps */var value=useMemo(function(){return{isShippingFormEnabled:isShippingFormEnabled,isShippingFormVisible:isShippingFormVisible,setIsShippingFormVisible:setIsShippingFormVisible,orderReserveOnly:orderReserveOnly,orderNeedsPayment:orderNeedsPayment,guestRegistrationEditMode:guestRegistrationEditMode,defaultBillingFormState:defaultBillingFormState,updateBillingForm:billingFormState.setValues,defaultShippingFormState:defaultShippingFormState,updateShippingForm:shippingFormState.setValues,defaultPickupFormState:defaultPickupFormState,updatePickupForm:pickupFormState.setValues,defaultExtraFormState:defaultExtraFormState,updateExtraForm:extraFormState.setValues,billingFormValidationErrors:convertValidationErrors(billingFormState.validationErrors||billingFormRequestErrors||{}),shippingFormValidationErrors:convertValidationErrors(shippingFormState.validationErrors||shippingFormRequestErrors||{}),pickupFormValidationErrors:convertValidationErrors(pickupFormState.validationErrors||pickupFormRequestErrors||{}),extraFormValidationErrors:convertValidationErrors(extraFormState.validationErrors||{}),isShippingAddressSelectionEnabled:isShippingAddressSelectionEnabled,isPickupContactSelectionEnabled:isPickupContactSelectionEnabled,customerAttributes:customerAttributes,numberOfAddressLines:numberOfAddressLines,userLocation:userLocation,supportedCountries:shopSettings.supportedCountries,isLocked:isLocked,handleSubmit:handleSubmit};},[isShippingFormEnabled,isShippingFormVisible,defaultBillingFormState,billingFormState.setValues,billingFormState.validationErrors,defaultShippingFormState,shippingFormState.setValues,shippingFormState.validationErrors,defaultExtraFormState,extraFormState.setValues,extraFormState.validationErrors,defaultPickupFormState,pickupFormState.setValues,pickupFormState.validationErrors,billingFormRequestErrors,shippingFormRequestErrors,pickupFormRequestErrors,orderReserveOnly,orderNeedsPayment,guestRegistrationEditMode,isShippingAddressSelectionEnabled,isPickupContactSelectionEnabled,customerAttributes,numberOfAddressLines,userLocation,shopSettings.supportedCountries,isLocked,handleSubmit]);if(!isDataReady||!isInitialized){return null;}return React.createElement(Context.Provider,{value:value},children);};GuestRegistrationProvider.defaultProps={children:null,customer:null,formContainerRef:null,billingAddress:null,shippingAddress:null,pickupAddress:null,billingPickupEquals:true,billingShippingEquals:true,cartHasDirectShipItems:false,orderReserveOnly:false,orderNeedsPayment:false,numberOfAddressLines:null,isShippingAddressSelectionEnabled:false,isPickupContactSelectionEnabled:false};export default connect(GuestRegistrationProvider);
16
+ setBillingFormRequestErrors((errors===null||errors===void 0?void 0:errors.billingFormData)||null);setShippingFormRequestErrors((errors===null||errors===void 0?void 0:errors.shippingFormData)||null);setPickupFormRequestErrors((errors===null||errors===void 0?void 0:errors.pickupFormData)||null);setExtraFormRequestErrors((errors===null||errors===void 0?void 0:errors.extraFormData)||null);// Release forms for additional submits
17
+ setIsBillingFormSubmitted(false);setIsShippingFormSubmitted(false);setIsPickupFormSubmitted(false);setIsExtraFormSubmitted(false);setIsLocked(false);case 26:case"end":return _context2.stop();}}},_callee2,null,[[1,7]]);}));return function fn(){return _ref3.apply(this,arguments);};}();fn();/* eslint-disable react-hooks/exhaustive-deps */},[isBillingFormSubmitted,isShippingFormSubmitted,isPickupFormSubmitted,isExtraFormSubmitted]);/* eslint-enable react-hooks/exhaustive-deps */ /* eslint-disable react-hooks/exhaustive-deps */useEffect(function(){billingFormState.scrollToError();},[billingFormRequestErrors,shippingFormRequestErrors,pickupFormRequestErrors,billingFormState.scrollToError]);/* eslint-enable react-hooks/exhaustive-deps */useEffect(function(){if(isLocked){LoadingProvider.setLoading(GUEST_CHECKOUT_PATTERN);return;}LoadingProvider.unsetLoading(GUEST_CHECKOUT_PATTERN);},[isLocked]);useEffect(function(){var timer=setTimeout(function(){if(!guestRegistrationEditMode){return;}var scrollToElement;if(guestRegistrationEditMode===ADDRESS_TYPE_SHIPPING){if(isShippingFormVisible){scrollToElement=ELEMENT_ID_SHIPPING_CONTACT;}else{scrollToElement=ELEMENT_ID_SHIPPING_CONTACT_TOGGLE;}}else if(guestRegistrationEditMode===ADDRESS_TYPE_PICKUP){scrollToElement=ELEMENT_ID_PICKUP_CONTACT;}if(scrollToElement){scrollTo("#".concat(scrollToElement));}},500);return function(){return clearTimeout(timer);};/* eslint-disable react-hooks/exhaustive-deps */},[]);/* eslint-enable react-hooks/exhaustive-deps */var value=useMemo(function(){return{isShippingFormEnabled:isShippingFormEnabled,isShippingFormVisible:isShippingFormVisible,setIsShippingFormVisible:setIsShippingFormVisible,orderReserveOnly:orderReserveOnly,orderNeedsPayment:orderNeedsPayment,guestRegistrationEditMode:guestRegistrationEditMode,defaultBillingFormState:defaultBillingFormState,updateBillingForm:billingFormState.setValues,defaultShippingFormState:defaultShippingFormState,updateShippingForm:shippingFormState.setValues,defaultPickupFormState:defaultPickupFormState,updatePickupForm:pickupFormState.setValues,defaultExtraFormState:defaultExtraFormState,updateExtraForm:extraFormState.setValues,billingFormValidationErrors:convertValidationErrors(billingFormState.validationErrors||billingFormRequestErrors||{}),shippingFormValidationErrors:convertValidationErrors(shippingFormState.validationErrors||shippingFormRequestErrors||{}),pickupFormValidationErrors:convertValidationErrors(pickupFormState.validationErrors||pickupFormRequestErrors||{}),extraFormValidationErrors:convertValidationErrors(extraFormState.validationErrors||extraFormRequestErrors||{}),isShippingAddressSelectionEnabled:isShippingAddressSelectionEnabled,isPickupContactSelectionEnabled:isPickupContactSelectionEnabled,customerAttributes:customerAttributes,numberOfAddressLines:numberOfAddressLines,userLocation:userLocation,supportedCountries:shopSettings.supportedCountries,isLocked:isLocked,handleSubmit:handleSubmit};},[isShippingFormEnabled,isShippingFormVisible,defaultBillingFormState,billingFormState.setValues,billingFormState.validationErrors,defaultShippingFormState,shippingFormState.setValues,shippingFormState.validationErrors,defaultExtraFormState,extraFormState.setValues,extraFormState.validationErrors,extraFormRequestErrors,defaultPickupFormState,pickupFormState.setValues,pickupFormState.validationErrors,billingFormRequestErrors,shippingFormRequestErrors,pickupFormRequestErrors,orderReserveOnly,orderNeedsPayment,guestRegistrationEditMode,isShippingAddressSelectionEnabled,isPickupContactSelectionEnabled,customerAttributes,numberOfAddressLines,userLocation,shopSettings.supportedCountries,isLocked,handleSubmit]);if(!isDataReady||!isInitialized){return null;}return React.createElement(Context.Provider,{value:value},children);};GuestRegistrationProvider.defaultProps={children:null,customer:null,formContainerRef:null,billingAddress:null,shippingAddress:null,pickupAddress:null,billingPickupEquals:true,billingShippingEquals:true,cartHasDirectShipItems:false,orderReserveOnly:false,orderNeedsPayment:false,numberOfAddressLines:null,isShippingAddressSelectionEnabled:false,isPickupContactSelectionEnabled:false};export default connect(GuestRegistrationProvider);
@@ -1,7 +1,7 @@
1
- import _regeneratorRuntime from"@babel/runtime/regenerator";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 _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded);var key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++){key=sourceSymbolKeys[i];if(excluded.indexOf(key)>=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key];}}return target;}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return{};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i<sourceKeys.length;i++){key=sourceKeys[i];if(excluded.indexOf(key)>=0)continue;target[key]=source[key];}return target;}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import{EVALIDATION}from'@shopgate/engage/core';import{extractAttributes}from'@shopgate/engage/account/helper/form';import{getMerchantCustomerAttributes}from'@shopgate/engage/core/selectors/merchantSettings';import{submitRegistration as submit}from"../actions";import{convertSubmitRegistrationValidationErrors}from"../helpers";/**
1
+ import _regeneratorRuntime from"@babel/runtime/regenerator";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 _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded);var key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++){key=sourceSymbolKeys[i];if(excluded.indexOf(key)>=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key];}}return target;}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return{};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i<sourceKeys.length;i++){key=sourceKeys[i];if(excluded.indexOf(key)>=0)continue;target[key]=source[key];}return target;}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import{EVALIDATION}from'@shopgate/engage/core';import{extractAttributes,convertPipelineValidationErrors}from'@shopgate/engage/account/helper/form';import{getMerchantCustomerAttributes}from'@shopgate/engage/core/selectors/merchantSettings';import{submitRegistration as submit}from"../actions";/**
2
2
  * Submits registration form data.
3
3
  * @param {Object} baseFormData Data from the base form
4
4
  * @param {Object} shippingFormData Data from the shipping form
5
5
  * @param {Object} additionalData Additional data for the request.
6
6
  * @returns {Function}
7
- */export var submitRegistration=function submitRegistration(_ref){var baseFormData=_ref.baseFormData,billingFormData=_ref.billingFormData,shippingFormData=_ref.shippingFormData,additionalFormData=_ref.additionalFormData;return(/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(dispatch,getState){var customerAttributes,marketingOptIn,attributeData,attributes,emailAddress,password,firstName,lastName,customer,errors,code,validationErrors,converted,_converted$validation2,_converted$validation3,_converted$validation4,_converted$validation5,_converted$validation,errEmailAddress,errPassword,billing,shipping;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:customerAttributes=getMerchantCustomerAttributes(getState());marketingOptIn=additionalFormData.marketingOptIn,attributeData=_objectWithoutProperties(additionalFormData,["marketingOptIn"]);attributes=extractAttributes(customerAttributes,attributeData);emailAddress=baseFormData.emailAddress,password=baseFormData.password;firstName=billingFormData.firstName,lastName=billingFormData.lastName;customer={firstName:firstName,lastName:lastName,emailAddress:emailAddress,password:password,attributes:attributes,settings:{marketingOptIn:marketingOptIn}};customer.contacts=[_extends({},billingFormData,{emailAddress:emailAddress,isDefaultBilling:true,isDefaultShipping:!shippingFormData})].concat(shippingFormData?[_extends({},shippingFormData,{emailAddress:emailAddress,isDefaultBilling:false,isDefaultShipping:true})]:[]);_context.prev=7;_context.next=10;return dispatch(submit(customer));case 10:_context.next=17;break;case 12:_context.prev=12;_context.t0=_context["catch"](7);code=_context.t0.code;validationErrors=_context.t0.errors;if(code===EVALIDATION){errors=validationErrors;}case 17:converted=convertSubmitRegistrationValidationErrors(errors);if(!((converted===null||converted===void 0?void 0:converted.validation)&&Object.keys(converted.validation).length>0)){_context.next=23;break;}_converted$validation=converted.validation,errEmailAddress=_converted$validation.emailAddress,errPassword=_converted$validation.password;billing=(converted===null||converted===void 0?void 0:(_converted$validation2=converted.validation)===null||_converted$validation2===void 0?void 0:(_converted$validation3=_converted$validation2.contacts)===null||_converted$validation3===void 0?void 0:_converted$validation3['0'])||{};shipping=(converted===null||converted===void 0?void 0:(_converted$validation4=converted.validation)===null||_converted$validation4===void 0?void 0:(_converted$validation5=_converted$validation4.contacts)===null||_converted$validation5===void 0?void 0:_converted$validation5['1'])||{};return _context.abrupt("return",{errors:{baseFormData:_extends({},errEmailAddress?{emailAddress:errEmailAddress}:{},{},errPassword?{password:errPassword}:{}),billingFormData:_extends({},billing),shippingFormData:_extends({},shipping)}});case 23:return _context.abrupt("return",null);case 24:case"end":return _context.stop();}}},_callee,null,[[7,12]]);}));return function(_x,_x2){return _ref2.apply(this,arguments);};}());};
7
+ */export var submitRegistration=function submitRegistration(_ref){var baseFormData=_ref.baseFormData,billingFormData=_ref.billingFormData,shippingFormData=_ref.shippingFormData,additionalFormData=_ref.additionalFormData;return(/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(dispatch,getState){var customerAttributes,marketingOptIn,attributeData,attributes,emailAddress,password,firstName,lastName,customer,errors,code,validationErrors,converted,_converted$validation2,_converted$validation3,_converted$validation4,_converted$validation5,_converted$validation6,_converted$validation,errEmailAddress,errPassword,billing,shipping,extra;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:customerAttributes=getMerchantCustomerAttributes(getState());marketingOptIn=additionalFormData.marketingOptIn,attributeData=_objectWithoutProperties(additionalFormData,["marketingOptIn"]);attributes=extractAttributes(customerAttributes,attributeData);emailAddress=baseFormData.emailAddress,password=baseFormData.password;firstName=billingFormData.firstName,lastName=billingFormData.lastName;customer={firstName:firstName,lastName:lastName,emailAddress:emailAddress,password:password,attributes:attributes,settings:{marketingOptIn:marketingOptIn}};customer.contacts=[_extends({},billingFormData,{emailAddress:emailAddress,isDefaultBilling:true,isDefaultShipping:!shippingFormData})].concat(shippingFormData?[_extends({},shippingFormData,{emailAddress:emailAddress,isDefaultBilling:false,isDefaultShipping:true})]:[]);_context.prev=7;_context.next=10;return dispatch(submit(customer));case 10:_context.next=17;break;case 12:_context.prev=12;_context.t0=_context["catch"](7);code=_context.t0.code;validationErrors=_context.t0.errors;if(code===EVALIDATION){errors=validationErrors;}case 17:converted=convertPipelineValidationErrors(errors,attributes);if(!((converted===null||converted===void 0?void 0:converted.validation)&&Object.keys(converted.validation).length>0)){_context.next=24;break;}_converted$validation=converted.validation,errEmailAddress=_converted$validation.emailAddress,errPassword=_converted$validation.password;billing=(converted===null||converted===void 0?void 0:(_converted$validation2=converted.validation)===null||_converted$validation2===void 0?void 0:(_converted$validation3=_converted$validation2.contacts)===null||_converted$validation3===void 0?void 0:_converted$validation3['0'])||{};shipping=(converted===null||converted===void 0?void 0:(_converted$validation4=converted.validation)===null||_converted$validation4===void 0?void 0:(_converted$validation5=_converted$validation4.contacts)===null||_converted$validation5===void 0?void 0:_converted$validation5['1'])||{};extra=(converted===null||converted===void 0?void 0:(_converted$validation6=converted.validation)===null||_converted$validation6===void 0?void 0:_converted$validation6.attributes)||{};return _context.abrupt("return",{errors:{baseFormData:_extends({},errEmailAddress?{emailAddress:errEmailAddress}:{},{},errPassword?{password:errPassword}:{}),billingFormData:_extends({},billing),shippingFormData:_extends({},shipping),extraFormData:_extends({},extra)}});case 24:return _context.abrupt("return",null);case 25:case"end":return _context.stop();}}},_callee,null,[[7,12]]);}));return function(_x,_x2){return _ref2.apply(this,arguments);};}());};
@@ -1,6 +1,6 @@
1
- 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);}import{i18n}from'@shopgate/engage/core';import{generateFormConstraints}from'@shopgate/engage/account/helper/form';/**
1
+ 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);}import{generateFormConstraints}from'@shopgate/engage/account/helper/form';/**
2
2
  * @returns {Object}
3
- */export var generateBaseConstraints=function generateBaseConstraints(){return{emailAddress:{presence:{message:'validation.required',allowEmpty:false},email:{message:'validation.email'}},password:{presence:{message:'validation.required',allowEmpty:false},length:{minimum:8,tooShort:i18n.text('validation.minPasswordLength')}},passwordConfirm:{presence:{message:'validation.required',allowEmpty:false},equality:{attribute:'password',message:'validation.passwordMismatch',comparator:function comparator(v1,v2){return JSON.stringify(v1)===JSON.stringify(v2);}}}};};var addressConstraints={firstName:{presence:{message:'validation.required',allowEmpty:false}},lastName:{presence:{message:'validation.required',allowEmpty:false}},address1:{presence:{message:'validation.required',allowEmpty:false}},city:{presence:{message:'validation.required',allowEmpty:false}},country:{presence:{message:'validation.required',allowEmpty:false}},postalCode:{presence:{message:'validation.required',allowEmpty:false}},mobile:{presence:{message:'validation.required',allowEmpty:false},format:{pattern:'^[+0-9]+',message:'validation.mobileNumber'}}};export var billingConstraints=_extends({},addressConstraints);export var shippingConstraints=_extends({},addressConstraints);/**
3
+ */export var generateBaseConstraints=function generateBaseConstraints(){return{emailAddress:{presence:{message:'validation.required',allowEmpty:false},email:{message:'validation.email'}},password:{presence:{message:'validation.required',allowEmpty:false}},passwordConfirm:{presence:{message:'validation.required',allowEmpty:false},equality:{attribute:'password',message:'validation.passwordMismatch',comparator:function comparator(v1,v2){return JSON.stringify(v1)===JSON.stringify(v2);}}}};};var addressConstraints={firstName:{presence:{message:'validation.required',allowEmpty:false}},lastName:{presence:{message:'validation.required',allowEmpty:false}},address1:{presence:{message:'validation.required',allowEmpty:false}},city:{presence:{message:'validation.required',allowEmpty:false}},country:{presence:{message:'validation.required',allowEmpty:false}},postalCode:{presence:{message:'validation.required',allowEmpty:false}},mobile:{presence:{message:'validation.required',allowEmpty:false},format:{pattern:'^[+0-9]+',message:'validation.mobileNumber'}}};export var billingConstraints=_extends({},addressConstraints);export var shippingConstraints=_extends({},addressConstraints);/**
4
4
  * Generates constraints for the "extra" form.
5
5
  * @param {Object} customerAttributes Customer attributes.
6
6
  * @returns {Object}
@@ -5,7 +5,7 @@ import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGenera
5
5
  */var convertValidationErrors=function convertValidationErrors(validationErrors){return Object.keys(validationErrors).map(function(key){return{path:key,message:i18n.text(validationErrors[key])};});};/**
6
6
  * Registration Provider
7
7
  * @returns {JSX}
8
- */var RegistrationProvider=function RegistrationProvider(_ref){var isDataReady=_ref.isDataReady,cartHasDirectShipItems=_ref.cartHasDirectShipItems,shopSettings=_ref.shopSettings,userLocation=_ref.userLocation,customerAttributes=_ref.customerAttributes,numberOfAddressLines=_ref.numberOfAddressLines,submitRegistration=_ref.submitRegistration,children=_ref.children,formContainerRef=_ref.formContainerRef;var _useState=useState(false),_useState2=_slicedToArray(_useState,2),isLocked=_useState2[0],setLocked=_useState2[1];var _useState3=useState(false),_useState4=_slicedToArray(_useState3,2),isBaseFormSubmitted=_useState4[0],setIsBaseFormSubmitted=_useState4[1];var _useState5=useState(false),_useState6=_slicedToArray(_useState5,2),isBillingFormSubmitted=_useState6[0],setIsBillingFormSubmitted=_useState6[1];var _useState7=useState(false),_useState8=_slicedToArray(_useState7,2),isShippingFormSubmitted=_useState8[0],setIsShippingFormSubmitted=_useState8[1];var _useState9=useState(false),_useState10=_slicedToArray(_useState9,2),isExtraFormSubmitted=_useState10[0],setIsExtraFormSubmitted=_useState10[1];var _useState11=useState(null),_useState12=_slicedToArray(_useState11,2),baseFormRequestErrors=_useState12[0],setBaseFormRequestErrors=_useState12[1];var _useState13=useState(null),_useState14=_slicedToArray(_useState13,2),billingFormRequestErrors=_useState14[0],setBillingFormRequestErrors=_useState14[1];var _useState15=useState(null),_useState16=_slicedToArray(_useState15,2),shippingFormRequestErrors=_useState16[0],setShippingFormRequestErrors=_useState16[1];var _useState17=useState(false),_useState18=_slicedToArray(_useState17,2),isShippingFormVisible=_useState18[0],setIsShippingFormVisible=_useState18[1];var _useRoute=useRoute(),query=_useRoute.query;var isShippingAddressSelectionEnabled=useMemo(function(){return(query===null||query===void 0?void 0:query.checkout)&&cartHasDirectShipItems;},[cartHasDirectShipItems,query]);// Determine values to prefill some form fields
8
+ */var RegistrationProvider=function RegistrationProvider(_ref){var isDataReady=_ref.isDataReady,cartHasDirectShipItems=_ref.cartHasDirectShipItems,shopSettings=_ref.shopSettings,userLocation=_ref.userLocation,customerAttributes=_ref.customerAttributes,numberOfAddressLines=_ref.numberOfAddressLines,submitRegistration=_ref.submitRegistration,children=_ref.children,formContainerRef=_ref.formContainerRef;var _useState=useState(false),_useState2=_slicedToArray(_useState,2),isLocked=_useState2[0],setLocked=_useState2[1];var _useState3=useState(false),_useState4=_slicedToArray(_useState3,2),isBaseFormSubmitted=_useState4[0],setIsBaseFormSubmitted=_useState4[1];var _useState5=useState(false),_useState6=_slicedToArray(_useState5,2),isBillingFormSubmitted=_useState6[0],setIsBillingFormSubmitted=_useState6[1];var _useState7=useState(false),_useState8=_slicedToArray(_useState7,2),isShippingFormSubmitted=_useState8[0],setIsShippingFormSubmitted=_useState8[1];var _useState9=useState(false),_useState10=_slicedToArray(_useState9,2),isExtraFormSubmitted=_useState10[0],setIsExtraFormSubmitted=_useState10[1];var _useState11=useState(null),_useState12=_slicedToArray(_useState11,2),baseFormRequestErrors=_useState12[0],setBaseFormRequestErrors=_useState12[1];var _useState13=useState(null),_useState14=_slicedToArray(_useState13,2),billingFormRequestErrors=_useState14[0],setBillingFormRequestErrors=_useState14[1];var _useState15=useState(null),_useState16=_slicedToArray(_useState15,2),shippingFormRequestErrors=_useState16[0],setShippingFormRequestErrors=_useState16[1];var _useState17=useState(null),_useState18=_slicedToArray(_useState17,2),extraFormRequestErrors=_useState18[0],setExtraFormRequestErrors=_useState18[1];var _useState19=useState(false),_useState20=_slicedToArray(_useState19,2),isShippingFormVisible=_useState20[0],setIsShippingFormVisible=_useState20[1];var _useRoute=useRoute(),query=_useRoute.query;var isShippingAddressSelectionEnabled=useMemo(function(){return(query===null||query===void 0?void 0:query.checkout)&&cartHasDirectShipItems;},[cartHasDirectShipItems,query]);// Determine values to prefill some form fields
9
9
  var userCountry=useMemo(function(){return(userLocation===null||userLocation===void 0?void 0:userLocation.country)||(appConfig===null||appConfig===void 0?void 0:appConfig.marketId)||null;},[userLocation]);var userRegion=useMemo(function(){return(userLocation===null||userLocation===void 0?void 0:userLocation.region)||null;},[userLocation]);var baseConstraints=useMemo(function(){return generateBaseConstraints();},[]);var extraConstraints=useMemo(function(){return generateExtraConstraints(customerAttributes);},[customerAttributes]);// Default form states
10
10
  var defaultBaseFormState=_extends({},initialBaseFormState);var defaultBillingFormState=useMemo(function(){return _extends({},initialBillingFormState,{country:userCountry,region:userRegion});},[userCountry,userRegion]);var defaultShippingFormState=useMemo(function(){return _extends({},initialShippingFormState,{country:userCountry,region:userRegion});},[userCountry,userRegion]);var defaultExtraFormState=useMemo(function(){return _extends({},initialOptInFormState,{},extractDefaultValues(customerAttributes));},[customerAttributes]);// Form submit handlers
11
11
  var handleBaseFormSubmit=useCallback(function(){setIsBaseFormSubmitted(true);},[setIsBaseFormSubmitted]);var handleBillingFormSubmit=useCallback(function(){setIsBillingFormSubmitted(true);},[setIsBillingFormSubmitted]);var handleShippingFormSubmit=useCallback(function(){setIsShippingFormSubmitted(true);},[setIsShippingFormSubmitted]);var handleExtraFormSubmit=useCallback(function(){setIsExtraFormSubmitted(true);},[]);// Form states
@@ -13,5 +13,5 @@ var baseFormState=useFormState(defaultBaseFormState,handleBaseFormSubmit,baseCon
13
13
  var handleSubmit=useCallback(function(){baseFormState.handleSubmit(new Event('submit'));billingFormState.handleSubmit(new Event('submit'));shippingFormState.handleSubmit(new Event('submit'));extraFormState.handleSubmit(new Event('submit'));},[baseFormState,billingFormState,extraFormState,shippingFormState]);useEffect(function(){// Break the process when the forms are not submitted yet
14
14
  if(!isBaseFormSubmitted||!isBillingFormSubmitted||!isShippingFormSubmitted||!isExtraFormSubmitted){return;}// Break the process when one of the forms has validation errors from the constraints
15
15
  if(!baseFormState.valid||!billingFormState.valid||isShippingFormVisible&&!shippingFormState.valid||!extraFormState.valid){setIsBaseFormSubmitted(false);setIsBillingFormSubmitted(false);setIsShippingFormSubmitted(false);setIsExtraFormSubmitted(false);return;}/** Async wrapper for submit registration */var fn=/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var response,_ref3,errors;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:setLocked(true);_context.next=3;return submitRegistration(_extends({baseFormData:baseFormState.values,billingFormData:billingFormState.values,additionalFormData:extraFormState.values},isShippingFormVisible?{shippingFormData:shippingFormState.values}:{}));case 3:response=_context.sent;_ref3=response||{},errors=_ref3.errors;// Updated the request validation errors
16
- setBaseFormRequestErrors((errors===null||errors===void 0?void 0:errors.baseFormData)||null);setBillingFormRequestErrors((errors===null||errors===void 0?void 0:errors.billingFormData)||null);setShippingFormRequestErrors((errors===null||errors===void 0?void 0:errors.shippingFormData)||null);// Release forms for additional submits
17
- setIsBaseFormSubmitted(false);setIsBillingFormSubmitted(false);setIsShippingFormSubmitted(false);setIsExtraFormSubmitted(false);setLocked(false);case 13:case"end":return _context.stop();}}},_callee);}));return function fn(){return _ref2.apply(this,arguments);};}();fn();/* eslint-disable react-hooks/exhaustive-deps */},[isBaseFormSubmitted,isBillingFormSubmitted,isShippingFormSubmitted,isExtraFormSubmitted,baseFormState.valid,billingFormState.valid,shippingFormState.valid,extraFormState.valid,isShippingFormVisible,submitRegistration]);/* eslint-enable react-hooks/exhaustive-deps */ /* eslint-disable react-hooks/exhaustive-deps */useEffect(function(){baseFormState.scrollToError();},[baseFormRequestErrors,billingFormRequestErrors,shippingFormRequestErrors,baseFormState.scrollToError]);/* eslint-enable react-hooks/exhaustive-deps */ /* eslint-disable react-hooks/exhaustive-deps */useEffect(function(){shippingFormState.setIgnoreErrors(!isShippingFormVisible);},[isShippingFormVisible]);/* eslint-enable react-hooks/exhaustive-deps */useEffect(function(){if(isLocked){LoadingProvider.setLoading(REGISTER_PATH);return;}LoadingProvider.unsetLoading(REGISTER_PATH);},[isLocked]);var value=useMemo(function(){return{supportedCountries:shopSettings.supportedCountries||[],customerAttributes:customerAttributes,userLocation:userLocation,defaultBaseFormState:defaultBaseFormState,defaultBillingFormState:defaultBillingFormState,defaultShippingFormState:defaultShippingFormState,defaultExtraFormState:defaultExtraFormState,baseFormValidationErrors:convertValidationErrors(baseFormState.validationErrors||baseFormRequestErrors||{}),billingFormValidationErrors:convertValidationErrors(billingFormState.validationErrors||billingFormRequestErrors||{}),shippingFormValidationErrors:convertValidationErrors(shippingFormState.validationErrors||shippingFormRequestErrors||{}),extraFormValidationErrors:convertValidationErrors(extraFormState.validationErrors||{}),handleSubmit:handleSubmit,updateBaseForm:baseFormState.setValues,updateBillingForm:billingFormState.setValues,updateShippingForm:shippingFormState.setValues,updateExtraForm:extraFormState.setValues,isShippingAddressSelectionEnabled:isShippingAddressSelectionEnabled,isShippingFormVisible:isShippingFormVisible,setIsShippingFormVisible:setIsShippingFormVisible,numberOfAddressLines:numberOfAddressLines};},[shopSettings.supportedCountries,customerAttributes,userLocation,defaultBaseFormState,defaultBillingFormState,defaultShippingFormState,baseFormState.validationErrors,baseFormState.setValues,baseFormRequestErrors,billingFormState.validationErrors,billingFormState.setValues,billingFormRequestErrors,shippingFormState.validationErrors,shippingFormState.setValues,shippingFormRequestErrors,handleSubmit,defaultExtraFormState,extraFormState.setValues,extraFormState.validationErrors,isShippingAddressSelectionEnabled,isShippingFormVisible,setIsShippingFormVisible,numberOfAddressLines]);if(!isDataReady){return null;}return React.createElement(Context.Provider,{value:value},children);};RegistrationProvider.defaultProps={formContainerRef:null,cartHasDirectShipItems:false,numberOfAddressLines:null};export default connect(RegistrationProvider);
16
+ setBaseFormRequestErrors((errors===null||errors===void 0?void 0:errors.baseFormData)||null);setBillingFormRequestErrors((errors===null||errors===void 0?void 0:errors.billingFormData)||null);setShippingFormRequestErrors((errors===null||errors===void 0?void 0:errors.shippingFormData)||null);setExtraFormRequestErrors((errors===null||errors===void 0?void 0:errors.extraFormData)||null);// Release forms for additional submits
17
+ setIsBaseFormSubmitted(false);setIsBillingFormSubmitted(false);setIsShippingFormSubmitted(false);setIsExtraFormSubmitted(false);setLocked(false);case 14:case"end":return _context.stop();}}},_callee);}));return function fn(){return _ref2.apply(this,arguments);};}();fn();/* eslint-disable react-hooks/exhaustive-deps */},[isBaseFormSubmitted,isBillingFormSubmitted,isShippingFormSubmitted,isExtraFormSubmitted,baseFormState.valid,billingFormState.valid,shippingFormState.valid,extraFormState.valid,isShippingFormVisible,submitRegistration]);/* eslint-enable react-hooks/exhaustive-deps */ /* eslint-disable react-hooks/exhaustive-deps */useEffect(function(){baseFormState.scrollToError();},[baseFormRequestErrors,billingFormRequestErrors,shippingFormRequestErrors,baseFormState.scrollToError]);/* eslint-enable react-hooks/exhaustive-deps */ /* eslint-disable react-hooks/exhaustive-deps */useEffect(function(){shippingFormState.setIgnoreErrors(!isShippingFormVisible);},[isShippingFormVisible]);/* eslint-enable react-hooks/exhaustive-deps */useEffect(function(){if(isLocked){LoadingProvider.setLoading(REGISTER_PATH);return;}LoadingProvider.unsetLoading(REGISTER_PATH);},[isLocked]);var value=useMemo(function(){return{supportedCountries:shopSettings.supportedCountries||[],customerAttributes:customerAttributes,userLocation:userLocation,defaultBaseFormState:defaultBaseFormState,defaultBillingFormState:defaultBillingFormState,defaultShippingFormState:defaultShippingFormState,defaultExtraFormState:defaultExtraFormState,baseFormValidationErrors:convertValidationErrors(baseFormState.validationErrors||baseFormRequestErrors||{}),billingFormValidationErrors:convertValidationErrors(billingFormState.validationErrors||billingFormRequestErrors||{}),shippingFormValidationErrors:convertValidationErrors(shippingFormState.validationErrors||shippingFormRequestErrors||{}),extraFormValidationErrors:convertValidationErrors(extraFormState.validationErrors||extraFormRequestErrors||{}),handleSubmit:handleSubmit,updateBaseForm:baseFormState.setValues,updateBillingForm:billingFormState.setValues,updateShippingForm:shippingFormState.setValues,updateExtraForm:extraFormState.setValues,isShippingAddressSelectionEnabled:isShippingAddressSelectionEnabled,isShippingFormVisible:isShippingFormVisible,setIsShippingFormVisible:setIsShippingFormVisible,numberOfAddressLines:numberOfAddressLines};},[shopSettings.supportedCountries,customerAttributes,userLocation,defaultBaseFormState,defaultBillingFormState,defaultShippingFormState,baseFormState.validationErrors,baseFormState.setValues,baseFormRequestErrors,billingFormState.validationErrors,billingFormState.setValues,billingFormRequestErrors,shippingFormState.validationErrors,shippingFormState.setValues,shippingFormRequestErrors,handleSubmit,defaultExtraFormState,extraFormState.setValues,extraFormState.validationErrors,extraFormRequestErrors,isShippingAddressSelectionEnabled,isShippingFormVisible,setIsShippingFormVisible,numberOfAddressLines]);if(!isDataReady){return null;}return React.createElement(Context.Provider,{value:value},children);};RegistrationProvider.defaultProps={formContainerRef:null,cartHasDirectShipItems:false,numberOfAddressLines:null};export default connect(RegistrationProvider);
@@ -1,6 +0,0 @@
1
- import{i18n}from'@shopgate/engage/core';/**
2
- * Generates form configuration.
3
- * @param {Array} supportedCountries A list of supported countries.
4
- * @param {Object} userLocation User location for better phone picker defaults.
5
- * @returns {Object}
6
- */var generateFormConfig=function generateFormConfig(supportedCountries,userLocation){return{fields:{firstName:{type:'text',label:"".concat(i18n.text('checkout.pickup_contact.form.firstName')," *")},lastName:{type:'text',label:"".concat(i18n.text('checkout.pickup_contact.form.lastName')," *")},company:{type:'text',label:i18n.text('checkout.pickup_contact.form.company')},address1:{type:'text',label:"".concat(i18n.text('checkout.pickup_contact.form.address1')," *")},address2:{type:'text',label:i18n.text('checkout.pickup_contact.form.address2')},city:{type:'text',label:"".concat(i18n.text('checkout.pickup_contact.form.city')," *")},region:{type:'province',label:"".concat(i18n.text('checkout.pickup_contact.form.region')," *"),required:true},country:{type:'country',label:"".concat(i18n.text('checkout.pickup_contact.form.country')," *"),countries:supportedCountries},postalCode:{type:'text',label:"".concat(i18n.text('checkout.pickup_contact.form.postalCode')," *")},mobile:{type:'phone_picker',label:"".concat(i18n.text('checkout.pickup_contact.form.mobile')," *"),config:{supportedCountries:supportedCountries,userLocation:userLocation}}}};};export default generateFormConfig;
@@ -1,5 +0,0 @@
1
- import setWith from'lodash/setWith';import{i18n}from'@shopgate/engage/core';/**
2
- * Converts validation errors from the shopgate.user.register pipeline
3
- * @param {Array} errors The errors
4
- * @returns {Object|null}
5
- */export var convertSubmitRegistrationValidationErrors=function convertSubmitRegistrationValidationErrors(errors){if(!Array.isArray(errors)||errors.length===0){return null;}var converted=errors.reduce(function(result,error){var _error$path=error.path,path=_error$path===void 0?[]:_error$path,code=error.code;var _error$subentityPath=error.subentityPath,subentityPath=_error$subentityPath===void 0?[]:_error$subentityPath;var message=error.message;if(path.length===0&&subentityPath.length===0){result.general.push(error);return result;}if(path.length>0){message=i18n.text('validation.checkField');setWith(result.validation,path.slice(2).join('.'),message,Object);}else if(subentityPath.length>0){var field=subentityPath[subentityPath.length-1];if(code===409&&field==='emailAddress'){message=i18n.text('validation.emailConflict');}else{message=i18n.text('validation.checkField');}setWith(result.validation,subentityPath.join('.'),message,Object);}return result;},{validation:{},general:[]});return converted;};