Skip to content

Commit

Permalink
fix(eslint-plugin-template): [prefer-self-closing-tags] improve code …
Browse files Browse the repository at this point in the history
…style of fixer result (#1520)
  • Loading branch information
json-derulo committed Sep 16, 2023
1 parent 470e12b commit 6a86f19
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,37 @@ The rule does not have any configuration options.
~~~~~~~~~~~~~~~
```

<br>

---

<br>

#### Default Config

```json
{
"rules": {
"@angular-eslint/template/prefer-self-closing-tags": [
"error"
]
}
}
```

<br>

#### ❌ Invalid Code

```html
<my-component
type="text"
[name]="foo"
[items]="items"
></my-component>
~~~~~~~~~~~~~~~
```

</details>

<br>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,19 @@ export default createESLintRule<[], typeof MESSAGE_ID>({
return;
}

// HTML tags always have more than two characters
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const openingTagLastChar = startSourceSpan.toString().at(-2)!;
const hasOwnWhitespace = openingTagLastChar.trim() === '';
const closingTagPrefix = hasOwnWhitespace ? '' : ' ';

context.report({
loc: parserServices.convertNodeSourceSpanToLoc(endSourceSpan),
messageId: MESSAGE_ID,
fix: (fixer) =>
fixer.replaceTextRange(
[startSourceSpan.end.offset - 1, endSourceSpan.end.offset],
' />',
closingTagPrefix + '/>',
),
});
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,25 @@ export const invalid = [
`,
messageId,
}),
convertAnnotatedSourceToFailureCase({
description:
'it should fail if the opening and closing tag are on the same new line',
annotatedSource: `
<my-component
type="text"
[name]="foo"
[items]="items"
></my-component>
~~~~~~~~~~~~~~~
`,
annotatedOutput: `
<my-component
type="text"
[name]="foo"
[items]="items"
/>
`,
messageId,
}),
];

0 comments on commit 6a86f19

Please sign in to comment.