Skip to content

Commit 83291a1

Browse files
authored
Fix using iterations for each without used props inside (#69)
* Turn on all tests for prop-types rule * Make sure we attach scope variables only for prop-related variables
1 parent 3a3b68c commit 83291a1

File tree

2 files changed

+24
-12
lines changed

2 files changed

+24
-12
lines changed

lib/util/getUsedVariablesInPug.js

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -135,9 +135,11 @@ const getUsedVariablesInPug = (template = '') => {
135135
},
136136
})
137137

138-
let variablesInScope = []
138+
const lastAddedVariable = usedVariables[usedVariables.length - 1]
139139

140-
if (token.type === 'each') {
140+
// If we define a scope with a variable connected to props in that definition,
141+
// we also mark all vars in that scope as used
142+
if (token.type === 'each' && lastAddedVariable) {
141143
const getLastTokenInScope = (all, start) => {
142144
const startIndex = all.findIndex(item => item === start)
143145
const lastToken = all.slice(startIndex).find(item => item.type === 'outdent' && item.loc.end.column <= start.loc.start.column)
@@ -151,7 +153,7 @@ const getUsedVariablesInPug = (template = '') => {
151153
const bodyLines = [''].concat(lines.slice(startToken.loc.start.line, endToken.loc.end.line - 1))
152154
const body = bodyLines.join('\n')
153155

154-
variablesInScope = getUsedVariablesInPug(body)
156+
const variablesInScope = getUsedVariablesInPug(body)
155157
.filter(item => item.allNames.length > 1 || item.extra.isSpreadElement === true)
156158
.map(item => ({
157159
...item,
@@ -169,16 +171,14 @@ const getUsedVariablesInPug = (template = '') => {
169171
? ['__COMPUTED_PROP__', ...item.allNames.slice(1)]
170172
: item.allNames,
171173
}))
172-
}
173-
174-
const lastAddedVariable = usedVariables[usedVariables.length - 1]
175174

176-
variablesInScope.forEach((item) => {
177-
usedVariables.push({
178-
...item,
179-
allNames: [...lastAddedVariable.allNames, ...item.allNames],
175+
variablesInScope.forEach((item) => {
176+
usedVariables.push({
177+
...item,
178+
allNames: [...lastAddedVariable.allNames, ...item.allNames],
179+
})
180180
})
181-
})
181+
}
182182
})
183183

184184
return usedVariables

tests/lib/rules/prop-types.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,19 @@ const cases = [
576576
}
577577
`,
578578
},
579+
{
580+
code: `
581+
function Component() {
582+
const list = []
583+
584+
return pug\`
585+
each item in list
586+
div(key=item.id)
587+
= item.test
588+
\`
589+
}
590+
`,
591+
},
579592
],
580593
invalid: [
581594
{
@@ -642,7 +655,6 @@ const cases = [
642655
],
643656
},
644657
{
645-
only: true,
646658
code: `
647659
function Component(props) {
648660
const id = true

0 commit comments

Comments
 (0)