Skip to content

fix: add ignoreLocalVariables to prefer-svelte-reactivity rule to avoid false positives #1273

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/petite-shirts-smash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'eslint-plugin-svelte': patch
---

fix: add `ignoreLocalVariables` to `prefer-svelte-reactivity` rule to avoid false positives
13 changes: 12 additions & 1 deletion docs/rules/prefer-svelte-reactivity.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,18 @@ export default e;

## :wrench: Options

Nothing.
```json
{
"svelte/prefer-svelte-reactivity": [
"error",
{
"ignoreLocalVariables": true
}
]
}
```

- `ignoreLocalVariables` ... Set to `true` to ignore variables declared anywhere other than the top level, such as inside functions. The default is `true`. In almost all cases, we do not need to set this to `false`.

## :books: Further Reading

Expand Down
4 changes: 2 additions & 2 deletions packages/eslint-plugin-svelte/src/meta.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// IMPORTANT!
// This file has been automatically generated,
// in order to update its content execute "pnpm run update"
export const name = 'eslint-plugin-svelte' as const;
export const version = '3.11.0' as const;
export const name = 'eslint-plugin-svelte';
export const version = '3.11.0';
6 changes: 5 additions & 1 deletion packages/eslint-plugin-svelte/src/rule-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ export interface RuleOptions {
* disallow using mutable instances of built-in classes where a reactive alternative is provided by svelte/reactivity
* @see https://sveltejs.github.io/eslint-plugin-svelte/rules/prefer-svelte-reactivity/
*/
'svelte/prefer-svelte-reactivity'?: Linter.RuleEntry<[]>
'svelte/prefer-svelte-reactivity'?: Linter.RuleEntry<SveltePreferSvelteReactivity>
/**
* Prefer using writable $derived instead of $state and $effect
* @see https://sveltejs.github.io/eslint-plugin-svelte/rules/prefer-writable-derived/
Expand Down Expand Up @@ -580,6 +580,10 @@ type SveltePreferConst = []|[{
excludedRunes?: string[]
[k: string]: unknown | undefined
}]
// ----- svelte/prefer-svelte-reactivity -----
type SveltePreferSvelteReactivity = []|[{
ignoreLocalVariables?: boolean
}]
// ----- svelte/require-event-prefix -----
type SvelteRequireEventPrefix = []|[{
checkAsyncFunctions?: boolean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { ReferenceTracker } from '@eslint-community/eslint-utils';
import { createRule } from '../utils/index.js';
import type { TSESTree } from '@typescript-eslint/types';
import { findVariable, isIn } from '../utils/ast-utils.js';
import { getSvelteContext } from '../utils/svelte-context.js';
import { getSvelteContext } from 'src/utils/svelte-context.js';
import type { AST } from 'svelte-eslint-parser';

export default createRule('prefer-svelte-reactivity', {
meta: {
Expand All @@ -12,7 +13,18 @@ export default createRule('prefer-svelte-reactivity', {
category: 'Possible Errors',
recommended: true
},
schema: [],
schema: [
{
type: 'object',
properties: {
ignoreLocalVariables: {
type: 'boolean',
default: true
}
},
additionalProperties: false
}
],
messages: {
mutableDateUsed:
'Found a mutable instance of the built-in Date class. Use SvelteDate instead.',
Expand All @@ -31,6 +43,7 @@ export default createRule('prefer-svelte-reactivity', {
]
},
create(context) {
const options = context.options[0] ?? { ignoreLocalVariables: true };
const exportedVars: TSESTree.Node[] = [];
return {
...(getSvelteContext(context)?.svelteFileType === '.svelte.[js|ts]' && {
Expand Down Expand Up @@ -78,6 +91,10 @@ export default createRule('prefer-svelte-reactivity', {
[ReferenceTracker.CONSTRUCT]: true
}
})) {
if (options.ignoreLocalVariables && !isTopLevelDeclaration(node)) {
continue;
}

const messageId =
path[0] === 'Date'
? 'mutableDateUsed'
Expand Down Expand Up @@ -135,6 +152,32 @@ export default createRule('prefer-svelte-reactivity', {
}
});

function isTopLevelDeclaration(node: TSESTree.Node | AST.SvelteNode): boolean {
let declaration: TSESTree.Node | AST.SvelteNode | null = node;
while (
declaration &&
declaration.type !== 'VariableDeclaration' &&
declaration.type !== 'FunctionDeclaration' &&
declaration.type !== 'ClassDeclaration' &&
declaration.type !== 'ExportDefaultDeclaration'
) {
declaration = declaration.parent as TSESTree.Node | AST.SvelteNode | null;
}

if (!declaration) {
return false;
}

const parentType: string | undefined = declaration.parent?.type;
return (
parentType === 'SvelteScriptElement' ||
parentType === 'Program' ||
parentType === 'ExportDefaultDeclaration' ||
parentType === 'ExportNamedDeclaration' ||
parentType === 'ExportAllDeclaration'
);
}

function isDateMutable(referenceTracker: ReferenceTracker, ctorNode: TSESTree.Expression): boolean {
return !referenceTracker
.iteratePropertyReferences(ctorNode, {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"options": [
{
"ignoreLocalVariables": false
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
- message: Found a mutable instance of the built-in Map class. Use SvelteMap instead.
line: 3
column: 15
suggestions: null
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<script>
const foo = () => {
const map = new Map();
map.set('foo', 'bar');
};
</script>

{foo()}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<script>
const foo = () => {
const date = new Date();
const map = new Map();
const set = new Set();
const url = new URL('https://svelte.dev/');
const objectURL = URL.createObjectURL(new MediaSource());
const urlSearchParams = new URLSearchParams();
console.log({ date, map, set, url, objectURL, urlSearchParams });
};
</script>

{foo()}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
let toys = $state([]);

export function getUniqueToys() {
let names = new Set();
let uniqueToys = [];
for (const toy in toys) {
if (!names.has(toy.name)) {
uniqueToys.push(toy);
}
}
return uniqueToys;
}

let uniqueToys = $derived.by(getUniqueToys);

console.log(uniqueToys)
Loading