This repository was archived by the owner on Feb 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 221
/
Copy pathreducers.ts
92 lines (87 loc) · 2.32 KB
/
reducers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* 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 ) => {
if ( typeof error?.message !== 'string' ) {
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_VALIDATION_ERROR:
if (
! isString( action.error ) ||
! newState.hasOwnProperty( action.error )
) {
return newState;
}
delete newState[ action.error ];
return newState;
case types.CLEAR_VALIDATION_ERRORS:
const { errors } = action;
if ( typeof errors === 'undefined' ) {
return {};
}
if ( ! Array.isArray( errors ) ) {
return newState;
}
errors.forEach( ( error ) => {
if ( newState.hasOwnProperty( error ) ) {
delete newState[ 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;