|
| 1 | +import type { TSESTree } from "@typescript-eslint/types" |
| 2 | +import { createRule } from "../utils" |
| 3 | + |
| 4 | +export default createRule("no-reactive-literals", { |
| 5 | + meta: { |
| 6 | + docs: { |
| 7 | + description: "Don't assign literal values in reactive statements", |
| 8 | + category: "Best Practices", |
| 9 | + recommended: false, |
| 10 | + }, |
| 11 | + hasSuggestions: true, |
| 12 | + schema: [], |
| 13 | + messages: { |
| 14 | + noReactiveLiterals: `Do not assign literal values inside reactive statements unless absolutely necessary.`, |
| 15 | + fixReactiveLiteral: `Move the literal out of the reactive statement into an assignment`, |
| 16 | + }, |
| 17 | + type: "suggestion", |
| 18 | + }, |
| 19 | + create(context) { |
| 20 | + return { |
| 21 | + [`SvelteReactiveStatement > ExpressionStatement > AssignmentExpression${[ |
| 22 | + // $: foo = "foo"; |
| 23 | + // $: foo = 1; |
| 24 | + `[right.type="Literal"]`, |
| 25 | +
|
| 26 | + // $: foo = []; |
| 27 | + `[right.type="ArrayExpression"][right.elements.length=0]`, |
| 28 | +
|
| 29 | + // $: foo = {}; |
| 30 | + `[right.type="ObjectExpression"][right.properties.length=0]`, |
| 31 | + ].join(",")}`](node: TSESTree.AssignmentExpression) { |
| 32 | + // Move upwards to include the entire reactive statement |
| 33 | + const parent = node.parent?.parent |
| 34 | + |
| 35 | + if (!parent) { |
| 36 | + return false |
| 37 | + } |
| 38 | + |
| 39 | + const source = context.getSourceCode() |
| 40 | + |
| 41 | + return context.report({ |
| 42 | + node: parent, |
| 43 | + loc: parent.loc, |
| 44 | + messageId: "noReactiveLiterals", |
| 45 | + suggest: [ |
| 46 | + { |
| 47 | + messageId: "fixReactiveLiteral", |
| 48 | + fix(fixer) { |
| 49 | + return [ |
| 50 | + // Insert "let" + whatever was in there |
| 51 | + fixer.insertTextBefore(parent, `let ${source.getText(node)}`), |
| 52 | + |
| 53 | + // Remove the original reactive statement |
| 54 | + fixer.remove(parent), |
| 55 | + ] |
| 56 | + }, |
| 57 | + }, |
| 58 | + ], |
| 59 | + }) |
| 60 | + }, |
| 61 | + } |
| 62 | + }, |
| 63 | +}) |
0 commit comments