-
-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathfunctionComponentDefinition.ts
More file actions
59 lines (52 loc) · 2.45 KB
/
Copy pathfunctionComponentDefinition.ts
File metadata and controls
59 lines (52 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import type { RuleFunction } from "@eslint-react/kit";
import { merge } from "@eslint-react/kit";
/** Enforce arrow function definitions for function components. */
export function functionComponentDefinition(): RuleFunction {
return (context, { collect, hint }) => {
const { query, visitor } = collect.components(context, {
hint: hint.component.Default & ~hint.component.DoNotIncludeFunctionDefinedAsObjectMethod,
});
return merge(
visitor,
{
"Program:exit"(program) {
for (const { node } of query.all(program)) {
// Guard: must not already be arrow function
if (node.type === "ArrowFunctionExpression") continue;
context.report({
node,
message: "Function components must be defined with arrow functions.",
suggest: [
{
desc: "Convert to arrow function.",
fix(fixer) {
const src = context.sourceCode;
if (node.generator) return null;
const prefix = node.async ? "async " : "";
const typeParams = node.typeParameters != null ? src.getText(node.typeParameters) : "";
const params = `(${node.params.map((p) => src.getText(p)).join(", ")})`;
const returnType = node.returnType != null ? src.getText(node.returnType) : "";
const body = src.getText(node.body);
if (node.type === "FunctionDeclaration" && node.id != null) {
// dprint-ignore
return fixer.replaceText(node, `const ${node.id.name} = ${prefix}${typeParams}${params}${returnType} => ${body};`);
}
if (node.type === "FunctionExpression" && node.parent.type === "VariableDeclarator") {
// dprint-ignore
return fixer.replaceText(node, `${prefix}${typeParams}${params}${returnType} => ${body}`);
}
if (node.type === "FunctionExpression" && node.parent.type === "Property") {
// dprint-ignore
return fixer.replaceText(node.parent, `${src.getText(node.parent.key)}: ${prefix}${typeParams}${params}${returnType} => ${body}`);
}
return null;
},
},
],
});
}
},
},
);
};
}