Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork688
Addvue/no-negated-v-if-condition
rule#2794
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Open
waynzh wants to merge12 commits intomasterChoose a base branch fromfeature/np-negated-condition
base:master
Could not load branches
Branch not found:{{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline, and old review comments may become outdated.
Uh oh!
There was an error while loading.Please reload this page.
Open
Changes fromall commits
Commits
Show all changes
12 commits Select commitHold shift + click to select a range
b30c051
Add `vue/no-negated-condition` rule
waynzhc7ded94
docs: update
waynzh1736e0a
Merge branch 'master' of github.com:vuejs/eslint-plugin-vue into feat…
waynzhecbd456
test: update
waynzh7919d9e
chore: update name
waynzhf215f13
feat: support suggestions
waynzhbf707fc
docs: update link
waynzh74b50e7
chore: add changeset
waynzh6f3ef44
Update .changeset/early-worlds-reply.md
waynzh1c79cda
Merge branch 'master' of github.com:vuejs/eslint-plugin-vue into feat…
waynzh73afcea
docs: update links
waynzhfa09bb8
Update lib/rules/no-negated-v-if-condition.js
waynzhFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
5 changes: 5 additions & 0 deletions.changeset/early-worlds-reply.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
'eslint-plugin-vue': minor | ||
--- | ||
Added new [`vue/no-negated-v-if-condition`](https://eslint.vuejs.org/rules/no-negated-v-if-condition.html) rule |
2 changes: 2 additions & 0 deletionsdocs/rules/index.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
1 change: 1 addition & 0 deletionsdocs/rules/no-negated-condition.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
64 changes: 64 additions & 0 deletionsdocs/rules/no-negated-v-if-condition.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
--- | ||
pageClass: rule-details | ||
sidebarDepth: 0 | ||
title: vue/no-negated-v-if-condition | ||
description: disallow negated conditions in v-if/v-else | ||
--- | ||
# vue/no-negated-v-if-condition | ||
waynzh marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
> disallow negated conditions in v-if/v-else | ||
- :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> _**This rule has not been released yet.**_ </badge> | ||
- :bulb: Some problems reported by this rule are manually fixable by editor [suggestions](https://eslint.org/docs/developer-guide/working-with-rules#providing-suggestions). | ||
## :book: Rule Details | ||
This rule disallows negated conditions in `v-if` and `v-else-if` directives which have an `v-else` branch. | ||
Negated conditions make the code less readable. When there's an `else` clause, it's better to use a positive condition and switch the branches. | ||
<eslint-code-block :rules="{'vue/no-negated-v-if-condition': ['error']}"> | ||
```vue | ||
<template> | ||
<!-- ✓ GOOD --> | ||
<div v-if="foo">First</div> | ||
<div v-else>Second</div> | ||
<div v-if="!foo">First</div> | ||
<div v-else-if="bar">Second</div> | ||
<div v-if="!foo">Content</div> | ||
<div v-if="a !== b">Not equal</div> | ||
<!-- ✗ BAD --> | ||
<div v-if="!foo">First</div> | ||
<div v-else>Second</div> | ||
<div v-if="a !== b">First</div> | ||
<div v-else>Second</div> | ||
<div v-if="foo">First</div> | ||
<div v-else-if="!bar">Second</div> | ||
<div v-else>Third</div> | ||
</template> | ||
``` | ||
</eslint-code-block> | ||
## :wrench: Options | ||
Nothing. | ||
## :couple: Related Rules | ||
FloEdelmann marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
- [no-negated-condition](https://eslint.org/docs/latest/rules/no-negated-condition) | ||
- [vue/no-negated-condition](https://eslint.vuejs.org/rules/no-negated-condition.html) | ||
- [unicorn/no-negated-condition](https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-negated-condition.md) | ||
## :mag: Implementation | ||
- [Rule source](https://github.com/vuejs/eslint-plugin-vue/blob/master/lib/rules/no-negated-v-if-condition.js) | ||
- [Test source](https://github.com/vuejs/eslint-plugin-vue/blob/master/tests/lib/rules/no-negated-v-if-condition.js) |
1 change: 1 addition & 0 deletionslib/index.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
204 changes: 204 additions & 0 deletionslib/rules/no-negated-v-if-condition.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,204 @@ | ||
/** | ||
* @author Wayne Zhang | ||
* See LICENSE file in root directory for full license. | ||
*/ | ||
'use strict' | ||
const utils = require('../utils') | ||
/** | ||
* @typedef { VDirective & { value: (VExpressionContainer & { expression: Expression | null } ) | null } } VIfDirective | ||
*/ | ||
/** | ||
* @param {Expression} expression | ||
* @returns {boolean} | ||
*/ | ||
function isNegatedExpression(expression) { | ||
return ( | ||
(expression.type === 'UnaryExpression' && expression.operator === '!') || | ||
(expression.type === 'BinaryExpression' && | ||
(expression.operator === '!=' || expression.operator === '!==')) | ||
) | ||
} | ||
/** | ||
* @param {VElement} node | ||
* @returns {VElement|null} | ||
*/ | ||
function getNextSibling(node) { | ||
if (!node.parent?.children) { | ||
return null | ||
} | ||
const siblings = node.parent.children | ||
const currentIndex = siblings.indexOf(node) | ||
for (let i = currentIndex + 1; i < siblings.length; i++) { | ||
const sibling = siblings[i] | ||
if (sibling.type === 'VElement') { | ||
return sibling | ||
} | ||
} | ||
return null | ||
} | ||
/** | ||
* @param {VElement} element | ||
* @returns {boolean} | ||
*/ | ||
function isDirectlyFollowedByElse(element) { | ||
const nextElement = getNextSibling(element) | ||
return nextElement ? utils.hasDirective(nextElement, 'else') : false | ||
} | ||
module.exports = { | ||
meta: { | ||
type: 'suggestion', | ||
docs: { | ||
description: 'disallow negated conditions in v-if/v-else', | ||
categories: undefined, | ||
url: 'https://eslint.vuejs.org/rules/no-negated-v-if-condition.html' | ||
}, | ||
fixable: null, | ||
hasSuggestions: true, | ||
schema: [], | ||
messages: { | ||
negatedCondition: 'Unexpected negated condition in v-if with v-else.', | ||
fixNegatedCondition: | ||
'Convert to positive condition and swap if/else blocks.' | ||
} | ||
}, | ||
/** @param {RuleContext} context */ | ||
create(context) { | ||
const sourceCode = context.getSourceCode() | ||
const templateTokens = | ||
sourceCode.parserServices.getTemplateBodyTokenStore && | ||
sourceCode.parserServices.getTemplateBodyTokenStore() | ||
/** | ||
* @param {VIfDirective} node | ||
*/ | ||
function checkNegatedCondition(node) { | ||
if (!node.value?.expression) { | ||
return | ||
} | ||
const expression = node.value.expression | ||
const element = node.parent.parent | ||
if ( | ||
!isNegatedExpression(expression) || | ||
!isDirectlyFollowedByElse(element) | ||
) { | ||
return | ||
} | ||
const elseElement = getNextSibling(element) | ||
if (!elseElement) { | ||
return | ||
} | ||
context.report({ | ||
node: expression, | ||
messageId: 'negatedCondition', | ||
suggest: [ | ||
{ | ||
messageId: 'fixNegatedCondition', | ||
*fix(fixer) { | ||
yield* convertNegatedCondition(fixer, expression) | ||
yield* swapElementContents(fixer, element, elseElement) | ||
} | ||
} | ||
] | ||
}) | ||
} | ||
/** | ||
* @param {RuleFixer} fixer | ||
* @param {Expression} expression | ||
*/ | ||
function* convertNegatedCondition(fixer, expression) { | ||
if ( | ||
expression.type === 'UnaryExpression' && | ||
expression.operator === '!' | ||
) { | ||
const token = templateTokens.getFirstToken(expression) | ||
if (token?.type === 'Punctuator' && token.value === '!') { | ||
yield fixer.remove(token) | ||
} | ||
return | ||
} | ||
if (expression.type === 'BinaryExpression') { | ||
const operatorToken = templateTokens.getTokenAfter( | ||
expression.left, | ||
(token) => | ||
token?.type === 'Punctuator' && token.value === expression.operator | ||
) | ||
if (!operatorToken) return | ||
if (expression.operator === '!=') { | ||
yield fixer.replaceText(operatorToken, '==') | ||
} else if (expression.operator === '!==') { | ||
yield fixer.replaceText(operatorToken, '===') | ||
} | ||
} | ||
} | ||
/** | ||
* @param {VElement} element | ||
* @returns {string} | ||
*/ | ||
function getElementContent(element) { | ||
if (element.children.length === 0 || !element.endTag) { | ||
return '' | ||
} | ||
const contentStart = element.startTag.range[1] | ||
const contentEnd = element.endTag.range[0] | ||
return sourceCode.text.slice(contentStart, contentEnd) | ||
} | ||
/** | ||
* @param {RuleFixer} fixer | ||
* @param {VElement} ifElement | ||
* @param {VElement} elseElement | ||
*/ | ||
function* swapElementContents(fixer, ifElement, elseElement) { | ||
if (!ifElement.endTag || !elseElement.endTag) { | ||
return | ||
} | ||
const ifContent = getElementContent(ifElement) | ||
const elseContent = getElementContent(elseElement) | ||
if (ifContent === elseContent) { | ||
return | ||
} | ||
yield fixer.replaceTextRange( | ||
[ifElement.startTag.range[1], ifElement.endTag.range[0]], | ||
elseContent | ||
) | ||
yield fixer.replaceTextRange( | ||
[elseElement.startTag.range[1], elseElement.endTag.range[0]], | ||
ifContent | ||
) | ||
} | ||
return utils.defineTemplateBodyVisitor(context, { | ||
/** @param {VIfDirective} node */ | ||
"VAttribute[directive=true][key.name.name='if']"(node) { | ||
checkNegatedCondition(node) | ||
}, | ||
/** @param {VIfDirective} node */ | ||
"VAttribute[directive=true][key.name.name='else-if']"(node) { | ||
checkNegatedCondition(node) | ||
} | ||
}) | ||
} | ||
} |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.