forked from sveltejs/eslint-plugin-svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathno-reactive-literals.ts
69 lines (59 loc) · 1.88 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
64
65
66
67
68
69
import type { TSESTree } from "@typescript-eslint/types"
import { createRule } from "../utils"
const labeledStatementBase = `SvelteReactiveStatement > ExpressionStatement > AssignmentExpression`
export default createRule("no-reactive-literals", {
meta: {
docs: {
description: "Don't assign literal values in reactive statements",
category: "Stylistic Issues",
recommended: false,
conflictWithPrettier: false,
},
fixable: "code",
schema: [],
messages: {
noReactiveLiterals: `Do not assign literal values inside reactive statements unless absolutely necessary.`,
},
type: "suggestion",
},
create(context) {
/**
* Reusable method for multiple types of nodes that should warn
*
* @param node TSESTree.AssignmentExpression the node that was found
* @returns void
*/
function warn(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",
fix(fixer) {
return [
// Insert "let" + whatever was in there
fixer.insertTextBefore(parent, `let ${source.getText(node)}`),
// Remove the original reactive statement
fixer.remove(parent),
]
},
})
}
return {
// $: foo = "foo";
// $: foo = 1;
[`${labeledStatementBase}[right.type="Literal"]`]: warn,
// $: foo = [];
[`${labeledStatementBase}[right.type="ArrayExpression"][right.elements.length=0]`]:
warn,
// $: foo = {};
[`${labeledStatementBase}[right.type="ObjectExpression"][right.properties.length=0]`]:
warn,
}
},
})