Skip to content
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/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: |
| [@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: |
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/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: |
| [@ota-meshi/svelte/no-dupe-else-if-blocks](./no-dupe-else-if-blocks.md) | disallow duplicate conditions in `{#if}` / `{:else if}` chains | :star: |
Expand Down
83 changes: 83 additions & 0 deletions docs/rules/max-attributes-per-line.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
---
pageClass: "rule-details"
sidebarDepth: 0
title: "@ota-meshi/svelte/max-attributes-per-line"
description: "enforce the maximum number of attributes per line"
---

# @ota-meshi/svelte/max-attributes-per-line

> enforce the maximum number of attributes per line

- :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

Limits the maximum number of attributes/directives per line to improve readability.

This rule aims to enforce a number of attributes per line in templates.
It checks all the elements in a template and verifies that the number of attributes per line does not exceed the defined maximum.
An attribute is considered to be in a new line when there is a line break between two attributes.

There is a configurable number of attributes that are acceptable in one-line case (default 1), as well as how many attributes are acceptable per line in multi-line case (default 1).

<eslint-code-block fix>

<!--eslint-skip-->

```html
<script>
/* eslint @ota-meshi/svelte/max-attributes-per-line: "error" */
</script>

<!-- ✓ GOOD -->
<input
type="text"
bind:value="{text}"
{maxlength}
{...attrs}
readonly
size="20"
/>
<button
type="button"
on:click="{click}"
{maxlength}
{...attrs}
disabled
data-my-data="foo"
>
CLICK ME!
</button>

<!-- ✗ BAD -->
<input type="text" bind:value="{text}" {maxlength} {...attrs} readonly />
<button type="button" on:click="{click}" {maxlength} {...attrs}>
CLICK ME!
</button>
```

</eslint-code-block>

## :wrench: Options

```json
{
"@ota-meshi/svelte/max-attributes-per-line": [
"error",
{
"multiline": 1,
"singleline": 1
}
]
}
```

- `singleline` ... The number of maximum attributes per line when the opening tag is in a single line. Default is `1`.
- `multiline` ... The number of maximum attributes per line when the opening tag is in multiple lines. Default is `1`.

## :mag: Implementation

- [Rule source](https://github.com/ota-meshi/eslint-plugin-svelte/blob/main/src/rules/max-attributes-per-line.ts)
- [Test source](https://github.com/ota-meshi/eslint-plugin-svelte/blob/main/tests/src/rules/max-attributes-per-line.ts)
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"homepage": "https://github.com/ota-meshi/eslint-plugin-svelte#readme",
"dependencies": {
"debug": "^4.3.1",
"svelte-eslint-parser": "^0.1.0"
"svelte-eslint-parser": "^0.2.0"
},
"peerDependencies": {
"eslint": "^7.0.0",
Expand Down
118 changes: 118 additions & 0 deletions src/rules/max-attributes-per-line.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import type { AST } from "svelte-eslint-parser"
import { createRule } from "../utils"

/**
* Check whether the component is declared in a single line or not.
*/
function isSingleLine(node: AST.SvelteStartTag) {
return node.loc.start.line === node.loc.end.line
}

/**
* Group attributes line by line.
*/
function groupAttributesByLine(attributes: AST.SvelteStartTag["attributes"]) {
const group: AST.SvelteStartTag["attributes"][] = []
for (const attr of attributes) {
if (group[0]?.[0]?.loc.end.line === attr.loc.start.line) {
group[0].push(attr)
} else {
group.unshift([attr])
}
}

return group.reverse()
}

export default createRule("max-attributes-per-line", {
meta: {
docs: {
description: "enforce the maximum number of attributes per line",
recommended: false,
},
fixable: "whitespace",
schema: [
{
type: "object",
properties: {
multiline: {
type: "number",
minimum: 1,
},
singleline: {
type: "number",
minimum: 1,
},
},
additionalProperties: false,
},
],
messages: {
requireNewline: "'{{name}}' should be on a new line.",
},
type: "layout",
},
create(context) {
const multilineMaximum = context.options[0]?.multiline ?? 1
const singlelineMaximum = context.options[0]?.singleline ?? 1
const sourceCode = context.getSourceCode()

/**
* Report attributes
*/
function report(
attribute: AST.SvelteStartTag["attributes"][number] | undefined,
) {
if (!attribute) {
return
}
let name: string
if (
attribute.type === "SvelteAttribute" ||
attribute.type === "SvelteShorthandAttribute" ||
attribute.type === "SvelteDirective" ||
attribute.type === "SvelteSpecialDirective"
) {
name = sourceCode.text.slice(...attribute.key.range!)
} else {
// if (attribute.type === "SvelteSpreadAttribute")
name = sourceCode.text.slice(...attribute.range)
}
context.report({
node: attribute,
loc: attribute.loc,
messageId: "requireNewline",
data: { name },
fix(fixer) {
// Find the closest token before the current attribute
// that is not a white space
const prevToken = sourceCode.getTokenBefore(attribute, {
includeComments: true,
})!

const range: AST.Range = [prevToken.range[1], attribute.range[0]]

return fixer.replaceTextRange(range, "\n")
},
})
}

return {
SvelteStartTag(node) {
const numberOfAttributes = node.attributes.length

if (!numberOfAttributes) return

if (isSingleLine(node)) {
if (numberOfAttributes > singlelineMaximum) {
report(node.attributes[singlelineMaximum])
}
} else {
for (const attrs of groupAttributesByLine(node.attributes)) {
report(attrs[multilineMaximum])
}
}
},
}
},
})
6 changes: 4 additions & 2 deletions src/utils/ast-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,13 +159,15 @@ export function findBindDirective<N extends string>(
name: N,
):
| (SvAST.SvelteBindingDirective & {
name: SvAST.SvelteBindingDirective["name"] & { name: N }
key: SvAST.SvelteDirectiveKey & {
name: SvAST.SvelteDirectiveKey["name"] & { name: N }
}
})
| null {
const startTag = node.type === "SvelteStartTag" ? node : node.startTag
for (const attr of startTag.attributes) {
if (attr.type === "SvelteDirective") {
if (attr.kind === "Binding" && attr.name.name === name) {
if (attr.kind === "Binding" && attr.key.name.name === name) {
return attr as never
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/utils/rules.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { RuleModule } from "../types"
import buttonHasType from "../rules/button-has-type"
import commentDirective from "../rules/comment-directive"
import maxAttributesPerLine from "../rules/max-attributes-per-line"
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"
Expand All @@ -14,6 +15,7 @@ import system from "../rules/system"
export const rules = [
buttonHasType,
commentDirective,
maxAttributesPerLine,
noAtDebugTags,
noAtHtmlTags,
noDupeElseIfBlocks,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"options": [{ "multiline": 3, "singleline": 3 }]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[
{
"message": "'{...attrs}' should be on a new line.",
"line": 8,
"column": 50
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<script>
let text = "abc"
const maxlength = 42
const attrs = { disabled: true }
function click() {}
</script>

<input type="text" bind:value={text} {maxlength} {...attrs} readonly />
<!-- prettier-ignore -->
<button type="button" on:click={click}
{maxlength} {...attrs}>
CLICK ME!
</button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<script>
let text = "abc"
const maxlength = 42
const attrs = { disabled: true }
function click() {}
</script>

<input type="text" bind:value={text} {maxlength}
{...attrs} readonly />
<!-- prettier-ignore -->
<button type="button" on:click={click}
{maxlength} {...attrs}>
CLICK ME!
</button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[
{
"message": "'bind:value' should be on a new line.",
"line": 8,
"column": 20
},
{
"message": "'on:click' should be on a new line.",
"line": 10,
"column": 23
},
{
"message": "'{...attrs}' should be on a new line.",
"line": 11,
"column": 15
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<script>
let text = "abc"
const maxlength = 42
const attrs = { disabled: true }
function click() {}
</script>

<input type="text" bind:value={text} {maxlength} {...attrs} readonly />
<!-- prettier-ignore -->
<button type="button" on:click={click}
{maxlength} {...attrs}>
CLICK ME!
</button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<script>
let text = "abc"
const maxlength = 42
const attrs = { disabled: true }
function click() {}
</script>

<input type="text"
bind:value={text} {maxlength} {...attrs} readonly />
<!-- prettier-ignore -->
<button type="button"
on:click={click}
{maxlength}
{...attrs}>
CLICK ME!
</button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<script>
let text = "abc"
const maxlength = 42
const attrs = { disabled: true }
function click() {}
</script>

<!-- prettier-ignore -->
<input
type="text"
bind:value={text}
{maxlength}
{...attrs}
readonly />
<!-- prettier-ignore -->
<button
type="button"
on:click={click}
{maxlength}
{...attrs}>
CLICK ME!
</button>
16 changes: 16 additions & 0 deletions tests/src/rules/max-attributes-per-line.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { RuleTester } from "eslint"
import rule from "../../../src/rules/max-attributes-per-line"
import { loadTestCases } from "../../utils/utils"

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

tester.run(
"max-attributes-per-line",
rule as any,
loadTestCases("max-attributes-per-line"),
)