forked from sveltejs/eslint-plugin-svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprefer-reactive-destructuring.ts
67 lines (63 loc) · 2.19 KB
/
prefer-reactive-destructuring.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
import type { TSESTree } from "@typescript-eslint/types"
import { createRule } from "../utils"
export default createRule("prefer-reactive-destructuring", {
meta: {
docs: {
description: "Prefer destructuring from objects in reactive statements",
category: "Best Practices",
recommended: false,
},
hasSuggestions: true,
schema: [],
messages: {
useDestructuring: `Prefer destructuring in reactive statements`,
suggestDestructuring: `Use destructuring to get finer-grained redraws`,
},
type: "suggestion",
},
create(context) {
return {
// Finds: $: info = foo.info
// Suggests: $: ({ info } = foo);
[`SvelteReactiveStatement > ExpressionStatement > AssignmentExpression[left.type="Identifier"][right.type="MemberExpression"]`](
node: TSESTree.AssignmentExpression,
) {
const left = node.left as TSESTree.Identifier
const right = node.right as TSESTree.MemberExpression
const prop = (right.property as TSESTree.Identifier).name
const source = context.getSourceCode()
const lToken = source.getFirstToken(left)
const rTokens = source.getLastTokens(right, {
includeComments: true,
count: 2,
})
const matched = prop === left.name
return context.report({
node,
loc: node.loc,
messageId: "useDestructuring",
suggest:
// Don't show suggestions for complex right-hand values, too tricky to get it right
right.object.type !== "Identifier" || right.computed
? []
: [
{
messageId: "suggestDestructuring",
fix: (fixer) => [
fixer.insertTextBefore(
lToken,
matched ? `({ ` : `({ ${prop}: `,
),
fixer.insertTextAfter(lToken, ` }`),
fixer.replaceTextRange(
[rTokens[0].range[0], rTokens[1].range[1]],
")",
),
],
},
],
})
},
}
},
})