import React, { ComponentType, FunctionComponent } from "react"; import { Fn, ToSchema } from "../types/Fn"; import { Hoc } from "../types/Hoc"; import { createHocNameFunction } from "../utils/hocNameForWithStyle"; import { newHoc } from "../utils/newHoc"; interface WithRenamesFn extends Fn { return: { [K in Extract[0]]: [ K extends T[1] ? Extract[0] : K, Extract[1], ]; }[Extract[0]]; } type WithRenamesHoc = >( /** * @example * function Box({ handleClick, handleHover }: { handleClick: () => void; handleHover: () => void }) { * ... * } * const NewBox = withRenames({ * onClick: "handleClick", * onMouseOver: "handleHover" * // ↑ oldProps goes to right * // ↑ newProps goes to left * })(Box); * {}} onMouseOver={() => {}} /> * // is equivalent to * {}} handleHover={() => {}} /> */ map: Map, ) => Hoc<[WithRenamesFn>]>; /** * Make your component receive new props by renaming them. * * @see {@link withRename} * @example * function Box({ handleClick, handleHover }: { handleClick: () => void; handleHover: () => void }) { * ... * } * const NewBox = withRenames({ * onClick: "handleClick", * onMouseOver: "handleHover" * // ↑ oldProps goes to right * // ↑ newProps goes to left * })(Box); * {}} onMouseOver={() => {}} /> * // is equivalent to * {}} handleHover={() => {}} /> */ export const withRenames: WithRenamesHoc = newHoc( createHocNameFunction((map: object) => Object.entries(map) .map(([from, to]) => `${from}→${to}`) .join("."), ), function withRename( Component: ComponentType, map: Record, ): FunctionComponent { return function WithRenames(props: any): JSX.Element { const newProps = { ...props }; for (const newProp in map) { const oldProp = map[newProp]; if (newProp in newProps) { newProps[oldProp] = newProps[newProp]; delete newProps[newProp]; } } return ; }; }, );