jsx.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * @fileoverview Utility functions for JSX
  3. */
  4. 'use strict';
  5. const elementType = require('jsx-ast-utils/elementType');
  6. // See https://github.com/babel/babel/blob/ce420ba51c68591e057696ef43e028f41c6e04cd/packages/babel-types/src/validators/react/isCompatTag.js
  7. // for why we only test for the first character
  8. const COMPAT_TAG_REGEX = /^[a-z]/;
  9. /**
  10. * Checks if a node represents a DOM element according to React.
  11. * @param {object} node - JSXOpeningElement to check.
  12. * @returns {boolean} Whether or not the node corresponds to a DOM element.
  13. */
  14. function isDOMComponent(node) {
  15. const name = elementType(node);
  16. return COMPAT_TAG_REGEX.test(name);
  17. }
  18. /**
  19. * Test whether a JSXElement is a fragment
  20. * @param {JSXElement} node
  21. * @param {string} reactPragma
  22. * @param {string} fragmentPragma
  23. * @returns {boolean}
  24. */
  25. function isFragment(node, reactPragma, fragmentPragma) {
  26. const name = node.openingElement.name;
  27. // <Fragment>
  28. if (name.type === 'JSXIdentifier' && name.name === fragmentPragma) {
  29. return true;
  30. }
  31. // <React.Fragment>
  32. if (
  33. name.type === 'JSXMemberExpression'
  34. && name.object.type === 'JSXIdentifier'
  35. && name.object.name === reactPragma
  36. && name.property.type === 'JSXIdentifier'
  37. && name.property.name === fragmentPragma
  38. ) {
  39. return true;
  40. }
  41. return false;
  42. }
  43. /**
  44. * Checks if a node represents a JSX element or fragment.
  45. * @param {object} node - node to check.
  46. * @returns {boolean} Whether or not the node if a JSX element or fragment.
  47. */
  48. function isJSX(node) {
  49. return node && ['JSXElement', 'JSXFragment'].indexOf(node.type) >= 0;
  50. }
  51. /**
  52. * Check if node is like `key={...}` as in `<Foo key={...} />`
  53. * @param {ASTNode} node
  54. * @returns {boolean}
  55. */
  56. function isJSXAttributeKey(node) {
  57. return node.type === 'JSXAttribute'
  58. && node.name
  59. && node.name.type === 'JSXIdentifier'
  60. && node.name.name === 'key';
  61. }
  62. /**
  63. * Check if value has only whitespaces
  64. * @param {string} value
  65. * @returns {boolean}
  66. */
  67. function isWhiteSpaces(value) {
  68. return typeof value === 'string' ? /^\s*$/.test(value) : false;
  69. }
  70. module.exports = {
  71. isDOMComponent,
  72. isFragment,
  73. isJSX,
  74. isJSXAttributeKey,
  75. isWhiteSpaces
  76. };