Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | 2x 11x 11x 11x 2x 9x 35x 2x 7x 2x 8x 9x 2x 8x 8x 18x 2x 11x 11x 8x 8x 11x 5x 5x 1x 4x 11x 10x 4x | import type { Rule } from "eslint";
import type { AST } from "vue-eslint-parser";
import { templateBodyVisitor } from "./selectorRule.ts";
type Node = AST.Node & { parent?: Node | null };
const rootName = (callee: AST.ESLintExpression | AST.ESLintSuper): string | undefined => {
let node: AST.ESLintExpression | AST.ESLintSuper = callee;
while (node.type === "MemberExpression") node = node.object;
return node.type === "Identifier" ? node.name : undefined;
};
const isEventHandler = (node: Node): boolean => {
for (let current = node.parent; current; current = current.parent) {
if (current.type === "VAttribute")
return current.directive && current.key.name.name === "on";
}
return false;
};
const container = (node: Node): AST.VExpressionContainer | undefined => {
for (let current = node.parent; current; current = current.parent) {
if (current.type === "VExpressionContainer") return current;
}
return undefined;
};
const readsLocal = (call: AST.ESLintCallExpression, scope: AST.VExpressionContainer): boolean => {
const [start, end] = call.range;
return scope.references.some(
({ id, variable }) =>
(variable?.kind === "v-for" || variable?.kind === "scope") &&
id.range[0] >= start &&
id.range[1] <= end,
);
};
const noTemplateCall: Rule.RuleModule = {
meta: {
type: "suggestion",
docs: {
description:
"Disallow template calls that read only component state; derive them in a `computed`.",
},
schema: [],
messages: {
call: "Move this call into a `computed`; template calls are only for `$` globals, event handlers and `v-for`/slot variables.",
},
},
create: (context) => {
const offends = (node: AST.ESLintCallExpression): boolean => {
if (rootName(node.callee)?.startsWith("$") || isEventHandler(node)) return false;
const scope = container(node);
return !scope || !readsLocal(node, scope);
};
const insideOffender = (node: Node): boolean => {
for (
let current = node.parent;
current && current.type !== "VExpressionContainer";
current = current.parent
) {
Eif (current.type === "CallExpression" && offends(current)) return true;
}
return false;
};
return templateBodyVisitor(context, {
CallExpression: (node: AST.ESLintCallExpression) => {
if (offends(node) && !insideOffender(node)) {
context.report({ node: node as unknown as Rule.Node, messageId: "call" });
}
},
});
},
};
export default noTemplateCall;
|