Skip to content

Commit a64ff9e

Browse files
committed
Creates unwrapRootFragment
1 parent 000f713 commit a64ff9e

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import React, { Fragment } from 'react';
2+
3+
import { unwrapRootFragment } from './unwrapRootFragment';
4+
5+
describe('packages/lib/unwrapRootFragment', () => {
6+
test('returns a single child that is not a Fragment', () => {
7+
const unwrapped = unwrapRootFragment(<div></div>);
8+
expect(unwrapped).toHaveLength(1);
9+
});
10+
11+
test('returns children unchanged when it is an array', () => {
12+
const unwrapped = unwrapRootFragment([
13+
<div key="1"></div>,
14+
<div key="2"></div>,
15+
]);
16+
expect(unwrapped).toHaveLength(2);
17+
});
18+
19+
test("returns a single Fragment's children", () => {
20+
const unwrapped = unwrapRootFragment(
21+
<Fragment>
22+
<div />
23+
<div />
24+
</Fragment>,
25+
);
26+
expect(unwrapped).toHaveLength(2);
27+
});
28+
29+
test('returns an empty array children has no length', () => {
30+
const unwrapped = unwrapRootFragment([]);
31+
expect(unwrapped).toBeDefined();
32+
expect(unwrapped).toHaveLength(0);
33+
});
34+
35+
test('returns undefined if no children are provided', () => {
36+
const unwrapped = unwrapRootFragment(undefined);
37+
expect(unwrapped).not.toBeDefined();
38+
});
39+
});
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { Children, Fragment, isValidElement, ReactNode } from 'react';
2+
3+
/**
4+
* If the provided `ReactNode` is a single Fragment,
5+
* return the children of that fragment.
6+
*
7+
* Otherwise, returns the `children` or an empty array
8+
*
9+
* e.g.
10+
* ```tsx
11+
* unwrapRootFragment(
12+
* <Fragment>
13+
* <Foo />
14+
* <Bar />
15+
* </Fragment>
16+
* ) // [<Foo />, <Bar />]
17+
* ```
18+
*/
19+
export const unwrapRootFragment = (
20+
children: ReactNode,
21+
): Array<ReactNode> | undefined => {
22+
if (!children) return undefined;
23+
24+
if (Children.count(children) === 0) {
25+
return [];
26+
}
27+
28+
if (Children.count(children) === 1) {
29+
const rootChild = Children.toArray(children)[0];
30+
31+
if (isValidElement(rootChild) && rootChild.type === Fragment) {
32+
return Children.toArray(rootChild.props.children);
33+
}
34+
35+
return [children];
36+
}
37+
38+
return children as Array<ReactNode>;
39+
};

tools/install/src/ALL_PACKAGES.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ export const ALL_PACKAGES = [
7676
'@leafygreen-ui/toolbar',
7777
'@leafygreen-ui/tooltip',
7878
'@leafygreen-ui/typography',
79+
'@leafygreen-ui/wizard',
7980
'@lg-charts/chart-card',
8081
'@lg-charts/colors',
8182
'@lg-charts/core',

0 commit comments

Comments
 (0)