pragma.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. function getCreateClassFromContext(context) {
  10. let pragma = 'createReactClass';
  11. // .eslintrc shared settings (http://eslint.org/docs/user-guide/configuring#adding-shared-settings)
  12. if (context.settings.react && context.settings.react.createClass) {
  13. pragma = context.settings.react.createClass;
  14. }
  15. if (!JS_IDENTIFIER_REGEX.test(pragma)) {
  16. throw new Error(`createClass pragma ${pragma} is not a valid function name`);
  17. }
  18. return pragma;
  19. }
  20. function getFragmentFromContext(context) {
  21. let pragma = 'Fragment';
  22. // .eslintrc shared settings (http://eslint.org/docs/user-guide/configuring#adding-shared-settings)
  23. if (context.settings.react && context.settings.react.fragment) {
  24. pragma = context.settings.react.fragment;
  25. }
  26. if (!JS_IDENTIFIER_REGEX.test(pragma)) {
  27. throw new Error(`Fragment pragma ${pragma} is not a valid identifier`);
  28. }
  29. return pragma;
  30. }
  31. function getFromContext(context) {
  32. let pragma = 'React';
  33. const sourceCode = context.getSourceCode();
  34. const pragmaNode = sourceCode.getAllComments().find((node) => JSX_ANNOTATION_REGEX.test(node.value));
  35. if (pragmaNode) {
  36. const matches = JSX_ANNOTATION_REGEX.exec(pragmaNode.value);
  37. pragma = matches[1].split('.')[0];
  38. // .eslintrc shared settings (http://eslint.org/docs/user-guide/configuring#adding-shared-settings)
  39. } else if (context.settings.react && context.settings.react.pragma) {
  40. pragma = context.settings.react.pragma;
  41. }
  42. if (!JS_IDENTIFIER_REGEX.test(pragma)) {
  43. throw new Error(`React pragma ${pragma} is not a valid identifier`);
  44. }
  45. return pragma;
  46. }
  47. module.exports = {
  48. getCreateClassFromContext,
  49. getFragmentFromContext,
  50. getFromContext
  51. };