11import * as React from 'react'
22import { ComponentType , ReactNode , ReactElement } from 'react'
33
4- const isAllElementValid = ( values : ReactNode [ ] ) : boolean =>
5- ! values . some ( value => ! React . isValidElement ( value ) )
6-
74export type ChildrenFn < P > = ( props : P ) => ReactNode
85
96export type RPC < Props > = ComponentType < {
@@ -12,31 +9,33 @@ export type RPC<Props> = ComponentType<{
129
1310export type Mapper < R > = Record < keyof R , ReactElement < any > | any >
1411
12+ const isValidRenderProp = ( prop : ReactNode | ChildrenFn ) : boolean =>
13+ React . isValidElement ( prop ) || typeof prop === 'function'
14+
15+ const Children = ( { children } : any ) => children ( )
16+
1517export function adopt < RP extends Record < string , any > > (
1618 mapper : Mapper < RP >
1719) : RPC < RP > {
18- if ( ! isAllElementValid ( Object . values ( mapper ) ) ) {
20+ if ( ! Object . values ( mapper ) . some ( isValidRenderProp ) ) {
1921 throw new Error (
2022 'The render props object mapper just accept valid elements as value'
2123 )
2224 }
2325
24- const Initial = ( { children } : any ) =>
25- children && typeof children === 'function' && children ( )
26-
2726 return Object . keys ( mapper ) . reduce (
28- ( Component : RPC < RP > , key : keyof RP ) : RPC < RP > => ( { children } ) => (
27+ ( Component : RPC < RP > , key : keyof RP ) : RPC < RP > => ( { children, ... rest } ) => (
2928 < Component >
30- { props =>
31- React . cloneElement ( mapper [ key ] , {
32- children : ( childProps : any ) =>
33- children &&
34- typeof children === 'function' &&
35- children ( Object . assign ( { } , props , { [ key ] : childProps } ) ) ,
36- } )
37- }
29+ { props => {
30+ const renderProp = ( childProps : any ) =>
31+ children ( Object . assign ( { } , props , { [ key ] : childProps } ) )
32+
33+ return typeof mapper [ key ] === 'function'
34+ ? mapper [ key ] ( Object . assign ( { } , rest , props , { renderProp } ) )
35+ : React . cloneElement ( mapper [ key ] , { children : renderProp } )
36+ } }
3837 </ Component >
3938 ) ,
40- Initial
39+ Children
4140 )
4241}
0 commit comments