Skip to content

Commit b0bf16c

Browse files
committed
feat(prefer-svelte-reactivity): ignoring variables encapsulated in functions
1 parent 5afcdab commit b0bf16c

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

packages/eslint-plugin-svelte/src/rules/prefer-svelte-reactivity.ts

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,18 @@ export default createRule('prefer-svelte-reactivity', {
1212
category: 'Possible Errors',
1313
recommended: true
1414
},
15-
schema: [],
15+
schema: [
16+
{
17+
type: 'object',
18+
properties: {
19+
ignoreEncapsulatedLocalVariables: {
20+
type: 'boolean',
21+
default: true
22+
}
23+
},
24+
additionalProperties: false
25+
}
26+
],
1627
messages: {
1728
mutableDateUsed:
1829
'Found a mutable instance of the built-in Date class. Use SvelteDate instead.',
@@ -31,6 +42,8 @@ export default createRule('prefer-svelte-reactivity', {
3142
]
3243
},
3344
create(context) {
45+
const ignoreEncapsulatedLocalVariables =
46+
context.options[0]?.ignoreEncapsulatedLocalVariables ?? true;
3447
const returnedVariables: Map<
3548
TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration,
3649
TSESTree.VariableDeclarator[]
@@ -122,6 +135,9 @@ export default createRule('prefer-svelte-reactivity', {
122135
});
123136
}
124137
}
138+
if (ignoreEncapsulatedLocalVariables && isEncapsulated(returnedVariables, node)) {
139+
continue;
140+
}
125141
for (const returnedVar of Array.from(returnedVariables.values()).flat()) {
126142
if (isIn(node, returnedVar)) {
127143
context.report({
@@ -198,6 +214,22 @@ function findEnclosingFunction(
198214
return findAncestorOfTypes(node, ['ArrowFunctionExpression', 'FunctionDeclaration']);
199215
}
200216

217+
function isEncapsulated(
218+
returnedVariables: Map<
219+
TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration,
220+
TSESTree.VariableDeclarator[]
221+
>,
222+
node: TSESTree.Node
223+
): boolean {
224+
const enclosingFunction = findEnclosingFunction(node);
225+
if (enclosingFunction === null) {
226+
return false;
227+
}
228+
return (
229+
returnedVariables.get(enclosingFunction)?.some((variable) => isIn(node, variable)) === false
230+
);
231+
}
232+
201233
function isDateMutable(referenceTracker: ReferenceTracker, ctorNode: TSESTree.Expression): boolean {
202234
return !referenceTracker
203235
.iteratePropertyReferences(ctorNode, {

0 commit comments

Comments
 (0)