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