-
-
Notifications
You must be signed in to change notification settings - Fork 695
Draft:Add new vue/require-mayberef-unwrap rule #2798
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
Draft
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
5 changes: 5 additions & 0 deletions
.changeset/happy-corners-shop.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/require-mayberef-unwrap`](https://eslint.vuejs.org/rules/require-mayberef-unwrap.html) rule |
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
72 changes: 72 additions & 0 deletions
docs/rules/require-mayberef-unwrap.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,72 @@ | ||
--- | ||
pageClass: rule-details | ||
sidebarDepth: 0 | ||
title: vue/require-mayberef-unwrap | ||
description: require `MaybeRef` values to be unwrapped with `unref()` before using in conditions | ||
since: v10.3.0 | ||
--- | ||
|
||
# vue/require-mayberef-unwrap | ||
|
||
> require unwrapping `MaybeRef` values with `unref()` in conditions | ||
|
||
- :gear: This rule is included in all of `"plugin:vue/essential"`, `*.configs["flat/essential"]`, `"plugin:vue/strongly-recommended"`, `*.configs["flat/strongly-recommended"]`, `"plugin:vue/recommended"` and `*.configs["flat/recommended"]`. | ||
- :wrench: The `--fix` option on the [command line](https://eslint.org/docs/user-guide/command-line-interface#fix-problems) can automatically fix some of the problems reported by this rule. | ||
|
||
## :book: Rule Details | ||
|
||
This rule reports cases where a `MaybeRef` value is used incorrectly in conditions. | ||
You must use `unref()` to access the inner value. | ||
|
||
<eslint-code-block fix :rules="{'vue/require-mayberef-unwrap': ['error']}"> | ||
|
||
```vue | ||
<script lang="ts"> | ||
import { ref, unref, type MaybeRef } from 'vue' | ||
|
||
export default { | ||
setup() { | ||
const maybeRef: MaybeRef<boolean> = ref(false) | ||
|
||
/* ✓ GOOD */ | ||
if (unref(maybeRef)) { | ||
console.log('good') | ||
} | ||
const result = unref(maybeRef) ? 'true' : 'false' | ||
|
||
/* ✗ BAD */ | ||
if (maybeRef) { | ||
console.log('bad') | ||
} | ||
const alt = maybeRef ? 'true' : 'false' | ||
|
||
return { | ||
maybeRef | ||
} | ||
} | ||
} | ||
</script> | ||
``` | ||
|
||
</eslint-code-block> | ||
|
||
## :wrench: Options | ||
|
||
Nothing. | ||
|
||
This rule also applies to `MaybeRefOrGetter` values in addition to `MaybeRef`. | ||
|
||
## :books: Further Reading | ||
|
||
- [Guide – Reactivity – `unref`](https://vuejs.org/guide/essentials/reactivity-fundamentals.html#unref) | ||
- [API – `MaybeRef`](https://vuejs.org/api/utility-types.html#mayberef) | ||
- [API – `MaybeRefOrGetter`](https://vuejs.org/api/utility-types.html#maybereforgetter) | ||
|
||
## :rocket: Version | ||
|
||
This rule was introduced in eslint-plugin-vue v10.3.0 | ||
|
||
## :mag: Implementation | ||
|
||
- [Rule source](https://github.com/vuejs/eslint-plugin-vue/blob/master/lib/rules/require-mayberef-unwrap.js) | ||
- [Test source](https://github.com/vuejs/eslint-plugin-vue/blob/master/tests/lib/rules/require-mayberef-unwrap.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
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
278 changes: 278 additions & 0 deletions
lib/rules/require-mayberef-unwrap.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,278 @@ | ||
/** | ||
* @author 2nofa11 | ||
* See LICENSE file in root directory for full license. | ||
*/ | ||
'use strict' | ||
|
||
const utils = require('../utils') | ||
|
||
/** | ||
* Check TypeScript type node for MaybeRef/MaybeRefOrGetter | ||
* @param {import('@typescript-eslint/types').TSESTree.TypeNode | undefined} typeNode | ||
* @returns {boolean} | ||
*/ | ||
function isMaybeRefTypeNode(typeNode) { | ||
if (!typeNode) return false | ||
if ( | ||
typeNode.type === 'TSTypeReference' && | ||
typeNode.typeName && | ||
typeNode.typeName.type === 'Identifier' | ||
) { | ||
return ( | ||
typeNode.typeName.name === 'MaybeRef' || | ||
typeNode.typeName.name === 'MaybeRefOrGetter' | ||
) | ||
} | ||
if (typeNode.type === 'TSUnionType') { | ||
return typeNode.types.some((t) => isMaybeRefTypeNode(t)) | ||
} | ||
return false | ||
} | ||
|
||
module.exports = { | ||
meta: { | ||
type: 'problem', | ||
docs: { | ||
description: | ||
'require `MaybeRef` values to be unwrapped with `unref()` before using in conditions', | ||
categories: undefined, | ||
url: 'https://eslint.vuejs.org/rules/require-mayberef-unwrap.html' | ||
}, | ||
fixable: 'code', | ||
schema: [], | ||
messages: { | ||
requireUnref: | ||
'MaybeRef should be unwrapped with `unref()` before using in conditions. Use `unref({{name}})` instead.' | ||
} | ||
}, | ||
/** @param {RuleContext} context */ | ||
create(context) { | ||
const filename = context.getFilename() | ||
if (!utils.isVueFile(filename) && !utils.isTypeScriptFile(filename)) { | ||
return {} | ||
} | ||
|
||
/** @type {Map<string, Set<string>>} */ | ||
const maybeRefPropsMap = new Map() | ||
|
||
/** | ||
* Determine if identifier should be considered MaybeRef | ||
* @param {Identifier} node | ||
*/ | ||
function isMaybeRef(node) { | ||
const variable = utils.findVariableByIdentifier(context, node) | ||
if (!variable) { | ||
return false | ||
} | ||
|
||
const definition = variable.defs[0] | ||
if (definition.type !== 'Variable') { | ||
return false | ||
} | ||
|
||
const id = definition.node?.id | ||
if (!id || id.type !== 'Identifier' || !id.typeAnnotation) { | ||
return false | ||
} | ||
|
||
return isMaybeRefTypeNode(id.typeAnnotation.typeAnnotation) | ||
} | ||
|
||
/** | ||
* Check if MemberExpression accesses a MaybeRef prop | ||
* @param {Identifier} objectNode | ||
* @param {string} propertyName | ||
*/ | ||
function isMaybeRefPropsAccess(objectNode, propertyName) { | ||
if (!propertyName) { | ||
return false | ||
} | ||
|
||
const variable = utils.findVariableByIdentifier(context, objectNode) | ||
if (!variable) { | ||
return false | ||
} | ||
|
||
const maybeRefProps = maybeRefPropsMap.get(variable.name) | ||
return maybeRefProps ? maybeRefProps.has(propertyName) : false | ||
} | ||
|
||
/** | ||
* Reports if the identifier is a MaybeRef type | ||
* @param {Identifier} node | ||
* @param {string} [customName] Custom name for error message | ||
*/ | ||
function reportIfMaybeRef(node, customName) { | ||
if (!isMaybeRef(node)) { | ||
return | ||
} | ||
|
||
const sourceCode = context.getSourceCode() | ||
context.report({ | ||
node, | ||
messageId: 'requireUnref', | ||
data: { name: customName || node.name }, | ||
fix(fixer) { | ||
return fixer.replaceText(node, `unref(${sourceCode.getText(node)})`) | ||
} | ||
}) | ||
} | ||
|
||
/** | ||
* Reports if the MemberExpression accesses a MaybeRef prop | ||
* @param {MemberExpression} node | ||
*/ | ||
function reportIfMaybeRefProps(node) { | ||
if (node.object.type !== 'Identifier') { | ||
return | ||
} | ||
|
||
const propertyName = utils.getStaticPropertyName(node) | ||
if (!propertyName) { | ||
return | ||
} | ||
|
||
if (!isMaybeRefPropsAccess(node.object, propertyName)) { | ||
return | ||
} | ||
|
||
const sourceCode = context.getSourceCode() | ||
context.report({ | ||
node: node.property, | ||
messageId: 'requireUnref', | ||
data: { name: `${node.object.name}.${propertyName}` }, | ||
fix(fixer) { | ||
return fixer.replaceText(node, `unref(${sourceCode.getText(node)})`) | ||
} | ||
}) | ||
} | ||
|
||
return utils.compositingVisitors( | ||
{ | ||
// if (maybeRef) | ||
/** @param {Identifier} node */ | ||
'IfStatement>Identifier'(node) { | ||
reportIfMaybeRef(node) | ||
}, | ||
// maybeRef ? x : y | ||
/** @param {Identifier & {parent: ConditionalExpression}} node */ | ||
'ConditionalExpression>Identifier'(node) { | ||
if (node.parent.test !== node) { | ||
return | ||
} | ||
reportIfMaybeRef(node) | ||
}, | ||
// !maybeRef, +maybeRef, -maybeRef, ~maybeRef, typeof maybeRef | ||
/** @param {Identifier} node */ | ||
'UnaryExpression>Identifier'(node) { | ||
reportIfMaybeRef(node) | ||
}, | ||
// maybeRef || other, maybeRef && other, maybeRef ?? other | ||
/** @param {Identifier & {parent: LogicalExpression}} node */ | ||
'LogicalExpression>Identifier'(node) { | ||
reportIfMaybeRef(node) | ||
}, | ||
// maybeRef == x, maybeRef != x, maybeRef === x, maybeRef !== x | ||
/** @param {Identifier} node */ | ||
'BinaryExpression>Identifier'(node) { | ||
reportIfMaybeRef(node) | ||
}, | ||
// Boolean(maybeRef), String(maybeRef) | ||
/** @param {Identifier} node */ | ||
'CallExpression>Identifier'(node) { | ||
const parent = node.parent | ||
if (parent?.type !== 'CallExpression') return | ||
|
||
const callee = parent.callee | ||
if (callee?.type !== 'Identifier') return | ||
|
||
if (!['Boolean', 'String'].includes(callee.name)) return | ||
|
||
if (parent.arguments[0] === node) { | ||
reportIfMaybeRef(node) | ||
} | ||
}, | ||
// props.maybeRefProp | ||
/** @param {MemberExpression} node */ | ||
MemberExpression(node) { | ||
reportIfMaybeRefProps(node) | ||
} | ||
}, | ||
utils.defineScriptSetupVisitor(context, { | ||
onDefinePropsEnter(node, props) { | ||
if ( | ||
!node.parent || | ||
node.parent.type !== 'VariableDeclarator' || | ||
node.parent.init !== node | ||
) { | ||
return | ||
} | ||
|
||
const propsParam = node.parent.id | ||
if (propsParam.type !== 'Identifier') { | ||
return | ||
} | ||
|
||
const maybeRefProps = new Set() | ||
for (const prop of props) { | ||
if (prop.type !== 'type' || !prop.node) { | ||
continue | ||
} | ||
|
||
if ( | ||
prop.node.type !== 'TSPropertySignature' || | ||
!prop.node.typeAnnotation | ||
) { | ||
continue | ||
} | ||
|
||
const typeAnnotation = prop.node.typeAnnotation.typeAnnotation | ||
if (isMaybeRefTypeNode(typeAnnotation)) { | ||
maybeRefProps.add(prop.propName) | ||
} | ||
} | ||
|
||
if (maybeRefProps.size > 0) { | ||
maybeRefPropsMap.set(propsParam.name, maybeRefProps) | ||
} | ||
} | ||
}), | ||
utils.defineVueVisitor(context, { | ||
onSetupFunctionEnter(node) { | ||
const propsParam = utils.skipDefaultParamValue(node.params[0]) | ||
if (!propsParam || propsParam.type !== 'Identifier') { | ||
return | ||
} | ||
|
||
if (!propsParam.typeAnnotation) { | ||
return | ||
} | ||
|
||
const typeAnnotation = propsParam.typeAnnotation.typeAnnotation | ||
const maybeRefProps = new Set() | ||
|
||
if (typeAnnotation.type === 'TSTypeLiteral') { | ||
for (const member of typeAnnotation.members) { | ||
if ( | ||
member.type === 'TSPropertySignature' && | ||
member.key && | ||
member.key.type === 'Identifier' && | ||
member.typeAnnotation && | ||
isMaybeRefTypeNode(member.typeAnnotation.typeAnnotation) | ||
) { | ||
maybeRefProps.add(member.key.name) | ||
} | ||
} | ||
} | ||
|
||
if (maybeRefProps.size > 0) { | ||
maybeRefPropsMap.set(propsParam.name, maybeRefProps) | ||
} | ||
}, | ||
onVueObjectExit() { | ||
maybeRefPropsMap.clear() | ||
} | ||
}) | ||
) | ||
} | ||
} |
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.