Skip to content

Add shorthand-directive rule #99

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
Jan 14, 2022
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 @@ -286,6 +286,7 @@ These rules relate to style guidelines, and are therefore quite subjective:
| [@ota-meshi/svelte/prefer-class-directive](https://ota-meshi.github.io/eslint-plugin-svelte/rules/prefer-class-directive/) | require class directives instead of ternary expressions | :wrench: |
| [@ota-meshi/svelte/prefer-style-directive](https://ota-meshi.github.io/eslint-plugin-svelte/rules/prefer-style-directive/) | require style directives instead of style attribute | :wrench: |
| [@ota-meshi/svelte/shorthand-attribute](https://ota-meshi.github.io/eslint-plugin-svelte/rules/shorthand-attribute/) | enforce use of shorthand syntax in attribute | :wrench: |
| [@ota-meshi/svelte/shorthand-directive](https://ota-meshi.github.io/eslint-plugin-svelte/rules/shorthand-directive/) | enforce use of shorthand syntax in directives | :wrench: |
| [@ota-meshi/svelte/spaced-html-comment](https://ota-meshi.github.io/eslint-plugin-svelte/rules/spaced-html-comment/) | enforce consistent spacing after the `<!--` and before the `-->` in a HTML comment | :wrench: |

## Extension Rules
Expand Down
1 change: 1 addition & 0 deletions docs/rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ These rules relate to style guidelines, and are therefore quite subjective:
| [@ota-meshi/svelte/prefer-class-directive](./rules/prefer-class-directive.md) | require class directives instead of ternary expressions | :wrench: |
| [@ota-meshi/svelte/prefer-style-directive](./rules/prefer-style-directive.md) | require style directives instead of style attribute | :wrench: |
| [@ota-meshi/svelte/shorthand-attribute](./rules/shorthand-attribute.md) | enforce use of shorthand syntax in attribute | :wrench: |
| [@ota-meshi/svelte/shorthand-directive](./rules/shorthand-directive.md) | enforce use of shorthand syntax in directives | :wrench: |
| [@ota-meshi/svelte/spaced-html-comment](./rules/spaced-html-comment.md) | enforce consistent spacing after the `<!--` and before the `-->` in a HTML comment | :wrench: |

## Extension Rules
Expand Down
6 changes: 6 additions & 0 deletions docs/rules/shorthand-attribute.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ This rule enforces the use of the shorthand syntax in attribute.
- `"always"` ... Expects that the shorthand will be used whenever possible. This is default.
- `"never"` ... Ensures that no shorthand is used in any attribute.

## :couple: Related Rules

- [@ota-meshi/svelte/shorthand-directive]

[@ota-meshi/svelte/shorthand-directive]: ./shorthand-directive.md

## :rocket: Version

This rule was introduced in @ota-meshi/eslint-plugin-svelte v0.5.0
Expand Down
73 changes: 73 additions & 0 deletions docs/rules/shorthand-directive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
---
pageClass: "rule-details"
sidebarDepth: 0
title: "@ota-meshi/svelte/shorthand-directive"
description: "enforce use of shorthand syntax in directives"
---

# @ota-meshi/svelte/shorthand-directive

> enforce use of shorthand syntax in directives

- :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> **_This rule has not been released yet._** </badge>
- :wrench: The `--fix` option on the [command line](https://eslint.org/docs/user-guide/command-line-interface#fixing-problems) can automatically fix some of the problems reported by this rule.

## :book: Rule Details

This rule enforces the use of the shorthand syntax in directives.

<ESLintCodeBlock fix>

<!-- prettier-ignore-start -->
<!--eslint-skip-->

```svelte
<script>
/* eslint @ota-meshi/svelte/shorthand-directive: "error" */
let value = 'hello!'
let active = true
let color = 'red'
</script>

<!-- ✓ GOOD -->
<input bind:value>
<div class:active>...</div>
<div style:color>...</div>

<!-- ✗ BAD -->
<input bind:value={value}>
<div class:active={active}>...</div>
<div style:color={color}>...</div>
```

<!-- prettier-ignore-end -->

</ESLintCodeBlock>

## :wrench: Options

```json
{
"@ota-meshi/svelte/shorthand-directive": [
"error",
{
"prefer": "always" // "never"
}
]
}
```

- `prefer`
- `"always"` ... Expects that the shorthand will be used whenever possible. This is default.
- `"never"` ... Ensures that no shorthand is used in any directive.

## :couple: Related Rules

- [@ota-meshi/svelte/shorthand-attribute]

[@ota-meshi/svelte/shorthand-attribute]: ./shorthand-directive.md

## :mag: Implementation

- [Rule source](https://github.com/ota-meshi/eslint-plugin-svelte/blob/main/src/rules/shorthand-directive.ts)
- [Test source](https://github.com/ota-meshi/eslint-plugin-svelte/blob/main/tests/src/rules/shorthand-directive.ts)
126 changes: 126 additions & 0 deletions src/rules/shorthand-directive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import type { AST } from "svelte-eslint-parser"
import { createRule } from "../utils"
import { getAttributeValueQuoteAndRange } from "../utils/ast-utils"

export default createRule("shorthand-directive", {
meta: {
docs: {
description: "enforce use of shorthand syntax in directives",
category: "Stylistic Issues",
recommended: false,
},
fixable: "code",
schema: [
{
type: "object",
properties: {
prefer: { enum: ["always", "never"] },
},
additionalProperties: false,
},
],
messages: {
expectedShorthand: "Expected shorthand directive.",
expectedRegular: "Expected regular directive syntax.",
},
type: "layout",
},
create(context) {
const sourceCode = context.getSourceCode()
const always: boolean = context.options[0]?.prefer !== "never"

/** Report for always */
function reportForAlways(
node: AST.SvelteDirective | AST.SvelteStyleDirective,
) {
context.report({
node,
messageId: "expectedShorthand",
*fix(fixer) {
const quoteAndRange = getAttributeValueQuoteAndRange(node, sourceCode)
if (quoteAndRange) {
yield fixer.remove(
sourceCode.getTokenBefore(quoteAndRange.firstToken)!,
)
yield fixer.removeRange(quoteAndRange.range)
}
},
})
}

/** Report for never */
function reportForNever(
node: AST.SvelteDirective | AST.SvelteStyleDirective,
) {
context.report({
node,
messageId: "expectedRegular",
*fix(fixer) {
yield fixer.insertTextAfter(node.key.name, `={${node.key.name.name}}`)
},
})
}

return {
SvelteDirective(node) {
if (node.kind !== "Binding" && node.kind !== "Class") {
return
}

const expression = node.expression
if (!expression) {
// Invalid ?
return
}
if (
expression.type !== "Identifier" ||
node.key.name.name !== expression.name
) {
// Cannot use shorthand
return
}
if (always) {
if (node.key.name.range![0] === expression.range![0]) {
// Use shorthand
return
}
reportForAlways(node)
} else {
if (node.key.name.range![1] < expression.range![0]) {
// Use longform
return
}
reportForNever(node)
}
},
SvelteStyleDirective(node) {
if (always) {
if (node.shorthand) {
// Use shorthand
return
}
if (node.value.length !== 1) {
// Cannot use shorthand
return
}
const expression = node.value[0]
if (
expression.type !== "SvelteMustacheTag" ||
expression.expression.type !== "Identifier" ||
expression.expression.name !== node.key.name.name
) {
// Cannot use shorthand
return
}
reportForAlways(node)
} else {
if (!node.shorthand) {
// Use longform
return
}
reportForNever(node)
}
},
}
},
})
14 changes: 10 additions & 4 deletions src/utils/ast-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,8 @@ export function getScope(
export type QuoteAndRange = {
quote: "unquoted" | "double" | "single"
range: [number, number]
firstToken: SvAST.Token | SvAST.Comment
lastToken: SvAST.Token | SvAST.Comment
}
/** Get the quote and range from given attribute values */
export function getAttributeValueQuoteAndRange(
Expand Down Expand Up @@ -262,6 +264,8 @@ export function getAttributeValueQuoteAndRange(
return {
quote: "unquoted",
range: [valueFirstToken.range[0], valueLastToken.range[1]],
firstToken: valueFirstToken,
lastToken: valueLastToken,
}
} else if (
beforeTokens.length > 1 ||
Expand All @@ -280,6 +284,8 @@ export function getAttributeValueQuoteAndRange(
return {
quote: beforeToken.value === '"' ? "double" : "single",
range: [beforeToken.range[0], afterToken.range[1]],
firstToken: beforeToken,
lastToken: afterToken,
}
}
export function getMustacheTokens(
Expand Down Expand Up @@ -381,11 +387,11 @@ function getAttributeValueRangeTokens(
if (!attr.value.length) {
return null
}
const firstToken = attr.value[0]
const lastToken = attr.value[attr.value.length - 1]
const first = attr.value[0]
const last = attr.value[attr.value.length - 1]
return {
firstToken,
lastToken,
firstToken: sourceCode.getFirstToken(first),
lastToken: sourceCode.getLastToken(last),
}
}
const tokens = getMustacheTokens(attr, sourceCode)
Expand Down
2 changes: 2 additions & 0 deletions src/utils/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import noUselessMustaches from "../rules/no-useless-mustaches"
import preferClassDirective from "../rules/prefer-class-directive"
import preferStyleDirective from "../rules/prefer-style-directive"
import shorthandAttribute from "../rules/shorthand-attribute"
import shorthandDirective from "../rules/shorthand-directive"
import spacedHtmlComment from "../rules/spaced-html-comment"
import system from "../rules/system"
import validCompile from "../rules/valid-compile"
Expand All @@ -46,6 +47,7 @@ export const rules = [
preferClassDirective,
preferStyleDirective,
shorthandAttribute,
shorthandDirective,
spacedHtmlComment,
system,
validCompile,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"options": [{ "prefer": "always" }]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
[
{
"message": "Expected shorthand directive.",
"line": 14,
"column": 8
},
{
"message": "Expected shorthand directive.",
"line": 16,
"column": 6
},
{
"message": "Expected shorthand directive.",
"line": 18,
"column": 6
},
{
"message": "Expected shorthand directive.",
"line": 21,
"column": 6
},
{
"message": "Expected shorthand directive.",
"line": 23,
"column": 6
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<script>
let value = "hello!"
let active = true
let color = "red"
</script>

<!-- ✓ GOOD -->
<input bind:value />
<div class:active>...</div>
<div style:color>...</div>

<!-- ✗ BAD -->
<!-- prettier-ignore -->
<input bind:value={value}>
<!-- prettier-ignore -->
<div class:active={active}>...</div>
<!-- prettier-ignore -->
<div style:color={color}>...</div>

<!-- prettier-ignore -->
<div class:active="{active}">...</div>
<!-- prettier-ignore -->
<div style:color="{color}">...</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<script>
let value = "hello!"
let active = true
let color = "red"
</script>

<!-- ✓ GOOD -->
<input bind:value />
<div class:active>...</div>
<div style:color>...</div>

<!-- ✗ BAD -->
<!-- prettier-ignore -->
<input bind:value>
<!-- prettier-ignore -->
<div class:active>...</div>
<!-- prettier-ignore -->
<div style:color>...</div>

<!-- prettier-ignore -->
<div class:active>...</div>
<!-- prettier-ignore -->
<div style:color>...</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"options": [{ "prefer": "never" }]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[
{
"message": "Expected regular directive syntax.",
"line": 8,
"column": 8
},
{
"message": "Expected regular directive syntax.",
"line": 9,
"column": 6
},
{
"message": "Expected regular directive syntax.",
"line": 10,
"column": 6
}
]
Loading