-
-
Notifications
You must be signed in to change notification settings - Fork 681
Require key for conditionally rendered repeated components #2280
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 30 commits into
vuejs:master
from
felipemelendez:require-key-for-conditionally-rendered-repeated-components
Nov 30, 2023
Merged
Changes from 16 commits
Commits
Show all changes
30 commits
Select commit
Hold shift + click to select a range
76ae5c7
create rule
felipemelendez 11769be
create tests
felipemelendez 7899246
add docs
felipemelendez a02a577
fix spacing
felipemelendez b7a7cbb
slots are abstract outlets and can possibly expand into multiple elem…
felipemelendez 17323fa
add test for slot exclusion
felipemelendez a5d7879
use more efficient Set rather than Array
felipemelendez 308e2a1
change vue 3 to vue 2
felipemelendez 0daeb91
target custom components
felipemelendez c4871c6
rename
felipemelendez 4aac97a
Merge branch 'master' into require-key-for-conditionally-rendered-rep…
felipemelendez 88d57d4
proper name updating
felipemelendez 4515954
Merge remote-tracking branch 'origin/require-key-for-conditionally-re…
felipemelendez c659339
removed references to html container elements
felipemelendez c89efd8
added test
felipemelendez 1f81ded
Merge branch 'master' into require-key-for-conditionally-rendered-rep…
felipemelendez d1b5039
add valid test case
felipemelendez fdd59a5
add Related rule link to require-v-for-key and vice-versa
felipemelendez 92bdc2f
remove md extension from brackets
felipemelendez 3212653
turned off formatting settings so I can submit this - changing the th…
felipemelendez 1206bbd
make if attribute required and finetune docstrings
felipemelendez 8da18db
fix type
felipemelendez a8709d7
fix condition
felipemelendez f039fb7
use double quotes
felipemelendez 2ff3a5f
fix conditional family completeness logic and add test
felipemelendez 608b4b9
reform helper function - exists only to ease code readability
felipemelendez 42500ce
inline logic for conditional family formation
felipemelendez 51cef47
match test file name with rule name
felipemelendez e6d5c92
move conditionalFamilies map into create function
felipemelendez ceab4c3
Merge branch 'master' into require-key-for-conditionally-rendered-rep…
felipemelendez 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,49 @@ | ||
--- | ||
pageClass: rule-details | ||
sidebarDepth: 0 | ||
title: vue/v-if-else-key | ||
description: require key attribute for conditionally rendered repeated components | ||
--- | ||
# vue/v-if-else-key | ||
|
||
> require key attribute for conditionally rendered repeated components | ||
|
||
- :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 checks for components that are both repeated and conditionally rendered within the same scope. If such a component is found, the rule then checks for the presence of a 'key' directive. If the 'key' directive is missing, the rule issues a warning and offers a fix. | ||
|
||
This rule is not required in Vue 3, as the key is automatically assigned to the elements. | ||
|
||
<eslint-code-block fix :rules="{'vue/v-if-else-key': ['error']}"> | ||
|
||
```vue | ||
<template> | ||
<!-- ✓ GOOD --> | ||
<my-component v-if="condition1" :key="one" /> | ||
<my-component v-else-if="condition2" :key="two" /> | ||
<my-component v-else :key="three" /> | ||
|
||
<!-- ✗ BAD --> | ||
<my-component v-if="condition1" /> | ||
<my-component v-else-if="condition2" /> | ||
<my-component v-else /> | ||
</template> | ||
``` | ||
|
||
</eslint-code-block> | ||
|
||
## :wrench: Options | ||
|
||
Nothing. | ||
|
||
## :books: Further Reading | ||
|
||
- [Guide (for v2) - v-if without key](https://v2.vuejs.org/v2/style-guide/#v-if-v-else-if-v-else-without-key-use-with-caution) | ||
|
||
## :mag: Implementation | ||
|
||
- [Rule source](https://github.com/vuejs/eslint-plugin-vue/blob/master/lib/rules/v-if-else-key.js) | ||
- [Test source](https://github.com/vuejs/eslint-plugin-vue/blob/master/tests/lib/rules/v-if-else-key.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,311 @@ | ||
/** | ||
* @author Felipe Melendez | ||
* See LICENSE file in root directory for full license. | ||
*/ | ||
'use strict' | ||
|
||
// ============================================================================= | ||
// Requirements | ||
// ============================================================================= | ||
|
||
const utils = require('../utils') | ||
const casing = require('../utils/casing') | ||
|
||
// ============================================================================= | ||
// Constants and Variables | ||
// ============================================================================= | ||
|
||
/** | ||
* Map to store conditionally rendered components and their respective conditional directives. | ||
* | ||
* A conditional family is a group of components that are conditionally rendered using v-if, v-else-if, and v-else. | ||
* This data structure helps track and manage the relation of such components with one another. | ||
* | ||
* This map links a parent node to its associated conditional family, representing | ||
* the relationship between different parts of a Vue conditional rendering chain | ||
* (v-if, v-else-if, v-else). Each entry in the map associates a parent node | ||
* (representing the scope of the conditional family) with an object that tracks | ||
* the nodes for each part of the conditional chain: | ||
* | ||
* - 'if': Represents the node associated with the 'v-if' directive. | ||
* - 'elseIf': An array representing nodes associated with any 'v-else-if' directives. | ||
* - 'else': Represents the node associated with the 'v-else' directive. | ||
* | ||
* This structure helps in understanding the relationship between conditional directives | ||
* within a given scope and aids in linting scenarios where these relationships matter. | ||
* | ||
* @type {Map<VElement, { if: VElement | null, elseIf: VElement[], else: VElement | null }>} | ||
FloEdelmann marked this conversation as resolved.
Show resolved
Hide resolved
|
||
*/ | ||
const conditionalFamilies = new Map() | ||
ota-meshi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// ============================================================================= | ||
// Rule Helpers | ||
// ============================================================================= | ||
|
||
/** | ||
* Checks for the presence of a 'key' attribute in the given Vue component node. If the | ||
* 'key' attribute is missing and the node is part of a conditional family (like v-if, v-else-if, or v-else), | ||
* a report is generated. The fix proposed adds a unique key based on the component's name | ||
* and count, following the format '${kebabCase(componentName)}-${componentCount}', e.g., 'some-component-2'. | ||
* | ||
* @param {VElement} node - The Vue component node to check for a 'key' attribute. | ||
* @param {RuleContext} context - The rule's context object, used for reporting. | ||
* @param {string} componentName - Name of the component. | ||
* @param {string} uniqueKey - A unique key for the repeated component, used for the fix. | ||
*/ | ||
const checkForKey = (node, context, componentName, uniqueKey) => { | ||
if (node.parent && node.parent.type === 'VElement') { | ||
const conditionalFamily = conditionalFamilies.get(node.parent) | ||
|
||
if ( | ||
conditionalFamily && | ||
(utils.hasDirective(node, 'bind', 'key') || | ||
utils.hasAttribute(node, 'key') || | ||
!hasConditionalDirective(node) || | ||
!isConditionalFamilyComplete(conditionalFamily)) | ||
) { | ||
return | ||
} | ||
|
||
context.report({ | ||
node: node.startTag, | ||
loc: node.startTag.loc, | ||
messageId: 'requireKey', | ||
data: { | ||
componentName | ||
}, | ||
fix(fixer) { | ||
const afterComponentNamePosition = | ||
node.startTag.range[0] + componentName.length + 1 | ||
return fixer.insertTextBeforeRange( | ||
[afterComponentNamePosition, afterComponentNamePosition], | ||
` key='${uniqueKey}'` | ||
FloEdelmann marked this conversation as resolved.
Show resolved
Hide resolved
|
||
) | ||
} | ||
}) | ||
} | ||
} | ||
|
||
/** | ||
* Checks for the presence of conditional directives such as 'v-if', 'v-else-if', or 'v-else' in the | ||
* given Vue component node. | ||
* | ||
* @param {VElement} node - The node to check for conditional directives. | ||
* @returns {boolean} Returns true if a conditional directive is found in the node or its parents, | ||
* false otherwise. | ||
*/ | ||
const hasConditionalDirective = (node) => | ||
utils.hasDirective(node, 'if') || | ||
utils.hasDirective(node, 'else-if') || | ||
utils.hasDirective(node, 'else') | ||
|
||
/** | ||
* Checks whether a conditional family (comprising of 'if', 'else-if', and 'else' conditions) is complete. | ||
* A conditional family is considered complete if: | ||
* 1. An 'if' condition is present. | ||
* 2. All elements of the family (if, else, else-if) share the same rawName. | ||
FloEdelmann marked this conversation as resolved.
Show resolved
Hide resolved
|
||
* 3. There exists either an 'else' condition or at least one 'else-if' condition. | ||
* | ||
* @param {{ if: VElement | null, elseIf: VElement[], else: VElement | null }} family - The conditional family object with 'if', 'else-if', and 'else' properties. | ||
* @returns {boolean} True if the conditional family is complete based on the above criteria, false otherwise. | ||
*/ | ||
const isConditionalFamilyComplete = (family) => { | ||
FloEdelmann marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (!family || !family.if) { | ||
FloEdelmann marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return false | ||
} | ||
const familyComponentName = family.if.rawName | ||
if (family.else && family.else.rawName !== familyComponentName) { | ||
return false | ||
} | ||
if (family.elseIf.some((node) => node.rawName !== familyComponentName)) { | ||
return false | ||
} | ||
return Boolean(family.else || family.elseIf.length > 0) | ||
} | ||
|
||
// ============================================================================= | ||
// Rule Definition | ||
// ============================================================================= | ||
|
||
/** @type {import('eslint').Rule.RuleModule} */ | ||
module.exports = { | ||
meta: { | ||
type: 'problem', | ||
docs: { | ||
description: | ||
'require key attribute for conditionally rendered repeated components', | ||
categories: null, | ||
recommended: false, | ||
url: 'https://eslint.vuejs.org/rules/v-if-else-key.html' | ||
}, | ||
fixable: 'code', | ||
schema: [], | ||
messages: { | ||
requireKey: | ||
"Conditionally rendered repeated component '{{componentName}}' expected to have a 'key' attribute." | ||
} | ||
}, | ||
/** | ||
* Creates and returns a rule object which checks usage of repeated components. If a component | ||
* is used more than once, it checks for the presence of a key. | ||
* | ||
* @param {RuleContext} context - The context object. | ||
* @returns {Object} A dictionary of functions to be called on traversal of the template body by | ||
* the eslint parser. | ||
*/ | ||
create(context) { | ||
/** | ||
* Array of Maps to keep track of components and their usage counts along with the first | ||
* node instance. Each Map represents a different scope level, and maps a component name to | ||
* an object containing the count and a reference to the first node. | ||
*/ | ||
/** @type {Map<string, { count: number; firstNode: any }>[]} */ | ||
const componentUsageStack = [new Map()] | ||
|
||
/** | ||
* Checks if a given node represents a custom component without any conditional directives. | ||
* | ||
* @param {VElement} node - The AST node to check. | ||
* @returns {boolean} True if the node represents a custom component without any conditional directives, false otherwise. | ||
*/ | ||
const isCustomComponentWithoutCondition = (node) => | ||
node.type === 'VElement' && | ||
utils.isCustomComponent(node) && | ||
!hasConditionalDirective(node) | ||
|
||
/** Set of built-in Vue components that are exempt from the rule. */ | ||
/** @type {Set<string>} */ | ||
const exemptTags = new Set(['component', 'slot', 'template']) | ||
|
||
/** Set to keep track of nodes we've pushed to the stack. */ | ||
/** @type {Set<any>} */ | ||
const pushedNodes = new Set() | ||
|
||
/** | ||
* Creates and returns an object representing a conditional family. | ||
* | ||
* @returns {{ if: VElement | null, elseIf: VElement[], else: VElement | null }} | ||
*/ | ||
const createConditionalFamily = () => ({ | ||
if: null, | ||
elseIf: [], | ||
else: null | ||
}) | ||
|
||
return utils.defineTemplateBodyVisitor(context, { | ||
/** | ||
* Callback to be executed when a Vue element is traversed. This function checks if the | ||
* Vue element is a component, increments the usage count of the component in the | ||
* current scope, and checks for the key directive if the component is repeated. | ||
* | ||
* @param {VElement} node - The traversed Vue element. | ||
*/ | ||
VElement(node) { | ||
if (exemptTags.has(node.rawName)) { | ||
return | ||
} | ||
|
||
const condition = | ||
utils.getDirective(node, 'if') || | ||
utils.getDirective(node, 'else-if') || | ||
utils.getDirective(node, 'else') | ||
|
||
if (condition) { | ||
const conditionType = condition.key.name.name | ||
|
||
if (node.parent && node.parent.type === 'VElement') { | ||
let conditionalFamily = conditionalFamilies.get(node.parent) | ||
|
||
if ( | ||
!conditionalFamily || | ||
(conditionalFamily.if && | ||
conditionalFamily.if.rawName !== node.rawName) | ||
) { | ||
conditionalFamily = createConditionalFamily() | ||
conditionalFamilies.set(node.parent, conditionalFamily) | ||
} | ||
|
||
switch (conditionType) { | ||
case 'if': { | ||
conditionalFamily.if = node | ||
break | ||
} | ||
case 'else-if': { | ||
conditionalFamily.elseIf.push(node) | ||
break | ||
} | ||
case 'else': { | ||
conditionalFamily.else = node | ||
break | ||
} | ||
} | ||
} | ||
} | ||
|
||
if (isCustomComponentWithoutCondition(node)) { | ||
componentUsageStack.push(new Map()) | ||
return | ||
} | ||
|
||
if (!utils.isCustomComponent(node)) { | ||
return | ||
} | ||
|
||
const componentName = node.rawName | ||
const currentScope = componentUsageStack[componentUsageStack.length - 1] | ||
const usageInfo = currentScope.get(componentName) || { | ||
count: 0, | ||
firstNode: null | ||
} | ||
|
||
if (hasConditionalDirective(node)) { | ||
// Store the first node if this is the first occurrence | ||
if (usageInfo.count === 0) { | ||
usageInfo.firstNode = node | ||
} | ||
|
||
if (usageInfo.count > 0) { | ||
const uniqueKey = `${casing.kebabCase(componentName)}-${ | ||
usageInfo.count + 1 | ||
}` | ||
checkForKey(node, context, componentName, uniqueKey) | ||
|
||
// If this is the second occurrence, also apply a fix to the first occurrence | ||
if (usageInfo.count === 1) { | ||
const uniqueKeyForFirstInstance = `${casing.kebabCase( | ||
componentName | ||
)}-1` | ||
checkForKey( | ||
usageInfo.firstNode, | ||
context, | ||
componentName, | ||
uniqueKeyForFirstInstance | ||
) | ||
} | ||
} | ||
usageInfo.count += 1 | ||
currentScope.set(componentName, usageInfo) | ||
} | ||
componentUsageStack.push(new Map()) | ||
pushedNodes.add(node) | ||
}, | ||
|
||
'VElement:exit'(node) { | ||
if (exemptTags.has(node.rawName)) { | ||
return | ||
} | ||
if (isCustomComponentWithoutCondition(node)) { | ||
componentUsageStack.pop() | ||
return | ||
} | ||
if (!utils.isCustomComponent(node)) { | ||
return | ||
} | ||
if (pushedNodes.has(node)) { | ||
componentUsageStack.pop() | ||
pushedNodes.delete(node) | ||
} | ||
} | ||
}) | ||
} | ||
} |
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.