Skip to content

Commit

Permalink
Merge pull request #166 from solidjs-community/components-return-once…
Browse files Browse the repository at this point in the history
…-hoisting

components-return-once: Support declarations after final return.
  • Loading branch information
joshwilsonvu authored Nov 12, 2024
2 parents 740f2c8 + 1cb6f2e commit 9304c4a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,9 @@ export default createRule({
const onFunctionEnter = (node: FunctionNode) => {
let lastReturn: T.ReturnStatement | undefined;
if (node.body.type === "BlockStatement") {
const { length } = node.body.body;
const last = length && node.body.body[length - 1];
// find last statement, ignoring function/class/variable declarations (hoisting)
const last = node.body.body.findLast((node) => !node.type.endsWith("Declaration"));
// if it's a return, store it
if (last && last.type === "ReturnStatement") {
lastReturn = last;
}
Expand Down Expand Up @@ -153,7 +154,7 @@ export default createRule({
return fixer.replaceText(argument, `<>${putIntoJSX(argument)}</>`);
},
});
} else if (argument?.type === "LogicalExpression")
} else if (argument?.type === "LogicalExpression") {
if (argument.operator === "&&") {
const sourceCode = getSourceCode(context);
// we have a `return condition && expression`--put that in a <Show />
Expand All @@ -175,6 +176,7 @@ export default createRule({
messageId: "noConditionalReturn",
});
}
}
}

// Pop on exit
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,20 @@ export const cases = run("components-return-once", rule, {
};
return <></>;
}`,
`function Component() {
return <>{hoisted()}</>;
function hoisted() {
return 'hoisted';
}
}`,
`function Component() {
return <></>;
const hoisted = 'hoisted';
}`,
`function Component() {
return <></>;
class Hoisted {}
}`,
],
invalid: [
// Early returns
Expand All @@ -70,6 +84,16 @@ export const cases = run("components-return-once", rule, {
}`,
errors: [{ messageId: "noEarlyReturn" }],
},
{
code: `const Component = () => {
if (condition) {
return <div />;
}
return <span />;
function hoisted() {}
}`,
errors: [{ messageId: "noEarlyReturn" }],
},
// Balanced ternaries
{
code: `function Component() {
Expand Down

0 comments on commit 9304c4a

Please sign in to comment.