Skip to content

Add svelte/no-reactive-literals rule #203

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

Merged
merged 5 commits into from
Jul 31, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
32 changes: 32 additions & 0 deletions docs/rules/no-reactive-literals.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# (svelte/no-reactive-literals)

> Don't assign literal values in reactive statements

## :book: Rule Details

This rule reports on any assignment of a static, unchanging value within a reactive statement because it's not necessary.

<ESLintCodeBlock>

<!--eslint-skip-->

```svelte
<script>
/* eslint svelte/no-reactive-literals: "error" */
/* ✓ GOOD */
let foo = "bar";

/* ✗ BAD */
$: foo = "bar";
</script>
```
</ESLintCodeBlock>

## :wrench: Options

Nothing

## :mag: Implementation

- [Rule source](https://github.com/ota-meshi/eslint-plugin-svelte/blob/main/src/rules/no-reactive-literals.ts)
- [Test source](https://github.com/ota-meshi/eslint-plugin-svelte/blob/main/tests/src/rules/no-reactive-literals.ts)
63 changes: 63 additions & 0 deletions src/rules/no-reactive-literals.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,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${[
// $: 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),
]
},
},
],
})
},
}
},
})
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export interface RuleMetaData {
}
messages: { [messageId: string]: string }
fixable?: "code" | "whitespace"
hasSuggestions?: boolean
schema: JSONSchema4 | JSONSchema4[]
deprecated?: boolean
replacedBy?: string[]
Expand Down Expand Up @@ -98,6 +99,7 @@ export interface PartialRuleMetaData {
)
messages: { [messageId: string]: string }
fixable?: "code" | "whitespace"
hasSuggestions?: boolean
schema: JSONSchema4 | JSONSchema4[]
deprecated?: boolean
replacedBy?: string[]
Expand Down
2 changes: 2 additions & 0 deletions src/utils/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import noDynamicSlotName from "../rules/no-dynamic-slot-name"
import noInnerDeclarations from "../rules/no-inner-declarations"
import noNotFunctionHandler from "../rules/no-not-function-handler"
import noObjectInTextMustaches from "../rules/no-object-in-text-mustaches"
import noReactiveLiterals from "../rules/no-reactive-literals"
import noShorthandStylePropertyOverrides from "../rules/no-shorthand-style-property-overrides"
import noSpacesAroundEqualSignsInAttribute from "../rules/no-spaces-around-equal-signs-in-attribute"
import noTargetBlank from "../rules/no-target-blank"
Expand Down Expand Up @@ -47,6 +48,7 @@ export const rules = [
noInnerDeclarations,
noNotFunctionHandler,
noObjectInTextMustaches,
noReactiveLiterals,
noShorthandStylePropertyOverrides,
noSpacesAroundEqualSignsInAttribute,
noTargetBlank,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
[
{
"message": "Do not assign literal values inside reactive statements unless absolutely necessary.",
"line": 3,
"column": 5,
"suggestions": [
{
"desc": "Move the literal out of the reactive statement into an assignment",
"messageId": "fixReactiveLiteral",
"output": "<!-- prettier-ignore -->\n<script>\n let foo = \"foo\"\n $: bar = [];\n $: baz = {};\n</script>\n"
}
]
},
{
"message": "Do not assign literal values inside reactive statements unless absolutely necessary.",
"line": 4,
"column": 5,
"suggestions": [
{
"desc": "Move the literal out of the reactive statement into an assignment",
"messageId": "fixReactiveLiteral",
"output": "<!-- prettier-ignore -->\n<script>\n $: foo = \"foo\";\n let bar = []\n $: baz = {};\n</script>\n"
}
]
},
{
"message": "Do not assign literal values inside reactive statements unless absolutely necessary.",
"line": 5,
"column": 5,
"suggestions": [
{
"desc": "Move the literal out of the reactive statement into an assignment",
"messageId": "fixReactiveLiteral",
"output": "<!-- prettier-ignore -->\n<script>\n $: foo = \"foo\";\n $: bar = [];\n let baz = {}\n</script>\n"
}
]
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<!-- prettier-ignore -->
<script>
$: foo = "foo";
$: bar = [];
$: baz = {};
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<!-- prettier-ignore -->
<script>
$: foo = `${"bar"}baz`
$: bar = [ "bar" ]
$: baz = { qux : true }
</script>
16 changes: 16 additions & 0 deletions tests/src/rules/no-reactive-literals.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { RuleTester } from "eslint"
import rule from "../../../src/rules/no-reactive-literals"
import { loadTestCases } from "../../utils/utils"

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

tester.run(
"no-reactive-literals",
rule as any,
loadTestCases("no-reactive-literals"),
)
18 changes: 18 additions & 0 deletions tests/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ export function loadTestCases(
throw new Error(`Empty code: ${test.filename}`)
}
}

return {
valid,
invalid,
Expand All @@ -155,6 +156,14 @@ function* itrListupInput(rootDir: string): IterableIterator<string> {
}
}

// Necessary because of this:
// https://github.com/eslint/eslint/issues/14936#issuecomment-906746754
function applySuggestion(code: string, suggestion: Linter.LintSuggestion) {
const { fix } = suggestion

return `${code.slice(0, fix.range[0])}${fix.text}${code.slice(fix.range[1])}`
}

function writeFixtures(
ruleName: string,
inputFile: string,
Expand Down Expand Up @@ -184,6 +193,7 @@ function writeFixtures(
},
config.filename,
)

if (force || !fs.existsSync(errorFile)) {
fs.writeFileSync(
errorFile,
Expand All @@ -192,6 +202,14 @@ function writeFixtures(
message: m.message,
line: m.line,
column: m.column,
suggestions: m.suggestions
? m.suggestions.map((s) => ({
desc: s.desc,
messageId: s.messageId,
// Need to have this be the *fixed* output, not just the fix content or anything
output: applySuggestion(config.code, s),
}))
: null,
})),
null,
2,
Expand Down