Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/add imports crash #27

Merged
merged 10 commits into from
Nov 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions __tests__/require-usememo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,66 @@ describe('Rule - Require-usememo', () => {
return <Child component={component} />;
}`
},
{
code: `
import {} from 'react';
function useTesty() {
const user = {};
const x = {
renderCell: (user) => <RoleIndicator roles={['role']} user={user} />,
};
return useData(x);
}`,
output: `
import { useMemo } from 'react';
function useTesty() {
const user = {};
const x = {
renderCell: (user) => <RoleIndicator roles={useMemo(() => ['role'], [])} user={user} />,
};
return useData(x);
}`,
errors: [{ messageId: "object-usememo-deps" }, { messageId: "array-usememo-props" }, { messageId: "unknown-usememo-hook" }],
options: [{ strict: true,
checkHookReturnObject: true,
fix: { addImports: true },
checkHookCalls: true,
ignoredHookCallsNames: {},
}],
},
{
code: `import type { ComponentProps } from 'react';
import React from 'react';

const Component = () => {
const myArray = [];
return <Child prop={myArray} />;
}`,
output: `import type { ComponentProps } from 'react';
import React, { useMemo } from 'react';

const Component = () => {
const myArray = useMemo(() => [], []);
return <Child prop={myArray} />;
}`,
errors: [{ messageId: "array-usememo-props" }],
},
{
code: `import type { ComponentProps } from 'react';

const Component = () => {
const myArray = [];
return <Child prop={myArray} />;
}`,
output: `import { useMemo } from 'react';
import type { ComponentProps } from 'react';

const Component = () => {
const myArray = useMemo(() => [], []);
return <Child prop={myArray} />;
}`,
errors: [{ messageId: "array-usememo-props" }],
},
],
});
});
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@arthurgeron/eslint-plugin-react-usememo",
"version": "2.1.3",
"version": "2.1.4",
"description": "",
"main": "dist/index.js",
"author": "Stefano J. Attardi <[email protected]> & Arthur Geron <[email protected]",
Expand Down
2 changes: 1 addition & 1 deletion src/require-memo.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Rule } from "eslint";
import { isComponentName } from './common';
import { isComponentName } from './utils';
import * as ESTree from "estree";
import * as path from "path";

Expand Down
2 changes: 1 addition & 1 deletion src/require-usememo-children.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { TSESTree } from "@typescript-eslint/types";
import {
getExpressionMemoStatus,
isComplexComponent,
} from "./common";
} from "./utils";
import { MessagesRequireUseMemoChildren } from "./constants";
import { MemoStatus } from "src/types";

Expand Down
1 change: 1 addition & 0 deletions src/require-usememo/constants.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { MemoStatus } from 'src/types';
import type { ExpressionData, MemoErrorHookDictionary } from './types';

export const defaultImportRangeStart = `import { `;
export const nameGeneratorUUID = 'b32a4d70-4f64-11eb-89d5-33e6ce8a6c99';
export const jsxEmptyExpressionClassData: ExpressionData = {
[MemoStatus.UnmemoizedObject.toString()]: "object-class-memo-props",
Expand Down
4 changes: 2 additions & 2 deletions src/require-usememo/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { MessagesRequireUseMemo } from '../constants';
import {
getExpressionMemoStatus,
isComplexComponent,
} from "../common";
} from "../utils";
import type {ExpressionTypes, NodeType, ESNode, ExpressionData, ReactImportInformation, ImportNode} from './types';
import { checkForErrors, fixBasedOnMessageId, getIsHook, shouldIgnoreNode } from './utils';

Expand Down Expand Up @@ -79,7 +79,7 @@ const rule: Rule.RuleModule = {
},

ImportDeclaration(node) {
if (node.source.value === 'react') {
if (node.source.value === 'react' && (node as TSESTree.ImportDeclaration).importKind !== 'type') {
importData.reactImported = true;
importData.importDeclaration = node as TSESTree.ImportDeclaration;
const specifiers = node.specifiers;
Expand Down
41 changes: 29 additions & 12 deletions src/require-usememo/utils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Rule, SourceCode } from "eslint";
import { Rule } from "eslint";
import { TSESTree } from "@typescript-eslint/types";
import type * as ESTree from "estree";
import { MessagesRequireUseMemo } from '../constants';
import type { ESNode, ExpressionData, ReactImportInformation } from "./types";
import { MemoStatusToReport } from "src/types";
import { messageIdToHookDict, nameGeneratorUUID } from "./constants";
import { getVariableInScope } from "src/common";
import { messageIdToHookDict, nameGeneratorUUID, defaultImportRangeStart } from "./constants";
import getVariableInScope from "src/utils/getVariableInScope";
import { v5 as uuidV5 } from 'uuid';

export function shouldIgnoreNode(node: ESNode, ignoredNames: Record<string, boolean | undefined>) {
Expand All @@ -29,7 +29,6 @@ export function checkForErrors<T, Y extends Rule.NodeParentExtension | TSESTree.
}

function addReactImports(context: Rule.RuleContext, kind: 'useMemo' | 'useCallback', reactImportData: ReactImportInformation, fixer: Rule.RuleFixer) {
const sourceCode = context.getSourceCode();
const importsDisabled = context.options?.[0]?.fix?.addImports === false;
let specifier: TSESTree.ImportClause | undefined = undefined;

Expand All @@ -45,35 +44,53 @@ function addReactImports(context: Rule.RuleContext, kind: 'useMemo' | 'useCallba
local: { type: 'Identifier', name: kind }
} as TSESTree.ImportSpecifier;

if (reactImportData.importDeclaration) {
// Do not add specifier if exists.
if (reactImportData.importDeclaration?.specifiers) {
const specifiers = reactImportData.importDeclaration.specifiers;
if (!specifiers.find(x => x.local.name === kind)) {
const hasDefaultExport = specifiers?.[0]?.type === 'ImportDefaultSpecifier';
const isEmpty = !specifiers.length;
// Default export counts as a specifier too
const shouldCreateSpecifiersBracket = specifiers.length <= 1 && hasDefaultExport;
const hasCurrentSpecifier = !isEmpty && !shouldCreateSpecifiersBracket && specifiers.find(x => x.local.name === kind);

if (shouldCreateSpecifiersBracket) {
specifiers.push(specifier);
return fixer.insertTextAfter(specifiers[0], `, { ${kind} }`);
}

if (isEmpty) {
const importDeclaration = reactImportData.importDeclaration as TSESTree.ImportDeclaration;
const fixRange = importDeclaration.range[0] + defaultImportRangeStart.length - 1;

return fixer.insertTextAfterRange([fixRange, fixRange], ` ${kind} `);
}

if (!hasCurrentSpecifier) {
specifiers.push(specifier);
return fixer.insertTextAfter(specifiers[specifiers.length - 2], `, ${kind}`);
const insertPosition = specifiers[specifiers.length - 2];

return fixer.insertTextAfter(insertPosition, `, ${kind}`);
}
}
}

// If React is not imported, create a new ImportDeclaration for it.
if (!reactImportData.reactImported && !reactImportData.importDeclaration) {
const importBracket = `import { `;
reactImportData.importDeclaration = {
type: 'ImportDeclaration',
specifiers: [
{
...specifier,
range: [
importBracket.length,
importBracket.length + kind.length]
defaultImportRangeStart.length,
defaultImportRangeStart.length + kind.length]
}],
source: { type: 'Literal', value: 'react' }
} as TSESTree.ImportDeclaration;
reactImportData.reactImported = true;
reactImportData[`${kind}Imported`] = true;

// Add an extra new line before const component and use indentSpace for proper spacing.
return fixer.insertTextBeforeRange([0, 0], `${importBracket}${kind} } from 'react';\n`);
return fixer.insertTextBeforeRange([0, 0], `${defaultImportRangeStart}${kind} } from 'react';\n`);
}
return;
}
Expand Down
5 changes: 5 additions & 0 deletions src/utils/getVariableInScope.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Rule } from "eslint";

export default function getVariableInScope(context: Rule.RuleContext, name: string) {
return context.getScope().variables.find((variable) => variable.name === name);
}
6 changes: 2 additions & 4 deletions src/common.ts → src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Rule } from "eslint";
import { TSESTree } from "@typescript-eslint/types";
import { ESNode } from "src/require-usememo/types";
import { MemoStatus, MemoStatusToReport } from "src/types";
import { getIsHook } from "src/require-usememo/utils";
import getVariableInScope from "src/utils/getVariableInScope";

const componentNameRegex = /^[^a-z]/;

Expand Down Expand Up @@ -41,9 +41,7 @@ function isCallExpression(
return false;
}

export function getVariableInScope(context: Rule.RuleContext, name: string) {
return context.getScope().variables.find((variable) => variable.name === name);
}


function getIdentifierMemoStatus(
context: Rule.RuleContext,
Expand Down