jsx-sort-props.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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 docsUrl = require('../util/docsUrl');
  8. const jsxUtil = require('../util/jsx');
  9. // ------------------------------------------------------------------------------
  10. // Rule Definition
  11. // ------------------------------------------------------------------------------
  12. function isCallbackPropName(name) {
  13. return /^on[A-Z]/.test(name);
  14. }
  15. const RESERVED_PROPS_LIST = [
  16. 'children',
  17. 'dangerouslySetInnerHTML',
  18. 'key',
  19. 'ref'
  20. ];
  21. function isReservedPropName(name, list) {
  22. return list.indexOf(name) >= 0;
  23. }
  24. function contextCompare(a, b, options) {
  25. let aProp = propName(a);
  26. let bProp = propName(b);
  27. if (options.reservedFirst) {
  28. const aIsReserved = isReservedPropName(aProp, options.reservedList);
  29. const bIsReserved = isReservedPropName(bProp, options.reservedList);
  30. if (aIsReserved && !bIsReserved) {
  31. return -1;
  32. }
  33. if (!aIsReserved && bIsReserved) {
  34. return 1;
  35. }
  36. }
  37. if (options.callbacksLast) {
  38. const aIsCallback = isCallbackPropName(aProp);
  39. const bIsCallback = isCallbackPropName(bProp);
  40. if (aIsCallback && !bIsCallback) {
  41. return 1;
  42. }
  43. if (!aIsCallback && bIsCallback) {
  44. return -1;
  45. }
  46. }
  47. if (options.shorthandFirst || options.shorthandLast) {
  48. const shorthandSign = options.shorthandFirst ? -1 : 1;
  49. if (!a.value && b.value) {
  50. return shorthandSign;
  51. }
  52. if (a.value && !b.value) {
  53. return -shorthandSign;
  54. }
  55. }
  56. if (options.noSortAlphabetically) {
  57. return 0;
  58. }
  59. if (options.ignoreCase) {
  60. aProp = aProp.toLowerCase();
  61. bProp = bProp.toLowerCase();
  62. return aProp.localeCompare(bProp);
  63. }
  64. if (aProp === bProp) {
  65. return 0;
  66. }
  67. return aProp < bProp ? -1 : 1;
  68. }
  69. /**
  70. * Create an array of arrays where each subarray is composed of attributes
  71. * that are considered sortable.
  72. * @param {Array<JSXSpreadAttribute|JSXAttribute>} attributes
  73. * @return {Array<Array<JSXAttribute>>}
  74. */
  75. function getGroupsOfSortableAttributes(attributes) {
  76. const sortableAttributeGroups = [];
  77. let groupCount = 0;
  78. for (let i = 0; i < attributes.length; i++) {
  79. const lastAttr = attributes[i - 1];
  80. // If we have no groups or if the last attribute was JSXSpreadAttribute
  81. // then we start a new group. Append attributes to the group until we
  82. // come across another JSXSpreadAttribute or exhaust the array.
  83. if (
  84. !lastAttr
  85. || (lastAttr.type === 'JSXSpreadAttribute'
  86. && attributes[i].type !== 'JSXSpreadAttribute')
  87. ) {
  88. groupCount++;
  89. sortableAttributeGroups[groupCount - 1] = [];
  90. }
  91. if (attributes[i].type !== 'JSXSpreadAttribute') {
  92. sortableAttributeGroups[groupCount - 1].push(attributes[i]);
  93. }
  94. }
  95. return sortableAttributeGroups;
  96. }
  97. const generateFixerFunction = (node, context, reservedList) => {
  98. const sourceCode = context.getSourceCode();
  99. const attributes = node.attributes.slice(0);
  100. const configuration = context.options[0] || {};
  101. const ignoreCase = configuration.ignoreCase || false;
  102. const callbacksLast = configuration.callbacksLast || false;
  103. const shorthandFirst = configuration.shorthandFirst || false;
  104. const shorthandLast = configuration.shorthandLast || false;
  105. const noSortAlphabetically = configuration.noSortAlphabetically || false;
  106. const reservedFirst = configuration.reservedFirst || false;
  107. // Sort props according to the context. Only supports ignoreCase.
  108. // Since we cannot safely move JSXSpreadAttribute (due to potential variable overrides),
  109. // we only consider groups of sortable attributes.
  110. const options = {
  111. ignoreCase,
  112. callbacksLast,
  113. shorthandFirst,
  114. shorthandLast,
  115. noSortAlphabetically,
  116. reservedFirst,
  117. reservedList
  118. };
  119. const sortableAttributeGroups = getGroupsOfSortableAttributes(attributes);
  120. const sortedAttributeGroups = sortableAttributeGroups
  121. .slice(0)
  122. .map((group) => group.slice(0).sort((a, b) => contextCompare(a, b, options)));
  123. return function fixFunction(fixer) {
  124. const fixers = [];
  125. let source = sourceCode.getText();
  126. // Replace each unsorted attribute with the sorted one.
  127. sortableAttributeGroups.forEach((sortableGroup, ii) => {
  128. sortableGroup.forEach((attr, jj) => {
  129. const sortedAttr = sortedAttributeGroups[ii][jj];
  130. const sortedAttrText = sourceCode.getText(sortedAttr);
  131. fixers.push({
  132. range: [attr.range[0], attr.range[1]],
  133. text: sortedAttrText
  134. });
  135. });
  136. });
  137. fixers.sort((a, b) => b.range[0] - a.range[0]);
  138. const rangeStart = fixers[fixers.length - 1].range[0];
  139. const rangeEnd = fixers[0].range[1];
  140. fixers.forEach((fix) => {
  141. source = `${source.substr(0, fix.range[0])}${fix.text}${source.substr(fix.range[1])}`;
  142. });
  143. return fixer.replaceTextRange([rangeStart, rangeEnd], source.substr(rangeStart, rangeEnd - rangeStart));
  144. };
  145. };
  146. /**
  147. * Checks if the `reservedFirst` option is valid
  148. * @param {Object} context The context of the rule
  149. * @param {Boolean|Array<String>} reservedFirst The `reservedFirst` option
  150. * @return {Function|undefined} If an error is detected, a function to generate the error message, otherwise, `undefined`
  151. */
  152. // eslint-disable-next-line consistent-return
  153. function validateReservedFirstConfig(context, reservedFirst) {
  154. if (reservedFirst) {
  155. if (Array.isArray(reservedFirst)) {
  156. // Only allow a subset of reserved words in customized lists
  157. const nonReservedWords = reservedFirst.filter((word) => !isReservedPropName(
  158. word,
  159. RESERVED_PROPS_LIST
  160. ));
  161. if (reservedFirst.length === 0) {
  162. return function report(decl) {
  163. context.report({
  164. node: decl,
  165. messageId: 'listIsEmpty'
  166. });
  167. };
  168. }
  169. if (nonReservedWords.length > 0) {
  170. return function report(decl) {
  171. context.report({
  172. node: decl,
  173. messageId: 'noUnreservedProps',
  174. data: {
  175. unreservedWords: nonReservedWords.toString()
  176. }
  177. });
  178. };
  179. }
  180. }
  181. }
  182. }
  183. module.exports = {
  184. meta: {
  185. docs: {
  186. description: 'Enforce props alphabetical sorting',
  187. category: 'Stylistic Issues',
  188. recommended: false,
  189. url: docsUrl('jsx-sort-props')
  190. },
  191. fixable: 'code',
  192. messages: {
  193. noUnreservedProps: 'A customized reserved first list must only contain a subset of React reserved props. Remove: {{unreservedWords}}',
  194. listIsEmpty: 'A customized reserved first list must not be empty',
  195. listReservedPropsFirst: 'Reserved props must be listed before all other props',
  196. listCallbacksLast: 'Callbacks must be listed after all other props',
  197. listShorthandFirst: 'Shorthand props must be listed before all other props',
  198. listShorthandLast: 'Shorthand props must be listed after all other props',
  199. sortPropsByAlpha: 'Props should be sorted alphabetically'
  200. },
  201. schema: [{
  202. type: 'object',
  203. properties: {
  204. // Whether callbacks (prefixed with "on") should be listed at the very end,
  205. // after all other props. Supersedes shorthandLast.
  206. callbacksLast: {
  207. type: 'boolean'
  208. },
  209. // Whether shorthand properties (without a value) should be listed first
  210. shorthandFirst: {
  211. type: 'boolean'
  212. },
  213. // Whether shorthand properties (without a value) should be listed last
  214. shorthandLast: {
  215. type: 'boolean'
  216. },
  217. ignoreCase: {
  218. type: 'boolean'
  219. },
  220. // Whether alphabetical sorting should be enforced
  221. noSortAlphabetically: {
  222. type: 'boolean'
  223. },
  224. reservedFirst: {
  225. type: ['array', 'boolean']
  226. }
  227. },
  228. additionalProperties: false
  229. }]
  230. },
  231. create(context) {
  232. const configuration = context.options[0] || {};
  233. const ignoreCase = configuration.ignoreCase || false;
  234. const callbacksLast = configuration.callbacksLast || false;
  235. const shorthandFirst = configuration.shorthandFirst || false;
  236. const shorthandLast = configuration.shorthandLast || false;
  237. const noSortAlphabetically = configuration.noSortAlphabetically || false;
  238. const reservedFirst = configuration.reservedFirst || false;
  239. const reservedFirstError = validateReservedFirstConfig(context, reservedFirst);
  240. let reservedList = Array.isArray(reservedFirst) ? reservedFirst : RESERVED_PROPS_LIST;
  241. return {
  242. JSXOpeningElement(node) {
  243. // `dangerouslySetInnerHTML` is only "reserved" on DOM components
  244. if (reservedFirst && !jsxUtil.isDOMComponent(node)) {
  245. reservedList = reservedList.filter((prop) => prop !== 'dangerouslySetInnerHTML');
  246. }
  247. node.attributes.reduce((memo, decl, idx, attrs) => {
  248. if (decl.type === 'JSXSpreadAttribute') {
  249. return attrs[idx + 1];
  250. }
  251. let previousPropName = propName(memo);
  252. let currentPropName = propName(decl);
  253. const previousValue = memo.value;
  254. const currentValue = decl.value;
  255. const previousIsCallback = isCallbackPropName(previousPropName);
  256. const currentIsCallback = isCallbackPropName(currentPropName);
  257. if (ignoreCase) {
  258. previousPropName = previousPropName.toLowerCase();
  259. currentPropName = currentPropName.toLowerCase();
  260. }
  261. if (reservedFirst) {
  262. if (reservedFirstError) {
  263. reservedFirstError(decl);
  264. return memo;
  265. }
  266. const previousIsReserved = isReservedPropName(previousPropName, reservedList);
  267. const currentIsReserved = isReservedPropName(currentPropName, reservedList);
  268. if (previousIsReserved && !currentIsReserved) {
  269. return decl;
  270. }
  271. if (!previousIsReserved && currentIsReserved) {
  272. context.report({
  273. node: decl.name,
  274. messageId: 'listReservedPropsFirst',
  275. fix: generateFixerFunction(node, context, reservedList)
  276. });
  277. return memo;
  278. }
  279. }
  280. if (callbacksLast) {
  281. if (!previousIsCallback && currentIsCallback) {
  282. // Entering the callback prop section
  283. return decl;
  284. }
  285. if (previousIsCallback && !currentIsCallback) {
  286. // Encountered a non-callback prop after a callback prop
  287. context.report({
  288. node: memo.name,
  289. messageId: 'listCallbacksLast',
  290. fix: generateFixerFunction(node, context, reservedList)
  291. });
  292. return memo;
  293. }
  294. }
  295. if (shorthandFirst) {
  296. if (currentValue && !previousValue) {
  297. return decl;
  298. }
  299. if (!currentValue && previousValue) {
  300. context.report({
  301. node: memo.name,
  302. messageId: 'listShorthandFirst',
  303. fix: generateFixerFunction(node, context, reservedList)
  304. });
  305. return memo;
  306. }
  307. }
  308. if (shorthandLast) {
  309. if (!currentValue && previousValue) {
  310. return decl;
  311. }
  312. if (currentValue && !previousValue) {
  313. context.report({
  314. node: memo.name,
  315. messageId: 'listShorthandLast',
  316. fix: generateFixerFunction(node, context, reservedList)
  317. });
  318. return memo;
  319. }
  320. }
  321. if (
  322. !noSortAlphabetically
  323. && (
  324. ignoreCase
  325. ? previousPropName.localeCompare(currentPropName) > 0
  326. : previousPropName > currentPropName
  327. )
  328. ) {
  329. context.report({
  330. node: decl.name,
  331. messageId: 'sortPropsByAlpha',
  332. fix: generateFixerFunction(node, context, reservedList)
  333. });
  334. return memo;
  335. }
  336. return decl;
  337. }, node.attributes[0]);
  338. }
  339. };
  340. }
  341. };