jsx-sort-props.js 17 KB

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