import React, { ComponentType } from 'react'; import moment from 'moment'; import { get, set, has } from './utils'; function convertProps( props: Record, list: string[], mapper: (v: any, key: string) => any, ) { const out: Record = {}; list.forEach(key => { if (has(props, key)) { set(out, key, mapper(get(props, key), key)); } }); return out; } /** * Simple wrap with no extra logic. * Some component refs are special; wrapping fixes that. */ export function withWrap(Comp: ComponentType) { return (props: any) => { return ; }; } /** * Some components use React.Children.only on children. * Handle that to avoid runtime errors. */ export function withSingleChild( Comp: ComponentType, needsConvert = ['children'], ) { return (props: any) => { const convertedProps = convertProps(props, needsConvert, prop => { let node = React.Children.toArray(prop)[0]; if (node === null || typeof node !== 'object') { node =
{node}
; } return node; }); return ; }; } export function withSingleFunctionChild(Comp: ComponentType) { return (props: any) => { const { children } = props; let node; if (typeof children === 'function') { node = children; } if ( Array.isArray(children) && children.length === 1 && typeof children[0] === 'function' ) { node = children[0]; } if (node) { return {node}; } return
{children}
; }; } /** * moment objects become strings after serialization. * Date components need to accept string values. */ export function withMomentProps( Comp: ComponentType, needsConvert = ['value', 'defaultValue'], ) { return (props: any) => { const convertedProps = convertProps(props, needsConvert, prop => { if (prop) { if (Array.isArray(prop)) { return prop.map(v => (moment.isMoment(v) ? v : moment(v))); } return moment.isMoment(prop) ? prop : moment(prop); } }); return ; }; }