/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import { useMemo, useEffect, Fragment } from '@wordpress/element';
import { AddressForm } from '@woocommerce/base-components/cart-checkout';
import {
useCheckoutAddress,
useStoreEvents,
useEditorContext,
} from '@woocommerce/base-context';
import { CheckboxControl } from '@woocommerce/blocks-checkout';
import Noninteractive from '@woocommerce/base-components/noninteractive';
import type {
BillingAddress,
ShippingAddress,
AddressField,
AddressFields,
} from '@woocommerce/settings';
/**
* Internal dependencies
*/
import PhoneNumber from '../../phone-number';
const Block = ( {
showCompanyField = false,
showApartmentField = false,
showPhoneField = false,
requireCompanyField = false,
requirePhoneField = false,
}: {
showCompanyField: boolean;
showApartmentField: boolean;
showPhoneField: boolean;
requireCompanyField: boolean;
requirePhoneField: boolean;
} ): JSX.Element => {
const {
defaultAddressFields,
setShippingAddress,
setBillingData,
shippingAddress,
setShippingPhone,
useShippingAsBilling,
setUseShippingAsBilling,
} = useCheckoutAddress();
const { dispatchCheckoutEvent } = useStoreEvents();
const { isEditor } = useEditorContext();
// Clears data if fields are hidden.
useEffect( () => {
if ( ! showPhoneField ) {
setShippingPhone( '' );
}
}, [ showPhoneField, setShippingPhone ] );
const addressFieldsConfig = useMemo( () => {
return {
company: {
hidden: ! showCompanyField,
required: requireCompanyField,
},
address_2: {
hidden: ! showApartmentField,
},
};
}, [
showCompanyField,
requireCompanyField,
showApartmentField,
] ) as Record< keyof AddressFields, Partial< AddressField > >;
const AddressFormWrapperComponent = isEditor ? Noninteractive : Fragment;
return (
<>
) => {
setShippingAddress( values );
if ( useShippingAsBilling ) {
setBillingData( values );
}
dispatchCheckoutEvent( 'set-shipping-address' );
} }
values={ shippingAddress }
fields={
Object.keys(
defaultAddressFields
) as ( keyof AddressFields )[]
}
fieldConfig={ addressFieldsConfig }
/>
{ showPhoneField && (
{
setShippingPhone( value );
dispatchCheckoutEvent( 'set-phone-number', {
step: 'shipping',
} );
} }
/>
) }
{
setUseShippingAsBilling( checked );
if ( checked ) {
setBillingData( shippingAddress as BillingAddress );
}
} }
/>
>
);
};
export default Block;