UNPKG

eslint-plugin-react-component-name

Version:

Eslint plugin for converting decorated anonymous functions to named functions.

77 lines (76 loc) 2.54 kB
const handler = (context, target) => (node) => { var _a, _b, _c; let parent = (_a = node.parent) == null ? void 0 : _a.parent; while (parent && parent.type !== "VariableDeclarator") { parent = parent.parent; } const parentVarName = (_b = parent == null ? void 0 : parent.id) == null ? void 0 : _b.name; const functionName = (_c = node.id) == null ? void 0 : _c.name; if (parentVarName ? functionName !== parentVarName : !functionName) { context.report({ node, messageId: "noAnonymousFunction", fix: parentVarName && ((fixer) => { const sourceCode = context.getSourceCode(); const newName = parentVarName; const params = node.params.map((param) => sourceCode.getText(param)).join(", "); if (node.type === "ArrowFunctionExpression") { const arrowBody = sourceCode.getText(node.body); const needsBrackets = node.body.type !== "BlockStatement"; const newBody = needsBrackets ? `{ return ${arrowBody}; }` : arrowBody; return fixer.replaceText( node, `function ${newName}(${params}) ${newBody}` ); } const functionBody = sourceCode.getText(node.body); return fixer.replaceText( node, `function ${newName}(${params}) ${functionBody}` ); }) }); } }; const create = (context) => { const options = context.options[0]; const targets = (options == null ? void 0 : options.targets) || ["memo", "forwardRef"]; const rules = {}; for (const target of targets) { const selector = `CallExpression[callee.name="${target}"] > :function, CallExpression[callee.object.name="React"][callee.property.name="${target}"] > :function`; rules[selector] = handler(context); } return rules; }; const rule = { create, meta: { type: "problem", docs: { description: "Ensure named functions are used with specific React helpers", category: "Best Practices", recommended: true }, messages: { noAnonymousFunction: "Function should have a name matching its parent variable." }, fixable: "code", schema: [ { type: "object", properties: { targets: { type: "array", items: { type: "string" }, description: "List of a component decorators to enforce named functions." } }, additionalProperties: false } ] } }; export { rule as default }; //# sourceMappingURL=react-component-name.mjs.map