diff --git a/src/column-layout/flexible-column-layout/index.tsx b/src/column-layout/flexible-column-layout/index.tsx index ef4fffb6bf6..edf89d44961 100644 --- a/src/column-layout/flexible-column-layout/index.tsx +++ b/src/column-layout/flexible-column-layout/index.tsx @@ -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'; @@ -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 (
{ - 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 (
{ + test('does not log a key warning when text children are mixed with elements', () => { + const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {}); + const wrapper = render( + +
Element
+ Text +
+ ); + 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']); diff --git a/src/grid/internal.tsx b/src/grid/internal.tsx index d6ad27632bc..a4df0ca2d9a 100644 --- a/src/grid/internal.tsx +++ b/src/grid/internal.tsx @@ -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'; @@ -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 (
({ ...jest.requireActual('@cloudscape-design/component-toolkit/internal'), @@ -97,3 +98,31 @@ describe('flattenChildren', () => { }); }); }); + +describe('getFlattenedChildKey', () => { + const mixedChildren = [ + A, + 'text', + 0, + B, + 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(Portal, 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(Portal, document.body), 2)).toBe('primitive-2'); + }); +}); diff --git a/src/internal/utils/flatten-children.ts b/src/internal/utils/flatten-children.ts index 557229677cb..99fa0037d61 100644 --- a/src/internal/utils/flatten-children.ts +++ b/src/internal/utils/flatten-children.ts @@ -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'; @@ -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}`; +} diff --git a/src/space-between/__tests__/space-between.test.tsx b/src/space-between/__tests__/space-between.test.tsx index 4f1c0f11270..9ef71954627 100644 --- a/src/space-between/__tests__/space-between.test.tsx +++ b/src/space-between/__tests__/space-between.test.tsx @@ -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( + + Element + Text + {42} + + ); + expect(consoleError).not.toHaveBeenCalled(); + expect(container.firstElementChild!.children).toHaveLength(3); + consoleError.mockRestore(); + }); +}); + describe('native attributes', () => { it('adds native attributes', () => { const { container } = render( diff --git a/src/space-between/internal.tsx b/src/space-between/internal.tsx index 7257cb153dc..a9202ab2615 100644 --- a/src/space-between/internal.tsx +++ b/src/space-between/internal.tsx @@ -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'; @@ -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 (
{child}