From ff9821329ab47cb0c59ca2cecb5c4b998ef5a600 Mon Sep 17 00:00:00 2001 From: bendtherules Date: Sat, 3 Aug 2019 18:48:01 +0530 Subject: [PATCH] src/utils - Add helpers for detecting react functional and class components --- src/utils.ts | 69 ++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 59 insertions(+), 10 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index d03253e..b0cacee 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,20 +1,69 @@ -import * as React from 'react'; -import { FiberNode, FiberNodeisHTMLLike, FiberNodeForFunctionComponent, FiberNodeForComponentClass } from './mocked-types'; +import * as React from "react"; +import { + FiberNode, + FiberNodeisHTMLLike, + FiberNodeForFunctionComponent, + FiberNodeForComponentClass +} from "./mocked-types"; function isNodeHtmlLike(node: FiberNode): node is FiberNodeisHTMLLike { - return (typeof node.type === "string") || node.type === null; + return typeof node.type === "string" || node.type === null; } -function isNodeNotHtmlLike(node: FiberNode): node is Exclude { - return !isNodeHtmlLike(node); +function isNodeNotHtmlLike( + node: FiberNode +): node is Exclude { + return !isNodeHtmlLike(node); } -function isNodeFunctionComponent(node: FiberNode): node is FiberNodeForFunctionComponent { - return isNodeNotHtmlLike(node) && node.stateNode === null; +function isNodeFunctionComponent( + node: FiberNode +): node is FiberNodeForFunctionComponent { + return isNodeNotHtmlLike(node) && node.stateNode === null; } -function isNodeComponentClass(node: FiberNode): node is FiberNodeForComponentClass { - return isNodeNotHtmlLike(node) && (node.stateNode instanceof React.Component); +function isNodeComponentClass( + node: FiberNode +): node is FiberNodeForComponentClass { + return isNodeNotHtmlLike(node) && node.stateNode instanceof React.Component; } -export { isNodeHtmlLike, isNodeNotHtmlLike, isNodeFunctionComponent, isNodeComponentClass }; \ No newline at end of file +function isConstructorHtmlLike(ctr: React.ElementType): ctr is Exclude { + if (typeof ctr === "string" || ctr === null) { + return true; + } + return false; +} + +function isConstructorComponentClass( + ctr: React.ElementType +): ctr is React.ComponentClass { + if (isConstructorHtmlLike(ctr)) { + return false; + } + + if ( + ctr.prototype !== undefined && + (ctr.prototype as any) instanceof React.Component + ) { + return true; + } + + return false; +} + +function isConstructorFunctionComponent( + ctr: React.ElementType +): ctr is React.FunctionComponent { + return !isConstructorComponentClass(ctr); +} + +export { + isNodeHtmlLike, + isNodeNotHtmlLike, + isNodeFunctionComponent, + isNodeComponentClass, + isConstructorHtmlLike, + isConstructorComponentClass, + isConstructorFunctionComponent +};