From 202962bd0c51e854994016021715e83751f4c549 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matuzal=C3=A9m=20Teles?= Date: Thu, 15 Feb 2024 10:49:37 -0600 Subject: [PATCH] fix(@clayui/core): fixes bug when visual focus is lost when items are updated in Picker --- packages/clay-core/src/picker/Picker.tsx | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/packages/clay-core/src/picker/Picker.tsx b/packages/clay-core/src/picker/Picker.tsx index bc477d9732..bfe117d346 100644 --- a/packages/clay-core/src/picker/Picker.tsx +++ b/packages/clay-core/src/picker/Picker.tsx @@ -192,7 +192,7 @@ export function Picker | string | number>({ }); const [activeDescendant, setActiveDescendant] = useState(() => - typeof selectedKey !== 'undefined' + selectedKey || selectedKey === 0 ? selectedKey : collection.getFirstItem().key ); @@ -272,6 +272,19 @@ export function Picker | string | number>({ } }, [active]); + // When the items are updated, the visual focus is stale, meaning that when + // navigating via the keyboard it will not work because the key does not + // exist in the list, so we need to update the visual focus when the list + // is updated during the component life cycle. + useEffect(() => { + if ( + !collection.getItem(selectedKey) && + !collection.getItem(activeDescendant) + ) { + setActiveDescendant(collection.getFirstItem().key); + } + }, [items]); + const [isArrowVisible, setIsArrowVisible] = useState< null | 'top' | 'bottom' | 'both' >(null); @@ -491,9 +504,9 @@ export function Picker | string | number>({ onPress(); } else { const key = - typeof selectedKey === 'undefined' - ? collection.getFirstItem().key - : selectedKey; + selectedKey || selectedKey === 0 + ? selectedKey + : collection.getFirstItem().key; if (key !== activeDescendant) { setActiveDescendant(key);