Skip to content

Add indent rule #29

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 2 commits into from
Jun 20, 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 @@ -243,6 +243,7 @@ The rules with the following star :star: are included in the configs.
|:--------|:------------|:---|
| [@ota-meshi/svelte/button-has-type](https://ota-meshi.github.io/eslint-plugin-svelte/rules/button-has-type.html) | disallow usage of button without an explicit type attribute | |
| [@ota-meshi/svelte/comment-directive](https://ota-meshi.github.io/eslint-plugin-svelte/rules/comment-directive.html) | support comment-directives in HTML template | :star: |
| [@ota-meshi/svelte/indent](https://ota-meshi.github.io/eslint-plugin-svelte/rules/indent.html) | enforce consistent indentation | :wrench: |
| [@ota-meshi/svelte/max-attributes-per-line](https://ota-meshi.github.io/eslint-plugin-svelte/rules/max-attributes-per-line.html) | enforce the maximum number of attributes per line | :wrench: |
| [@ota-meshi/svelte/no-at-debug-tags](https://ota-meshi.github.io/eslint-plugin-svelte/rules/no-at-debug-tags.html) | disallow the use of `{@debug}` | :star: |
| [@ota-meshi/svelte/no-at-html-tags](https://ota-meshi.github.io/eslint-plugin-svelte/rules/no-at-html-tags.html) | disallow use of `{@html}` to prevent XSS attack | :star: |
Expand Down
1 change: 1 addition & 0 deletions docs/rules/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ The rules with the following star :star: are included in the `plugin:@ota-meshi/
|:--------|:------------|:---|
| [@ota-meshi/svelte/button-has-type](./button-has-type.md) | disallow usage of button without an explicit type attribute | |
| [@ota-meshi/svelte/comment-directive](./comment-directive.md) | support comment-directives in HTML template | :star: |
| [@ota-meshi/svelte/indent](./indent.md) | enforce consistent indentation | :wrench: |
| [@ota-meshi/svelte/max-attributes-per-line](./max-attributes-per-line.md) | enforce the maximum number of attributes per line | :wrench: |
| [@ota-meshi/svelte/no-at-debug-tags](./no-at-debug-tags.md) | disallow the use of `{@debug}` | :star: |
| [@ota-meshi/svelte/no-at-html-tags](./no-at-html-tags.md) | disallow use of `{@html}` to prevent XSS attack | :star: |
Expand Down
75 changes: 75 additions & 0 deletions docs/rules/indent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
---
pageClass: "rule-details"
sidebarDepth: 0
title: "@ota-meshi/svelte/indent"
description: "enforce consistent indentation"
---

# @ota-meshi/svelte/indent

> enforce consistent indentation

- :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 a consistent indentation style in `.svelte`. The default style is 2 spaces.

- This rule checks all tags, also all expressions in directives and mustaches.
- In the expressions, this rule supports ECMAScript 2020 syntaxes. It ignores unknown AST nodes, but it might be confused by non-standard syntaxes.

<eslint-code-block fix>

<!--eslint-skip-->
<!-- prettier-ignore -->
```html
<script>
/* eslint @ota-meshi/svelte/indent: "error" */
function click() {}
</script>

<!-- ✓ GOOD -->
<button
type="button"
on:click="{click}"
class="my-button primally"
>
CLICK ME!
</button>

<!-- ✗ BAD -->
<button
type="button"
on:click="{click}"
class="my-button primally"
>
CLICK ME!
</button>
```

</eslint-code-block>

## :wrench: Options

```json
{
"@ota-meshi/svelte/indent": [
"error",
{
"indent": 2,
"ignoredNodes": [],
"switchCase": 1
}
]
}
```

- `indent` (`number | "tab"`) ... The type of indentation. Default is `2`. If this is a number, it's the number of spaces for one indent. If this is `"tab"`, it uses one tab for one indent.
- `ignoredNodes` ... Can be used to disable indentation checking for any AST node. This accepts an array of [selectors](https://eslint.org/docs/developer-guide/selectors). If an AST node is matched by any of the selectors, the indentation of tokens which are direct children of that node will be ignored. This can be used as an escape hatch to relax the rule if you disagree with the indentation that it enforces for a particular syntactic pattern.
- `switchCase` ... Enforces indentation level for case clauses in switch statements. Default is `1`.

## :mag: Implementation

- [Rule source](https://github.com/ota-meshi/eslint-plugin-svelte/blob/main/src/rules/indent.ts)
- [Test source](https://github.com/ota-meshi/eslint-plugin-svelte/blob/main/tests/src/rules/indent.ts)
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"homepage": "https://github.com/ota-meshi/eslint-plugin-svelte#readme",
"dependencies": {
"debug": "^4.3.1",
"eslint-utils": "^3.0.0",
"svelte-eslint-parser": "^0.3.0"
},
"peerDependencies": {
Expand Down
22 changes: 22 additions & 0 deletions src/rules/indent-helpers/ast.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { AST } from "svelte-eslint-parser"
import type * as ESTree from "estree"
type AnyToken = AST.Token | AST.Comment
/**
* Check whether the given token is a whitespace.
*/
export function isWhitespace(
token: AnyToken | ESTree.Comment | null | undefined,
): boolean {
return token != null && token.type === "HTMLText" && !token.value.trim()
}

/**
* Check whether the given token is a not whitespace.
*/
export function isNotWhitespace(
token: AnyToken | ESTree.Comment | null | undefined,
): boolean {
return (
token != null && (token.type !== "HTMLText" || Boolean(token.value.trim()))
)
}
135 changes: 135 additions & 0 deletions src/rules/indent-helpers/commons.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import type { ASTNode, SourceCode } from "../../types"
import type { AST } from "svelte-eslint-parser"
import { isOpeningParenToken, isClosingParenToken } from "eslint-utils"
import { isNotWhitespace, isWhitespace } from "./ast"

type AnyToken = AST.Token | AST.Comment

export type IndentOptions = {
indentChar: " " | "\t"
indentSize: number
switchCase: number
ignoredNodes: string[]
}
export type IndentContext = {
sourceCode: SourceCode
options: IndentOptions
/**
* Set offset to the given tokens.
*/
setOffset: (
token: AnyToken | null | undefined | (AnyToken | null | undefined)[],
offset: number,
baseToken: AnyToken,
) => void
/**
* Copy offset to the given tokens from srcToken.
*/
copyOffset: (
token: AnyToken | null | undefined | (AnyToken | null | undefined)[],
srcToken: AnyToken,
) => void

/**
* Set baseline offset to the given token.
*/
setOffsetBaseLine: (
token: AnyToken | null | undefined | (AnyToken | null | undefined)[],
offset: number,
) => void
/**
* Ignore all tokens of the given node.
*/
ignore: (node: ASTNode) => void
}

/**
* Set offset to the given nodes.
* The first node is offsetted from the given base token.
*/
export function setOffsetNodes(
{ sourceCode, setOffset }: IndentContext,
nodes: (ASTNode | AnyToken | null | undefined)[],
baseNodeOrToken: ASTNode | AnyToken,
lastNodeOrToken: ASTNode | AnyToken | null,
offset: number,
): void {
const baseToken = sourceCode.getFirstToken(baseNodeOrToken)

let prevToken = sourceCode.getLastToken(baseNodeOrToken)
for (const node of nodes) {
if (node == null) {
continue
}
const elementTokens = getFirstAndLastTokens(
sourceCode,
node,
prevToken.range[1],
)

let t: AnyToken | null = prevToken
while (
(t = sourceCode.getTokenAfter(t, {
includeComments: true,
filter: isNotWhitespace,
})) != null &&
t.range[1] <= elementTokens.firstToken.range[0]
) {
setOffset(t, offset, baseToken)
}
setOffset(elementTokens.firstToken, offset, baseToken)

prevToken = elementTokens.lastToken
}

if (lastNodeOrToken) {
const lastToken = sourceCode.getFirstToken(lastNodeOrToken)
let t: AnyToken | null = prevToken
while (
(t = sourceCode.getTokenAfter(t, {
includeComments: true,
filter: isNotWhitespace,
})) != null &&
t.range[1] <= lastToken.range[0]
) {
setOffset(t, offset, baseToken)
}
setOffset(lastToken, 0, baseToken)
}
}

/**
* Get the first and last tokens of the given node.
* If the node is parenthesized, this gets the outermost parentheses.
* If the node have whitespace at the start and the end, they will be skipped.
*/
export function getFirstAndLastTokens(
sourceCode: SourceCode,
node: ASTNode | AnyToken,
borderOffset = 0,
): { firstToken: AST.Token; lastToken: AST.Token } {
let firstToken = sourceCode.getFirstToken(node)
let lastToken = sourceCode.getLastToken(node)

// Get the outermost left parenthesis if it's parenthesized.
let left: AST.Token | null, right: AST.Token | null
while (
(left = sourceCode.getTokenBefore(firstToken)) != null &&
(right = sourceCode.getTokenAfter(lastToken)) != null &&
isOpeningParenToken(left) &&
isClosingParenToken(right) &&
borderOffset <= left.range[0]
) {
firstToken = left
lastToken = right
}

while (isWhitespace(firstToken) && firstToken.range[0] < lastToken.range[0]) {
firstToken = sourceCode.getTokenAfter(firstToken) as AST.Token
}
while (isWhitespace(lastToken) && firstToken.range[0] < lastToken.range[0]) {
lastToken = sourceCode.getTokenBefore(lastToken) as AST.Token
}

return { firstToken, lastToken }
}
Loading