jsx-sort-props.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. // ------------------------------------------------------------------------------
  13. // Rule Definition
  14. // ------------------------------------------------------------------------------
  15. function isCallbackPropName(name) {
  16. return /^on[A-Z]/.test(name);
  17. }
  18. function isMultilineProp(node) {
  19. return node.loc.start.line !== node.loc.end.line;
  20. }
  21. const messages = {
  22. noUnreservedProps: 'A customized reserved first list must only contain a subset of React reserved props. Remove: {{unreservedWords}}',
  23. listIsEmpty: 'A customized reserved first list must not be empty',
  24. listReservedPropsFirst: 'Reserved props must be listed before all other props',
  25. listCallbacksLast: 'Callbacks must be listed after all other props',
  26. listShorthandFirst: 'Shorthand props must be listed before all other props',
  27. listShorthandLast: 'Shorthand props must be listed after all other props',
  28. listMultilineFirst: 'Multiline props must be listed before all other props',
  29. listMultilineLast: 'Multiline props must be listed after all other props',
  30. sortPropsByAlpha: 'Props should be sorted alphabetically',
  31. };
  32. const RESERVED_PROPS_LIST = [
  33. 'children',
  34. 'dangerouslySetInnerHTML',
  35. 'key',
  36. 'ref',
  37. ];
  38. function isReservedPropName(name, list) {
  39. return list.indexOf(name) >= 0;
  40. }
  41. let attributeMap;
  42. // attributeMap = { end: endrange, hasComment: true||false if comment in between nodes exists, it needs to be sorted to end }
  43. function shouldSortToEnd(node) {
  44. const attr = attributeMap.get(node);
  45. return !!attr && !!attr.hasComment;
  46. }
  47. function contextCompare(a, b, options) {
  48. let aProp = propName(a);
  49. let bProp = propName(b);
  50. const aSortToEnd = shouldSortToEnd(a);
  51. const bSortToEnd = shouldSortToEnd(b);
  52. if (aSortToEnd && !bSortToEnd) {
  53. return 1;
  54. }
  55. if (!aSortToEnd && bSortToEnd) {
  56. return -1;
  57. }
  58. if (options.reservedFirst) {
  59. const aIsReserved = isReservedPropName(aProp, options.reservedList);
  60. const bIsReserved = isReservedPropName(bProp, options.reservedList);
  61. if (aIsReserved && !bIsReserved) {
  62. return -1;
  63. }
  64. if (!aIsReserved && bIsReserved) {
  65. return 1;
  66. }
  67. }
  68. if (options.callbacksLast) {
  69. const aIsCallback = isCallbackPropName(aProp);
  70. const bIsCallback = isCallbackPropName(bProp);
  71. if (aIsCallback && !bIsCallback) {
  72. return 1;
  73. }
  74. if (!aIsCallback && bIsCallback) {
  75. return -1;
  76. }
  77. }
  78. if (options.shorthandFirst || options.shorthandLast) {
  79. const shorthandSign = options.shorthandFirst ? -1 : 1;
  80. if (!a.value && b.value) {
  81. return shorthandSign;
  82. }
  83. if (a.value && !b.value) {
  84. return -shorthandSign;
  85. }
  86. }
  87. if (options.multiline !== 'ignore') {
  88. const multilineSign = options.multiline === 'first' ? -1 : 1;
  89. const aIsMultiline = isMultilineProp(a);
  90. const bIsMultiline = isMultilineProp(b);
  91. if (aIsMultiline && !bIsMultiline) {
  92. return multilineSign;
  93. }
  94. if (!aIsMultiline && bIsMultiline) {
  95. return -multilineSign;
  96. }
  97. }
  98. if (options.noSortAlphabetically) {
  99. return 0;
  100. }
  101. const actualLocale = options.locale === 'auto' ? undefined : options.locale;
  102. if (options.ignoreCase) {
  103. aProp = aProp.toLowerCase();
  104. bProp = bProp.toLowerCase();
  105. return aProp.localeCompare(bProp, actualLocale);
  106. }
  107. if (aProp === bProp) {
  108. return 0;
  109. }
  110. if (options.locale === 'auto') {
  111. return aProp < bProp ? -1 : 1;
  112. }
  113. return aProp.localeCompare(bProp, actualLocale);
  114. }
  115. /**
  116. * Create an array of arrays where each subarray is composed of attributes
  117. * that are considered sortable.
  118. * @param {Array<JSXSpreadAttribute|JSXAttribute>} attributes
  119. * @param {Object} context The context of the rule
  120. * @return {Array<Array<JSXAttribute>>}
  121. */
  122. function getGroupsOfSortableAttributes(attributes, context) {
  123. const sourceCode = context.getSourceCode();
  124. const sortableAttributeGroups = [];
  125. let groupCount = 0;
  126. function addtoSortableAttributeGroups(attribute) {
  127. sortableAttributeGroups[groupCount - 1].push(attribute);
  128. }
  129. for (let i = 0; i < attributes.length; i++) {
  130. const attribute = attributes[i];
  131. const nextAttribute = attributes[i + 1];
  132. const attributeline = attribute.loc.start.line;
  133. let comment = [];
  134. try {
  135. comment = sourceCode.getCommentsAfter(attribute);
  136. } catch (e) { /**/ }
  137. const lastAttr = attributes[i - 1];
  138. const attrIsSpread = attribute.type === 'JSXSpreadAttribute';
  139. // If we have no groups or if the last attribute was JSXSpreadAttribute
  140. // then we start a new group. Append attributes to the group until we
  141. // come across another JSXSpreadAttribute or exhaust the array.
  142. if (
  143. !lastAttr
  144. || (lastAttr.type === 'JSXSpreadAttribute' && !attrIsSpread)
  145. ) {
  146. groupCount += 1;
  147. sortableAttributeGroups[groupCount - 1] = [];
  148. }
  149. if (!attrIsSpread) {
  150. if (comment.length === 0) {
  151. attributeMap.set(attribute, { end: attribute.range[1], hasComment: false });
  152. addtoSortableAttributeGroups(attribute);
  153. } else {
  154. const firstComment = comment[0];
  155. const commentline = firstComment.loc.start.line;
  156. if (comment.length === 1) {
  157. if (attributeline + 1 === commentline && nextAttribute) {
  158. attributeMap.set(attribute, { end: nextAttribute.range[1], hasComment: true });
  159. addtoSortableAttributeGroups(attribute);
  160. i += 1;
  161. } else if (attributeline === commentline) {
  162. if (firstComment.type === 'Block' && nextAttribute) {
  163. attributeMap.set(attribute, { end: nextAttribute.range[1], hasComment: true });
  164. i += 1;
  165. } else if (firstComment.type === 'Block') {
  166. attributeMap.set(attribute, { end: firstComment.range[1], hasComment: true });
  167. } else {
  168. attributeMap.set(attribute, { end: firstComment.range[1], hasComment: false });
  169. }
  170. addtoSortableAttributeGroups(attribute);
  171. }
  172. } else if (comment.length > 1 && attributeline + 1 === comment[1].loc.start.line && nextAttribute) {
  173. const commentNextAttribute = sourceCode.getCommentsAfter(nextAttribute);
  174. attributeMap.set(attribute, { end: nextAttribute.range[1], hasComment: true });
  175. if (
  176. commentNextAttribute.length === 1
  177. && nextAttribute.loc.start.line === commentNextAttribute[0].loc.start.line
  178. ) {
  179. attributeMap.set(attribute, { end: commentNextAttribute[0].range[1], hasComment: true });
  180. }
  181. addtoSortableAttributeGroups(attribute);
  182. i += 1;
  183. }
  184. }
  185. }
  186. }
  187. return sortableAttributeGroups;
  188. }
  189. function generateFixerFunction(node, context, reservedList) {
  190. const sourceCode = context.getSourceCode();
  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 = sourceCode.getText();
  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|Array<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. module.exports = {
  302. meta: {
  303. docs: {
  304. description: 'Enforce props alphabetical sorting',
  305. category: 'Stylistic Issues',
  306. recommended: false,
  307. url: docsUrl('jsx-sort-props'),
  308. },
  309. fixable: 'code',
  310. messages,
  311. schema: [{
  312. type: 'object',
  313. properties: {
  314. // Whether callbacks (prefixed with "on") should be listed at the very end,
  315. // after all other props. Supersedes shorthandLast.
  316. callbacksLast: {
  317. type: 'boolean',
  318. },
  319. // Whether shorthand properties (without a value) should be listed first
  320. shorthandFirst: {
  321. type: 'boolean',
  322. },
  323. // Whether shorthand properties (without a value) should be listed last
  324. shorthandLast: {
  325. type: 'boolean',
  326. },
  327. // Whether multiline properties should be listed first or last
  328. multiline: {
  329. enum: ['ignore', 'first', 'last'],
  330. default: 'ignore',
  331. },
  332. ignoreCase: {
  333. type: 'boolean',
  334. },
  335. // Whether alphabetical sorting should be enforced
  336. noSortAlphabetically: {
  337. type: 'boolean',
  338. },
  339. reservedFirst: {
  340. type: ['array', 'boolean'],
  341. },
  342. locale: {
  343. type: 'string',
  344. default: 'auto',
  345. },
  346. },
  347. additionalProperties: false,
  348. }],
  349. },
  350. create(context) {
  351. const configuration = context.options[0] || {};
  352. const ignoreCase = configuration.ignoreCase || false;
  353. const callbacksLast = configuration.callbacksLast || false;
  354. const shorthandFirst = configuration.shorthandFirst || false;
  355. const shorthandLast = configuration.shorthandLast || false;
  356. const multiline = configuration.multiline || 'ignore';
  357. const noSortAlphabetically = configuration.noSortAlphabetically || false;
  358. const reservedFirst = configuration.reservedFirst || false;
  359. const reservedFirstError = validateReservedFirstConfig(context, reservedFirst);
  360. const reservedList = Array.isArray(reservedFirst) ? reservedFirst : RESERVED_PROPS_LIST;
  361. const locale = configuration.locale || 'auto';
  362. return {
  363. Program() {
  364. attributeMap = new WeakMap();
  365. },
  366. JSXOpeningElement(node) {
  367. // `dangerouslySetInnerHTML` is only "reserved" on DOM components
  368. const nodeReservedList = reservedFirst && !jsxUtil.isDOMComponent(node) ? reservedList.filter((prop) => prop !== 'dangerouslySetInnerHTML') : reservedList;
  369. node.attributes.reduce((memo, decl, idx, attrs) => {
  370. if (decl.type === 'JSXSpreadAttribute') {
  371. return attrs[idx + 1];
  372. }
  373. let previousPropName = propName(memo);
  374. let currentPropName = propName(decl);
  375. const previousValue = memo.value;
  376. const currentValue = decl.value;
  377. const previousIsCallback = isCallbackPropName(previousPropName);
  378. const currentIsCallback = isCallbackPropName(currentPropName);
  379. if (ignoreCase) {
  380. previousPropName = previousPropName.toLowerCase();
  381. currentPropName = currentPropName.toLowerCase();
  382. }
  383. if (reservedFirst) {
  384. if (reservedFirstError) {
  385. reservedFirstError(decl);
  386. return memo;
  387. }
  388. const previousIsReserved = isReservedPropName(previousPropName, nodeReservedList);
  389. const currentIsReserved = isReservedPropName(currentPropName, nodeReservedList);
  390. if (previousIsReserved && !currentIsReserved) {
  391. return decl;
  392. }
  393. if (!previousIsReserved && currentIsReserved) {
  394. reportNodeAttribute(decl, 'listReservedPropsFirst', node, context, nodeReservedList);
  395. return memo;
  396. }
  397. }
  398. if (callbacksLast) {
  399. if (!previousIsCallback && currentIsCallback) {
  400. // Entering the callback prop section
  401. return decl;
  402. }
  403. if (previousIsCallback && !currentIsCallback) {
  404. // Encountered a non-callback prop after a callback prop
  405. reportNodeAttribute(memo, 'listCallbacksLast', node, context, nodeReservedList);
  406. return memo;
  407. }
  408. }
  409. if (shorthandFirst) {
  410. if (currentValue && !previousValue) {
  411. return decl;
  412. }
  413. if (!currentValue && previousValue) {
  414. reportNodeAttribute(decl, 'listShorthandFirst', node, context, nodeReservedList);
  415. return memo;
  416. }
  417. }
  418. if (shorthandLast) {
  419. if (!currentValue && previousValue) {
  420. return decl;
  421. }
  422. if (currentValue && !previousValue) {
  423. reportNodeAttribute(memo, 'listShorthandLast', node, context, nodeReservedList);
  424. return memo;
  425. }
  426. }
  427. const previousIsMultiline = isMultilineProp(memo);
  428. const currentIsMultiline = isMultilineProp(decl);
  429. if (multiline === 'first') {
  430. if (previousIsMultiline && !currentIsMultiline) {
  431. // Exiting the multiline prop section
  432. return decl;
  433. }
  434. if (!previousIsMultiline && currentIsMultiline) {
  435. // Encountered a non-multiline prop before a multiline prop
  436. reportNodeAttribute(decl, 'listMultilineFirst', node, context, nodeReservedList);
  437. return memo;
  438. }
  439. } else if (multiline === 'last') {
  440. if (!previousIsMultiline && currentIsMultiline) {
  441. // Entering the multiline prop section
  442. return decl;
  443. }
  444. if (previousIsMultiline && !currentIsMultiline) {
  445. // Encountered a non-multiline prop after a multiline prop
  446. reportNodeAttribute(memo, 'listMultilineLast', node, context, nodeReservedList);
  447. return memo;
  448. }
  449. }
  450. if (
  451. !noSortAlphabetically
  452. && (
  453. (ignoreCase || locale !== 'auto')
  454. ? previousPropName.localeCompare(currentPropName, locale === 'auto' ? undefined : locale) > 0
  455. : previousPropName > currentPropName
  456. )
  457. ) {
  458. reportNodeAttribute(decl, 'sortPropsByAlpha', node, context, nodeReservedList);
  459. return memo;
  460. }
  461. return decl;
  462. }, node.attributes[0]);
  463. },
  464. };
  465. },
  466. };