import React, { ComponentType, FunctionComponent, useMemo } from "react"; import { DependencyNames } from "../types/DependencyNames"; import { Fn, IntersectionFn, ToSchema } from "../types/Fn"; import { Hoc } from "../types/Hoc"; import { newHoc } from "../utils/newHoc"; interface WithIfFn extends Fn { return: [PropName, any] extends this["arg0"] ? this["arg0"] : this["arg0"] | [PropName, PropValue]; } interface WithIfHoc { ( propName: PropName, options?: { Else?: ComponentType; }, ): Hoc<[WithIfFn]>; < DependencyProps extends {}, TDependencyNames extends DependencyNames = DependencyNames, >( factory: (props: DependencyProps) => any, options: { Else?: ComponentType; dependencyNames: TDependencyNames; }, ): Hoc<[IntersectionFn>]>; } /** * renders conditionally * * @experimental It could have a better name * * @example * const AdminDashboard: React.FC = () => { * return <>... * } * const SafeAdminDashboard = withIf<"isAdmin", boolean>("isAdmin")(AdminDashboard) * * // renders * * * // renders null * * * @example * const HappyScreen: React.FC = () => { * return <>... * } * const BlueErrorScreen: React.FC = () => { * return <>... * } * const NewComponent = withIf("error", { * Else: BlueErrorScreen * })(HappyScreen) * * // renders * * * // renders * * * @example * type HappinessLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10; * const HappyScreen: React.FC = () => { * return <>... * } * const SadScreen: React.FC = () => { * return <>... * } * const MoodScreen = withIf<{ happinessLevel: HappinessLevel }>( * ({ happinessLevel }) => happinessLevel >= 5, * { * dependencyNames: ["happinessLevel"], * Else: SadScreen, * }, * )(HappyScreen); * * // renders * * * // renders * */ export const withIf = newHoc(function withIf( Component: ComponentType, propNameOrFactory: string | Function, { dependencyNames, Else, }: { dependencyNames?: string[]; Else?: ComponentType; } = {}, ): FunctionComponent { if (process.env.NODE_ENV !== "production") { if (typeof propNameOrFactory === "function" && !dependencyNames) { throw new Error( "withIf with function should have dependencyNames assigned", ); } } return function WithIf(props: any): JSX.Element { let condition: boolean; if (typeof propNameOrFactory === "string") { condition = props[propNameOrFactory]; } else { // is function condition = useMemo( () => propNameOrFactory(props), dependencyNames!.map((key) => props[key]), ); } if (condition) { return ; } else { if (Else) { return ; } // @ts-expect-error null is valid return null; } }; });