import { PLAN_PERSONAL } from '@automattic/calypso-products';
import page from '@automattic/calypso-router';
import { Spinner } from '@automattic/components';
import {
isWithThemeFlow,
isHostingSignupFlow,
isOnboardingFlow,
StepContainer,
isAIBuilderFlow,
isTailoredSignupFlow,
Step,
isNewHostedSiteCreationFlow,
NEW_HOSTED_SITE_FLOW,
DOMAIN_FOR_GRAVATAR_FLOW,
isDomainForGravatarFlow,
AI_SITE_BUILDER_FLOW,
} from '@automattic/onboarding';
import { withShoppingCart } from '@automattic/shopping-cart';
import { Button } from '@wordpress/components';
import { getQueryArg } from '@wordpress/url';
import { withViewportMatch } from '@wordpress/viewport';
import clsx from 'clsx';
import { localize } from 'i18n-calypso';
import { defer, get, isEmpty } from 'lodash';
import PropTypes from 'prop-types';
import { parse } from 'qs';
import { Children, Component, isValidElement } from 'react';
import { connect } from 'react-redux';
import AsyncLoad from 'calypso/components/async-load';
import QueryProductsList from 'calypso/components/data/query-products-list';
import RegisterDomainStepV2 from 'calypso/components/domain-search-v2/register-domain-step';
import { useMyDomainInputMode as inputMode } from 'calypso/components/domains/connect-domain-step/constants';
import RegisterDomainStep from 'calypso/components/domains/register-domain-step';
import { recordUseYourDomainButtonClick } from 'calypso/components/domains/register-domain-step/analytics';
import SideExplainer from 'calypso/components/domains/side-explainer';
import UseMyDomain from 'calypso/components/domains/use-my-domain';
import FormattedHeader from 'calypso/components/formatted-header';
import Notice from 'calypso/components/notice';
import { shouldUseStepContainerV2 } from 'calypso/landing/stepper/declarative-flow/helpers/should-use-step-container-v2';
import {
LOCAL_STORAGE_KEY_FOR_PG_ID as PG_ID,
LOCAL_STORAGE_KEY_FOR_PG_ID_TS as PG_TS,
LOCAL_STORAGE_KEY_FOR_PG_VALIDITY as PG_ID_VALIDITY,
} from 'calypso/landing/stepper/declarative-flow/internals/steps-repository/playground/lib/initialize-playground';
import BodySectionCssClass from 'calypso/layout/body-section-css-class';
import { SIGNUP_DOMAIN_ORIGIN } from 'calypso/lib/analytics/signup';
import {
domainRegistration,
domainMapping,
domainTransfer,
updatePrivacyForDomain,
planItem,
hasPlan,
hasDomainRegistration,
getDomainsInCart,
hasPersonalPlan,
} from 'calypso/lib/cart-values/cart-items';
import {
getDomainProductSlug,
getDomainSuggestionSearch,
getFixedDomainSearch,
} from 'calypso/lib/domains';
import { getSuggestionsVendor } from 'calypso/lib/domains/suggestions';
import { useDomainSearchV2 } from 'calypso/lib/domains/use-domain-search-v2';
import { triggerGuidesForStep } from 'calypso/lib/guides/trigger-guides-for-step';
import CalypsoShoppingCartProvider from 'calypso/my-sites/checkout/calypso-shopping-cart-provider';
import withCartKey from 'calypso/my-sites/checkout/with-cart-key';
import { domainManagementRoot } from 'calypso/my-sites/domains/paths';
import {
getStepUrl,
isPlanSelectionAvailableLaterInFlow,
getPreviousStepName,
} from 'calypso/signup/utils';
import {
composeAnalytics,
recordGoogleEvent,
recordTracksEvent,
} from 'calypso/state/analytics/actions';
import {
getCurrentUser,
getCurrentUserSiteCount,
isUserLoggedIn,
} from 'calypso/state/current-user/selectors';
import {
recordAddDomainButtonClick,
recordAddDomainButtonClickInMapDomain,
recordAddDomainButtonClickInTransferDomain,
recordAddDomainButtonClickInUseYourDomain,
} from 'calypso/state/domains/actions';
import { getAvailableProductsList } from 'calypso/state/products-list/selectors';
import getSitesItems from 'calypso/state/selectors/get-sites-items';
import { fetchUsernameSuggestion } from 'calypso/state/signup/optional-dependencies/actions';
import {
removeStep,
saveSignupStep,
submitSignupStep,
} from 'calypso/state/signup/progress/actions';
import { isPlanStepExistsAndSkipped } from 'calypso/state/signup/progress/selectors';
import { setDesignType } from 'calypso/state/signup/steps/design-type/actions';
import { getDesignType } from 'calypso/state/signup/steps/design-type/selectors';
import { getSelectedSite } from 'calypso/state/ui/selectors';
import DomainsMiniCart from './domains-mini-cart';
import {
getExternalBackUrl,
shouldUseMultipleDomainsInCart,
sortProductsByPriceDescending,
} from './utils';
import './style.scss';
class RenderDomainsStepComponent extends Component {
static propTypes = {
cart: PropTypes.object,
shoppingCartManager: PropTypes.any,
forceDesignType: PropTypes.string,
domainsWithPlansOnly: PropTypes.bool,
flowName: PropTypes.string.isRequired,
goToNextStep: PropTypes.func.isRequired,
goBack: PropTypes.func,
isDomainOnly: PropTypes.bool.isRequired,
locale: PropTypes.string,
path: PropTypes.string.isRequired,
positionInFlow: PropTypes.number.isRequired,
queryObject: PropTypes.object,
step: PropTypes.object,
stepName: PropTypes.string.isRequired,
stepSectionName: PropTypes.string,
selectedSite: PropTypes.object,
recordTracksEvent: PropTypes.func,
allowSkipWithoutSearch: PropTypes.bool,
};
constructor( props ) {
super( props );
const domain = get( props, 'queryObject.new', false );
const search = get( props, 'queryObject.search', false ) === 'yes';
const suggestedDomain = get( props, 'signupDependencies.suggestedDomain' );
const siteUrl = get( props, 'signupDependencies.siteUrl' );
// If we landed anew from `/domains` and it's the `new-flow` variation
// or there's a suggestedDomain from previous steps, always rerun the search.
if ( ( search && props.path.indexOf( '?' ) !== -1 ) || suggestedDomain ) {
this.searchOnInitialRender = true;
}
if (
props.isDomainOnly &&
domain &&
! search && // Testing /domains sending to NUX for search
// If someone has a better idea on how to figure if the user landed anew
// Because we persist the signupDependencies, but still want the user to be able to go back to search screen
props.path.indexOf( '?' ) !== -1
) {
this.skipRender = true;
const productSlug = getDomainProductSlug( domain );
const domainItem = domainRegistration( { productSlug, domain } );
const domainCart = shouldUseMultipleDomainsInCart( props.flowName )
? getDomainsInCart( this.props.cart )
: {};
props.submitSignupStep(
{
stepName: props.stepName,
domainItem,
siteUrl: domain,
isPurchasingItem: true,
stepSectionName: props.stepSectionName,
domainCart,
},
{
domainItem,
siteUrl: domain,
domainCart,
}
);
props.goToNextStep();
}
this.setCurrentFlowStep = this.setCurrentFlowStep.bind( this );
// Get playground ID from either GET param or localStorage
const playgroundIdFromUrl = getQueryArg( window.location.href, 'playground' );
const playgroundIdFromStorage = window.localStorage.getItem( PG_ID );
const playgroundIdTimestamp = window.localStorage.getItem( PG_TS );
const playgroundId =
playgroundIdFromUrl ||
( Date.now() - playgroundIdTimestamp < PG_ID_VALIDITY ? playgroundIdFromStorage : null );
// Clean up localStorage regardless of whether we used the value
window.localStorage.removeItem( PG_ID );
window.localStorage.removeItem( PG_TS );
// Update URL if we got the ID from localStorage
if ( playgroundId && playgroundIdFromStorage && ! playgroundIdFromUrl ) {
const url = new URL( window.location.href );
url.searchParams.set( 'playground', playgroundId );
window.history.replaceState( {}, '', url.toString() );
}
this.state = {
currentStep: null,
isCartPendingUpdateDomain: null,
wpcomSubdomainSelected:
siteUrl && siteUrl.indexOf( '.wordpress.com' ) !== -1 ? { domain_name: siteUrl } : null,
domainRemovalQueue: [],
isMiniCartContinueButtonBusy: false,
temporaryCart: [],
replaceDomainFailedMessage: null,
domainAddingQueue: [],
domainsWithMappingError: [],
checkDomainAvailabilityPromises: [],
removeDomainTimeout: 0,
addDomainTimeout: 0,
playgroundId,
};
}
componentDidMount() {
if ( isTailoredSignupFlow( this.props.flowName ) ) {
triggerGuidesForStep( this.props.flowName, 'domains' );
}
// We add a plan to cart on Multi Domains to show the proper discount on the mini-cart.
if (
shouldUseMultipleDomainsInCart( this.props.flowName ) &&
hasDomainRegistration( this.props.cart ) &&
this.props.multiDomainDefaultPlan
) {
// This call is expensive, so we only do it if the mini-cart hasDomainRegistration.
this.props.shoppingCartManager.addProductsToCart( [ this.props.multiDomainDefaultPlan ] );
}
}
componentDidUpdate( prevProps ) {
if ( prevProps?.cart?.products?.length !== this.props?.cart?.products?.length ) {
if (
shouldUseMultipleDomainsInCart( this.props.flowName ) &&
hasDomainRegistration( this.props.cart ) &&
! hasPersonalPlan( this.props.cart ) &&
this.props.multiDomainDefaultPlan
) {
// This call is expensive, so we only do it if the mini-cart hasDomainRegistration.
this.props.shoppingCartManager.addProductsToCart( [ this.props.multiDomainDefaultPlan ] );
}
}
}
getLocale() {
return ! this.props.userLoggedIn ? this.props.locale : '';
}
getUseYourDomainUrl = () => {
if ( this.props.getUseYourDomainUrl ) {
const lastQuery = get( this.props.step, 'domainForm.lastQuery' );
return this.props.getUseYourDomainUrl( lastQuery );
}
return getStepUrl(
this.props.flowName,
this.props.stepName,
'use-your-domain',
this.getLocale()
);
};
handleAddDomain = async ( suggestion, position, previousState ) => {
const stepData = {
stepName: this.props.stepName,
suggestion,
};
const signupDomainOrigin = suggestion?.is_free
? SIGNUP_DOMAIN_ORIGIN.FREE
: SIGNUP_DOMAIN_ORIGIN.CUSTOM;
if ( shouldUseMultipleDomainsInCart( this.props.flowName ) ) {
const domainInAddingQueue = this.state.domainAddingQueue.find(
( item ) => item.meta === suggestion.domain_name
);
const domainInRemovalQueue = this.state.domainRemovalQueue.find(
( item ) => item.meta === suggestion.domain_name
);
if ( domainInAddingQueue || domainInRemovalQueue ) {
// return false;
}
} else {
this.setState( { isCartPendingUpdateDomain: suggestion } );
}
this.props.recordAddDomainButtonClick(
suggestion.domain_name,
this.getAnalyticsSection(),
position,
suggestion?.is_premium,
this.props.flowName,
suggestion?.vendor
);
await this.props.saveSignupStep( stepData );
if (
shouldUseMultipleDomainsInCart( this.props.flowName ) &&
suggestion?.isSubDomainSuggestion
) {
if ( this.state.wpcomSubdomainSelected ) {
await this.freeDomainRemoveClickHandler();
}
this.setState( { wpcomSubdomainSelected: suggestion }, () => {
this.props.saveSignupStep( stepData );
} );
return;
}
if ( shouldUseMultipleDomainsInCart( this.props.flowName ) && suggestion ) {
await this.handleDomainToDomainCart( previousState );
// If we already have a free selection in place, let's enforce that as a free site suggestion
if ( this.state.wpcomSubdomainSelected ) {
await this.props.saveSignupStep( {
stepName: this.props.stepName,
suggestion: this.state.wpcomSubdomainSelected,
} );
}
} else {
await this.submitWithDomain( { signupDomainOrigin, position, suggestion } );
}
};
handleDomainMappingError = async ( domain_name ) => {
this.state.domainsWithMappingError.push( domain_name );
const productToRemove = this.props.cart.products.find(
( product ) => product.meta === domain_name
);
if ( productToRemove ) {
this.setState( ( prevState ) => ( {
domainRemovalQueue: [
...prevState.domainRemovalQueue,
{ meta: productToRemove.meta, productSlug: productToRemove.product_slug },
],
} ) );
this.setState( { isMiniCartContinueButtonBusy: true } );
await this.removeDomain( { domain_name, product_slug: productToRemove.product_slug } );
this.setState( { isMiniCartContinueButtonBusy: false } );
} else if ( this.state.temporaryCart?.length > 0 ) {
this.setState( ( state ) => ( {
temporaryCart: state.temporaryCart.filter( ( domain ) => domain.meta !== domain_name ),
} ) );
}
};
isPurchasingTheme = () => {
return this.props.queryObject && this.props.queryObject.premium;
};
getThemeSlug = () => {
return this.props.queryObject ? this.props.queryObject.theme : undefined;
};
getThemeStyleVariation = () => {
return this.props.queryObject ? this.props.queryObject.style_variation : undefined;
};
getThemeArgs = () => {
const themeSlug = this.getThemeSlug();
const themeStyleVariation = this.getThemeStyleVariation();
const themeSlugWithRepo = this.getThemeSlugWithRepo( themeSlug );
return { themeSlug, themeSlugWithRepo, themeStyleVariation };
};
getThemeSlugWithRepo = ( themeSlug ) => {
if ( ! themeSlug ) {
return undefined;
}
const repo = this.isPurchasingTheme() ? 'premium' : 'pub';
return `${ repo }/${ themeSlug }`;
};
shouldUseThemeAnnotation() {
return this.getThemeSlug() ? true : false;
}
isDependencyShouldHideFreePlanProvided = () => {
/**
* This prop is used to supress providing the dependency - shouldHideFreePlan - when the plans step is in the current flow
*/
return (
! this.props.forceHideFreeDomainExplainerAndStrikeoutUi &&
this.props.isPlanSelectionAvailableLaterInFlow
);
};
handleSkip = ( googleAppsCartItem, shouldHideFreePlan = false, signupDomainOrigin ) => {
const tracksProperties = Object.assign(
{
section: this.getAnalyticsSection(),
flow: this.props.flowName,
step: this.props.stepName,
},
this.isDependencyShouldHideFreePlanProvided()
? { should_hide_free_plan: shouldHideFreePlan }
: {}
);
this.props.recordTracksEvent( 'calypso_signup_skip_step', tracksProperties );
const stepData = {
stepName: this.props.stepName,
suggestion: undefined,
domainCart: {},
siteUrl: '',
};
this.props.saveSignupStep( stepData );
defer( () => {
this.submitWithDomain( { googleAppsCartItem, shouldHideFreePlan, signupDomainOrigin } );
} );
};
handleDomainExplainerClick = () => {
const hideFreePlan = true;
this.handleSkip( undefined, hideFreePlan, SIGNUP_DOMAIN_ORIGIN.CHOOSE_LATER );
};
handleUseYourDomainClick = () => {
// Stepper doesn't support page.js
const navigate = this.props.page || page;
this.props.recordUseYourDomainButtonClick( this.getAnalyticsSection() );
if ( this.props.useStepperWrapper ) {
this.props.goToNextStep( { navigateToUseMyDomain: true } );
} else {
navigate( this.getUseYourDomainUrl() );
}
};
handleDomainToDomainCart = async ( previousState ) => {
const { suggestion } = this.props.step;
if ( previousState ) {
await this.removeDomain( suggestion );
} else {
await this.addDomain( suggestion );
this.props.setDesignType( this.getDesignType() );
}
};
submitWithDomain = ( {
googleAppsCartItem,
shouldHideFreePlan = false,
signupDomainOrigin,
suggestion,
} ) => {
const { step } = this.props;
if ( step.suggestion ) {
suggestion = step.suggestion;
}
const shouldUseThemeAnnotation = this.shouldUseThemeAnnotation();
const useThemeHeadstartItem = shouldUseThemeAnnotation
? { useThemeHeadstart: shouldUseThemeAnnotation }
: {};
const { lastDomainSearched } = step.domainForm ?? {};
const isPurchasingItem = suggestion && Boolean( suggestion.product_slug );
const siteUrl =
suggestion &&
( isPurchasingItem
? suggestion.domain_name
: suggestion.domain_name.replace( '.wordpress.com', '' ) );
const domainItem = isPurchasingItem
? domainRegistration( {
domain: suggestion.domain_name,
productSlug: suggestion.product_slug,
} )
: undefined;
suggestion && this.props.submitDomainStepSelection( suggestion, this.getAnalyticsSection() );
this.props.submitSignupStep(
Object.assign(
{
stepName: this.props.stepName,
domainItem,
googleAppsCartItem,
isPurchasingItem,
siteUrl,
stepSectionName: this.props.stepSectionName,
domainCart: {},
},
this.getThemeArgs()
),
Object.assign(
{ domainItem },
this.isDependencyShouldHideFreePlanProvided() ? { shouldHideFreePlan } : {},
useThemeHeadstartItem,
signupDomainOrigin ? { signupDomainOrigin } : {},
suggestion?.domain_name ? { siteUrl: suggestion?.domain_name } : {},
lastDomainSearched ? { lastDomainSearched } : {},
{ domainCart: {} }
)
);
this.props.setDesignType( this.getDesignType() );
// For the domain for Gravatar flow, add an extra `is_gravatar_domain` property to the domain registration product,
// pre-select the "domain" choice in the "site or domain" step and skip the others, going straight to checkout
if ( isDomainForGravatarFlow( this.props.flowName ) ) {
const domainForGravatarItem = domainRegistration( {
domain: suggestion.domain_name,
productSlug: suggestion.product_slug,
extra: {
is_gravatar_domain: true,
},
} );
this.props.submitSignupStep(
{
stepName: 'site-or-domain',
domainItem: domainForGravatarItem,
designType: 'domain',
siteSlug: domainForGravatarItem.meta,
siteUrl,
isPurchasingItem: true,
},
{ designType: 'domain', domainItem: domainForGravatarItem, siteUrl }
);
this.props.submitSignupStep(
{ stepName: 'site-picker', wasSkipped: true },
{ themeSlugWithRepo: 'pub/twentysixteen' }
);
return;
}
this.props.goToNextStep();
// Start the username suggestion process.
siteUrl && this.props.fetchUsernameSuggestion( siteUrl.split( '.' )[ 0 ] );
};
handleAddMapping = ( { sectionName, domain, state } ) => {
if ( this.props.handleAddMapping ) {
this.props.handleAddMapping( domain );
return;
}
const domainItem = domainMapping( { domain } );
const isPurchasingItem = true;
const shouldUseThemeAnnotation = this.shouldUseThemeAnnotation();
const useThemeHeadstartItem = shouldUseThemeAnnotation
? { useThemeHeadstart: shouldUseThemeAnnotation }
: {};
this.props.recordAddDomainButtonClickInMapDomain(
domain,
this.getAnalyticsSection(),
this.props.flowName
);
this.props.submitSignupStep(
Object.assign(
{
stepName: this.props.stepName,
[ sectionName ]: state,
domainItem,
isPurchasingItem,
siteUrl: domain,
stepSectionName: this.props.stepSectionName,
domainCart: {},
},
this.getThemeArgs()
),
Object.assign(
{ domainItem },
useThemeHeadstartItem,
{
signupDomainOrigin: SIGNUP_DOMAIN_ORIGIN.USE_YOUR_DOMAIN,
},
{ siteUrl: domain },
{ domainCart: {} }
)
);
this.props.goToNextStep();
};
handleAddTransfer = ( { domain, authCode } ) => {
if ( this.props.handleAddTransfer ) {
this.props.handleAddTransfer( domain );
return;
}
const domainItem = domainTransfer( {
domain,
extra: {
auth_code: authCode,
signup: true,
},
} );
const isPurchasingItem = true;
const shouldUseThemeAnnotation = this.shouldUseThemeAnnotation();
const useThemeHeadstartItem = shouldUseThemeAnnotation
? { useThemeHeadstart: shouldUseThemeAnnotation }
: {};
this.props.recordAddDomainButtonClickInTransferDomain(
domain,
this.getAnalyticsSection(),
this.props.flowName
);
this.props.submitSignupStep(
Object.assign(
{
stepName: this.props.stepName,
transfer: {},
domainItem,
isPurchasingItem,
siteUrl: domain,
stepSectionName: this.props.stepSectionName,
domainCart: {},
},
this.getThemeArgs()
),
Object.assign(
{ domainItem },
useThemeHeadstartItem,
{ siteUrl: domain },
{ domainCart: {} }
)
);
this.props.goToNextStep();
};
handleSave = ( sectionName, state ) => {
this.props.saveSignupStep( {
stepName: this.props.stepName,
stepSectionName: this.props.stepSectionName,
[ sectionName ]: state,
} );
};
getDesignType = () => {
if ( this.props.forceDesignType ) {
return this.props.forceDesignType;
}
if ( this.props.signupDependencies && this.props.signupDependencies.designType ) {
return this.props.signupDependencies.designType;
}
return this.props.designType;
};
shouldIncludeDotBlogSubdomain() {
const { flowName, isDomainOnly } = this.props;
// 'subdomain' flow coming from .blog landing pages
if ( flowName === 'subdomain' ) {
return true;
}
// No .blog subdomains for domain only sites
if ( isDomainOnly ) {
return false;
}
const lastQuery = get( this.props.step, 'domainForm.lastQuery' );
return typeof lastQuery === 'string' && lastQuery.includes( '.blog' );
}
shouldHideDomainExplainer = () => {
const { flowName } = this.props;
return [
'domain',
DOMAIN_FOR_GRAVATAR_FLOW,
'onboarding-with-email',
NEW_HOSTED_SITE_FLOW,
'domains/add',
].includes( flowName );
};
shouldHideUseYourDomain = () => {
const { flowName } = this.props;
return [
'domain',
DOMAIN_FOR_GRAVATAR_FLOW,
'onboarding-with-email',
NEW_HOSTED_SITE_FLOW,
AI_SITE_BUILDER_FLOW,
].includes( flowName );
};
shouldDisplayDomainOnlyExplainer = () => {
const { flowName } = this.props;
return [ 'domain' ].includes( flowName );
};
async addDomain( suggestion ) {
const {
domain_name: domain,
product_slug: productSlug,
supports_privacy: supportsPrivacy,
} = suggestion;
let registration = domainRegistration( {
domain,
productSlug,
extra: { privacy_available: supportsPrivacy },
} );
if ( supportsPrivacy ) {
registration = updatePrivacyForDomain( registration, true );
}
// Add item_subtotal_integer property to registration, so it can be sorted by price.
registration.item_subtotal_integer = ( suggestion.sale_cost ?? suggestion.raw_price ) * 100;
if ( shouldUseMultipleDomainsInCart( this.props.flowName ) ) {
this.setState( { replaceDomainFailedMessage: null, isMiniCartContinueButtonBusy: true } );
if (
! this.state.temporaryCart ||
! this.state.temporaryCart.some(
( domainInCart ) => domainInCart.meta === suggestion.domain_name
)
) {
this.setState( ( state ) => ( {
isCartPendingUpdateDomain: { domain_name: suggestion.domain_name },
temporaryCart: [
...( state.temporaryCart || [] ),
{
meta: suggestion.domain_name,
temporary: true,
},
],
} ) );
}
await this.setState( ( prevState ) => ( {
domainAddingQueue: [ ...prevState.domainAddingQueue, registration ],
} ) );
// We add a plan to cart on Multi Domains to show the proper discount on the mini-cart.
// TODO: remove productsToAdd
const productsToAdd =
! hasPlan( this.props.cart ) && this.props.multiDomainDefaultPlan
? [ registration, this.props.multiDomainDefaultPlan ]
: [ registration ];
// Replace the products in the cart with the freshly sorted products.
clearTimeout( this.state.addDomainTimeout );
// Avoid too much API calls for Multi-domains flow
this.state.addDomainTimeout = setTimeout( async () => {
// Only saves after all domain are checked.
Promise.all( this.state.checkDomainAvailabilityPromises ).then( async () => {
if ( this.props.currentUser ) {
try {
await this.props.shoppingCartManager.reloadFromServer();
} catch {
this.setState( {
replaceDomainFailedMessage: this.props.translate(
'Sorry, there was a problem adding that domain. Please try again later.'
),
isMiniCartContinueButtonBusy: false,
} );
return;
}
}
// Add productsToAdd to productsInCart.
let productsInCart = [
...this.props.cart.products,
...productsToAdd,
...this.state.domainAddingQueue,
];
// Remove domains with domainsWithMappingError from productsInCart.
productsInCart = productsInCart.filter( ( product ) => {
return ! this.state.domainsWithMappingError.includes( product.meta );
} );
// Sort products to ensure the user gets the best deal with the free domain bundle promotion.
const sortedProducts = sortProductsByPriceDescending( productsInCart );
this.props.shoppingCartManager
.replaceProductsInCart( sortedProducts )
.then( () => {
this.setState( { replaceDomainFailedMessage: null } );
if ( this.state.domainAddingQueue?.length > 0 ) {
this.setState( ( state ) => ( {
domainAddingQueue: state.domainAddingQueue.filter(
( domainInQueue ) =>
! sortedProducts.find( ( item ) => item.meta === domainInQueue.meta )
),
} ) );
}
if ( this.state.temporaryCart?.length > 0 ) {
this.setState( ( state ) => ( {
temporaryCart: state.temporaryCart.filter(
( temporaryCart ) =>
! sortedProducts.find( ( item ) => item.meta === temporaryCart.meta )
),
} ) );
}
} )
.catch( () => {
this.handleReplaceProductsInCartError(
this.props.translate(
'Sorry, there was a problem adding that domain. Please try again later.'
)
);
} )
.then( () => {
this.setState( { isMiniCartContinueButtonBusy: false } );
} );
} );
}, 500 );
} else {
this.setState( {
replaceDomainFailedMessage: null,
isMiniCartContinueButtonBusy: true,
} );
try {
await this.props.shoppingCartManager.addProductsToCart( registration );
} catch {
this.handleReplaceProductsInCartError(
this.props.translate(
'Sorry, there was a problem adding that domain. Please try again later.'
)
);
} finally {
this.setState( { isMiniCartContinueButtonBusy: false } );
}
}
this.setState( { isCartPendingUpdateDomain: null } );
}
removeDomainClickHandler = ( domain ) => async () => {
await this.removeDomain( {
domain_name: domain.meta,
product_slug: domain.product_slug,
} );
this.props.recordRemoveDomainButtonClick?.( domain.meta );
};
async removeDomain( { domain_name, product_slug } ) {
if ( this.state.temporaryCart?.length > 0 ) {
this.setState( ( state ) => ( {
temporaryCart: state.temporaryCart.filter( ( domain ) => domain.meta !== domain_name ),
} ) );
}
// check if the domain is alreay in the domainRemovalQueue queue
if ( ! this.state.domainRemovalQueue.find( ( domain ) => domain.meta === domain_name ) ) {
this.setState( ( prevState ) => ( {
isMiniCartContinueButtonBusy: true,
domainRemovalQueue: [
...prevState.domainRemovalQueue,
{ meta: domain_name, productSlug: product_slug },
],
} ) );
}
this.setState( {
replaceDomainFailedMessage: null,
isMiniCartContinueButtonBusy: true,
isCartPendingUpdateDomain: { domain_name: domain_name },
} );
clearTimeout( this.state.removeDomainTimeout );
// Avoid too much API calls for Multi-domains flow
this.state.removeDomainTimeout = setTimeout( async () => {
if ( this.props.currentUser ) {
try {
await this.props.shoppingCartManager.reloadFromServer();
} catch {
this.setState( {
replaceDomainFailedMessage: this.props.translate(
'Sorry, there was a problem removing that domain. Please try again later.'
),
isMiniCartContinueButtonBusy: false,
} );
return;
}
}
const productsToKeep = this.props.cart.products.filter( ( product ) => {
// check current item
if ( product.meta === domain_name && product.product_slug === product_slug ) {
// this is to be removed
return false;
}
// check removal queue
return ! this.state.domainRemovalQueue.find(
( domain ) => product.meta === domain.meta && product.product_slug === domain.productSlug
);
} );
await this.props.shoppingCartManager
.replaceProductsInCart( productsToKeep )
.then( () => {
this.setState( { replaceDomainFailedMessage: null } );
} )
.catch( () => {
this.handleReplaceProductsInCartError(
this.props.translate(
'Sorry, there was a problem removing that domain. Please try again later.'
)
);
} )
.finally( () => {
if ( this.state.domainRemovalQueue?.length > 0 ) {
this.setState( ( state ) => ( {
domainRemovalQueue: state.domainRemovalQueue.filter( ( domainInQueue ) =>
productsToKeep.find( ( item ) => item.meta === domainInQueue.meta )
),
} ) );
}
} );
this.setState( { isMiniCartContinueButtonBusy: false } );
}, 500 );
}
handleReplaceProductsInCartError = ( errorMessage ) => {
const errors = this.props.shoppingCartManager.responseCart.messages?.errors;
if ( errors && errors.length === 0 ) {
this.setState( {
replaceDomainFailedMessage: errorMessage,
} );
}
this.setState( () => ( { temporaryCart: [] } ) );
this.props.shoppingCartManager.reloadFromServer();
};
goToNext = ( event ) => {
event?.stopPropagation();
this.setState( { isMiniCartContinueButtonBusy: true } );
const shouldUseThemeAnnotation = this.shouldUseThemeAnnotation();
const useThemeHeadstartItem = shouldUseThemeAnnotation
? { useThemeHeadstart: shouldUseThemeAnnotation }
: {};
const { step, cart, multiDomainDefaultPlan, shoppingCartManager, goToNextStep } = this.props;
const { lastDomainSearched } = step.domainForm ?? {};
const domainCart = getDomainsInCart( this.props.cart );
const { suggestion } = step;
const isPurchasingItem =
( suggestion && Boolean( suggestion.product_slug ) ) || domainCart?.length > 0;
const siteUrl =
suggestion &&
// If we have a free domain in the cart, we want to use it as the siteUrl
( isPurchasingItem && ! this.state.wpcomSubdomainSelected
? suggestion.domain_name
: suggestion.domain_name.replace( '.wordpress.com', '' ) );
let domainItem;
if ( isPurchasingItem ) {
const selectedDomain = domainCart?.length > 0 ? domainCart[ 0 ] : suggestion;
domainItem = domainRegistration( {
domain: selectedDomain?.domain_name || selectedDomain?.meta,
productSlug: selectedDomain?.product_slug,
} );
}
const signupDomainOrigin = isPurchasingItem
? SIGNUP_DOMAIN_ORIGIN.CUSTOM
: SIGNUP_DOMAIN_ORIGIN.FREE;
const stepDependencies = Object.assign(
{
stepName: this.props.stepName,
domainItem,
isPurchasingItem,
siteUrl,
stepSectionName: this.props.stepSectionName,
domainCart,
},
this.getThemeArgs()
);
const providedDependencies = Object.assign(
{ domainItem, domainCart },
useThemeHeadstartItem,
signupDomainOrigin ? { signupDomainOrigin } : {},
{ siteUrl: suggestion?.domain_name },
lastDomainSearched ? { lastDomainSearched } : {},
{ domainCart }
);
this.props.submitSignupStep( stepDependencies, providedDependencies );
const productToRemove = multiDomainDefaultPlan
? cart.products.find(
( product ) => product.product_slug === multiDomainDefaultPlan.product_slug
)
: null;
if ( productToRemove && productToRemove.uuid ) {
shoppingCartManager.removeProductFromCart( productToRemove.uuid ).then( () => {
goToNextStep();
} );
} else {
goToNextStep();
}
};
freeDomainRemoveClickHandler = () => {
return new Promise( ( resolve ) => {
this.setState( { wpcomSubdomainSelected: false } );
this.props.saveSignupStep( {
stepName: this.props.stepName,
suggestion: {
domain_name: false,
},
} );
resolve();
} );
};
getDomainsMiniCart = ( domainsInCart ) => {
const cartIsLoading = this.props.shoppingCartManager.isLoading;
if ( cartIsLoading && domainsInCart.length === 0 ) {
return null;
}
return (