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
[New] add rule to enforce fragment syntax #1994
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
# Enforce shorthand or standard form for React fragments (react/jsx-fragments) | ||
|
||
In JSX, a React fragment is created either with `<React.Fragment>...</React.Fragment>`, or, using the shorthand syntax, `<>...</>`. This rule allows you to enforce one way or the other. | ||
|
||
Support for fragments was added in React v16.2, so the rule will warn on either of these forms if an older React version is specified in [shared settings][shared_settings]. | ||
|
||
## Rule Options | ||
|
||
```js | ||
... | ||
"react/jsx-fragments": [<enabled>, <mode>] | ||
... | ||
``` | ||
|
||
### `syntax` mode | ||
|
||
This is the default mode. It will enforce the shorthand syntax for React fragments, with one exception. [Keys or attributes are not supported by the shorthand syntax][short_syntax], so the rule will not warn on standard-form fragments that use those. | ||
|
||
The following pattern is considered a warning: | ||
|
||
```jsx | ||
<React.Fragment><Foo /></React.Fragment> | ||
``` | ||
|
||
The following patterns are **not** considered warnings: | ||
|
||
```jsx | ||
<><Foo /></> | ||
``` | ||
|
||
```jsx | ||
<React.Fragment key="key"><Foo /></React.Fragment> | ||
``` | ||
|
||
### `element` mode | ||
|
||
This mode enforces the standard form for React fragments. | ||
|
||
The following pattern is considered a warning: | ||
|
||
```jsx | ||
<><Foo /></> | ||
``` | ||
|
||
The following patterns are **not** considered warnings: | ||
|
||
```jsx | ||
<React.Fragment><Foo /></React.Fragment> | ||
``` | ||
|
||
```jsx | ||
<React.Fragment key="key"><Foo /></React.Fragment> | ||
``` | ||
|
||
[fragments]: https://reactjs.org/docs/fragments.html | ||
[shared_settings]: /README.md#configuration | ||
[short_syntax]: https://reactjs.org/docs/fragments.html#short-syntax |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,179 @@ | ||
/** | ||
* @fileoverview Enforce shorthand or standard form for React fragments. | ||
* @author Alex Zherdev | ||
*/ | ||
'use strict'; | ||
|
||
const elementType = require('jsx-ast-utils/elementType'); | ||
const pragmaUtil = require('../util/pragma'); | ||
const variableUtil = require('../util/variable'); | ||
const versionUtil = require('../util/version'); | ||
const docsUrl = require('../util/docsUrl'); | ||
|
||
// ------------------------------------------------------------------------------ | ||
// Rule Definition | ||
// ------------------------------------------------------------------------------ | ||
|
||
function replaceNode(source, node, text) { | ||
return `${source.slice(0, node.range[0])}${text}${source.slice(node.range[1])}`; | ||
} | ||
|
||
module.exports = { | ||
meta: { | ||
docs: { | ||
description: 'Enforce shorthand or standard form for React fragments', | ||
category: 'Stylistic Issues', | ||
recommended: false, | ||
url: docsUrl('jsx-fragments') | ||
}, | ||
fixable: 'code', | ||
|
||
schema: [{ | ||
enum: ['syntax', 'element'] | ||
}] | ||
}, | ||
|
||
create: function(context) { | ||
const configuration = context.options[0] || 'syntax'; | ||
const sourceCode = context.getSourceCode(); | ||
const reactPragma = pragmaUtil.getFromContext(context); | ||
const fragmentPragma = pragmaUtil.getFragmentFromContext(context); | ||
const openFragShort = '<>'; | ||
const closeFragShort = '</>'; | ||
const openFragLong = `<${reactPragma}.${fragmentPragma}>`; | ||
const closeFragLong = `</${reactPragma}.${fragmentPragma}>`; | ||
|
||
function reportOnReactVersion(node) { | ||
if (!versionUtil.testReactVersion(context, '16.2.0')) { | ||
context.report({ | ||
node, | ||
message: 'Fragments are only supported starting from React v16.2' | ||
}); | ||
return true; | ||
} | ||
|
||
return false; | ||
} | ||
|
||
function getFixerToLong(jsxFragment) { | ||
return function(fixer) { | ||
let source = sourceCode.getText(); | ||
source = replaceNode(source, jsxFragment.closingFragment, closeFragLong); | ||
source = replaceNode(source, jsxFragment.openingFragment, openFragLong); | ||
const lengthDiff = openFragLong.length - sourceCode.getText(jsxFragment.openingFragment).length | ||
+ closeFragLong.length - sourceCode.getText(jsxFragment.closingFragment).length; | ||
const range = jsxFragment.range; | ||
return fixer.replaceTextRange(range, source.slice(range[0], range[1] + lengthDiff)); | ||
}; | ||
} | ||
|
||
function getFixerToShort(jsxElement) { | ||
return function(fixer) { | ||
let source = sourceCode.getText(); | ||
source = replaceNode(source, jsxElement.closingElement, closeFragShort); | ||
source = replaceNode(source, jsxElement.openingElement, openFragShort); | ||
const lengthDiff = sourceCode.getText(jsxElement.openingElement).length - openFragShort.length | ||
+ sourceCode.getText(jsxElement.closingElement).length - closeFragShort.length; | ||
const range = jsxElement.range; | ||
return fixer.replaceTextRange(range, source.slice(range[0], range[1] - lengthDiff)); | ||
}; | ||
} | ||
|
||
function refersToReactFragment(name) { | ||
const variableInit = variableUtil.findVariableByName(context, name); | ||
if (!variableInit) { | ||
return false; | ||
} | ||
|
||
// const { Fragment } = React; | ||
if (variableInit.type === 'Identifier' && variableInit.name === reactPragma) { | ||
return true; | ||
} | ||
|
||
// const Fragment = React.Fragment; | ||
if ( | ||
variableInit.type === 'MemberExpression' | ||
&& variableInit.object.type === 'Identifier' | ||
&& variableInit.object.name === reactPragma | ||
&& variableInit.property.type === 'Identifier' | ||
&& variableInit.property.name === fragmentPragma | ||
) { | ||
return true; | ||
} | ||
|
||
// const { Fragment } = require('react'); | ||
if ( | ||
variableInit.callee | ||
&& variableInit.callee.name === 'require' | ||
&& variableInit.arguments | ||
&& variableInit.arguments[0] | ||
&& variableInit.arguments[0].value === 'react' | ||
) { | ||
return true; | ||
} | ||
|
||
return false; | ||
} | ||
|
||
const jsxElements = []; | ||
const fragmentNames = new Set([`${reactPragma}.${fragmentPragma}`]); | ||
|
||
// -------------------------------------------------------------------------- | ||
// Public | ||
// -------------------------------------------------------------------------- | ||
|
||
return { | ||
JSXElement(node) { | ||
jsxElements.push(node); | ||
}, | ||
|
||
JSXFragment(node) { | ||
if (reportOnReactVersion(node)) { | ||
return; | ||
} | ||
|
||
if (configuration === 'element') { | ||
context.report({ | ||
node, | ||
message: `Prefer ${reactPragma}.${fragmentPragma} over fragment shorthand`, | ||
fix: getFixerToLong(node) | ||
}); | ||
} | ||
}, | ||
|
||
ImportDeclaration(node) { | ||
if (node.source && node.source.value === 'react') { | ||
node.specifiers.forEach(spec => { | ||
if (spec.imported && spec.imported.name === fragmentPragma) { | ||
if (spec.local) { | ||
fragmentNames.add(spec.local.name); | ||
} | ||
} | ||
}); | ||
} | ||
}, | ||
|
||
'Program:exit'() { | ||
jsxElements.forEach(node => { | ||
const openingEl = node.openingElement; | ||
const elName = elementType(openingEl); | ||
|
||
if (fragmentNames.has(elName) || refersToReactFragment(elName)) { | ||
if (reportOnReactVersion(node)) { | ||
return; | ||
} | ||
|
||
const attrs = openingEl.attributes; | ||
if (configuration === 'syntax' && !(attrs && attrs.length > 0)) { | ||
context.report({ | ||
node, | ||
message: `Prefer fragment shorthand over ${reactPragma}.${fragmentPragma}`, | ||
fix: getFixerToShort(node) | ||
}); | ||
} | ||
} | ||
}); | ||
} | ||
}; | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could we add something along the lines of:
I think it's always a good idea to give users an action to do to help them resolve the error/warning.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That sounds like a great improvement.