|
| 1 | +import type { AST } from "svelte-eslint-parser" |
| 2 | +import type { TSESTree } from "@typescript-eslint/types" |
| 3 | +import { createRule } from "../utils" |
| 4 | +import { equalTokens, getAttributeKeyText } from "../utils/ast-utils" |
| 5 | + |
| 6 | +export default createRule("no-dupe-use-directives", { |
| 7 | + meta: { |
| 8 | + docs: { |
| 9 | + description: "disallow duplicate `use:` directives", |
| 10 | + category: "Possible Errors", |
| 11 | + recommended: false, |
| 12 | + }, |
| 13 | + schema: [], |
| 14 | + messages: { |
| 15 | + duplication: |
| 16 | + "This `{{keyText}}` directive is the same and duplicate directives in L{{lineNo}}.", |
| 17 | + }, |
| 18 | + type: "problem", |
| 19 | + }, |
| 20 | + create(context) { |
| 21 | + const sourceCode = context.getSourceCode() |
| 22 | + |
| 23 | + const directiveDataMap = new Map< |
| 24 | + string, // key text |
| 25 | + { |
| 26 | + expression: null | TSESTree.Expression |
| 27 | + nodes: AST.SvelteActionDirective[] |
| 28 | + }[] |
| 29 | + >() |
| 30 | + return { |
| 31 | + SvelteDirective(node) { |
| 32 | + if (node.kind !== "Action") return |
| 33 | + |
| 34 | + const keyText = getAttributeKeyText(node, context) |
| 35 | + |
| 36 | + const directiveDataList = directiveDataMap.get(keyText) |
| 37 | + if (!directiveDataList) { |
| 38 | + directiveDataMap.set(keyText, [ |
| 39 | + { |
| 40 | + expression: node.expression, |
| 41 | + nodes: [node], |
| 42 | + }, |
| 43 | + ]) |
| 44 | + return |
| 45 | + } |
| 46 | + const directiveData = directiveDataList.find((data) => { |
| 47 | + if (!data.expression || !node.expression) { |
| 48 | + return data.expression === node.expression |
| 49 | + } |
| 50 | + return equalTokens(data.expression, node.expression, sourceCode) |
| 51 | + }) |
| 52 | + if (!directiveData) { |
| 53 | + directiveDataList.push({ |
| 54 | + expression: node.expression, |
| 55 | + nodes: [node], |
| 56 | + }) |
| 57 | + return |
| 58 | + } |
| 59 | + |
| 60 | + directiveData.nodes.push(node) |
| 61 | + }, |
| 62 | + "SvelteStartTag:exit"() { |
| 63 | + for (const [keyText, directiveDataList] of directiveDataMap) { |
| 64 | + for (const { nodes } of directiveDataList) { |
| 65 | + if (nodes.length < 2) { |
| 66 | + continue |
| 67 | + } |
| 68 | + for (const node of nodes) { |
| 69 | + context.report({ |
| 70 | + node, |
| 71 | + messageId: "duplication", |
| 72 | + data: { |
| 73 | + keyText, |
| 74 | + lineNo: String( |
| 75 | + (nodes[0] !== node ? nodes[0] : nodes[1]).loc.start.line, |
| 76 | + ), |
| 77 | + }, |
| 78 | + }) |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + directiveDataMap.clear() |
| 83 | + }, |
| 84 | + } |
| 85 | + }, |
| 86 | +}) |
0 commit comments