woocommerce/plugins/woocommerce-blocks/assets/js/data/validation/reducers.ts

81 lines
2.0 KiB
TypeScript
Raw Normal View History

Convert validation context to data store (https://github.com/woocommerce/woocommerce-blocks/pull/6402) * Add validation reducers, actions, and action types * Add selector for getValidationErrors * Export store key and register store * Export validation store key * Move TextInput files to checkout package * Export ValidatedTextInput from blocks-checkout package * Update imports of ValidatedTextInput to reflect new location * Use the validation wp-data store for showing error messages * Export getValidationError in checkout package * Move validation store to checkout package * Move ValidationInputError to blocks-checkout package * Only export "exposedSelectors" from validation * Convert validation context to data store * Fixed linting error * Fixed linting error * Change the validation selectors to return a function * Convert reducer and selectors to TS * Remove superfluous comments and improve test titles * Test to ensure visible errors remain visible * Make test for hasValidationErrors more robust * Augment the wp-data module to include our selectors and actions * Removed unused `exposedSelectors` variable * Remove TS error because of `instanceId` on props * Remove unnecessary as const * Use function returned by getValidationError * Use correct selector/action names now context has been decoupled * hide validation error when input value changes * Add correct aria-describedBy now we can get error id from store * Clear validation error from store when component unmounts * Clear validation error if input is valid * convert ValidationInputError to TS and get correct id/error from store * Ensure checkout block doesn't break when there are no errors * Get validation data from the store instead of context * Update country input to remove validation context * Move validation store out of checkout package * Move TextInput and ValidationInputError back out of the checkout package * Remove duplicate internal styles comment * Remove exports that no longer exist * Get validation store key from block-data * Make attribute-select-control use validation data store * Export FieldValidationStatus type * Make combobox use validation store not context * Make Address use validation store not context * Make Address use validation store not context * Use hasValidationErrors selector as a function in shipping calculator * Remove validation context from coupon story * Import VALIDATION_STORE_KEY from correct location * Stop coupon story from erroring * Update useStoreCartCoupons to use validation store not context * Make TotalsCoupon use validation store instead of context * Make AddToCartFormContext use validation store not context * Remove ValidationContext * Import FieldValidationStatus from correct location * Import ValidatedTextInput and ValidatedTextInput from correct location * Remove ValidationContextProvider * Update components to use validation store not context * Update useValidation to use the data store * Replace the validation context in checkout-events file * Use the re-mapped path for the store key import * Use "register" instead of the deprecated "registerStore" * Fix import error of the "FieldValidationStatus" type * Use TS instead of React's "PropTypes" * Fix the type of "ValidationInputError" in the "payment-method-interface" * Fix error not showing on the first place order click bug We were mutating the state in the reducer, which prevented re-rendering on state change * Fix state mutation issue in the Validation reducer Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-07-01 23:06:25 +00:00
/**
* External dependencies
*/
import type { Reducer } from 'redux';
import { pickBy } from 'lodash';
import isShallowEqual from '@wordpress/is-shallow-equal';
import { isString } from '@woocommerce/types';
/**
* Internal dependencies
*/
import { ValidationAction } from './actions';
import { ACTION_TYPES as types } from './action-types';
import { FieldValidationStatus } from '../types';
const reducer: Reducer< Record< string, FieldValidationStatus > > = (
state: Record< string, FieldValidationStatus > = {},
action: Partial< ValidationAction >
) => {
const newState = { ...state };
switch ( action.type ) {
case types.SET_VALIDATION_ERRORS:
const newErrors = pickBy( action.errors, ( error, property ) => {
Refactor `getValidationError` and `getValidationErrorId` selectors in `wc/store/validation` data store (https://github.com/woocommerce/woocommerce-blocks/pull/7146) * Convert checkout context to data store - part 1 (https://github.com/woocommerce/woocommerce-blocks/pull/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 <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * 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 <5656702+opr@users.noreply.github.com> * Move checkout state code into thunks and rename `CheckoutState` context to `CheckoutEvents` (https://github.com/woocommerce/woocommerce-blocks/pull/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 059533da4eb34f9982f66cd4adacc7b2c24f939f. * 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` (https://github.com/woocommerce/woocommerce-blocks/pull/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 4479a2ef5599d9c8d99c3629616b3d662210fc08. * 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 <thomas.roberts@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * 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 <alex.florisca@automattic.com> Co-authored-by: Niels Lange <info@nielslange.de>
2022-09-22 09:54:02 +00:00
if ( typeof error?.message !== 'string' ) {
Convert validation context to data store (https://github.com/woocommerce/woocommerce-blocks/pull/6402) * Add validation reducers, actions, and action types * Add selector for getValidationErrors * Export store key and register store * Export validation store key * Move TextInput files to checkout package * Export ValidatedTextInput from blocks-checkout package * Update imports of ValidatedTextInput to reflect new location * Use the validation wp-data store for showing error messages * Export getValidationError in checkout package * Move validation store to checkout package * Move ValidationInputError to blocks-checkout package * Only export "exposedSelectors" from validation * Convert validation context to data store * Fixed linting error * Fixed linting error * Change the validation selectors to return a function * Convert reducer and selectors to TS * Remove superfluous comments and improve test titles * Test to ensure visible errors remain visible * Make test for hasValidationErrors more robust * Augment the wp-data module to include our selectors and actions * Removed unused `exposedSelectors` variable * Remove TS error because of `instanceId` on props * Remove unnecessary as const * Use function returned by getValidationError * Use correct selector/action names now context has been decoupled * hide validation error when input value changes * Add correct aria-describedBy now we can get error id from store * Clear validation error from store when component unmounts * Clear validation error if input is valid * convert ValidationInputError to TS and get correct id/error from store * Ensure checkout block doesn't break when there are no errors * Get validation data from the store instead of context * Update country input to remove validation context * Move validation store out of checkout package * Move TextInput and ValidationInputError back out of the checkout package * Remove duplicate internal styles comment * Remove exports that no longer exist * Get validation store key from block-data * Make attribute-select-control use validation data store * Export FieldValidationStatus type * Make combobox use validation store not context * Make Address use validation store not context * Make Address use validation store not context * Use hasValidationErrors selector as a function in shipping calculator * Remove validation context from coupon story * Import VALIDATION_STORE_KEY from correct location * Stop coupon story from erroring * Update useStoreCartCoupons to use validation store not context * Make TotalsCoupon use validation store instead of context * Make AddToCartFormContext use validation store not context * Remove ValidationContext * Import FieldValidationStatus from correct location * Import ValidatedTextInput and ValidatedTextInput from correct location * Remove ValidationContextProvider * Update components to use validation store not context * Update useValidation to use the data store * Replace the validation context in checkout-events file * Use the re-mapped path for the store key import * Use "register" instead of the deprecated "registerStore" * Fix import error of the "FieldValidationStatus" type * Use TS instead of React's "PropTypes" * Fix the type of "ValidationInputError" in the "payment-method-interface" * Fix error not showing on the first place order click bug We were mutating the state in the reducer, which prevented re-rendering on state change * Fix state mutation issue in the Validation reducer Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> Co-authored-by: Saad Tarhi <saad.trh@gmail.com>
2022-07-01 23:06:25 +00:00
return false;
}
if ( state.hasOwnProperty( property ) ) {
return ! isShallowEqual( state[ property ], error );
}
return true;
} );
if ( Object.values( newErrors ).length === 0 ) {
return state;
}
return { ...state, ...action.errors };
case types.CLEAR_ALL_VALIDATION_ERRORS:
return {};
case types.CLEAR_VALIDATION_ERROR:
if (
! isString( action.error ) ||
! newState.hasOwnProperty( action.error )
) {
return newState;
}
delete newState[ action.error ];
return newState;
case types.HIDE_VALIDATION_ERROR:
if (
! isString( action.error ) ||
! newState.hasOwnProperty( action.error )
) {
return newState;
}
newState[ action.error ].hidden = true;
return newState;
case types.SHOW_VALIDATION_ERROR:
if (
! isString( action.error ) ||
! newState.hasOwnProperty( action.error )
) {
return newState;
}
newState[ action.error ].hidden = false;
return newState;
case types.SHOW_ALL_VALIDATION_ERRORS:
Object.keys( newState ).forEach( ( property ) => {
if ( newState[ property ].hidden ) {
newState[ property ].hidden = false;
}
} );
return { ...newState };
default:
return state;
}
};
export type State = ReturnType< typeof reducer >;
export default reducer;