formatReactFragmentNode.js.flow 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* @flow */
  2. import type { Key } from 'react';
  3. import formatReactElementNode from './formatReactElementNode';
  4. import type { Options } from './../options';
  5. import type {
  6. ReactElementTreeNode,
  7. ReactFragmentTreeNode,
  8. TreeNode,
  9. } from './../tree';
  10. const REACT_FRAGMENT_TAG_NAME_SHORT_SYNTAX = '';
  11. const REACT_FRAGMENT_TAG_NAME_EXPLICIT_SYNTAX = 'React.Fragment';
  12. const toReactElementTreeNode = (
  13. displayName: string,
  14. key: ?Key,
  15. childrens: TreeNode[]
  16. ): ReactElementTreeNode => {
  17. let props = {};
  18. if (key) {
  19. props = { key };
  20. }
  21. return {
  22. type: 'ReactElement',
  23. displayName,
  24. props,
  25. defaultProps: {},
  26. childrens,
  27. };
  28. };
  29. const isKeyedFragment = ({ key }: ReactFragmentTreeNode) => Boolean(key);
  30. const hasNoChildren = ({ childrens }: ReactFragmentTreeNode) =>
  31. childrens.length === 0;
  32. export default (
  33. node: ReactFragmentTreeNode,
  34. inline: boolean,
  35. lvl: number,
  36. options: Options
  37. ): string => {
  38. const { type, key, childrens } = node;
  39. if (type !== 'ReactFragment') {
  40. throw new Error(
  41. `The "formatReactFragmentNode" function could only format node of type "ReactFragment". Given: ${type}`
  42. );
  43. }
  44. const { useFragmentShortSyntax } = options;
  45. let displayName;
  46. if (useFragmentShortSyntax) {
  47. if (hasNoChildren(node) || isKeyedFragment(node)) {
  48. displayName = REACT_FRAGMENT_TAG_NAME_EXPLICIT_SYNTAX;
  49. } else {
  50. displayName = REACT_FRAGMENT_TAG_NAME_SHORT_SYNTAX;
  51. }
  52. } else {
  53. displayName = REACT_FRAGMENT_TAG_NAME_EXPLICIT_SYNTAX;
  54. }
  55. return formatReactElementNode(
  56. toReactElementTreeNode(displayName, key, childrens),
  57. inline,
  58. lvl,
  59. options
  60. );
  61. };