|
| 1 | +import type { TSESTree } from "@typescript-eslint/types" |
| 2 | +import type { AST } from "svelte-eslint-parser" |
| 3 | +import { createRule } from "../utils" |
| 4 | + |
| 5 | +export default createRule("no-reactive-functions", { |
| 6 | + meta: { |
| 7 | + docs: { |
| 8 | + description: |
| 9 | + "It's not necessary to define functions in reactive statements", |
| 10 | + category: "Best Practices", |
| 11 | + recommended: false, |
| 12 | + }, |
| 13 | + hasSuggestions: true, |
| 14 | + schema: [], |
| 15 | + messages: { |
| 16 | + noReactiveFns: `Do not create functions inside reactive statements unless absolutely necessary.`, |
| 17 | + fixReactiveFns: `Move the function out of the reactive statement`, |
| 18 | + }, |
| 19 | + type: "suggestion", // "problem", or "layout", |
| 20 | + }, |
| 21 | + create(context) { |
| 22 | + return { |
| 23 | + // $: foo = () => { ... } |
| 24 | + [`SvelteReactiveStatement > ExpressionStatement > AssignmentExpression > :function`]( |
| 25 | + node: TSESTree.ArrowFunctionExpression, |
| 26 | + ) { |
| 27 | + // Move upwards to include the entire label |
| 28 | + const parent = node.parent?.parent?.parent |
| 29 | + |
| 30 | + if (!parent) { |
| 31 | + return false |
| 32 | + } |
| 33 | + |
| 34 | + const source = context.getSourceCode() |
| 35 | + |
| 36 | + return context.report({ |
| 37 | + node: parent, |
| 38 | + loc: parent.loc, |
| 39 | + messageId: "noReactiveFns", |
| 40 | + suggest: [ |
| 41 | + { |
| 42 | + messageId: "fixReactiveFns", |
| 43 | + fix(fixer) { |
| 44 | + const tokens = source.getFirstTokens(parent, { |
| 45 | + includeComments: false, |
| 46 | + count: 3, |
| 47 | + }) |
| 48 | + |
| 49 | + const noExtraSpace = source.isSpaceBetweenTokens( |
| 50 | + tokens[1] as AST.Token, |
| 51 | + tokens[2] as AST.Token, |
| 52 | + ) |
| 53 | + |
| 54 | + // Replace the entire reactive label with "const" |
| 55 | + return fixer.replaceTextRange( |
| 56 | + [tokens[0].range[0], tokens[1].range[1]], |
| 57 | + noExtraSpace ? "const" : "const ", |
| 58 | + ) |
| 59 | + }, |
| 60 | + }, |
| 61 | + ], |
| 62 | + }) |
| 63 | + }, |
| 64 | + } |
| 65 | + }, |
| 66 | +}) |
0 commit comments