Skip to content

Commit

Permalink
refactor: move function isFragment to utils/jsx.js
Browse files Browse the repository at this point in the history
  • Loading branch information
golopot committed Jul 12, 2019
1 parent cfbea9d commit 01eb97e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 31 deletions.
33 changes: 2 additions & 31 deletions lib/rules/jsx-no-useless-fragment.js
Expand Up @@ -4,6 +4,7 @@

'use strict';
const pragmaUtil = require('../util/pragma');
const jsxUtil = require('../util/jsx');
const docsUrl = require('../util/docsUrl');


Expand All @@ -27,36 +28,6 @@ module.exports = {
const reactPragma = pragmaUtil.getFromContext(context);
const fragmentPragma = pragmaUtil.getFragmentFromContext(context);

/**
* Test whether a JSXElement is a fragment
* @param {JSXElement} node
* @returns {boolean}
*/
function isFragment(node) {
const name = node.openingElement.name;

// <Fragment>
if (
name.type === 'JSXIdentifier'
&& name.name === fragmentPragma
) {
return true;
}

// <React.Fragment>
if (
name.type === 'JSXMemberExpression'
&& name.object.type === 'JSXIdentifier'
&& name.object.name === reactPragma
&& name.property.type === 'JSXIdentifier'
&& name.property.name === fragmentPragma
) {
return true;
}

return false;
}

/**
* Test whether a node is an padding spaces trimmed by react runtime.
* @param {ASTNode} node
Expand Down Expand Up @@ -157,7 +128,7 @@ module.exports = {

return {
JSXElement(node) {
if (isFragment(node)) {
if (jsxUtil.isFragment(node, reactPragma, fragmentPragma)) {
checkNode(node);
}
},
Expand Down
30 changes: 30 additions & 0 deletions lib/util/jsx.js
Expand Up @@ -25,6 +25,35 @@ function isDOMComponent(node) {
return COMPAT_TAG_REGEX.test(name);
}

/**
* Test whether a JSXElement is a fragment
* @param {JSXElement} node
* @param {string} reactPragma
* @param {string} fragmentPragma
* @returns {boolean}
*/
function isFragment(node, reactPragma, fragmentPragma) {
const name = node.openingElement.name;

// <Fragment>
if (name.type === 'JSXIdentifier' && name.name === fragmentPragma) {
return true;
}

// <React.Fragment>
if (
name.type === 'JSXMemberExpression'
&& name.object.type === 'JSXIdentifier'
&& name.object.name === reactPragma
&& name.property.type === 'JSXIdentifier'
&& name.property.name === fragmentPragma
) {
return true;
}

return false;
}

/**
* Checks if a node represents a JSX element or fragment.
* @param {object} node - node to check.
Expand All @@ -36,5 +65,6 @@ function isJSX(node) {

module.exports = {
isDOMComponent: isDOMComponent,
isFragment,
isJSX: isJSX
};

0 comments on commit 01eb97e

Please sign in to comment.