-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathvalid-each-key.ts
59 lines (58 loc) · 1.71 KB
/
valid-each-key.ts
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
import type { AST } from "svelte-eslint-parser"
import { createRule } from "../utils"
import { getScope } from "../utils/ast-utils"
export default createRule("valid-each-key", {
meta: {
docs: {
description:
"enforce keys to use variables defined in the `{#each}` block",
category: "Best Practices",
// TODO Switch to recommended in the major version.
recommended: false,
},
schema: [],
messages: {
keyUseEachVars:
"Expected key to use the variables which are defined by the `{#each}` block.",
},
type: "suggestion",
},
create(context) {
return {
SvelteEachBlock(node: AST.SvelteEachBlock) {
if (node.key == null) {
return
}
const scope = getScope(context, node.key)
for (const variable of scope.variables) {
if (
!variable.defs.some(
(def) =>
(node.context.range[0] <= def.name.range[0] &&
def.name.range[1] <= node.context.range[1]) ||
(node.index &&
node.index.range[0] <= def.name.range[0] &&
def.name.range[1] <= node.index.range[1]),
)
) {
// It's not an iteration variable.
continue
}
for (const reference of variable.references) {
if (
node.key.range[0] <= reference.identifier.range[0] &&
reference.identifier.range[1] <= node.key.range[1]
) {
// A variable is used in the key.
return
}
}
}
context.report({
node: node.key,
messageId: "keyUseEachVars",
})
},
}
},
})