Skip to content

Add prefer-reactive-destructuring rule #205

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,7 @@ These rules relate to better ways of doing things to help you avoid problems:
| [svelte/no-reactive-literals](https://ota-meshi.github.io/eslint-plugin-svelte/rules/no-reactive-literals/) | Don't assign literal values in reactive statements | :bulb: |
| [svelte/no-unused-svelte-ignore](https://ota-meshi.github.io/eslint-plugin-svelte/rules/no-unused-svelte-ignore/) | disallow unused svelte-ignore comments | :star: |
| [svelte/no-useless-mustaches](https://ota-meshi.github.io/eslint-plugin-svelte/rules/no-useless-mustaches/) | disallow unnecessary mustache interpolations | :wrench: |
| [svelte/prefer-reactive-destructuring](https://ota-meshi.github.io/eslint-plugin-svelte/rules/prefer-reactive-destructuring/) | Prefer destructuring from objects in reactive statements | |
| [svelte/require-optimized-style-attribute](https://ota-meshi.github.io/eslint-plugin-svelte/rules/require-optimized-style-attribute/) | require style attributes that can be optimized | |

## Stylistic Issues
Expand Down
1 change: 1 addition & 0 deletions docs/rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ These rules relate to better ways of doing things to help you avoid problems:
| [svelte/no-reactive-literals](./rules/no-reactive-literals.md) | Don't assign literal values in reactive statements | :bulb: |
| [svelte/no-unused-svelte-ignore](./rules/no-unused-svelte-ignore.md) | disallow unused svelte-ignore comments | :star: |
| [svelte/no-useless-mustaches](./rules/no-useless-mustaches.md) | disallow unnecessary mustache interpolations | :wrench: |
| [svelte/prefer-reactive-destructuring](./rules/prefer-reactive-destructuring.md) | Prefer destructuring from objects in reactive statements | |
| [svelte/require-optimized-style-attribute](./rules/require-optimized-style-attribute.md) | require style attributes that can be optimized | |

## Stylistic Issues
Expand Down
55 changes: 55 additions & 0 deletions docs/rules/prefer-reactive-destructuring.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
---
pageClass: "rule-details"
sidebarDepth: 0
title: "svelte/prefer-reactive-destructuring"
description: "Prefer destructuring from objects in reactive statements"
---

# svelte/prefer-reactive-destructuring

> Prefer destructuring from objects in reactive statements

- :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> **_This rule has not been released yet._** </badge>

## :book: Rule Details

This rule triggers whenever a reactive statement contains an assignment that could be rewritten using destructuring. This is beneficial because it allows svelte's change-tracking to prevent wasteful redraws whenever the object is changed.

This [svelte REPL](https://svelte.dev/repl/96759f4772314d0a840e11370ef76711) example shows just how effective this can be at preventing bogus redraws.

<ESLintCodeBlock>

<!--eslint-skip-->

```svelte
<script>
/* eslint svelte/prefer-reactive-destructuring: "error" */
/* ✓ GOOD */
$: ({ foo } = info)
$: ({ bar: baz } = info)

/* ✗ BAD */
$: foo = info.foo
$: baz = info.bar
</script>


```

</ESLintCodeBlock>

## :wrench: Options

Nothing

## :heart: Compatibility

This rule was taken from [@tivac/eslint-plugin-svelte].
This rule is compatible with `@tivac/svelte/reactive-destructuring` rule.

[@tivac/eslint-plugin-svelte]: https://github.com/tivac/eslint-plugin-svelte/

## :mag: Implementation

- [Rule source](https://github.com/ota-meshi/eslint-plugin-svelte/blob/main/src/rules/prefer-reactive-destructuring.ts)
- [Test source](https://github.com/ota-meshi/eslint-plugin-svelte/blob/main/tests/src/rules/prefer-reactive-destructuring.ts)
67 changes: 67 additions & 0 deletions src/rules/prefer-reactive-destructuring.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,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",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The first letter should be lowercase to be consistent with existing rules. (see #218)

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]],
")",
),
],
},
],
})
},
}
},
})
2 changes: 2 additions & 0 deletions src/utils/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import noUnknownStyleDirectiveProperty from "../rules/no-unknown-style-directive
import noUnusedSvelteIgnore from "../rules/no-unused-svelte-ignore"
import noUselessMustaches from "../rules/no-useless-mustaches"
import preferClassDirective from "../rules/prefer-class-directive"
import preferReactiveDestructuring from "../rules/prefer-reactive-destructuring"
import preferStyleDirective from "../rules/prefer-style-directive"
import requireOptimizedStyleAttribute from "../rules/require-optimized-style-attribute"
import shorthandAttribute from "../rules/shorthand-attribute"
Expand Down Expand Up @@ -59,6 +60,7 @@ export const rules = [
noUnusedSvelteIgnore,
noUselessMustaches,
preferClassDirective,
preferReactiveDestructuring,
preferStyleDirective,
requireOptimizedStyleAttribute,
shorthandAttribute,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
[
{
"message": "Prefer destructuring in reactive statements",
"line": 3,
"column": 8,
"suggestions": [
{
"desc": "Use destructuring to get finer-grained redraws",
"messageId": "suggestDestructuring",
"output": "<!-- prettier-ignore -->\n<script>\n $: ({ info } = foo)\n $: bar = foo.something\n $: baz = foo.bar.baz\n $: qux = foo[bar]\n $: dux = foo.baz().bar\n</script>\n"
}
]
},
{
"message": "Prefer destructuring in reactive statements",
"line": 4,
"column": 8,
"suggestions": [
{
"desc": "Use destructuring to get finer-grained redraws",
"messageId": "suggestDestructuring",
"output": "<!-- prettier-ignore -->\n<script>\n $: info = foo.info\n $: ({ something: bar } = foo)\n $: baz = foo.bar.baz\n $: qux = foo[bar]\n $: dux = foo.baz().bar\n</script>\n"
}
]
},
{
"message": "Prefer destructuring in reactive statements",
"line": 5,
"column": 8,
"suggestions": null
},
{
"message": "Prefer destructuring in reactive statements",
"line": 6,
"column": 8,
"suggestions": null
},
{
"message": "Prefer destructuring in reactive statements",
"line": 7,
"column": 8,
"suggestions": null
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!-- prettier-ignore -->
<script>
$: info = foo.info
$: bar = foo.something
$: baz = foo.bar.baz
$: qux = foo[bar]
$: dux = foo.baz().bar
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<!-- prettier-ignore -->
<script>
$: ({ info } = foo)
$: bar = baz
$: qux = `bar ${baz}`
</script>
16 changes: 16 additions & 0 deletions tests/src/rules/prefer-reactive-destructuring.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { RuleTester } from "eslint"
import rule from "../../../src/rules/prefer-reactive-destructuring"
import { loadTestCases } from "../../utils/utils"

const tester = new RuleTester({
parserOptions: {
ecmaVersion: 2020,
sourceType: "module",
},
})

tester.run(
"prefer-reactive-destructuring",
rule as any,
loadTestCases("prefer-reactive-destructuring"),
)