no-array-index-key.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /**
  2. * @fileoverview Prevent usage of Array index in keys
  3. * @author Joe Lencioni
  4. */
  5. 'use strict';
  6. const has = require('object.hasown/polyfill')();
  7. const astUtil = require('../util/ast');
  8. const docsUrl = require('../util/docsUrl');
  9. const pragma = require('../util/pragma');
  10. const report = require('../util/report');
  11. const variableUtil = require('../util/variable');
  12. // ------------------------------------------------------------------------------
  13. // Rule Definition
  14. // ------------------------------------------------------------------------------
  15. function isCreateCloneElement(node, context) {
  16. if (!node) {
  17. return false;
  18. }
  19. if (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression') {
  20. return node.object
  21. && node.object.name === pragma.getFromContext(context)
  22. && ['createElement', 'cloneElement'].indexOf(node.property.name) !== -1;
  23. }
  24. if (node.type === 'Identifier') {
  25. const variable = variableUtil.findVariableByName(context, node.name);
  26. if (variable && variable.type === 'ImportSpecifier') {
  27. return variable.parent.source.value === 'react';
  28. }
  29. }
  30. return false;
  31. }
  32. const messages = {
  33. noArrayIndex: 'Do not use Array index in keys',
  34. };
  35. module.exports = {
  36. meta: {
  37. docs: {
  38. description: 'Disallow usage of Array index in keys',
  39. category: 'Best Practices',
  40. recommended: false,
  41. url: docsUrl('no-array-index-key'),
  42. },
  43. messages,
  44. schema: [],
  45. },
  46. create(context) {
  47. // --------------------------------------------------------------------------
  48. // Public
  49. // --------------------------------------------------------------------------
  50. const indexParamNames = [];
  51. const iteratorFunctionsToIndexParamPosition = {
  52. every: 1,
  53. filter: 1,
  54. find: 1,
  55. findIndex: 1,
  56. flatMap: 1,
  57. forEach: 1,
  58. map: 1,
  59. reduce: 2,
  60. reduceRight: 2,
  61. some: 1,
  62. };
  63. function isArrayIndex(node) {
  64. return node.type === 'Identifier'
  65. && indexParamNames.indexOf(node.name) !== -1;
  66. }
  67. function isUsingReactChildren(node) {
  68. const callee = node.callee;
  69. if (
  70. !callee
  71. || !callee.property
  72. || !callee.object
  73. ) {
  74. return null;
  75. }
  76. const isReactChildMethod = ['map', 'forEach'].indexOf(callee.property.name) > -1;
  77. if (!isReactChildMethod) {
  78. return null;
  79. }
  80. const obj = callee.object;
  81. if (obj && obj.name === 'Children') {
  82. return true;
  83. }
  84. if (obj && obj.object && obj.object.name === pragma.getFromContext(context)) {
  85. return true;
  86. }
  87. return false;
  88. }
  89. function getMapIndexParamName(node) {
  90. const callee = node.callee;
  91. if (callee.type !== 'MemberExpression' && callee.type !== 'OptionalMemberExpression') {
  92. return null;
  93. }
  94. if (callee.property.type !== 'Identifier') {
  95. return null;
  96. }
  97. if (!has(iteratorFunctionsToIndexParamPosition, callee.property.name)) {
  98. return null;
  99. }
  100. const callbackArg = isUsingReactChildren(node)
  101. ? node.arguments[1]
  102. : node.arguments[0];
  103. if (!callbackArg) {
  104. return null;
  105. }
  106. if (!astUtil.isFunctionLikeExpression(callbackArg)) {
  107. return null;
  108. }
  109. const params = callbackArg.params;
  110. const indexParamPosition = iteratorFunctionsToIndexParamPosition[callee.property.name];
  111. if (params.length < indexParamPosition + 1) {
  112. return null;
  113. }
  114. return params[indexParamPosition].name;
  115. }
  116. function getIdentifiersFromBinaryExpression(side) {
  117. if (side.type === 'Identifier') {
  118. return side;
  119. }
  120. if (side.type === 'BinaryExpression') {
  121. // recurse
  122. const left = getIdentifiersFromBinaryExpression(side.left);
  123. const right = getIdentifiersFromBinaryExpression(side.right);
  124. return [].concat(left, right).filter(Boolean);
  125. }
  126. return null;
  127. }
  128. function checkPropValue(node) {
  129. if (isArrayIndex(node)) {
  130. // key={bar}
  131. report(context, messages.noArrayIndex, 'noArrayIndex', {
  132. node,
  133. });
  134. return;
  135. }
  136. if (node.type === 'TemplateLiteral') {
  137. // key={`foo-${bar}`}
  138. node.expressions.filter(isArrayIndex).forEach(() => {
  139. report(context, messages.noArrayIndex, 'noArrayIndex', {
  140. node,
  141. });
  142. });
  143. return;
  144. }
  145. if (node.type === 'BinaryExpression') {
  146. // key={'foo' + bar}
  147. const identifiers = getIdentifiersFromBinaryExpression(node);
  148. identifiers.filter(isArrayIndex).forEach(() => {
  149. report(context, messages.noArrayIndex, 'noArrayIndex', {
  150. node,
  151. });
  152. });
  153. return;
  154. }
  155. if (node.type === 'CallExpression'
  156. && node.callee
  157. && node.callee.type === 'MemberExpression'
  158. && node.callee.object
  159. && isArrayIndex(node.callee.object)
  160. && node.callee.property
  161. && node.callee.property.type === 'Identifier'
  162. && node.callee.property.name === 'toString'
  163. ) {
  164. // key={bar.toString()}
  165. report(context, messages.noArrayIndex, 'noArrayIndex', {
  166. node,
  167. });
  168. return;
  169. }
  170. if (node.type === 'CallExpression'
  171. && node.callee
  172. && node.callee.type === 'Identifier'
  173. && node.callee.name === 'String'
  174. && Array.isArray(node.arguments)
  175. && node.arguments.length > 0
  176. && isArrayIndex(node.arguments[0])
  177. ) {
  178. // key={String(bar)}
  179. report(context, messages.noArrayIndex, 'noArrayIndex', {
  180. node: node.arguments[0],
  181. });
  182. }
  183. }
  184. function popIndex(node) {
  185. const mapIndexParamName = getMapIndexParamName(node);
  186. if (!mapIndexParamName) {
  187. return;
  188. }
  189. indexParamNames.pop();
  190. }
  191. return {
  192. 'CallExpression, OptionalCallExpression'(node) {
  193. if (isCreateCloneElement(node.callee, context) && node.arguments.length > 1) {
  194. // React.createElement
  195. if (!indexParamNames.length) {
  196. return;
  197. }
  198. const props = node.arguments[1];
  199. if (props.type !== 'ObjectExpression') {
  200. return;
  201. }
  202. props.properties.forEach((prop) => {
  203. if (!prop.key || prop.key.name !== 'key') {
  204. // { ...foo }
  205. // { foo: bar }
  206. return;
  207. }
  208. checkPropValue(prop.value);
  209. });
  210. return;
  211. }
  212. const mapIndexParamName = getMapIndexParamName(node);
  213. if (!mapIndexParamName) {
  214. return;
  215. }
  216. indexParamNames.push(mapIndexParamName);
  217. },
  218. JSXAttribute(node) {
  219. if (node.name.name !== 'key') {
  220. // foo={bar}
  221. return;
  222. }
  223. if (!indexParamNames.length) {
  224. // Not inside a call expression that we think has an index param.
  225. return;
  226. }
  227. const value = node.value;
  228. if (!value || value.type !== 'JSXExpressionContainer') {
  229. // key='foo' or just simply 'key'
  230. return;
  231. }
  232. checkPropValue(value.expression);
  233. },
  234. 'CallExpression:exit': popIndex,
  235. 'OptionalCallExpression:exit': popIndex,
  236. };
  237. },
  238. };