Skip to content

Commit

Permalink
Simplify logic for safeToFix
Browse files Browse the repository at this point in the history
  • Loading branch information
golopot committed Jul 13, 2019
1 parent 75e9990 commit 76f65f7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
24 changes: 18 additions & 6 deletions lib/rules/jsx-no-useless-fragment.js
Expand Up @@ -12,6 +12,13 @@ function isJSXText(node) {
return !!node && (node.type === 'JSXText' || node.type === 'Literal');
}

/**
* @param {string} text
*/
function isOnlyWhitespace(text) {
return text.trim().length === 0;
}

/**
* Test if node is like `<Fragment key={_}>_</Fragment>`
* @param {JSXElement} node
Expand Down Expand Up @@ -55,7 +62,7 @@ module.exports = {
*/
function isPaddingSpaces(node) {
return isJSXText(node) &&
/^\s*$/.test(node.raw) &&
isOnlyWhitespace(node.raw) &&
node.raw.includes('\n');
}

Expand Down Expand Up @@ -86,14 +93,15 @@ module.exports = {
}

/**
* Avoid fixing case like:
* Avoid fixing cases that involve tricky whitespaces changes like:
* ```jsx
* <div>
* pine<>
* apple
* </>
* </div>
* ```
* Give up fixing if one neighboring node is JSXText and is not only whitespaces
* @param {JSXElement|JSXFragment} node
* @returns {boolean}
*/
Expand All @@ -106,10 +114,14 @@ module.exports = {
const previousChild = node.parent.children[i - 1];
const nextChild = node.parent.children[i + 1];

return (
(!isJSXText(previousChild) || /\s$/.test(previousChild.value)) &&
(!isJSXText(nextChild) || /^\s/.test(nextChild.value))
);
if (
(isJSXText(previousChild) && !isOnlyWhitespace(previousChild.value)) ||
(isJSXText(nextChild) && !isOnlyWhitespace(nextChild.value))
) {
return false;
}

return true;
}

function fix(node, fixer) {
Expand Down
2 changes: 1 addition & 1 deletion tests/lib/rules/jsx-no-useless-fragment.js
Expand Up @@ -164,7 +164,7 @@ ruleTester.run('jsx-no-uselses-fragment', rule, {
},
{
code: '<div>a <>{""}{""}</> a</div>',
output: '<div>a {""}{""} a</div>',
output: null,
errors: [{messageId: 'ChildOfHtmlElement'}],
parser: parsers.BABEL_ESLINT
}
Expand Down

0 comments on commit 76f65f7

Please sign in to comment.