Skip to content

Commit

Permalink
feat(helpers): makeJSXElementSelfClosing helper
Browse files Browse the repository at this point in the history
  • Loading branch information
adamviktora committed Aug 12, 2024
1 parent b6c3d2e commit 49506de
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export * from "./includesImport";
export * from "./interfaces";
export * from "./JSXAttributes";
export * from "./JSXElements";
export * from "./makeJSXElementSelfClosing";
export * from "./nodeMatches";
export * from "./pfPackageMatches";
export * from "./removeElement";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Rule } from "eslint";
import { JSXElement, JSXText } from "estree-jsx";

/** Transforms JSXElement to a self-closing tag.
* Works only on elements without children by default, but you can overwrite this behaviour with the removeChildren parameter.
*/
export function makeJSXElementSelfClosing(
node: JSXElement,
context: Rule.RuleContext,
fixer: Rule.RuleFixer,
removeChildren: boolean = false
): Rule.Fix[] {
if (!node.closingElement) {
return [];
}

const fixes = [];

const childrenIsEmptyString =
node.children &&
node.children.length === 1 &&
node.children[0].type === "JSXText" &&
node.children[0].value.trim() === "";

if (removeChildren || !node.children || childrenIsEmptyString) {
const closingSymbol = context
.getSourceCode()
.getLastToken(node.openingElement)!;

fixes.push(
fixer.replaceText(closingSymbol, " />"),
fixer.remove(node.closingElement)
);

if (removeChildren && node.children) {
fixes.push(
fixer.removeRange([
node.children[0].range![0],
node.children[node.children.length - 1].range![1],
])
);
} else if (childrenIsEmptyString) {
fixes.push(fixer.remove(node.children[0] as JSXText));
}
}

return fixes;
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
getAttributeValue,
getExpression,
getChildrenAsAttributeValueText,
makeJSXElementSelfClosing,
} from "../../helpers";

// https://github.com/patternfly/patternfly-react/pull/10663
Expand Down Expand Up @@ -80,24 +81,11 @@ module.exports = {

if (childrenProp) {
fixes.push(fixer.remove(childrenProp));
} else {
node.children.forEach(
(child) =>
child.type !== "JSXSpreadChild" &&
fixes.push(fixer.replaceText(child, ""))
);
}

if (node.closingElement) {
const closingSymbol = context
.getSourceCode()
.getLastToken(node.openingElement)!;

fixes.push(
fixer.replaceText(closingSymbol, " />"),
fixer.remove(node.closingElement)
);
}
fixes.push(
...makeJSXElementSelfClosing(node, context, fixer, true)
);

return fixes;
},
Expand Down

0 comments on commit 49506de

Please sign in to comment.