|
| 1 | +import { Dispatch } from 'redux' |
| 2 | +import verifyPlainObject from '../utils/verifyPlainObject' |
| 3 | + |
| 4 | +type MergeProps<TStateProps, TDispatchProps, TOwnProps, TMergedProps> = (stateProps: TStateProps, dispatchProps: TDispatchProps, ownProps: TOwnProps) => TMergedProps |
| 5 | + |
| 6 | +export function defaultMergeProps<TStateProps, TDispatchProps, TOwnProps>(stateProps: TStateProps, dispatchProps: TDispatchProps, ownProps: TOwnProps) { |
| 7 | + return { ...ownProps, ...stateProps, ...dispatchProps } |
| 8 | +} |
| 9 | + |
| 10 | +interface InitMergeOptions { |
| 11 | + displayName: string; |
| 12 | + pure?: boolean; |
| 13 | + areMergedPropsEqual: (a: any, b: any) => boolean; |
| 14 | +} |
| 15 | + |
| 16 | +export function wrapMergePropsFunc<TStateProps, TDispatchProps, TOwnProps, TMergedProps>(mergeProps: MergeProps<TStateProps, TDispatchProps, TOwnProps, TMergedProps>): (dispatch: Dispatch, options: InitMergeOptions) => MergeProps<TStateProps, TDispatchProps, TOwnProps, TMergedProps> { |
| 17 | + return function initMergePropsProxy( |
| 18 | + dispatch, |
| 19 | + { displayName, pure, areMergedPropsEqual } |
| 20 | + ) { |
| 21 | + let hasRunOnce = false |
| 22 | + let mergedProps: TMergedProps |
| 23 | + |
| 24 | + return function mergePropsProxy(stateProps: TStateProps, dispatchProps: TDispatchProps, ownProps: TOwnProps) { |
| 25 | + const nextMergedProps = mergeProps(stateProps, dispatchProps, ownProps) |
| 26 | + |
| 27 | + if (hasRunOnce) { |
| 28 | + if (!pure || !areMergedPropsEqual(nextMergedProps, mergedProps)) |
| 29 | + mergedProps = nextMergedProps |
| 30 | + } else { |
| 31 | + hasRunOnce = true |
| 32 | + mergedProps = nextMergedProps |
| 33 | + |
| 34 | + if (process.env.NODE_ENV !== 'production') |
| 35 | + verifyPlainObject(mergedProps, displayName, 'mergeProps') |
| 36 | + } |
| 37 | + |
| 38 | + return mergedProps |
| 39 | + } |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +export function whenMergePropsIsFunction<TStateProps, TDispatchProps, TOwnProps, TMergedProps>(mergeProps: MergeProps<TStateProps, TDispatchProps, TOwnProps, TMergedProps>) { |
| 44 | + return typeof mergeProps === 'function' |
| 45 | + ? wrapMergePropsFunc(mergeProps) |
| 46 | + : undefined |
| 47 | +} |
| 48 | + |
| 49 | +export function whenMergePropsIsOmitted<TStateProps, TDispatchProps, TOwnProps, TMergedProps>(mergeProps?: MergeProps<TStateProps, TDispatchProps, TOwnProps, TMergedProps>) { |
| 50 | + return !mergeProps ? () => defaultMergeProps : undefined |
| 51 | +} |
| 52 | + |
| 53 | +export default [whenMergePropsIsFunction, whenMergePropsIsOmitted] as const |
0 commit comments