/** * External dependencies */ import { __ } from '@wordpress/i18n'; import { useState, useEffect, useRef } from '@wordpress/element'; import Button from '@woocommerce/base-components/button'; import { ValidatedTextInput } from '@woocommerce/base-components/text-input'; import Label from '@woocommerce/base-components/label'; import LoadingMask from '@woocommerce/base-components/loading-mask'; import { withInstanceId } from '@wordpress/compose'; import { ValidationInputError, useValidationContext, } from '@woocommerce/base-context'; import { Panel } from '@woocommerce/blocks-checkout'; /** * Internal dependencies */ import './style.scss'; export interface TotalsCouponProps { /** * Instance id of the input */ instanceId: string; /** * Whether the component is in a loading state */ isLoading?: boolean; /** * Whether the component's parent panel will begin in an open state */ initialOpen?: boolean; /** * Submit handler */ onSubmit?: ( couponValue: string ) => void; } export const TotalsCoupon = ( { instanceId, isLoading = false, initialOpen = false, onSubmit = () => void 0, }: TotalsCouponProps ): JSX.Element => { const [ couponValue, setCouponValue ] = useState( '' ); const currentIsLoading = useRef( false ); const { getValidationError, getValidationErrorId } = useValidationContext(); const validationError = getValidationError( 'coupon' ); useEffect( () => { if ( currentIsLoading.current !== isLoading ) { if ( ! isLoading && couponValue && ! validationError ) { setCouponValue( '' ); } currentIsLoading.current = isLoading; } }, [ isLoading, couponValue, validationError ] ); const textInputId = `wc-block-components-totals-coupon__input-${ instanceId }`; return ( } > { setCouponValue( newCouponValue ); } } focusOnMount={ true } showError={ false } /> ) => { e.preventDefault(); onSubmit( couponValue ); } } type="submit" > { __( 'Apply', 'woo-gutenberg-products-block' ) } ); }; export default withInstanceId( TotalsCoupon );