import React, { ComponentType, FunctionComponent } from "react"; import { IntersectionFn, ToSchema } from "../types/Fn"; import { Hoc } from "../types/Hoc"; import { newHoc } from "../utils/newHoc"; export interface WithWrapperHoc { < const WrapperProps, const PickOptions extends string[] = [never], const OmitOptions extends string[] = [never], >( Wrapper: ComponentType, options?: | { /** * @example * const NewComponent = withWrapper(Wrapper, { pickProps: ['a', 'b'] })(Component) * * // is equivalent to * * * */ pickProps: PickOptions; omitProps?: undefined; } | { /** * @example * const NewComponent = withWrapper(Wrapper, { omitProps: ['a', 'b'] })(Component) * * // is equivalent to * * * */ omitProps: OmitOptions; pickProps?: undefined; }, ): PickOptions extends [never] ? OmitOptions extends [never] ? // has none Hoc<[]> : // has omit Hoc< [ IntersectionFn< Exclude< ToSchema, [OmitOptions[number] | "children", any] > >, ] > : // has pick Hoc< [ IntersectionFn< Extract< Exclude, ["children", any]>, [PickOptions[number], any] > >, ] >; } /** * Wraps the component with the provided Component Wrapper * * @example * const NewComponent = withWrapper(Wrapper)(Component) * * // is equivalent to * // by default, it does not bring any prop * * * * @example * const NewComponent = withWrapper(Wrapper, { pickProps: ['a', 'b'] })(Component) * * // is equivalent to * * * * * @example * const NewComponent = withWrapper(Wrapper, { omitProps: ['a', 'b'] })(Component) * * // is equivalent to * * * * * @example * // to carry all props, use omitProps with empty array * const NewComponent = withWrapper(Wrapper, { omitProps: [] })(Component) * * // is equivalent to * * * */ export const withWrapper = newHoc(function withWrapper( Component: ComponentType, Wrapper: ComponentType, { pickProps, omitProps, }: { pickProps?: string[]; omitProps?: string[]; } = { pickProps: [] }, ): FunctionComponent { if (process.env.NODE_ENV !== "production") { const bothAssigned = pickProps && omitProps; const noneAssigned = !pickProps && !omitProps; if (bothAssigned || noneAssigned) { throw new Error( "withWrapper should have either pickProps or omitProps assigned", ); } } const set = new Set(pickProps || omitProps); return function WithWrapper(props: any): JSX.Element { if (set.size === 0 && pickProps) { return ( ); } if (set.size === 0 && omitProps) { return ( ); } const parentProps = {} as any; if (pickProps) { for (const prop in props) { if (set.has(prop)) { parentProps[prop] = props[prop]; } } } else if (omitProps) { for (const prop in props) { if (!set.has(prop)) { parentProps[prop] = props[prop]; } } } return ( ); }; });