import React, { ComponentType, FunctionComponent } from "react"; import { Fn } from "../types/Fn"; import { Hoc } from "../types/Hoc"; import { createHocNameFunction } from "../utils/hocNameForWithStyle"; import { newHoc } from "../utils/newHoc"; interface WithRenameFn extends Fn { return: [OldProp, any] extends this["arg0"] ? | Exclude | [NewProp, Extract[1]] : this["arg0"]; } type WithRenameHoc = < const NewProp extends string, const OldProp extends string, >( /** * @example * function Box({ handleClick }: { handleClick: () => void }) { * ... * } * const NewBox = withRename("onClick", "handleClick")(Box); * // ↑ this will be the property * {}} /> * // ↑ onClick is the new prop * // is equivalent to * {}} /> */ newProp: NewProp, /** * @example * function Box({ handleClick }: { handleClick: () => void }) { * ... * } * const NewBox = withRename("onClick", "handleClick")(Box); * // ↑ this is the old prop * {}} /> * // is equivalent to * {}} /> * // ↑ this is the old prop */ oldProp: OldProp, ) => Hoc<[WithRenameFn]>; /** * Make your component receive a new prop by renaming it. * * @see {@link withRenames} * @example * function Box({ handleClick }: { handleClick: () => void }) { * ... * } * const NewBox = withRename("onClick", "handleClick")(Box); * {}} /> * // is equivalent to * {}} /> */ export const withRename = newHoc( createHocNameFunction( (newProp: string, oldProp: string) => `${newProp}→${oldProp}`, ), function withRename( Component: ComponentType, newProp: string, oldProp: string, ): FunctionComponent { return function WithRename(props: any): JSX.Element { const newProps = { ...props }; if (newProp in newProps) { newProps[oldProp] = newProps[newProp]; delete newProps[newProp]; } return ; }; }, );