Skip to content

Add no-object-in-text-mustaches rule #34

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 1 commit into from
Jun 28, 2021
Merged
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 @@ -246,6 +246,7 @@ These rules relate to possible syntax or logic errors in Svelte code:
| Rule ID | Description | |
|:--------|:------------|:---|
| [@ota-meshi/svelte/no-dupe-else-if-blocks](https://ota-meshi.github.io/eslint-plugin-svelte/rules/no-dupe-else-if-blocks.html) | disallow duplicate conditions in `{#if}` / `{:else if}` chains | :star: |
| [@ota-meshi/svelte/no-object-in-text-mustaches](https://ota-meshi.github.io/eslint-plugin-svelte/rules/no-object-in-text-mustaches.html) | disallow objects in text mustache interpolation | :star: |

## Security Vulnerability

Expand Down
1 change: 1 addition & 0 deletions docs/rules/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ These rules relate to possible syntax or logic errors in Svelte code:
| Rule ID | Description | |
|:--------|:------------|:---|
| [@ota-meshi/svelte/no-dupe-else-if-blocks](./no-dupe-else-if-blocks.md) | disallow duplicate conditions in `{#if}` / `{:else if}` chains | :star: |
| [@ota-meshi/svelte/no-object-in-text-mustaches](./no-object-in-text-mustaches.md) | disallow objects in text mustache interpolation | :star: |

## Security Vulnerability

Expand Down
48 changes: 48 additions & 0 deletions docs/rules/no-object-in-text-mustaches.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
---
pageClass: "rule-details"
sidebarDepth: 0
title: "@ota-meshi/svelte/no-object-in-text-mustaches"
description: "disallow objects in text mustache interpolation"
---

# @ota-meshi/svelte/no-object-in-text-mustaches

> disallow objects in text mustache interpolation

- :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> **_This rule has not been released yet._** </badge>
- :gear: This rule is included in `"plugin:@ota-meshi/svelte/recommended"`.

## :book: Rule Details

This rule disallows the use of objects in text mustache interpolation.
When you use an object for text interpolation, it is drawn as `[object Object]`. It's almost always a mistake. You may have written a lot of unnecessary curly braces.

<eslint-code-block>

<!--eslint-skip-->

```svelte
<script>
/* eslint @ota-meshi/svelte/no-object-in-text-mustaches: "error" */
</script>

<!-- ✓ GOOD -->
{foo}
<input class="{foo} bar" />
<MyComponent prop={{ foo }} />

<!-- ✗ BAD -->
{{ foo }}
<input class="{{ foo }} bar" />
```

</eslint-code-block>

## :wrench: Options

Nothing.

## :mag: Implementation

- [Rule source](https://github.com/ota-meshi/eslint-plugin-svelte/blob/main/src/rules/no-object-in-text-mustaches.ts)
- [Test source](https://github.com/ota-meshi/eslint-plugin-svelte/blob/main/tests/src/rules/no-object-in-text-mustaches.ts)
1 change: 1 addition & 0 deletions src/configs/recommended.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export = {
"@ota-meshi/svelte/no-at-html-tags": "error",
"@ota-meshi/svelte/no-dupe-else-if-blocks": "error",
"@ota-meshi/svelte/no-inner-declarations": "error",
"@ota-meshi/svelte/no-object-in-text-mustaches": "error",
"@ota-meshi/svelte/system": "error",
},
}
6 changes: 5 additions & 1 deletion src/rules/indent-helpers/ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ type AnyToken = AST.Token | AST.Comment
export function isWhitespace(
token: AnyToken | ESTree.Comment | null | undefined,
): boolean {
return token != null && token.type === "HTMLText" && !token.value.trim()
return (
token != null &&
((token.type === "HTMLText" && !token.value.trim()) ||
(token.type === "JSXText" && !token.value.trim()))
)
}

/**
Expand Down
47 changes: 23 additions & 24 deletions src/rules/indent-helpers/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -464,42 +464,41 @@ export function defineVisitor(context: IndentContext): NodeListener {
node: ESTree.FunctionDeclaration | ESTree.FunctionExpression,
) {
const firstToken = sourceCode.getFirstToken(node)
let leftParenToken, bodyBaseToken

const leftParenToken = sourceCode.getTokenBefore(
node.params[0] ||
(node as TSESTree.FunctionExpression).returnType ||
sourceCode.getTokenBefore(node.body),
{
filter: isOpeningParenToken,
includeComments: false,
},
)!
let bodyBaseToken
if (firstToken.type === "Punctuator") {
// method
leftParenToken = firstToken
bodyBaseToken = sourceCode.getFirstToken(getParent(node)!)
} else {
let nextToken = sourceCode.getTokenAfter(firstToken)
let nextTokenOffset = 0
while (
nextToken &&
!isOpeningParenToken(nextToken) &&
nextToken.value !== "<"
) {
let tokenOffset = 0
for (const token of sourceCode.getTokensBetween(
firstToken,
leftParenToken,
)) {
if (token.value === "<") {
break
}
if (
nextToken.value === "*" ||
(node.id && nextToken.range[0] === node.id.range![0])
token.value === "*" ||
(node.id && token.range[0] === node.id.range![0])
) {
nextTokenOffset = 1
tokenOffset = 1
}
offsets.setOffsetToken(nextToken, nextTokenOffset, firstToken)
nextToken = sourceCode.getTokenAfter(nextToken)
offsets.setOffsetToken(token, tokenOffset, firstToken)
}

leftParenToken = nextToken!
bodyBaseToken = firstToken
}

if (
!isOpeningParenToken(leftParenToken) &&
(node as TSESTree.FunctionExpression).typeParameters
) {
leftParenToken = sourceCode.getTokenAfter(
(node as TSESTree.FunctionExpression).typeParameters!,
)!
}

const rightParenToken = sourceCode.getTokenAfter(
node.params[node.params.length - 1] || leftParenToken,
{ filter: isClosingParenToken, includeComments: false },
Expand Down
54 changes: 54 additions & 0 deletions src/rules/no-object-in-text-mustaches.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { createRule } from "../utils"

const PHRASES = {
ObjectExpression: "object",
ArrayExpression: "array",
ArrowFunctionExpression: "function",
FunctionExpression: "function",
ClassExpression: "class",
}

export default createRule("no-object-in-text-mustaches", {
meta: {
docs: {
description: "disallow objects in text mustache interpolation",
category: "Possible Errors",
recommended: true,
},
schema: [],
messages: {
unexpected: "Unexpected {{phrase}} in text mustache interpolation.",
},
type: "problem", // "problem", or "layout",
},
create(context) {
return {
SvelteMustacheTag(node) {
const { expression } = node
if (
expression.type !== "ObjectExpression" &&
expression.type !== "ArrayExpression" &&
expression.type !== "ArrowFunctionExpression" &&
expression.type !== "FunctionExpression" &&
expression.type !== "ClassExpression"
) {
return
}
if (node.parent.type === "SvelteAttribute") {
if (node.parent.value.length === 1) {
// Maybe props
return
}
}

context.report({
node,
messageId: "unexpected",
data: {
phrase: PHRASES[expression.type],
},
})
},
}
},
})
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ type ASTNodeListenerMap<T extends ASTNodeWithParent = ASTNodeWithParent> = {
[key in ASTNodeWithParent["type"]]: T extends { type: key } ? T : never
}

type ASTNodeListener = {
export type ASTNodeListener = {
[T in keyof ASTNodeListenerMap]?: (node: ASTNodeListenerMap[T]) => void
}
export interface RuleListener extends ASTNodeListener {
Expand Down
2 changes: 2 additions & 0 deletions src/utils/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import noAtDebugTags from "../rules/no-at-debug-tags"
import noAtHtmlTags from "../rules/no-at-html-tags"
import noDupeElseIfBlocks from "../rules/no-dupe-else-if-blocks"
import noInnerDeclarations from "../rules/no-inner-declarations"
import noObjectInTextMustaches from "../rules/no-object-in-text-mustaches"
import noTargetBlank from "../rules/no-target-blank"
import noUselessMustaches from "../rules/no-useless-mustaches"
import preferClassDirective from "../rules/prefer-class-directive"
Expand All @@ -25,6 +26,7 @@ export const rules = [
noAtHtmlTags,
noDupeElseIfBlocks,
noInnerDeclarations,
noObjectInTextMustaches,
noTargetBlank,
noUselessMustaches,
preferClassDirective,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[
{
"message": "Unexpected array in text mustache interpolation.",
"line": 5,
"column": 1
},
{
"message": "Unexpected array in text mustache interpolation.",
"line": 6,
"column": 15
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<script>
let a = "hello!"
</script>

{[a]}
<input class="{[a]} a" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[
{
"message": "Unexpected class in text mustache interpolation.",
"line": 4,
"column": 1
},
{
"message": "Unexpected class in text mustache interpolation.",
"line": 6,
"column": 15
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<script>
</script>

{class A {}}

<input class="{class B {}} a" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[
{
"message": "Unexpected function in text mustache interpolation.",
"line": 5,
"column": 1
},
{
"message": "Unexpected function in text mustache interpolation.",
"line": 6,
"column": 1
},
{
"message": "Unexpected function in text mustache interpolation.",
"line": 9,
"column": 15
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script>
let a = "hello!"
</script>

{() => a}
{function () {
return a
}}
<input class="{() => a} a" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[
{
"message": "Unexpected object in text mustache interpolation.",
"line": 5,
"column": 1
},
{
"message": "Unexpected object in text mustache interpolation.",
"line": 6,
"column": 15
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<script>
let a = "hello!"
</script>

{{ a }}
<input class="{{ a }} a" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<script>
import MyComponent from "./MyComponent.svelte"
let a = "hello!"
</script>

<MyComponent prop={{ a }} />
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<script>
let a = "hello!"
</script>

{a}
<input class="{a} a" />
<input class:foo={{ a }} />
16 changes: 16 additions & 0 deletions tests/src/rules/no-object-in-text-mustaches.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-object-in-text-mustaches"
import { loadTestCases } from "../../utils/utils"

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

tester.run(
"no-object-in-text-mustaches",
rule as any,
loadTestCases("no-object-in-text-mustaches"),
)