jsx-sort-props.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /**
  2. * @fileoverview Enforce props alphabetical sorting
  3. * @author Ilya Volodin, Yannick Croissant
  4. */
  5. 'use strict';
  6. const propName = require('jsx-ast-utils/propName');
  7. const includes = require('array-includes');
  8. const toSorted = require('array.prototype.tosorted');
  9. const docsUrl = require('../util/docsUrl');
  10. const jsxUtil = require('../util/jsx');
  11. const report = require('../util/report');
  12. const propTypesSortUtil = require('../util/propTypesSort');
  13. const eslintUtil = require('../util/eslint');
  14. const getText = eslintUtil.getText;
  15. const getSourceCode = eslintUtil.getSourceCode;
  16. // ------------------------------------------------------------------------------
  17. // Rule Definition
  18. // ------------------------------------------------------------------------------
  19. function isMultilineProp(node) {
  20. return node.loc.start.line !== node.loc.end.line;
  21. }
  22. const messages = {
  23. noUnreservedProps: 'A customized reserved first list must only contain a subset of React reserved props. Remove: {{unreservedWords}}',
  24. listIsEmpty: 'A customized reserved first list must not be empty',
  25. listReservedPropsFirst: 'Reserved props must be listed before all other props',
  26. listCallbacksLast: 'Callbacks must be listed after all other props',
  27. listShorthandFirst: 'Shorthand props must be listed before all other props',
  28. listShorthandLast: 'Shorthand props must be listed after all other props',
  29. listMultilineFirst: 'Multiline props must be listed before all other props',
  30. listMultilineLast: 'Multiline props must be listed after all other props',
  31. sortPropsByAlpha: 'Props should be sorted alphabetically',
  32. };
  33. const RESERVED_PROPS_LIST = [
  34. 'children',
  35. 'dangerouslySetInnerHTML',
  36. 'key',
  37. 'ref',
  38. ];
  39. function isReservedPropName(name, list) {
  40. return list.indexOf(name) >= 0;
  41. }
  42. let attributeMap;
  43. // attributeMap = { end: endrange, hasComment: true||false if comment in between nodes exists, it needs to be sorted to end }
  44. function shouldSortToEnd(node) {
  45. const attr = attributeMap.get(node);
  46. return !!attr && !!attr.hasComment;
  47. }
  48. function contextCompare(a, b, options) {
  49. let aProp = propName(a);
  50. let bProp = propName(b);
  51. const aSortToEnd = shouldSortToEnd(a);
  52. const bSortToEnd = shouldSortToEnd(b);
  53. if (aSortToEnd && !bSortToEnd) {
  54. return 1;
  55. }
  56. if (!aSortToEnd && bSortToEnd) {
  57. return -1;
  58. }
  59. if (options.reservedFirst) {
  60. const aIsReserved = isReservedPropName(aProp, options.reservedList);
  61. const bIsReserved = isReservedPropName(bProp, options.reservedList);
  62. if (aIsReserved && !bIsReserved) {
  63. return -1;
  64. }
  65. if (!aIsReserved && bIsReserved) {
  66. return 1;
  67. }
  68. }
  69. if (options.callbacksLast) {
  70. const aIsCallback = propTypesSortUtil.isCallbackPropName(aProp);
  71. const bIsCallback = propTypesSortUtil.isCallbackPropName(bProp);
  72. if (aIsCallback && !bIsCallback) {
  73. return 1;
  74. }
  75. if (!aIsCallback && bIsCallback) {
  76. return -1;
  77. }
  78. }
  79. if (options.shorthandFirst || options.shorthandLast) {
  80. const shorthandSign = options.shorthandFirst ? -1 : 1;
  81. if (!a.value && b.value) {
  82. return shorthandSign;
  83. }
  84. if (a.value && !b.value) {
  85. return -shorthandSign;
  86. }
  87. }
  88. if (options.multiline !== 'ignore') {
  89. const multilineSign = options.multiline === 'first' ? -1 : 1;
  90. const aIsMultiline = isMultilineProp(a);
  91. const bIsMultiline = isMultilineProp(b);
  92. if (aIsMultiline && !bIsMultiline) {
  93. return multilineSign;
  94. }
  95. if (!aIsMultiline && bIsMultiline) {
  96. return -multilineSign;
  97. }
  98. }
  99. if (options.noSortAlphabetically) {
  100. return 0;
  101. }
  102. const actualLocale = options.locale === 'auto' ? undefined : options.locale;
  103. if (options.ignoreCase) {
  104. aProp = aProp.toLowerCase();
  105. bProp = bProp.toLowerCase();
  106. return aProp.localeCompare(bProp, actualLocale);
  107. }
  108. if (aProp === bProp) {
  109. return 0;
  110. }
  111. if (options.locale === 'auto') {
  112. return aProp < bProp ? -1 : 1;
  113. }
  114. return aProp.localeCompare(bProp, actualLocale);
  115. }
  116. /**
  117. * Create an array of arrays where each subarray is composed of attributes
  118. * that are considered sortable.
  119. * @param {Array<JSXSpreadAttribute|JSXAttribute>} attributes
  120. * @param {Object} context The context of the rule
  121. * @return {Array<Array<JSXAttribute>>}
  122. */
  123. function getGroupsOfSortableAttributes(attributes, context) {
  124. const sourceCode = getSourceCode(context);
  125. const sortableAttributeGroups = [];
  126. let groupCount = 0;
  127. function addtoSortableAttributeGroups(attribute) {
  128. sortableAttributeGroups[groupCount - 1].push(attribute);
  129. }
  130. for (let i = 0; i < attributes.length; i++) {
  131. const attribute = attributes[i];
  132. const nextAttribute = attributes[i + 1];
  133. const attributeline = attribute.loc.start.line;
  134. let comment = [];
  135. try {
  136. comment = sourceCode.getCommentsAfter(attribute);
  137. } catch (e) { /**/ }
  138. const lastAttr = attributes[i - 1];
  139. const attrIsSpread = attribute.type === 'JSXSpreadAttribute';
  140. // If we have no groups or if the last attribute was JSXSpreadAttribute
  141. // then we start a new group. Append attributes to the group until we
  142. // come across another JSXSpreadAttribute or exhaust the array.
  143. if (
  144. !lastAttr
  145. || (lastAttr.type === 'JSXSpreadAttribute' && !attrIsSpread)
  146. ) {
  147. groupCount += 1;
  148. sortableAttributeGroups[groupCount - 1] = [];
  149. }
  150. if (!attrIsSpread) {
  151. if (comment.length === 0) {
  152. attributeMap.set(attribute, { end: attribute.range[1], hasComment: false });
  153. addtoSortableAttributeGroups(attribute);
  154. } else {
  155. const firstComment = comment[0];
  156. const commentline = firstComment.loc.start.line;
  157. if (comment.length === 1) {
  158. if (attributeline + 1 === commentline && nextAttribute) {
  159. attributeMap.set(attribute, { end: nextAttribute.range[1], hasComment: true });
  160. addtoSortableAttributeGroups(attribute);
  161. i += 1;
  162. } else if (attributeline === commentline) {
  163. if (firstComment.type === 'Block' && nextAttribute) {
  164. attributeMap.set(attribute, { end: nextAttribute.range[1], hasComment: true });
  165. i += 1;
  166. } else if (firstComment.type === 'Block') {
  167. attributeMap.set(attribute, { end: firstComment.range[1], hasComment: true });
  168. } else {
  169. attributeMap.set(attribute, { end: firstComment.range[1], hasComment: false });
  170. }
  171. addtoSortableAttributeGroups(attribute);
  172. }
  173. } else if (comment.length > 1 && attributeline + 1 === comment[1].loc.start.line && nextAttribute) {
  174. const commentNextAttribute = sourceCode.getCommentsAfter(nextAttribute);
  175. attributeMap.set(attribute, { end: nextAttribute.range[1], hasComment: true });
  176. if (
  177. commentNextAttribute.length === 1
  178. && nextAttribute.loc.start.line === commentNextAttribute[0].loc.start.line
  179. ) {
  180. attributeMap.set(attribute, { end: commentNextAttribute[0].range[1], hasComment: true });
  181. }
  182. addtoSortableAttributeGroups(attribute);
  183. i += 1;
  184. }
  185. }
  186. }
  187. }
  188. return sortableAttributeGroups;
  189. }
  190. function generateFixerFunction(node, context, reservedList) {
  191. const attributes = node.attributes.slice(0);
  192. const configuration = context.options[0] || {};
  193. const ignoreCase = configuration.ignoreCase || false;
  194. const callbacksLast = configuration.callbacksLast || false;
  195. const shorthandFirst = configuration.shorthandFirst || false;
  196. const shorthandLast = configuration.shorthandLast || false;
  197. const multiline = configuration.multiline || 'ignore';
  198. const noSortAlphabetically = configuration.noSortAlphabetically || false;
  199. const reservedFirst = configuration.reservedFirst || false;
  200. const locale = configuration.locale || 'auto';
  201. // Sort props according to the context. Only supports ignoreCase.
  202. // Since we cannot safely move JSXSpreadAttribute (due to potential variable overrides),
  203. // we only consider groups of sortable attributes.
  204. const options = {
  205. ignoreCase,
  206. callbacksLast,
  207. shorthandFirst,
  208. shorthandLast,
  209. multiline,
  210. noSortAlphabetically,
  211. reservedFirst,
  212. reservedList,
  213. locale,
  214. };
  215. const sortableAttributeGroups = getGroupsOfSortableAttributes(attributes, context);
  216. const sortedAttributeGroups = sortableAttributeGroups
  217. .slice(0)
  218. .map((group) => toSorted(group, (a, b) => contextCompare(a, b, options)));
  219. return function fixFunction(fixer) {
  220. const fixers = [];
  221. let source = getText(context);
  222. sortableAttributeGroups.forEach((sortableGroup, ii) => {
  223. sortableGroup.forEach((attr, jj) => {
  224. const sortedAttr = sortedAttributeGroups[ii][jj];
  225. const sortedAttrText = source.slice(sortedAttr.range[0], attributeMap.get(sortedAttr).end);
  226. fixers.push({
  227. range: [attr.range[0], attributeMap.get(attr).end],
  228. text: sortedAttrText,
  229. });
  230. });
  231. });
  232. fixers.sort((a, b) => b.range[0] - a.range[0]);
  233. const firstFixer = fixers[0];
  234. const lastFixer = fixers[fixers.length - 1];
  235. const rangeStart = lastFixer ? lastFixer.range[0] : 0;
  236. const rangeEnd = firstFixer ? firstFixer.range[1] : -0;
  237. fixers.forEach((fix) => {
  238. source = `${source.slice(0, fix.range[0])}${fix.text}${source.slice(fix.range[1])}`;
  239. });
  240. return fixer.replaceTextRange([rangeStart, rangeEnd], source.slice(rangeStart, rangeEnd));
  241. };
  242. }
  243. /**
  244. * Checks if the `reservedFirst` option is valid
  245. * @param {Object} context The context of the rule
  246. * @param {boolean | string[]} reservedFirst The `reservedFirst` option
  247. * @return {Function | undefined} If an error is detected, a function to generate the error message, otherwise, `undefined`
  248. */
  249. // eslint-disable-next-line consistent-return
  250. function validateReservedFirstConfig(context, reservedFirst) {
  251. if (reservedFirst) {
  252. if (Array.isArray(reservedFirst)) {
  253. // Only allow a subset of reserved words in customized lists
  254. const nonReservedWords = reservedFirst.filter((word) => !isReservedPropName(
  255. word,
  256. RESERVED_PROPS_LIST
  257. ));
  258. if (reservedFirst.length === 0) {
  259. return function Report(decl) {
  260. report(context, messages.listIsEmpty, 'listIsEmpty', {
  261. node: decl,
  262. });
  263. };
  264. }
  265. if (nonReservedWords.length > 0) {
  266. return function Report(decl) {
  267. report(context, messages.noUnreservedProps, 'noUnreservedProps', {
  268. node: decl,
  269. data: {
  270. unreservedWords: nonReservedWords.toString(),
  271. },
  272. });
  273. };
  274. }
  275. }
  276. }
  277. }
  278. const reportedNodeAttributes = new WeakMap();
  279. /**
  280. * Check if the current node attribute has already been reported with the same error type
  281. * if that's the case then we don't report a new error
  282. * otherwise we report the error
  283. * @param {Object} nodeAttribute The node attribute to be reported
  284. * @param {string} errorType The error type to be reported
  285. * @param {Object} node The parent node for the node attribute
  286. * @param {Object} context The context of the rule
  287. * @param {Array<String>} reservedList The list of reserved props
  288. */
  289. function reportNodeAttribute(nodeAttribute, errorType, node, context, reservedList) {
  290. const errors = reportedNodeAttributes.get(nodeAttribute) || [];
  291. if (includes(errors, errorType)) {
  292. return;
  293. }
  294. errors.push(errorType);
  295. reportedNodeAttributes.set(nodeAttribute, errors);
  296. report(context, messages[errorType], errorType, {
  297. node: nodeAttribute.name,
  298. fix: generateFixerFunction(node, context, reservedList),
  299. });
  300. }
  301. /** @type {import('eslint').Rule.RuleModule} */
  302. module.exports = {
  303. meta: {
  304. docs: {
  305. description: 'Enforce props alphabetical sorting',
  306. category: 'Stylistic Issues',
  307. recommended: false,
  308. url: docsUrl('jsx-sort-props'),
  309. },
  310. fixable: 'code',
  311. messages,
  312. schema: [{
  313. type: 'object',
  314. properties: {
  315. // Whether callbacks (prefixed with "on") should be listed at the very end,
  316. // after all other props. Supersedes shorthandLast.
  317. callbacksLast: {
  318. type: 'boolean',
  319. },
  320. // Whether shorthand properties (without a value) should be listed first
  321. shorthandFirst: {
  322. type: 'boolean',
  323. },
  324. // Whether shorthand properties (without a value) should be listed last
  325. shorthandLast: {
  326. type: 'boolean',
  327. },
  328. // Whether multiline properties should be listed first or last
  329. multiline: {
  330. enum: ['ignore', 'first', 'last'],
  331. default: 'ignore',
  332. },
  333. ignoreCase: {
  334. type: 'boolean',
  335. },
  336. // Whether alphabetical sorting should be enforced
  337. noSortAlphabetically: {
  338. type: 'boolean',
  339. },
  340. reservedFirst: {
  341. type: ['array', 'boolean'],
  342. },
  343. locale: {
  344. type: 'string',
  345. default: 'auto',
  346. },
  347. },
  348. additionalProperties: false,
  349. }],
  350. },
  351. create(context) {
  352. const configuration = context.options[0] || {};
  353. const ignoreCase = configuration.ignoreCase || false;
  354. const callbacksLast = configuration.callbacksLast || false;
  355. const shorthandFirst = configuration.shorthandFirst || false;
  356. const shorthandLast = configuration.shorthandLast || false;
  357. const multiline = configuration.multiline || 'ignore';
  358. const noSortAlphabetically = configuration.noSortAlphabetically || false;
  359. const reservedFirst = configuration.reservedFirst || false;
  360. const reservedFirstError = validateReservedFirstConfig(context, reservedFirst);
  361. const reservedList = Array.isArray(reservedFirst) ? reservedFirst : RESERVED_PROPS_LIST;
  362. const locale = configuration.locale || 'auto';
  363. return {
  364. Program() {
  365. attributeMap = new WeakMap();
  366. },
  367. JSXOpeningElement(node) {
  368. // `dangerouslySetInnerHTML` is only "reserved" on DOM components
  369. const nodeReservedList = reservedFirst && !jsxUtil.isDOMComponent(node) ? reservedList.filter((prop) => prop !== 'dangerouslySetInnerHTML') : reservedList;
  370. node.attributes.reduce((memo, decl, idx, attrs) => {
  371. if (decl.type === 'JSXSpreadAttribute') {
  372. return attrs[idx + 1];
  373. }
  374. let previousPropName = propName(memo);
  375. let currentPropName = propName(decl);
  376. const previousValue = memo.value;
  377. const currentValue = decl.value;
  378. const previousIsCallback = propTypesSortUtil.isCallbackPropName(previousPropName);
  379. const currentIsCallback = propTypesSortUtil.isCallbackPropName(currentPropName);
  380. if (ignoreCase) {
  381. previousPropName = previousPropName.toLowerCase();
  382. currentPropName = currentPropName.toLowerCase();
  383. }
  384. if (reservedFirst) {
  385. if (reservedFirstError) {
  386. reservedFirstError(decl);
  387. return memo;
  388. }
  389. const previousIsReserved = isReservedPropName(previousPropName, nodeReservedList);
  390. const currentIsReserved = isReservedPropName(currentPropName, nodeReservedList);
  391. if (previousIsReserved && !currentIsReserved) {
  392. return decl;
  393. }
  394. if (!previousIsReserved && currentIsReserved) {
  395. reportNodeAttribute(decl, 'listReservedPropsFirst', node, context, nodeReservedList);
  396. return memo;
  397. }
  398. }
  399. if (callbacksLast) {
  400. if (!previousIsCallback && currentIsCallback) {
  401. // Entering the callback prop section
  402. return decl;
  403. }
  404. if (previousIsCallback && !currentIsCallback) {
  405. // Encountered a non-callback prop after a callback prop
  406. reportNodeAttribute(memo, 'listCallbacksLast', node, context, nodeReservedList);
  407. return memo;
  408. }
  409. }
  410. if (shorthandFirst) {
  411. if (currentValue && !previousValue) {
  412. return decl;
  413. }
  414. if (!currentValue && previousValue) {
  415. reportNodeAttribute(decl, 'listShorthandFirst', node, context, nodeReservedList);
  416. return memo;
  417. }
  418. }
  419. if (shorthandLast) {
  420. if (!currentValue && previousValue) {
  421. return decl;
  422. }
  423. if (currentValue && !previousValue) {
  424. reportNodeAttribute(memo, 'listShorthandLast', node, context, nodeReservedList);
  425. return memo;
  426. }
  427. }
  428. const previousIsMultiline = isMultilineProp(memo);
  429. const currentIsMultiline = isMultilineProp(decl);
  430. if (multiline === 'first') {
  431. if (previousIsMultiline && !currentIsMultiline) {
  432. // Exiting the multiline prop section
  433. return decl;
  434. }
  435. if (!previousIsMultiline && currentIsMultiline) {
  436. // Encountered a non-multiline prop before a multiline prop
  437. reportNodeAttribute(decl, 'listMultilineFirst', node, context, nodeReservedList);
  438. return memo;
  439. }
  440. } else if (multiline === 'last') {
  441. if (!previousIsMultiline && currentIsMultiline) {
  442. // Entering the multiline prop section
  443. return decl;
  444. }
  445. if (previousIsMultiline && !currentIsMultiline) {
  446. // Encountered a non-multiline prop after a multiline prop
  447. reportNodeAttribute(memo, 'listMultilineLast', node, context, nodeReservedList);
  448. return memo;
  449. }
  450. }
  451. if (
  452. !noSortAlphabetically
  453. && (
  454. (ignoreCase || locale !== 'auto')
  455. ? previousPropName.localeCompare(currentPropName, locale === 'auto' ? undefined : locale) > 0
  456. : previousPropName > currentPropName
  457. )
  458. ) {
  459. reportNodeAttribute(decl, 'sortPropsByAlpha', node, context, nodeReservedList);
  460. return memo;
  461. }
  462. return decl;
  463. }, node.attributes[0]);
  464. },
  465. };
  466. },
  467. };