Skip to content
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
7 changes: 2 additions & 5 deletions src/column-layout/flexible-column-layout/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import clsx from 'clsx';

import { useContainerQuery } from '@cloudscape-design/component-toolkit';

import { flattenChildren } from '../../internal/utils/flatten-children';
import { flattenChildren, getFlattenedChildKey } from '../../internal/utils/flatten-children';
import { InternalColumnLayoutProps } from '../internal-interfaces';

import styles from './styles.css.js';
Expand Down Expand Up @@ -67,12 +67,9 @@ export default function FlexibleColumnLayout({
style={{ gridTemplateColumns: `repeat(${columnCount}, minmax(0, 1fr))` }}
>
{flattenedChildren.map((child, i) => {
// If this react child is a primitive value, the key will be undefined
const key = child && typeof child === 'object' ? (child as Record<'key', unknown>).key : undefined;

return (
<div
key={key ? String(key) : undefined}
key={getFlattenedChildKey(child, i)}
className={clsx(styles.item, {
[styles['first-column']]: i % columnCount === 0,
})}
Expand Down
5 changes: 2 additions & 3 deletions src/control-group/internal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
import { FormFieldContext, useFormFieldContext } from '../internal/context/form-field-context';
import { InternalBaseComponentProps } from '../internal/hooks/use-base-component';
import { useFitsInline } from '../internal/hooks/use-fits-inline';
import { flattenChildren } from '../internal/utils/flatten-children';
import { flattenChildren, getFlattenedChildKey } from '../internal/utils/flatten-children';
import { joinStrings } from '../internal/utils/strings/join-strings';
import { ControlGroupProps } from './interfaces';

Expand Down Expand Up @@ -64,13 +64,12 @@ export default function InternalControlGroup({
? 'horizontal' // The ghost always uses horizontal mode for measuring
: resolvedDirection;
return flattenedChildren.map((child, index) => {
const key = child && typeof child === 'object' ? (child as Record<'key', unknown>).key : undefined;
const position: GroupedControlPosition =
controlCount === 1 ? 'only' : index === 0 ? 'first' : index === controlCount - 1 ? 'last' : 'middle';
const isLeading = slotDirection === 'vertical' || position === 'first' || position === 'only';
return (
<div
key={key !== null && key !== undefined ? String(key) : index}
key={getFlattenedChildKey(child, index)}
className={clsx(
// Make sure that test utils exclude the ghost
!isGhost && testUtilStyles.control,
Expand Down
13 changes: 13 additions & 0 deletions src/grid/__tests__/grid.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ function renderColumnInGrid(props: GridProps = {}) {
}

describe('Grid component', () => {
test('does not log a key warning when text children are mixed with elements', () => {
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {});
const wrapper = render(
<Grid gridDefinition={[{ colspan: 6 }, { colspan: 6 }]}>
<div>Element</div>
Text
</Grid>
);
expect(consoleError).not.toHaveBeenCalled();
expect(createWrapper(wrapper.container).findGrid()!.findColumn(2)!.getElement()).toHaveTextContent('Text');
consoleError.mockRestore();
});

test('has gutters by default', () => {
const wrapper = renderGrid();
expect(wrapper.getElement()).not.toHaveClass(styles['no-gutters']);
Expand Down
7 changes: 2 additions & 5 deletions src/grid/internal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { matchBreakpointMapping } from '../internal/breakpoints';
import { useContainerBreakpoints } from '../internal/hooks/container-queries';
import { InternalBaseComponentProps } from '../internal/hooks/use-base-component';
import { isDevelopment } from '../internal/is-development';
import { flattenChildren } from '../internal/utils/flatten-children';
import { flattenChildren, getFlattenedChildKey } from '../internal/utils/flatten-children';
import { Breakpoint } from '../types/breakpoint';
import { GridProps } from './interfaces';

Expand Down Expand Up @@ -82,12 +82,9 @@ const InternalGrid = React.forwardRef(
ref={mergedRef}
>
{flattenedChildren.map((child, i) => {
// If this react child is a primitive value, the key will be undefined
const key = child && typeof child === 'object' ? (child as Record<'key', unknown>).key : undefined;

return (
<div
key={key ? String(key) : undefined}
key={getFlattenedChildKey(child, i)}
className={clsx(
styles['grid-column'],
getColumnClassNames('colspan', gridDefinition[i]?.colspan, defaultBreakpoint),
Expand Down
31 changes: 30 additions & 1 deletion src/internal/utils/__tests__/flatten-children.test.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import React, { Fragment } from 'react';
import { createPortal } from 'react-dom';

import { warnOnce } from '@cloudscape-design/component-toolkit/internal';

import { flattenChildren } from '../flatten-children';
import { flattenChildren, getFlattenedChildKey } from '../flatten-children';

jest.mock('@cloudscape-design/component-toolkit/internal', () => ({
...jest.requireActual('@cloudscape-design/component-toolkit/internal'),
Expand Down Expand Up @@ -97,3 +98,31 @@ describe('flattenChildren', () => {
});
});
});

describe('getFlattenedChildKey', () => {
const mixedChildren = [
<span key="a">A</span>,
'text',
0,
<span key="b">B</span>,
React.createElement('span', null, 'C'),
'more text',
];

it('returns unique keys for mixed children', () => {
const keys = flattenChildren(mixedChildren, 'TestComponent').map(getFlattenedChildKey);
expect(keys).toHaveLength(mixedChildren.length);
expect(new Set(keys).size).toBe(keys.length);
expect(keys.filter(key => key.startsWith('primitive-'))).toEqual(['primitive-1', 'primitive-2', 'primitive-5']);
});

it('keeps keyed portals stable across positions', () => {
const portal = createPortal(<span>Portal</span>, document.body, 'p1');
expect(getFlattenedChildKey(portal, 0)).toBe('portal-p1');
expect(getFlattenedChildKey(portal, 3)).toBe('portal-p1');
});

it('keys unkeyed portals by position', () => {
expect(getFlattenedChildKey(createPortal(<span>Portal</span>, document.body), 2)).toBe('primitive-2');
});
});
19 changes: 18 additions & 1 deletion src/internal/utils/flatten-children.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import React, { ReactNode } from 'react';
import React, { isValidElement, ReactNode } from 'react';
import { isPortal } from 'react-is';

import flattenChildrenLegacy from '../vendor/react-keyed-flatten-children';
import { getReactMajorVersion } from './react-version';
Expand All @@ -26,3 +27,19 @@ export function flattenChildren(children: ReactNode, componentName: string): Rea
}
return React.Children.toArray(children);
}

/**
* Returns a key for a wrapper element rendered around a flattened child. Elements keep the key that
* flattening assigned them, which always contains a "." (such as ".0" or ".$custom"). Portals keep
* their own key, which flattening leaves as-is, so it gets a prefix. Strings, numbers, and unkeyed
* portals are keyed by position. The prefixes keep the three kinds of keys from colliding.
*/
export function getFlattenedChildKey(child: ReactNode, index: number): string {
if (isValidElement(child) && child.key !== null) {
return String(child.key);
}
if (isPortal(child) && child.key !== null) {
return `portal-${child.key}`;
}
return `primitive-${index}`;
}
16 changes: 16 additions & 0 deletions src/space-between/__tests__/space-between.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,22 @@ describe('SpaceBetween', () => {
});
});

describe('mixed children', () => {
it('does not log a key warning when text children are mixed with elements', () => {
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {});
const { container } = render(
<SpaceBetween size="s">
<span>Element</span>
Text
{42}
</SpaceBetween>
);
expect(consoleError).not.toHaveBeenCalled();
expect(container.firstElementChild!.children).toHaveLength(3);
consoleError.mockRestore();
});
});

describe('native attributes', () => {
it('adds native attributes', () => {
const { container } = render(
Expand Down
9 changes: 3 additions & 6 deletions src/space-between/internal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { useMergeRefs } from '@cloudscape-design/component-toolkit/internal';

import { getBaseProps } from '../internal/base-component';
import { InternalBaseComponentProps } from '../internal/hooks/use-base-component';
import { flattenChildren } from '../internal/utils/flatten-children';
import { flattenChildren, getFlattenedChildKey } from '../internal/utils/flatten-children';
import WithNativeAttributes from '../internal/utils/with-native-attributes';
import { SpaceBetweenProps } from './interfaces';

Expand Down Expand Up @@ -53,13 +53,10 @@ const InternalSpaceBetween = forwardRef(
)}
ref={mergedRef}
>
{flattenedChildren.map(child => {
// If this react child is a primitive value, the key will be undefined
const key = child && typeof child === 'object' ? (child as Record<'key', unknown>).key : undefined;

{flattenedChildren.map((child, index) => {
return (
<div
key={key ? String(key) : undefined}
key={getFlattenedChildKey(child, index)}
className={clsx(styles.child, propagateAlignment && styles['child-aligned'])}
>
{child}
Expand Down
Loading