Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Commit

Permalink
Refactor getValidationError and getValidationErrorId selectors in…
Browse files Browse the repository at this point in the history
… `wc/store/validation` data store (#7146)

* Convert checkout context to data store - part 1 (#6232)

* Add checkout data store

* wip on checkout data store

* CheckoutContext now uses the checkout store

* Investigated and removed setting the redirectUrl on the default state

* update extension and address hooks to use checkout data store

* use checkout data store in checkout-processor and use-checkout-button

* trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity

* Remove useCheckoutContext from shipping provider

* Remove isCalculating from state

* Removed useCheckoutContext from lots of places

* Remove useCheckoutContext from checkout-payment-block

* Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block

* add isCart selector and action and update the checkoutstate context

* Fixed redirectUrl bug by using thunks

* Remove dispatchActions from checkout-state

* Change SET_HAS_ERROR action to be neater

* Thomas' feedback

* Tidy up

* Oops, deleted things I shouldn't have

* Typescript

* Fix types

* Fix tests

* Remove isCart

* Update docs and remove unecessary getRedirectUrl() selector

* set correct type for preloadedCheckoutData

* Remove duplicate Address type

* Fix missing addresses from type-defs index

* Update docs/block-client-apis/checkout/checkout-api.md

Co-authored-by: Thomas Roberts <[email protected]>

* Update docs/block-client-apis/checkout/checkout-api.md

Co-authored-by: Thomas Roberts <[email protected]>

* Update docs

* Update docs/block-client-apis/checkout/checkout-api.md

Co-authored-by: Thomas Roberts <[email protected]>

* Update docs/block-client-apis/checkout/checkout-api.md

Co-authored-by: Thomas Roberts <[email protected]>

* Revert feedback changes

* REvert feedback formatting

* Update docs formatting

* Delete empty types.ts file

* remove merge conflict from docs

* Correct linting in docs

Co-authored-by: Thomas Roberts <[email protected]>

* Move checkout state code into thunks and rename `CheckoutState` context to `CheckoutEvents` (#6455)

* Add checkout data store

* wip on checkout data store

* CheckoutContext now uses the checkout store

* Investigated and removed setting the redirectUrl on the default state

* update extension and address hooks to use checkout data store

* use checkout data store in checkout-processor and use-checkout-button

* trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity

* Remove useCheckoutContext from shipping provider

* Remove isCalculating from state

* Removed useCheckoutContext from lots of places

* Remove useCheckoutContext from checkout-payment-block

* Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block

* add isCart selector and action and update the checkoutstate context

* Fixed redirectUrl bug by using thunks

* Remove dispatchActions from checkout-state

* Change SET_HAS_ERROR action to be neater

* Thomas' feedback

* Tidy up

* Oops, deleted things I shouldn't have

* Typescript

* Fix types

* Fix tests

* Remove isCart

* Update docs and remove unecessary getRedirectUrl() selector

* validate event emitter button

* Added thunks in a separate file

* Call thunks from checkout-state

* Checkout logic tested and working

* Remove dependency injection as much as poss, tidy up and fix some TS errors

* Fix types in thunks.ts

* Fixed some ts errors

* WIP

* Fixed bug

* Shift side effects from checkout-state to checkout-processor

* Revert "Shift side effects from checkout-state to checkout-processor"

This reverts commit 059533d.

* Rename CheckoutState to CheckoutEvents

* Move status check outside the thunk

* remove duplicate EVENTS constant

* remove temp buttons

* Remove console logs

* Augment @wordpress/data package with our new store types

* Add correct type for CheckoutAction

* Remove createErrorNotice arg from runCheckoutAfterProcessingWithErrorObservers

* Remove createErrorNotice from emit event types

* Use type keyword when importing types

* Add correct types for dispatch and select in thunks

* Update wordpress/data types

* Replace store creation with new preferred method

* Set correct action type on reducer

* Remove unnecessary async from thunk

* add CHECKOUT_ prefix to checkout events again

* export EVENTS with eveything else in checkout0-events/event-emit

* Remove duplicate SelectFromMap and TailParameters

* Updated type for paymentStatus

* TODO remove wp/data experimental thunks

* Remove `setCustomerId` from events and `processCheckoutResponseHeaders` (#6586)

* Prevent passing dispatch, instead get actions direct from store

* Get setCustomerId from the store instead of passing it to processCheckoutResponseHeaders

* Revert "Prevent passing dispatch, instead get actions direct from store"

This reverts commit 4479a2e.

* Auto stash before revert of "Prevent passing dispatch, instead get actions direct from store"

* Remove duplicate dispatch

* Fix unit tests

Co-authored-by: Thomas Roberts <[email protected]>
Co-authored-by: Thomas Roberts <[email protected]>

* Refactor selectors to not return functions anymore

This is a poor DevEx and naming did not reflect what the selector was returning.

* Update combobox to be more explicit when selecting validation error

* Update useValidation to use the new getValidationError selector

* Include @woocommerce/base-hooks in tsconfig

* Update ValidationInputError to use new selector

* Update ValidatedTextInput to use new selectors

* Prevent reference errors when getting validation errors in ComboBox

* Defend against case where message prop of error object is undefined

* Fix totals/coupon to use new validation selector

* Use validation data store in CheckoutTerms block

* Update AddressForm to use new validation selector

* Update AttributeSelectControl to use new validation selector

* Fix syntax error in ValidatedTextInput

* Fix multiple import error from rebase

* Fix lint issue in useStoreCartItemQantity

* Fix tests to reflect new selector API

* Remove unused validation prop from CheckoutTermsBlock

* Change CheckoutTermsBlock unit tests to use validation data store

* Fix JSDOC syntax

* fix merge conflict in checkout-api.md

Co-authored-by: Alex Florisca <[email protected]>
Co-authored-by: Niels Lange <[email protected]>
  • Loading branch information
3 people committed Sep 28, 2022
1 parent a23a6cb commit 9735e9c
Show file tree
Hide file tree
Showing 17 changed files with 63,014 additions and 49,606 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,17 @@ const AttributeSelectControl = ( {
'woo-gutenberg-products-block'
),
} ) => {
const errorId = attributeName;

const { setValidationErrors, clearValidationError } =
useDispatch( VALIDATION_STORE_KEY );

const { getValidationError } = useSelect( ( select ) => {
const { error } = useSelect( ( select ) => {
const store = select( VALIDATION_STORE_KEY );
return {
getValidationError: store.getValidationError(),
error: store.getValidationError( errorId ) || {},
};
} );
const errorId = attributeName;
const error = getValidationError( errorId ) || {};

useEffect( () => {
if ( value ) {
Expand Down Expand Up @@ -79,7 +79,7 @@ const AttributeSelectControl = ( {
className={ classnames(
'wc-block-components-product-add-to-cart-attribute-picker__select',
{
'has-error': error.message && ! error.hidden,
'has-error': error?.message && ! error?.hidden,
}
) }
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,14 @@ const validateShippingCountry = (
clearValidationError: ( error: string ) => void,
hasValidationError: boolean
): void => {
const validationErrorId = 'shipping-missing-country';
if (
! hasValidationError &&
! values.country &&
( values.city || values.state || values.postcode )
) {
setValidationErrors( {
'shipping-missing-country': {
[ validationErrorId ]: {
message: __(
'Please select a country to calculate rates.',
'woo-gutenberg-products-block'
Expand All @@ -58,7 +59,7 @@ const validateShippingCountry = (
} );
}
if ( hasValidationError && values.country ) {
clearValidationError( 'shipping-missing-country' );
clearValidationError( validationErrorId );
}
};

Expand Down Expand Up @@ -93,23 +94,17 @@ const AddressForm = ( {
type = 'shipping',
values,
}: AddressFormProps ): JSX.Element => {
const validationErrorId = 'shipping-missing-country';
const { setValidationErrors, clearValidationError } =
useDispatch( VALIDATION_STORE_KEY );

const getValidationError = useSelect( ( select ) => {
const countryValidationError = useSelect( ( select ) => {
const store = select( VALIDATION_STORE_KEY );
return store.getValidationError();
return store.getValidationError( validationErrorId );
} );

const currentFields = useShallowEqual( fields );

const countryValidationError = ( getValidationError(
'shipping-missing-country'
) || {} ) as {
message: string;
hidden: boolean;
};

const addressFormFields = useMemo( () => {
return prepareAddressFields(
currentFields,
Expand All @@ -136,14 +131,14 @@ const AddressForm = ( {
values,
setValidationErrors,
clearValidationError,
!! countryValidationError.message &&
! countryValidationError.hidden
!! countryValidationError?.message &&
! countryValidationError?.hidden
);
}
}, [
values,
countryValidationError.message,
countryValidationError.hidden,
countryValidationError?.message,
countryValidationError?.hidden,
setValidationErrors,
clearValidationError,
type,
Expand Down
31 changes: 15 additions & 16 deletions assets/js/base/components/cart-checkout/totals/coupon/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,17 @@ export const TotalsCoupon = ( {
}: TotalsCouponProps ): JSX.Element => {
const [ couponValue, setCouponValue ] = useState( '' );
const currentIsLoading = useRef( false );
const { getValidationError, getValidationErrorId } = useSelect(
( select ) => {
const store = select( VALIDATION_STORE_KEY );
return {
getValidationError: store.getValidationError(),
getValidationErrorId: store.getValidationErrorId(),
};
}
);

const validationError = getValidationError( 'coupon' );
const validationErrorKey = 'coupon';
const textInputId = `wc-block-components-totals-coupon__input-${ instanceId }`;

const { validationError, validationErrorId } = useSelect( ( select ) => {
const store = select( VALIDATION_STORE_KEY );
return {
validationError: store.getValidationError( validationErrorKey ),
validationErrorId: store.getValidationErrorId( textInputId ),
};
} );

useEffect( () => {
if ( currentIsLoading.current !== isLoading ) {
Expand All @@ -66,8 +66,6 @@ export const TotalsCoupon = ( {
}
}, [ isLoading, couponValue, validationError ] );

const textInputId = `wc-block-components-totals-coupon__input-${ instanceId }`;

return (
<Panel
className="wc-block-components-totals-coupon"
Expand Down Expand Up @@ -106,9 +104,7 @@ export const TotalsCoupon = ( {
'woo-gutenberg-products-block'
) }
value={ couponValue }
ariaDescribedBy={ getValidationErrorId(
textInputId
) }
ariaDescribedBy={ validationErrorId }
onChange={ ( newCouponValue ) => {
setCouponValue( newCouponValue );
} }
Expand All @@ -120,7 +116,10 @@ export const TotalsCoupon = ( {
disabled={ isLoading || ! couponValue }
showSpinner={ isLoading }
onClick={ (
e: React.MouseEvent< HTMLElement, 'click' >
e: React.MouseEvent<
HTMLButtonElement,
MouseEvent
>
) => {
e.preventDefault();
onSubmit( couponValue );
Expand Down
23 changes: 8 additions & 15 deletions assets/js/base/components/combobox/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,24 +54,17 @@ const Combobox = ( {
instanceId = '0',
autoComplete = 'off',
}: ComboboxProps ): JSX.Element => {
const controlRef = useRef< HTMLDivElement >( null );
const controlId = id || 'control-' + instanceId;
const errorId = incomingErrorId || controlId;

const { setValidationErrors, clearValidationError } =
useDispatch( VALIDATION_STORE_KEY );
const getValidationError = useSelect( ( select ) => {
const error = useSelect( ( select ) => {
const store = select( VALIDATION_STORE_KEY );
return store.getValidationError();
return store.getValidationError( errorId );
} );

const controlRef = useRef< HTMLDivElement >( null );
const controlId = id || 'control-' + instanceId;
const errorId = incomingErrorId || controlId;
const error = ( getValidationError( errorId ) || {
message: '',
hidden: false,
} ) as {
message: string;
hidden: boolean;
};

useEffect( () => {
if ( ! required || value ) {
clearValidationError( errorId );
Expand Down Expand Up @@ -102,7 +95,7 @@ const Combobox = ( {
id={ controlId }
className={ classnames( 'wc-block-components-combobox', className, {
'is-active': value,
'has-error': error.message && ! error.hidden,
'has-error': error?.message && ! error?.hidden,
} ) }
ref={ controlRef }
>
Expand Down Expand Up @@ -145,7 +138,7 @@ const Combobox = ( {
value={ value || '' }
allowReset={ false }
autoComplete={ autoComplete }
aria-invalid={ error.message && ! error.hidden }
aria-invalid={ error?.message && ! error?.hidden }
/>
<ValidationInputError propertyName={ errorId } />
</div>
Expand Down
26 changes: 11 additions & 15 deletions assets/js/base/components/text-input/validated-text-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,13 @@ const ValidatedTextInput = ( {
typeof id !== 'undefined' ? id : 'textinput-' + instanceId;
const errorIdString = errorId !== undefined ? errorId : textInputId;

const { getValidationError, getValidationErrorId } = useSelect(
( select ) => {
const store = select( VALIDATION_STORE_KEY );
return {
getValidationError: store.getValidationError(),
getValidationErrorId: store.getValidationErrorId(),
};
}
);
const { validationError, validationErrorId } = useSelect( ( select ) => {
const store = select( VALIDATION_STORE_KEY );
return {
validationError: store.getValidationError( errorIdString ),
validationErrorId: store.getValidationErrorId( errorIdString ),
};
} );

const validateInput = useCallback(
( errorsHidden = true ) => {
Expand Down Expand Up @@ -124,16 +122,14 @@ const ValidatedTextInput = ( {
};
}, [ clearValidationError, errorIdString ] );

const errorMessage = getValidationError( errorIdString );

if ( isString( passedErrorMessage ) && passedErrorMessage !== '' ) {
errorMessage.message = passedErrorMessage;
validationError.message = passedErrorMessage;
}

const hasError = errorMessage?.message && ! errorMessage?.hidden;
const hasError = validationError?.message && ! validationError?.hidden;
const describedBy =
showError && hasError && getValidationErrorId( errorIdString )
? getValidationErrorId( errorIdString )
showError && hasError && validationErrorId
? validationErrorId
: ariaDescribedBy;

return (
Expand Down
3 changes: 2 additions & 1 deletion assets/js/base/components/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"../../atomic/utils",
"../../atomic/blocks/component-init.js",
"../../data",
"../../shared/context"
"../../shared/context",
"../hooks/index.js"
],
"exclude": [ "**/test/**" ]
}
24 changes: 10 additions & 14 deletions assets/js/base/components/validation-input-error/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,29 +20,25 @@ export const ValidationInputError = ( {
propertyName = '',
elementId = '',
}: ValidationInputErrorProps ): JSX.Element | null => {
const { getValidationError, getValidationErrorId } = useSelect(
( select ) => {
const store = select( VALIDATION_STORE_KEY );
return {
getValidationError: store.getValidationError(),
getValidationErrorId: store.getValidationErrorId(),
};
}
);
const validationError = getValidationError( propertyName );
const { validationError, validationErrorId } = useSelect( ( select ) => {
const store = select( VALIDATION_STORE_KEY );
return {
validationError: store.getValidationError( propertyName ),
validationErrorId: store.getValidationErrorId( elementId ),
};
} );

if ( ! errorMessage || typeof errorMessage !== 'string' ) {
const error = validationError || {};
if ( error.message && ! error.hidden ) {
errorMessage = error.message;
if ( validationError?.message && ! validationError?.hidden ) {
errorMessage = validationError.message;
} else {
return null;
}
}

return (
<div className="wc-block-components-validation-error" role="alert">
<p id={ getValidationErrorId( elementId ) }>{ errorMessage }</p>
<p id={ validationErrorId }>{ errorMessage }</p>
</div>
);
};
Expand Down
23 changes: 12 additions & 11 deletions assets/js/base/context/hooks/use-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,25 @@ import { VALIDATION_STORE_KEY } from '@woocommerce/block-data';
export const useValidation = (): ValidationData => {
const { clearValidationError, hideValidationError, setValidationErrors } =
useDispatch( VALIDATION_STORE_KEY );

const prefix = 'extensions-errors';

const { hasValidationErrors, getValidationError } = useSelect(
( select ) => {
const store = select( VALIDATION_STORE_KEY );
( mapSelect ) => {
const store = mapSelect( VALIDATION_STORE_KEY );
return {
hasValidationErrors: store.hasValidationErrors,
getValidationError: store.getValidationError(),
hasValidationErrors: store.hasValidationErrors(),
getValidationError: ( validationErrorId: string ) =>
store.getValidationError(
`${ prefix }-${ validationErrorId }`
),
};
}
);
const prefix = 'extensions-errors';

return {
hasValidationErrors: hasValidationErrors(),
getValidationError: useCallback(
( validationErrorId: string ) =>
getValidationError( `${ prefix }-${ validationErrorId }` ),
[ getValidationError ]
),
hasValidationErrors,
getValidationError,
clearValidationError: useCallback(
( validationErrorId: string ) =>
clearValidationError( `${ prefix }-${ validationErrorId }` ),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import { useState, useEffect } from '@wordpress/element';
import { CheckboxControl } from '@woocommerce/blocks-checkout';
import { useCheckoutSubmit } from '@woocommerce/base-context/hooks';
import { withInstanceId } from '@wordpress/compose';
import type { ValidationData } from '@woocommerce/type-defs/contexts';
import { useDispatch, useSelect } from '@wordpress/data';
import { VALIDATION_STORE_KEY } from '@woocommerce/block-data';

/**
* Internal dependencies
*/
Expand All @@ -18,25 +20,27 @@ const FrontendBlock = ( {
text,
checkbox,
instanceId,
validation,
className,
}: {
text: string;
checkbox: boolean;
instanceId: string;
validation: ValidationData;
className?: string;
} ): JSX.Element => {
const [ checked, setChecked ] = useState( false );

const { isDisabled } = useCheckoutSubmit();

const validationErrorId = 'terms-and-conditions-' + instanceId;
const { getValidationError, setValidationErrors, clearValidationError } =
validation;
const { setValidationErrors, clearValidationError } =
useDispatch( VALIDATION_STORE_KEY );

const error = getValidationError( validationErrorId ) || {};
const hasError = error.message && ! error.hidden;
const error = useSelect( ( select ) => {
return select( VALIDATION_STORE_KEY ).getValidationError(
validationErrorId
);
} );
const hasError = !! ( error?.message && ! error?.hidden );

// Track validation errors for this input.
useEffect( () => {
Expand Down
Loading

0 comments on commit 9735e9c

Please sign in to comment.