diff --git a/packages/@react-stately/list/src/useListState.ts b/packages/@react-stately/list/src/useListState.ts index c373633426e..22d4a497cbd 100644 --- a/packages/@react-stately/list/src/useListState.ts +++ b/packages/@react-stately/list/src/useListState.ts @@ -90,18 +90,8 @@ function useFocusedKeyReset(collection: Collection>, selectionManager useEffect(() => { if (selectionManager.focusedKey != null && !collection.getItem(selectionManager.focusedKey) && cachedCollection.current) { const startItem = cachedCollection.current.getItem(selectionManager.focusedKey); - const cachedItemNodes = [...cachedCollection.current.getKeys()].map( - key => { - const itemNode = cachedCollection.current!.getItem(key); - return itemNode?.type === 'item' ? itemNode : null; - } - ).filter(node => node !== null); - const itemNodes = [...collection.getKeys()].map( - key => { - const itemNode = collection.getItem(key); - return itemNode?.type === 'item' ? itemNode : null; - } - ).filter(node => node !== null); + const cachedItemNodes = Array.from(cachedCollection.current).filter(itemNode => itemNode.type === 'item'); + const itemNodes = Array.from(collection).filter(itemNode => itemNode.type === 'item'); const diff: number = (cachedItemNodes?.length ?? 0) - (itemNodes?.length ?? 0); let index = Math.min( ( diff --git a/packages/react-aria-components/stories/TagGroup.stories.tsx b/packages/react-aria-components/stories/TagGroup.stories.tsx index 7fe3a0159a2..393bbb064b8 100644 --- a/packages/react-aria-components/stories/TagGroup.stories.tsx +++ b/packages/react-aria-components/stories/TagGroup.stories.tsx @@ -11,9 +11,9 @@ */ import {action} from '@storybook/addon-actions'; -import {Button, Label, OverlayArrow, Tag, TagGroup, TagGroupProps, TagList, TagProps, Tooltip, TooltipTrigger} from 'react-aria-components'; +import {Button, Label, OverlayArrow, Tag, TagGroup, TagGroupProps, TagList, TagProps, Tooltip, TooltipTrigger, useListData} from 'react-aria-components'; import {Meta, StoryObj} from '@storybook/react'; -import React from 'react'; +import React, {useRef} from 'react'; import './styles.css'; const meta: Meta = { @@ -120,3 +120,37 @@ export const EmptyTagGroup: Story = { ) }; + +const RestoreFocus = (props: TagGroupProps) => { + const list = useListData<{id: number, label: string}>({ + initialItems: [] + }); + + const nextIdRef = useRef(0); + + const insertItem = () => { + const id = nextIdRef.current++; + list.insert(0, { + id, + label: `Item ${id + 1}` + }); + }; + + return ( +
+ list.remove(...keys)}> + + + 'No categories.'}> + {item => {item.label}} + + +
+ ); +}; + +export const RestoreFocusExample: Story = { + render: (props: TagGroupProps) => ( + + ) +};