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

feat(Dropdown deprecated): added rule to replace with MenuToggle #702

Merged
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
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ An eslint plugin (with an extra CLI utility) to help ease products transitioning
- You can also replace `v5` with another version directory within the repo
1. Run `yarn test:v5:single` to run the `pf-codemods` command against the `test.tsx` file and to check what error/warning messages a consumer would see when running our codemods
- You can also run `yarn test:v5:single --fix` to see what the `test.tsx` file looks like after fixes are applied, allowing you to check whether fixes are applied as expected. Make sure to not save the `test.tsx` file after applying fixes.
1. If the rule you're adding should have a severity of `warning` rather than `error`, add the rule name to the `warningRules` array in `eslint-plugin-pf-codemods/index.js`.
1. If the rule you're adding has not yet been merged into pf-react, add the rule name to the `betaRuleNames` array in `eslint-plugin-pf-codemods/index.js`.
1. If the rule you're adding should have a severity of `warning` rather than `error`, add the rule name to the `warningRules` array in `eslint-plugin-pf-codemods/src/ruleCustomization.js`.
1. If the rule you're adding is intended for a consumer to explicitly run manually, add the rule name to the `betaRuleNames` array in `eslint-plugin-pf-codemods/src/ruleCustomization.js`.

## Troubleshooting

Expand Down
12 changes: 5 additions & 7 deletions packages/eslint-plugin-pf-codemods/src/ruleCustomization.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
// if you want your rule to only run when explicitly called for using the --only flag, add the rule name to the below array
export const betaRuleNames: string[] = [
"checkbox-radio-replace-isLabelBeforeButton",
"formGroup-rename-labelIcon",
"menuItemAction-warn-update-markup",
"menuToggle-warn-iconOnly-toggle",
];
/** if you want your rule to only run when explicitly called for using the --only flag,
* add the rule name to the below array. Do not add rules here if the React PR is
* not yet merged; instead add a "do not merge" label to the codemod PR.
*/
export const betaRuleNames: string[] = ["kebabToggle-replace-with-menuToggle"];

// if you want a rule to have a severity that defaults to warning rather than error, add the rule name to the below array
export const warningRules = [
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Node } from "estree-jsx";
import { AST, Rule } from "eslint";

export function replaceNodeText(
context: Rule.RuleContext,
node: Node,
nodeToReplace: Node | AST.Token,
message: string,
replacement: string
) {
return context.report({
node,
message,
fix(fixer) {
return fixer.replaceText(nodeToReplace, replacement);
},
});
}
50 changes: 50 additions & 0 deletions packages/eslint-plugin-pf-codemods/src/rules/helpers/fixers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { Rule } from "eslint";
import {
JSXElement,
ImportDeclaration,
ExportNamedDeclaration,
ImportSpecifier,
ExportSpecifier,
ImportDefaultSpecifier,
ImportNamespaceSpecifier,
} from "estree-jsx";
import { getEndRange } from "./getEndRange";
import { removeElement, removeEmptyLineAfter } from "./index";

export function removeSpecifierFromDeclaration(
fixer: Rule.RuleFixer,
context: Rule.RuleContext,
node: ImportDeclaration | ExportNamedDeclaration,
specifierToRemove:
| ImportSpecifier
| ImportDefaultSpecifier
| ImportNamespaceSpecifier
| ExportSpecifier
) {
if (node.specifiers.length === 1) {
return [fixer.remove(node)];
}
if (!specifierToRemove.range) {
return [];
}

const startRange = specifierToRemove.range[0];
const endRange = getEndRange(context.getSourceCode(), specifierToRemove);
if (!startRange || !endRange) {
return [];
}
return [fixer.removeRange([startRange, endRange])];
}

export const getRemoveElementFixes = (
context: Rule.RuleContext,
fixer: Rule.RuleFixer,
elementsToRemove: JSXElement[]
) => {
return elementsToRemove
.map((element) => [
...removeElement(fixer, element),
...removeEmptyLineAfter(context, fixer, element),
])
.flat();
};
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@ import {
ImportSpecifier,
ImportDefaultSpecifier,
ImportNamespaceSpecifier,
ExportSpecifier,
} from "estree-jsx";

export const getEndRange = (
sourceCode: SourceCode,
specifier: ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier
specifier:
| ImportSpecifier
| ImportDefaultSpecifier
| ImportNamespaceSpecifier
| ExportSpecifier
) => {
const tokenAfter = sourceCode.getTokenAfter(specifier);
const commentsAfter = sourceCode.getCommentsAfter(specifier);
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Rule } from "eslint";
import {
ImportDeclaration,
ExportNamedDeclaration,
Directive,
Statement,
ModuleDeclaration,
} from "estree-jsx";

function filterByDeclarationType(
astBody: (Directive | Statement | ModuleDeclaration)[],
nodeType: "ImportDeclaration" | "ExportNamedDeclaration",
packageName?: string | RegExp
) {
return astBody.filter(
(node) =>
node.type === nodeType &&
(packageName ? node.source?.value === packageName : true)
);
}

export function getAllImportDeclarations(
context: Rule.RuleContext,
packageName?: string
) {
const astBody = context.getSourceCode().ast.body;

const importDeclarationsFromPackage = filterByDeclarationType(
astBody,
"ImportDeclaration",
packageName
) as ImportDeclaration[];

return importDeclarationsFromPackage;
}
12 changes: 7 additions & 5 deletions packages/eslint-plugin-pf-codemods/src/rules/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
export * from "./contextReports";
export * from "./findAncestor";
export * from "./helpers";
export * from "./fixers";
export * from "./getEndRange";
export * from "./getFromPackage";
export * from "./getText";
export * from "./helpers";
export * from "./importAndExport";
export * from "./includesImport";
export * from "./interfaces";
export * from "./JSXAttributes";
export * from "./JSXElements";
export * from "./pfPackageMatches";
export * from "./renameProps";
export * from "./getImportDeclaration";
export * from "./getEndRange";
export * from "./getRemoveElementFixes";
export * from "./removeElement";
export * from "./removeEmptyLineAfter";
export * from "./renameProps";
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Node, Identifier } from "estree-jsx";

export interface IdentifierWithParent extends Identifier {
parent?: Node;
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import {
getAllJSXElements,
getAttribute,
getFromPackage,
getImportDeclarations,
} from '../../helpers';
getAllImportDeclarations,
} from "../../helpers";
import {
ImportDeclaration,
ImportSpecifier,
Expand All @@ -14,8 +14,8 @@ import {
Literal,
Node,
JSXIdentifier,
} from 'estree-jsx';
import { Rule } from 'eslint';
} from "estree-jsx";
import { Rule } from "eslint";

type JSXAttributeValue =
| Literal
Expand All @@ -26,11 +26,11 @@ type JSXAttributeValue =
const parseBadgeAttributeValue = (
badgeAttributeValue: JSXAttributeValue
): Node => {
if (badgeAttributeValue.type !== 'JSXExpressionContainer') {
if (badgeAttributeValue.type !== "JSXExpressionContainer") {
return badgeAttributeValue;
}

const isValueJSX = ['JSXElement', 'JSXEmptyExpression'].includes(
const isValueJSX = ["JSXElement", "JSXEmptyExpression"].includes(
badgeAttributeValue.expression.type
);

Expand All @@ -42,13 +42,13 @@ const moveBadgeAttributeToBody = (
fixer: Rule.RuleFixer,
context: Rule.RuleContext
) => {
const badgeAttribute = getAttribute(node, 'badge');
const badgeAttribute = getAttribute(node, "badge");

const textToInsert = badgeAttribute?.value
? ` ${context
.getSourceCode()
.getText(parseBadgeAttributeValue(badgeAttribute.value))}`
: '';
: "";

return badgeAttribute
? [
Expand All @@ -62,10 +62,10 @@ const moveBadgeAttributeToBody = (
};

const renameOnClickAttribute = (node: JSXElement, fixer: Rule.RuleFixer) => {
const onClickAttribute = getAttribute(node, 'onClick');
const onClickAttribute = getAttribute(node, "onClick");

return onClickAttribute
? [fixer.replaceText(onClickAttribute.name, 'onClose')]
? [fixer.replaceText(onClickAttribute.name, "onClose")]
: [];
};

Expand All @@ -77,35 +77,35 @@ const removeIsReadOnlyProp = (node: JSXElement, fixer: Rule.RuleFixer) => {

// https://github.com/patternfly/patternfly-react/pull/10049
module.exports = {
meta: { fixable: 'code' },
meta: { fixable: "code" },
create: function (context: Rule.RuleContext) {
const { imports } = getFromPackage(context, '@patternfly/react-core');
const { imports } = getFromPackage(context, "@patternfly/react-core");

const labelImport = imports.find(
(specifier) => specifier.imported.name === 'Label'
(specifier) => specifier.imported.name === "Label"
);

const labelGroupImport = imports.find(
(specifier) => specifier.imported.name === 'LabelGroup'
(specifier) => specifier.imported.name === "LabelGroup"
);

const { imports: importsFromDeprecated } = getFromPackage(
context,
'@patternfly/react-core/deprecated'
"@patternfly/react-core/deprecated"
);

const chipImport = importsFromDeprecated.find(
(specifier) => specifier.imported.name === 'Chip'
(specifier) => specifier.imported.name === "Chip"
);

const chipGroupImport = importsFromDeprecated.find(
(specifier) => specifier.imported.name === 'ChipGroup'
(specifier) => specifier.imported.name === "ChipGroup"
);

const isImportDeclarationWithChipOrChipGroup = (node: ImportDeclaration) =>
node.source.value === '@patternfly/react-core/deprecated' &&
node.source.value === "@patternfly/react-core/deprecated" &&
node.specifiers.every(
(specifier) => specifier.type === 'ImportSpecifier'
(specifier) => specifier.type === "ImportSpecifier"
) &&
((chipImport && node.specifiers.includes(chipImport)) ||
(chipGroupImport && node.specifiers.includes(chipGroupImport)));
Expand All @@ -124,7 +124,7 @@ module.exports = {
const importIncludesOnlyChipAndChipGroup = (
node.specifiers as ImportSpecifier[]
).every((specifier) =>
['Chip', 'ChipGroup'].includes(specifier.imported.name)
["Chip", "ChipGroup"].includes(specifier.imported.name)
);

if (importIncludesOnlyChipAndChipGroup) {
Expand All @@ -138,7 +138,7 @@ module.exports = {
const tokenAfter = context
.getSourceCode()
.getTokenAfter(specifier);
if (tokenAfter?.value === ',') {
if (tokenAfter?.value === ",") {
fixes.push(fixer.remove(tokenAfter));
}
}
Expand All @@ -148,17 +148,17 @@ module.exports = {

const addLabelAndLabelGroupImports = (fixer: Rule.RuleFixer) => {
if (!labelImport && !labelGroupImport) {
const pfImportDeclarations = getImportDeclarations(
const pfImportDeclarations = getAllImportDeclarations(
context,
'@patternfly/react-core'
"@patternfly/react-core"
);

const labelImportsToAdd = [chipImport, chipGroupImport]
.map((specifier, index) =>
specifier ? ['Label', 'LabelGroup'][index] : null
specifier ? ["Label", "LabelGroup"][index] : null
)
.filter((value) => value !== null)
.join(', ');
.join(", ");

if (pfImportDeclarations.length) {
// add label specifiers at the beginning of first import declaration
Expand All @@ -180,20 +180,20 @@ module.exports = {
}

if (chipImport && !labelImport) {
return [fixer.insertTextAfter(labelGroupImport!, ', Label')];
return [fixer.insertTextAfter(labelGroupImport!, ", Label")];
}
if (chipGroupImport && !labelGroupImport) {
return [fixer.insertTextAfter(labelImport!, ', LabelGroup')];
return [fixer.insertTextAfter(labelImport!, ", LabelGroup")];
}
return [];
};

const handleJSXElements = (fixer: Rule.RuleFixer) => {
const elements: JSXElement[] = getAllJSXElements(context);

const labelName = labelImport?.local.name ?? 'Label';
const labelName = labelImport?.local.name ?? "Label";
const labelGroupName =
labelGroupImport?.local.name ?? 'LabelGroup';
labelGroupImport?.local.name ?? "LabelGroup";

const getChipFixes = (
node: JSXElement,
Expand Down Expand Up @@ -233,7 +233,7 @@ module.exports = {

for (const node of elements) {
if (
node.openingElement.name.type !== 'JSXIdentifier' ||
node.openingElement.name.type !== "JSXIdentifier" ||
![
chipImport?.local.name,
chipGroupImport?.local.name,
Expand Down
Loading
Loading