Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(formatting): render children as function #338

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/formatter/formatReactFunctionNode.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/* @flow */

import spacer from './spacer';
import formatTreeNode from './formatTreeNode';
import type { Options } from './../options';
import type { ReactFunctionTreeNode } from './../tree';

export default (
node: ReactFunctionTreeNode,
inline: boolean,
lvl: number,
options: Options
): string => {
const { tabStop } = options;
const { type, childrens } = node;

if (type !== 'ReactFunction') {
throw new Error(
`The "formatReactFunctionNode" function could only format node of type "ReactFunction". Given: ${type}`
);
}

const functionRender = Array.isArray(childrens)
? childrens
.map(children => formatTreeNode(children, false, lvl + 1, options))
.join('\n')
: formatTreeNode(childrens, false, lvl + 1, options);

const out = `{() => (
${spacer(lvl + 1, tabStop)}${functionRender}
${spacer(lvl, tabStop)})}`;

return `${out}`;
};
5 changes: 5 additions & 0 deletions src/formatter/formatTreeNode.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import formatReactElementNode from './formatReactElementNode';
import formatReactFragmentNode from './formatReactFragmentNode';
import formatReactFunctionNode from './formatReactFunctionNode';
import type { Options } from './../options';
import type { TreeNode } from './../tree';

Expand Down Expand Up @@ -54,5 +55,9 @@ export default (
return formatReactFragmentNode(node, inline, lvl, options);
}

if (node.type === 'ReactFunction') {
return formatReactFunctionNode(node, inline, lvl, options);
}

throw new TypeError(`Unknow format type "${node.type}"`);
};
16 changes: 16 additions & 0 deletions src/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -898,6 +898,22 @@ describe('reactElementToJSXString(ReactElement)', () => {
);
});

it('reactElementToJSXString(<div>{() => (<div>Hello World</div>)}</div>)', () => {
expect(
reactElementToJSXString(<div>{() => <div>Hello World</div>}</div>, {
showFunctions: true,
})
).toEqual(
`<div>
{() => (
<div>
Hello World
</div>
)}
</div>`
);
});

it('reactElementToJSXString(<DisplayNamePrecedence />)', () => {
expect(reactElementToJSXString(<DisplayNamePrecedence />)).toEqual(
'<This should take precedence />'
Expand Down
9 changes: 9 additions & 0 deletions src/parser/parseReactElement.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
createStringTreeNode,
createNumberTreeNode,
createReactElementTreeNode,
createReactFunctionTreeNode,
createReactFragmentTreeNode,
} from './../tree';
import type { TreeNode } from './../tree';
Expand Down Expand Up @@ -71,6 +72,14 @@ const parseReactElement = (
.filter(onlyMeaningfulChildren)
.map(child => parseReactElement(child, options));

if (typeof element.props.children === 'function') {
const functionChildrens = parseReactElement(
element.props.children(),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm worried about the need to call the children function to be able to format it's result. This could have unwanted side effect in the user land.

For example:

reactElementToJSXString(
  <div>
    {() => {
      console.log('Should not be logged');

      return <div>Hello World</div>;
    }}
  </div>,
  {
    showFunctions: true,
  }
)

options
);
childrens.push(createReactFunctionTreeNode([functionChildrens]));
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One gotcha with this detection method is is case of mixed children (or multiple function as a children):

// Multiple functions as child
reactElementToJSXString(
  <div>
    {() => <div>Hello Foo</div>}
    {() => <div>Hello Bar</div>}
  </div>,
  {
    showFunctions: true,
  }
)

// Mixed content
reactElementToJSXString(
  <div>
    {() => <div>Hello Foo</div>}
    <span>Some other children</span>
  </div>,
  {
    showFunctions: true,
  }
)

I know this is should not be frequent or maybe event imaginable but the JSX allow it 🤷‍♂️

I do some try with you PR, it's a shame that React.Children filters out the function children. We do not want to re-implement it to be able to conserve function in our parsing.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This and this is related to React.Children behavior.

if (supportFragment && element.type === Fragment) {
return createReactFragmentTreeNode(key, childrens);
}
Expand Down
25 changes: 25 additions & 0 deletions src/parser/parseReactElement.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,31 @@ describe('parseReactElement', () => {
});
});

it('should parse a react element with a function as children', () => {
expect(
parseReactElement(<h1>{() => <div>hello world</div>}</h1>, options)
).toEqual({
childrens: [
{
childrens: [
{
childrens: [{ type: 'string', value: 'hello world' }],
defaultProps: {},
displayName: 'div',
props: {},
type: 'ReactElement',
},
],
type: 'ReactFunction',
},
],
defaultProps: {},
displayName: 'h1',
props: {},
type: 'ReactElement',
});
});

it('should filter empty childrens', () => {
expect(
parseReactElement(
Expand Down
15 changes: 14 additions & 1 deletion src/tree.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ export type NumberTreeNode = {|
value: number,
|};

export type ReactFunctionTreeNode = {|
type: 'ReactFunction',
childrens: TreeNode[],
|};

export type ReactElementTreeNode = {|
type: 'ReactElement',
displayName: string,
Expand All @@ -34,7 +39,8 @@ export type TreeNode =
| StringTreeNode
| NumberTreeNode
| ReactElementTreeNode
| ReactFragmentTreeNode;
| ReactFragmentTreeNode
| ReactFunctionTreeNode;

export const createStringTreeNode = (value: string): StringTreeNode => ({
type: 'string',
Expand All @@ -46,6 +52,13 @@ export const createNumberTreeNode = (value: number): NumberTreeNode => ({
value,
});

export const createReactFunctionTreeNode = (
childrens: TreeNode[]
): ReactFunctionTreeNode => ({
type: 'ReactFunction',
childrens,
});

export const createReactElementTreeNode = (
displayName: string,
props: PropsType,
Expand Down