-
-
Notifications
You must be signed in to change notification settings - Fork 679
Add new rule vue/prefer-separate-static-class
#1729
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
ota-meshi
merged 8 commits into
vuejs:master
from
FloEdelmann:prefer-separate-static-class
Dec 3, 2021
Merged
Changes from 4 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
a441eab
Add new rule `vue/prefer-separate-static-class`
FloEdelmann b5dc1f3
Also find static identifier object keys
FloEdelmann 18ab74b
Add auto-fix
FloEdelmann 4bf2645
Fix removing whole class directive if it's not empty
FloEdelmann bd51d1e
Simplify check with `property.computed`
FloEdelmann ad77407
Change rule type to `suggestion`
FloEdelmann 031ba99
Make rule docs more consistent
FloEdelmann 9ff6b7c
Drop unnecessary `references` parameter
FloEdelmann File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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,43 @@ | ||
--- | ||
pageClass: rule-details | ||
sidebarDepth: 0 | ||
title: vue/prefer-separate-static-class | ||
description: require static class names in template to be in a separate `class` attribute | ||
--- | ||
# vue/prefer-separate-static-class | ||
|
||
> require static class names in template to be in a separate `class` attribute | ||
|
||
- :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 reports static class names in dynamic class attributes. | ||
|
||
<eslint-code-block fix :rules="{'vue/prefer-separate-static-class': ['error']}"> | ||
|
||
```vue | ||
<template> | ||
<!-- FAIL --> | ||
<div :class="'static-class'" /> | ||
<div :class="{'static-class': true, 'dynamic-class': foo}" /> | ||
<div :class="['static-class', dynamicClass]" /> | ||
|
||
<!-- PASS --> | ||
FloEdelmann marked this conversation as resolved.
Show resolved
Hide resolved
|
||
<div class="static-class" /> | ||
<div class="static-class" :class="{'dynamic-class': foo}" /> | ||
<div class="static-class" :class="[dynamicClass]" /> | ||
</template> | ||
``` | ||
|
||
</eslint-code-block> | ||
|
||
## :wrench: Options | ||
|
||
Nothing. | ||
|
||
## :mag: Implementation | ||
|
||
- [Rule source](https://github.com/vuejs/eslint-plugin-vue/blob/master/lib/rules/prefer-separate-static-class.js) | ||
- [Test source](https://github.com/vuejs/eslint-plugin-vue/blob/master/tests/lib/rules/prefer-separate-static-class.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
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,245 @@ | ||
/** | ||
* @author Flo Edelmann | ||
* See LICENSE file in root directory for full license. | ||
*/ | ||
'use strict' | ||
|
||
// ------------------------------------------------------------------------------ | ||
// Requirements | ||
// ------------------------------------------------------------------------------ | ||
|
||
const { defineTemplateBodyVisitor, getStringLiteralValue } = require('../utils') | ||
|
||
// ------------------------------------------------------------------------------ | ||
// Helpers | ||
// ------------------------------------------------------------------------------ | ||
|
||
/** | ||
* @param {ASTNode} node | ||
* @returns {node is Literal | TemplateLiteral} | ||
*/ | ||
function isStringLiteral(node) { | ||
return ( | ||
(node.type === 'Literal' && typeof node.value === 'string') || | ||
(node.type === 'TemplateLiteral' && node.expressions.length === 0) | ||
) | ||
} | ||
|
||
/** | ||
* @param {VReference[]} references | ||
* @param {Identifier} identifier | ||
* @returns {boolean} | ||
*/ | ||
function referencesInclude(references, identifier) { | ||
return references.some((reference) => reference.id === identifier) | ||
} | ||
|
||
/** | ||
* @param {Expression | VForExpression | VOnExpression | VSlotScopeExpression | VFilterSequenceExpression} expressionNode | ||
* @param {VReference[]} references | ||
* @returns {(Literal | TemplateLiteral | Identifier)[]} | ||
*/ | ||
function findStaticClasses(expressionNode, references) { | ||
if (isStringLiteral(expressionNode)) { | ||
return [expressionNode] | ||
} | ||
|
||
if (expressionNode.type === 'ArrayExpression') { | ||
return expressionNode.elements.flatMap((element) => { | ||
if (element === null || element.type === 'SpreadElement') { | ||
return [] | ||
} | ||
return findStaticClasses(element, references) | ||
}) | ||
} | ||
|
||
if (expressionNode.type === 'ObjectExpression') { | ||
return expressionNode.properties.flatMap((property) => { | ||
if ( | ||
property.type === 'Property' && | ||
property.value.type === 'Literal' && | ||
property.value.value === true && | ||
(isStringLiteral(property.key) || | ||
(property.key.type === 'Identifier' && | ||
!referencesInclude(references, property.key))) | ||
FloEdelmann marked this conversation as resolved.
Show resolved
Hide resolved
|
||
) { | ||
return [property.key] | ||
} | ||
return [] | ||
}) | ||
} | ||
|
||
return [] | ||
} | ||
|
||
/** | ||
* @param {VAttribute | VDirective} attributeNode | ||
* @returns {attributeNode is VAttribute & { value: VLiteral }} | ||
*/ | ||
function isStaticClassAttribute(attributeNode) { | ||
return ( | ||
!attributeNode.directive && | ||
attributeNode.key.name === 'class' && | ||
attributeNode.value !== null | ||
) | ||
} | ||
|
||
/** | ||
* Removes the node together with the comma before or after the node. | ||
* @param {RuleFixer} fixer | ||
* @param {ParserServices.TokenStore} tokenStore | ||
* @param {ASTNode} node | ||
*/ | ||
function* removeNodeWithComma(fixer, tokenStore, node) { | ||
const prevToken = tokenStore.getTokenBefore(node) | ||
if (prevToken.type === 'Punctuator' && prevToken.value === ',') { | ||
yield fixer.removeRange([prevToken.range[0], node.range[1]]) | ||
return | ||
} | ||
|
||
const [nextToken, nextNextToken] = tokenStore.getTokensAfter(node, { | ||
count: 2 | ||
}) | ||
if ( | ||
nextToken.type === 'Punctuator' && | ||
nextToken.value === ',' && | ||
(nextNextToken.type !== 'Punctuator' || | ||
(nextNextToken.value !== ']' && nextNextToken.value !== '}')) | ||
) { | ||
yield fixer.removeRange([node.range[0], nextNextToken.range[0]]) | ||
return | ||
} | ||
|
||
yield fixer.remove(node) | ||
} | ||
|
||
// ------------------------------------------------------------------------------ | ||
// Rule Definition | ||
// ------------------------------------------------------------------------------ | ||
|
||
module.exports = { | ||
meta: { | ||
type: 'problem', | ||
FloEdelmann marked this conversation as resolved.
Show resolved
Hide resolved
|
||
docs: { | ||
description: | ||
'require static class names in template to be in a separate `class` attribute', | ||
categories: undefined, | ||
url: 'https://eslint.vuejs.org/rules/prefer-separate-static-class.html' | ||
}, | ||
fixable: 'code', | ||
schema: [], | ||
messages: { | ||
preferSeparateStaticClass: | ||
'Static class "{{className}}" should be in a static `class` attribute.' | ||
} | ||
}, | ||
/** @param {RuleContext} context */ | ||
create(context) { | ||
return defineTemplateBodyVisitor(context, { | ||
/** @param {VDirectiveKey} directiveKeyNode */ | ||
"VAttribute[directive=true] > VDirectiveKey[name.name='bind'][argument.name='class']"( | ||
directiveKeyNode | ||
) { | ||
const attributeNode = directiveKeyNode.parent | ||
if (!attributeNode.value || !attributeNode.value.expression) { | ||
return | ||
} | ||
|
||
const expressionNode = attributeNode.value.expression | ||
const staticClassNameNodes = findStaticClasses( | ||
expressionNode, | ||
attributeNode.value.references | ||
) | ||
|
||
for (const staticClassNameNode of staticClassNameNodes) { | ||
const className = | ||
staticClassNameNode.type === 'Identifier' | ||
? staticClassNameNode.name | ||
: getStringLiteralValue(staticClassNameNode, true) | ||
|
||
if (className === null) { | ||
continue | ||
} | ||
|
||
context.report({ | ||
node: staticClassNameNode, | ||
messageId: 'preferSeparateStaticClass', | ||
data: { className }, | ||
*fix(fixer) { | ||
let dynamicClassDirectiveRemoved = false | ||
|
||
yield* removeFromClassDirective() | ||
yield* addToClassAttribute() | ||
|
||
/** | ||
* Remove class from dynamic `:class` directive. | ||
*/ | ||
function* removeFromClassDirective() { | ||
if (isStringLiteral(expressionNode)) { | ||
yield fixer.remove(attributeNode) | ||
dynamicClassDirectiveRemoved = true | ||
return | ||
} | ||
|
||
const listElement = | ||
staticClassNameNode.parent.type === 'Property' | ||
? staticClassNameNode.parent | ||
: staticClassNameNode | ||
|
||
const listNode = listElement.parent | ||
if ( | ||
listNode.type === 'ArrayExpression' || | ||
listNode.type === 'ObjectExpression' | ||
) { | ||
const elements = | ||
listNode.type === 'ObjectExpression' | ||
? listNode.properties | ||
: listNode.elements | ||
|
||
if (elements.length === 1 && listNode === expressionNode) { | ||
yield fixer.remove(attributeNode) | ||
dynamicClassDirectiveRemoved = true | ||
return | ||
} | ||
|
||
const tokenStore = | ||
context.parserServices.getTemplateBodyTokenStore() | ||
|
||
if (elements.length === 1) { | ||
yield* removeNodeWithComma(fixer, tokenStore, listNode) | ||
return | ||
} | ||
|
||
yield* removeNodeWithComma(fixer, tokenStore, listElement) | ||
} | ||
} | ||
|
||
/** | ||
* Add class to static `class` attribute. | ||
*/ | ||
function* addToClassAttribute() { | ||
const existingStaticClassAttribute = | ||
attributeNode.parent.attributes.find(isStaticClassAttribute) | ||
if (existingStaticClassAttribute) { | ||
const literalNode = existingStaticClassAttribute.value | ||
yield fixer.replaceText( | ||
literalNode, | ||
`"${literalNode.value} ${className}"` | ||
) | ||
return | ||
} | ||
|
||
// new static `class` attribute | ||
const separator = dynamicClassDirectiveRemoved ? '' : ' ' | ||
yield fixer.insertTextBefore( | ||
attributeNode, | ||
`class="${className}"${separator}` | ||
) | ||
} | ||
} | ||
}) | ||
} | ||
} | ||
}) | ||
} | ||
} |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.