/** * External dependencies */ import clsx from 'clsx'; import { _n, sprintf } from '@wordpress/i18n'; import { decodeEntities } from '@wordpress/html-entities'; import { Label, Panel } from '@woocommerce/blocks-components'; import { useCallback, useMemo } from '@wordpress/element'; import { useShippingData } from '@woocommerce/base-context/hooks'; import { sanitizeHTML } from '@woocommerce/utils'; import type { ReactElement } from 'react'; import { useSelect } from '@wordpress/data'; import { CART_STORE_KEY } from '@woocommerce/block-data'; /** * Internal dependencies */ import PackageRates from './package-rates'; import type { PackageProps } from './types'; import './style.scss'; export const ShippingRatesControlPackage = ( { packageId, className = '', noResultsMessage, renderOption, packageData, collapsible, showItems, highlightChecked = false, }: PackageProps ): ReactElement => { const { selectShippingRate, isSelectingRate } = useShippingData(); const internalPackageCount = useSelect( ( select ) => select( CART_STORE_KEY )?.getCartData()?.shippingRates?.length ); // We have no built-in way of checking if other extensions have added packages e.g. if subscriptions has added them. const multiplePackages = internalPackageCount > 1 || document.querySelectorAll( '.wc-block-components-shipping-rates-control__package' ).length > 1; // If showItems is not set, we check if we have multiple packages. // We sometimes don't want to show items even if we have multiple packages. const shouldShowItems = showItems ?? multiplePackages; // If collapsible is not set, we check if we have multiple packages. // We sometimes don't want to collapse even if we have multiple packages. const shouldBeCollapsible = collapsible ?? multiplePackages; const header = ( <> { ( shouldBeCollapsible || shouldShowItems ) && (
) } { shouldShowItems && ( ) } ); const onSelectRate = useCallback( ( newShippingRateId: string ) => { selectShippingRate( newShippingRateId, packageId ); }, [ packageId, selectShippingRate ] ); const packageRatesProps = { className, noResultsMessage, rates: packageData.shipping_rates, onSelectRate, selectedRate: packageData.shipping_rates.find( ( rate ) => rate.selected ), renderOption, disabled: isSelectingRate, highlightChecked, }; const selectedOptionNumber = useMemo( () => { return packageData?.shipping_rates?.findIndex( ( rate ) => rate?.selected ); }, [ packageData?.shipping_rates ] ); if ( shouldBeCollapsible ) { return ( ); } return (
{ header }
); }; export default ShippingRatesControlPackage;