Skip to content

Commit 64a7825

Browse files
Update src/rules/infinite-reactive-loop.ts
Co-authored-by: Yosuke Ota <[email protected]>
1 parent 0ff0b62 commit 64a7825

File tree

1 file changed

+41
-10
lines changed

1 file changed

+41
-10
lines changed

src/rules/infinite-reactive-loop.ts

+41-10
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,37 @@ function isPromiseThenOrCatchBody(node: TSESTree.Node): boolean {
162162
return ["then", "catch"].includes(property.name)
163163
}
164164

165+
166+
/**
167+
* Get all reactive variable reference.
168+
*/
169+
function getAllReactiveVariableReferences(context: RuleContext) {
170+
const scopeManager = context.getSourceCode().scopeManager
171+
// Find the top-level (module or global) scope.
172+
// Any variable defined at the top-level (module scope or global scope) can be made reactive.
173+
const toplevelScope =
174+
scopeManager.globalScope?.childScopes.find(
175+
(scope) => scope.type === "module",
176+
) || scopeManager.globalScope
177+
if (!toplevelScope) {
178+
return []
179+
}
180+
181+
// Extracts all reactive references to variables defined in the top-level scope.
182+
const reactiveVariableNodes: TSESTree.Identifier[] = []
183+
for (const variable of toplevelScope.variables) {
184+
for (const reference of variable.references) {
185+
if (
186+
reference.identifier.type === "Identifier" &&
187+
!isFunctionCall(reference.identifier)
188+
) {
189+
reactiveVariableNodes.push(reference.identifier)
190+
}
191+
}
192+
}
193+
return reactiveVariableNodes
194+
}
195+
165196
/**
166197
* Get all tracked reactive variables.
167198
*/
@@ -170,16 +201,16 @@ function getTrackedVariableNodes(
170201
ast: AST.SvelteReactiveStatement,
171202
) {
172203
const reactiveVariableNodes: TSESTree.Identifier[] = []
173-
traverseNodes(ast.body, {
174-
enterNode(node) {
175-
if (isReactiveVariableNode(context, node)) {
176-
reactiveVariableNodes.push(node)
177-
}
178-
},
179-
leaveNode() {
180-
/* noop */
181-
},
182-
})
204+
for (const identifier of getAllReactiveVariableReferences(context)) {
205+
if (
206+
// If the identifier is within the reactive statement range,
207+
// it is used within the reactive statement.
208+
ast.range[0] <= identifier.range[0] &&
209+
identifier.range[1] <= ast.range[1]
210+
) {
211+
reactiveVariableNodes.push(identifier)
212+
}
213+
}
183214
return reactiveVariableNodes
184215
}
185216

0 commit comments

Comments
 (0)