/* eslint-disable perfectionist/sort-interfaces */ /* eslint-disable perfectionist/sort-objects */ import { Check, Extract, type TSESTreeDirective, type TSESTreeFunction, Traverse } from "@eslint-react/ast"; import type { RuleContext } from "@eslint-react/eslint"; import { isCreateElementChildrenArgument } from "@eslint-react/jsx"; import { RE_COMPONENT_NAME, RE_COMPONENT_NAME_LOOSE } from "@eslint-react/shared"; import { AST_NODE_TYPES as AST, type TSESTree } from "@typescript-eslint/types"; import { isCreateElementCall, isForwardRefCall, isMemoCall } from "./api"; import { isRenderMethodCallback } from "./class-component"; import { type FunctionID, type FunctionInitPath, getFunctionId, isFunctionHasCallInInitPath } from "./function"; import type { HookCall } from "./hook"; import { JSXDetectionHint } from "./jsx"; import type { SemanticNode } from "./semantic"; // #region Types /** * Represents a React Function Component. */ export interface FunctionComponentSemanticNode extends SemanticNode { /** The identifier or identifier sequence of the component. */ id: FunctionID; /** The kind of component. */ kind: "component"; /** The AST node of the function. */ node: TSESTreeFunction; /** Flags describing the component's characteristics. */ flag: bigint; /** Detection hints configured by the caller when collecting this component; identical for every component collected under the same settings. */ hint: bigint; /** List of expressions returned by the component. */ rets: TSESTree.ReturnStatement["argument"][]; /** The initialization path of the function. */ initPath: | null | FunctionInitPath; /** Indicates if the component is inside an export default declaration. */ isExportDefault: boolean; /** Indicates if the component is itself an export default declaration. */ isExportDefaultDeclaration: boolean; /** List of hook calls within the component. */ hookCalls: HookCall[]; /** The display name of the component. */ displayName: | null | TSESTree.Expression; /** The directives used in the function (ex: "use strict", "use client", etc.). */ directives: TSESTreeDirective[]; } // #endregion // #region Component Flags /** * Component flag constants. */ export const FunctionComponentFlag = { /** No flags set. */ None: 0n, /** * Indicates the component is a pure component. * @deprecated This flag is never set; purity of class components (`extends PureComponent`) is not tracked here. */ PureComponent: 1n << 0n, /** * Indicates the component creates elements using `createElement` instead of JSX. * @deprecated This flag is never set; createElement usage is not tracked here. */ CreateElement: 1n << 1n, /** Indicates the component is memoized (ex: React.memo). */ Memo: 1n << 2n, /** Indicates the component forwards a ref (ex: React.forwardRef). */ ForwardRef: 1n << 3n, }; /** * Get component flag from init path. * @param initPath The init path of the function component. * @returns The component flag. * @internal */ export function getFunctionComponentFlagFromInitPath(initPath: FunctionComponentSemanticNode["initPath"]) { let flag = FunctionComponentFlag.None; if (initPath != null && isFunctionHasCallInInitPath("memo", initPath)) flag |= FunctionComponentFlag.Memo; if (initPath != null && isFunctionHasCallInInitPath("forwardRef", initPath)) flag |= FunctionComponentFlag.ForwardRef; return flag; } // #endregion // #region Component Wrapper Detection /** * Check if the node is a call expression for a component wrapper. * @param context The ESLint rule context. * @param node The node to check. * @returns `true` if the node is a call expression for a component wrapper. */ export function isFunctionComponentWrapperCall(context: RuleContext, node: TSESTree.CallExpression) { return isMemoCall(context, node) || isForwardRefCall(context, node); } /** * Check if the node is a callback function passed to a component wrapper. * @param context The ESLint rule context. * @param node The node to check. * @returns `true` if the node is a callback function passed to a component wrapper. */ export function isFunctionComponentWrapperCallback(context: RuleContext, node: TSESTreeFunction) { let argument: TSESTree.Node = node; let parent = node.parent; while (Check.isTypeExpression(parent)) { argument = parent; parent = parent.parent; } if (parent.type !== AST.CallExpression) return false; // Only the first argument is the render callback: memo(Component, propsAreEqual?), forwardRef(render). if (parent.arguments[0] !== argument) return false; return isFunctionComponentWrapperCall(context, parent); } // #endregion // #region Component ID (internal) /** * Get function component identifier from `const Component = memo(() => {});`. * Only the first argument of a component wrapper is treated as the wrapped * component; later arguments (ex: memo's propsAreEqual comparator) do not * inherit the surrounding binding. * @param context The rule context. * @param node The AST node to get the function component identifier from. * @internal */ export function getFunctionComponentId(context: RuleContext, node: TSESTreeFunction): FunctionID { const functionId = getFunctionId(node); if (functionId != null) return functionId; let parent: TSESTree.Node = node.parent; let child: TSESTree.Node = node; while (Check.isTypeExpression(parent)) { child = parent; parent = parent.parent; } switch (true) { case parent.type === AST.CallExpression && parent.arguments[0] === child && isFunctionComponentWrapperCall(context, parent) && parent.parent.type === AST.VariableDeclarator: return parent.parent.id; case parent.type === AST.CallExpression && parent.arguments[0] === child && isFunctionComponentWrapperCall(context, parent) && parent.parent.type === AST.CallExpression && parent.parent.arguments[0] === parent && isFunctionComponentWrapperCall(context, parent.parent) && parent.parent.parent.type === AST.VariableDeclarator: return parent.parent.parent.id; default: return null; } } // #endregion // #region Component Name /** * Check if a string matches the strict component name pattern. * @param name The name to check. * @returns `true` if the name matches the strict component name pattern. */ export function isFunctionComponentName(name: string) { return RE_COMPONENT_NAME.test(name); } /** * Check if a string matches the loose component name pattern. * @param name The name to check. * @returns `true` if the name matches the loose component name pattern. */ export function isFunctionComponentNameLoose(name: string) { return RE_COMPONENT_NAME_LOOSE.test(name); } /** * Check if a function has a loose component name. * @param context The rule context. * @param fn The function to check. * @param allowNone Whether to allow no name. * @returns `true` if the function has a loose component name. */ export function isFunctionWithLooseComponentName(context: RuleContext, fn: TSESTreeFunction, allowNone = false) { const id = getFunctionComponentId(context, fn); if (id == null) return allowNone; if (Check.isIdentifier(id)) { return isFunctionComponentNameLoose(id.name); } if (id.type === AST.MemberExpression && Check.isIdentifier(id.property)) { return isFunctionComponentNameLoose(id.property.name); } return false; } // #endregion // #region Component Detection /** The bit-flags for customizing function component detection. */ export type FunctionComponentDetectionHint = bigint; /** * Hints for component collector. */ export const FunctionComponentDetectionHint = { ...JSXDetectionHint, /** Exclude functions defined as class methods from component detection. */ DoNotIncludeFunctionDefinedAsClassMethod: 1n << 11n, /** Exclude functions defined as class properties from component detection. */ DoNotIncludeFunctionDefinedAsClassProperty: 1n << 12n, /** Exclude functions defined as object methods from component detection. */ DoNotIncludeFunctionDefinedAsObjectMethod: 1n << 13n, /** Exclude functions defined as array expression elements from component detection. */ DoNotIncludeFunctionDefinedAsArrayExpressionElement: 1n << 14n, /** * Exclude functions defined as array pattern elements or as their default values from * component detection (ex: `const [Nav = () => {}] = arr`). */ DoNotIncludeFunctionDefinedAsArrayPatternElement: 1n << 15n, /** Exclude functions defined as array flatMap callbacks (named or anonymous) from component detection. */ DoNotIncludeFunctionDefinedAsArrayFlatMapCallback: 1n << 16n, /** Exclude functions defined as array map callbacks (named or anonymous) from component detection. */ DoNotIncludeFunctionDefinedAsArrayMapCallback: 1n << 17n, /** Exclude anonymous functions defined as arbitrary call expression callbacks from component detection. */ DoNotIncludeFunctionDefinedAsArbitraryCallExpressionCallback: 1n << 18n, } as const; /** * Default component detection hint. */ export const DEFAULT_COMPONENT_DETECTION_HINT = 0n | FunctionComponentDetectionHint.DoNotIncludeJSXWithBigIntValue | FunctionComponentDetectionHint.DoNotIncludeJSXWithBooleanValue | FunctionComponentDetectionHint.DoNotIncludeJSXWithNumberValue | FunctionComponentDetectionHint.DoNotIncludeJSXWithStringValue | FunctionComponentDetectionHint.DoNotIncludeJSXWithUndefinedValue | FunctionComponentDetectionHint.DoNotIncludeFunctionDefinedAsArbitraryCallExpressionCallback | FunctionComponentDetectionHint.DoNotIncludeFunctionDefinedAsArrayExpressionElement | FunctionComponentDetectionHint.DoNotIncludeFunctionDefinedAsArrayFlatMapCallback | FunctionComponentDetectionHint.DoNotIncludeFunctionDefinedAsArrayMapCallback | FunctionComponentDetectionHint.DoNotIncludeFunctionDefinedAsArrayPatternElement | FunctionComponentDetectionHint.RequireAllArrayElementsToBeJSX | FunctionComponentDetectionHint.RequireBothBranchesOfConditionalExpressionToBeJSX | FunctionComponentDetectionHint.RequireBothSidesOfLogicalExpressionToBeJSX; /** * Check if the function node is a valid React component definition. * * @param context The rule context. * @param node The function node to analyze. * @param hint Component detection hints (bit flags) to customize detection logic. * @returns `true` if the node is considered a component definition. */ export function isFunctionComponentDefinition(context: RuleContext, node: TSESTreeFunction, hint: bigint) { // 1. Check for basic naming conventions if (!isFunctionWithLooseComponentName(context, node, true)) return false; // 2. Traverse up to find the non-type expression parent let parent = node.parent; while (Check.isTypeExpression(parent)) parent = parent.parent; // 3. Check immediate contextual exclusions if (isRenderMethodCallback(node)) return false; if (isCreateElementChildrenArgument(context, node)) return false; // A function in a non-first argument position of a component wrapper is a // configuration callback (ex: memo's propsAreEqual), never the wrapped // component. This is structural, so it applies regardless of detection hints. if (Check.isCallExpression(parent) && isFunctionComponentWrapperCall(context, parent) && !isFunctionComponentWrapperCallback(context, node)) { return false; } // 4. Apply contextual exclusions via hints const [parentCallee, parentCalleeName] = parent.type === AST.CallExpression ? [Extract.unwrap(parent.callee), Extract.getCalleeName(parent)] : [null, null]; switch (true) { case Check.isOneOf([AST.ArrowFunctionExpression, AST.FunctionExpression])(node) && parent.type === AST.Property && parent.parent.type === AST.ObjectExpression: if (hint & FunctionComponentDetectionHint.DoNotIncludeFunctionDefinedAsObjectMethod) return false; break; case Check.isOneOf([AST.ArrowFunctionExpression, AST.FunctionExpression])(node) && parent.type === AST.MethodDefinition: if (hint & FunctionComponentDetectionHint.DoNotIncludeFunctionDefinedAsClassMethod) return false; break; case Check.isOneOf([AST.ArrowFunctionExpression, AST.FunctionExpression])(node) && parent.type === AST.PropertyDefinition: if (hint & FunctionComponentDetectionHint.DoNotIncludeFunctionDefinedAsClassProperty) return false; break; // Functions can appear in an array pattern as an element default, which puts // them under an `AssignmentPattern` (ex: `const [Nav = () => {}] = arr`), or // as a direct element in parser-accepted-but-invalid destructuring // assignments (ex: `[() => {}] = arr`), so cover both shapes. case parent.type === AST.ArrayPattern || Check.isArrayPatternElementDefault(parent): if (hint & FunctionComponentDetectionHint.DoNotIncludeFunctionDefinedAsArrayPatternElement) return false; break; case parent.type === AST.ArrayExpression: if (hint & FunctionComponentDetectionHint.DoNotIncludeFunctionDefinedAsArrayExpressionElement) return false; break; case parentCallee != null && parentCallee.type === AST.MemberExpression && parentCalleeName === "map": // Unlike the arbitrary-call case below, map callbacks are excluded even when named: // `items.map(function Item() { ... })` is the common render-list pattern, and downstream // rules (e.g. no-nested-component-definitions) rely on this hint to allow it. if (hint & FunctionComponentDetectionHint.DoNotIncludeFunctionDefinedAsArrayMapCallback) return false; break; case parentCallee != null && parentCallee.type === AST.MemberExpression && parentCalleeName === "flatMap": if (hint & FunctionComponentDetectionHint.DoNotIncludeFunctionDefinedAsArrayFlatMapCallback) return false; break; case parent.type === AST.CallExpression && getFunctionId(node) == null && !isFunctionComponentWrapperCall(context, parent) && !isCreateElementCall(context, parent): if (hint & FunctionComponentDetectionHint.DoNotIncludeFunctionDefinedAsArbitraryCallExpressionCallback) return false; break; } // 5. Exclude inline JSX callbacks (event handlers, render props) // Ordered by observed nearest-ancestor frequency (most frequent first). const significantParent = Traverse.findParent( node, Check.isOneOf([ AST.ArrowFunctionExpression, AST.Property, AST.FunctionExpression, AST.ClassBody, AST.JSXExpressionContainer, ]), ); if (significantParent == null) return true; return significantParent.type !== AST.JSXExpressionContainer; } // #endregion