import { ComponentType, FunctionComponent } from "react"; import { Hoc } from "../types/Hoc"; import { componentDisplayName } from "./componentDisplayName"; import { HocNameFactory, defaultHocName } from "./hocNameForWithStyle"; export type NewHocReturn = ( ...args: HocArgs ) => Hoc; export type HocDefinition = ( Component: ComponentType, ...args: HocArgs ) => FunctionComponent; export type GetHocArgs = Extract< T extends NewHocReturn ? R : T extends HocDefinition ? R : never, any[] >; type Name = | string | (( functions: { Component: ComponentType; hoc: HocDefinition; }, ...args: HocArgs ) => string); type FirstArgumentOptional = T extends [unknown, ...infer Rest] ? Rest | T : never; function newHoc>( hoc: HocDefinition>, ): TNewHocReturn; function newHoc>( name: Name>, hoc: HocDefinition>, ): TNewHocReturn; function newHoc>( ...args: FirstArgumentOptional< [Name>, HocDefinition>] > ): TNewHocReturn { const name: HocNameFactory | string = process.env.NODE_ENV != "production" && args.length === 2 ? args[0] : defaultHocName; const hoc: HocDefinition> = args.length === 2 ? args[1] : args[0]; return ((...args: any) => (Component: ComponentType): FunctionComponent => { if (process.env.NODE_ENV !== "production") { if (!hoc.name) { throw new Error(`Trying to create a new hoc without a name: ${hoc}`, { cause: hoc, }); } } const Ret = hoc(Component, ...args); if (process.env.NODE_ENV !== "production") { componentDisplayName.set( typeof name === "string" ? name : name({ Component, hoc }, ...args), Ret, ); } return Ret; }) as TNewHocReturn; } const newHocProduction: any = (...args: any[]) => { const hoc: any = args[args.length - 1]; return (...args: any) => (Component: ComponentType): FunctionComponent => { return hoc(Component, ...args); }; }; const exportNewHoc: typeof newHoc = process.env.NODE_ENV === "production" ? newHocProduction : newHoc; export { exportNewHoc as newHoc };