Skip to content

Commit

Permalink
add check for empty/newlines
Browse files Browse the repository at this point in the history
  • Loading branch information
vkbansal committed Jan 5, 2016
1 parent f7817a7 commit f301ad4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 10 deletions.
18 changes: 13 additions & 5 deletions lib/rules/jsx-if-single-child.js
Expand Up @@ -20,11 +20,19 @@ module.exports = function(context) {
return n.name && n.name.type === "JSXIdentifier" && n.name.name === "Else" && n.selfClosing;
}

function hasSingleChild(node) {
var children = node.parent.children;
function filterChildren(children) {
return children.filter(function(c) {
if (c.type === "JSXElement") return true;

return children.length && children.length === 1
&& ["JSXElement", "Literal"].indexOf(children[0].type) > -1;
if (c.type === "Literal") return c.value.trim() !== "";

return false;
});
}

function hasSingleChild(node) {
var children = filterChildren(node.parent.children);
return children.length && children.length === 1;
}

function hasElseCondition(node) {
Expand All @@ -36,7 +44,7 @@ module.exports = function(context) {
}

function hasSingleChildrenBetween(node) {
var children = node.parent.children;
var children = filterChildren(node.parent.children);

return children.length
&& children.length === 3
Expand Down
20 changes: 15 additions & 5 deletions tests/lib/rules/jsx-if-single-child.js
Expand Up @@ -26,7 +26,7 @@ ruleTester.run("jsx-if-single-child", rule, {
jsx: true
}
}, {
code: "<If><div/><Else/><div/></If>",
code: "\n<If>\n\t<div/>\n<Else/>\n\t<div/>\n</If>",
ecmaFeatures: {
jsx: true
}
Expand All @@ -40,12 +40,22 @@ ruleTester.run("jsx-if-single-child", rule, {
ecmaFeatures: {
jsx: true
}
}, {
code: "\n<If>\n\t<foobar/>\n</If>",
ecmaFeatures: {
jsx: true
}
}, {
code: "\n<If>\n\t<div>\n\t\t<foo/>\n\t</div>\n<Else/>\n\t<div>\n\t\t<bar/>\n\t</div>\n</If>",
ecmaFeatures: {
jsx: true
}
}
],

invalid: [
{
code: "<If><div/><div/></If>",
code: "\n<If>\n\t<div/>\n\t<div/>\n</If>",
ecmaFeatures: {
jsx: true
},
Expand All @@ -54,7 +64,7 @@ ruleTester.run("jsx-if-single-child", rule, {
type: "JSXOpeningElement"
}]
}, {
code: "<If><div/><div/><Else/><div/><div/></If>",
code: "\n<If>\n\t<div/>\n\t<div/>\n<Else/>\n\t<div/>\n\t<div/>\n</If>",
ecmaFeatures: {
jsx: true
},
Expand All @@ -63,7 +73,7 @@ ruleTester.run("jsx-if-single-child", rule, {
type: "JSXOpeningElement"
}]
}, {
code: "<If><div/><div/><Else/><div/></If>",
code: "\n<If>\n\t<div/>\n\t<div/>\n<Else/>\n\t<div/>\n</If>",
ecmaFeatures: {
jsx: true
},
Expand All @@ -72,7 +82,7 @@ ruleTester.run("jsx-if-single-child", rule, {
type: "JSXOpeningElement"
}]
}, {
code: "<If><div/><Else/><div/><div/></If>",
code: "\n<If>\n\t<div/>\n<Else/>\n\t<div/>\n\t<div/>\n</If>",
ecmaFeatures: {
jsx: true
},
Expand Down

0 comments on commit f301ad4

Please sign in to comment.