pragma.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * @fileoverview Utility functions for React pragma configuration
  3. * @author Yannick Croissant
  4. */
  5. 'use strict';
  6. const JSX_ANNOTATION_REGEX = /@jsx\s+([^\s]+)/;
  7. // Does not check for reserved keywords or unicode characters
  8. const JS_IDENTIFIER_REGEX = /^[_$a-zA-Z][_$a-zA-Z0-9]*$/;
  9. /**
  10. * @param {Context} context
  11. * @returns {string}
  12. */
  13. function getCreateClassFromContext(context) {
  14. let pragma = 'createReactClass';
  15. // .eslintrc shared settings (https://eslint.org/docs/user-guide/configuring#adding-shared-settings)
  16. if (context.settings.react && context.settings.react.createClass) {
  17. pragma = context.settings.react.createClass;
  18. }
  19. if (!JS_IDENTIFIER_REGEX.test(pragma)) {
  20. throw new Error(`createClass pragma ${pragma} is not a valid function name`);
  21. }
  22. return pragma;
  23. }
  24. /**
  25. * @param {Context} context
  26. * @returns {string}
  27. */
  28. function getFragmentFromContext(context) {
  29. let pragma = 'Fragment';
  30. // .eslintrc shared settings (https://eslint.org/docs/user-guide/configuring#adding-shared-settings)
  31. if (context.settings.react && context.settings.react.fragment) {
  32. pragma = context.settings.react.fragment;
  33. }
  34. if (!JS_IDENTIFIER_REGEX.test(pragma)) {
  35. throw new Error(`Fragment pragma ${pragma} is not a valid identifier`);
  36. }
  37. return pragma;
  38. }
  39. /**
  40. * @param {Context} context
  41. * @returns {string}
  42. */
  43. function getFromContext(context) {
  44. let pragma = 'React';
  45. const sourceCode = context.getSourceCode();
  46. const pragmaNode = sourceCode.getAllComments().find((node) => JSX_ANNOTATION_REGEX.test(node.value));
  47. if (pragmaNode) {
  48. const matches = JSX_ANNOTATION_REGEX.exec(pragmaNode.value);
  49. pragma = matches[1].split('.')[0];
  50. // .eslintrc shared settings (https://eslint.org/docs/user-guide/configuring#adding-shared-settings)
  51. } else if (context.settings.react && context.settings.react.pragma) {
  52. pragma = context.settings.react.pragma;
  53. }
  54. if (!JS_IDENTIFIER_REGEX.test(pragma)) {
  55. throw new Error(`React pragma ${pragma} is not a valid identifier`);
  56. }
  57. return pragma;
  58. }
  59. module.exports = {
  60. getCreateClassFromContext,
  61. getFragmentFromContext,
  62. getFromContext,
  63. };