From 64efcf43d0197fda4f077f89025a3a75d06c89d4 Mon Sep 17 00:00:00 2001 From: Frankie Yan Date: Thu, 10 Aug 2023 23:45:15 -0700 Subject: [PATCH] Better focus management on open and on search --- src/combobox/combobox.module.css | 7 +++++ src/combobox/combobox.stories.tsx | 43 +++++++++++++++++-------------- 2 files changed, 31 insertions(+), 19 deletions(-) diff --git a/src/combobox/combobox.module.css b/src/combobox/combobox.module.css index 7f4fe8f9a..0e9f8f931 100644 --- a/src/combobox/combobox.module.css +++ b/src/combobox/combobox.module.css @@ -1,5 +1,12 @@ +/* Item being hovered or focused */ .comboboxItem[data-active-item], +/* Item currently selected */ .comboboxItem[aria-selected='true'] { background-color: hsl(204 100% 40%); color: white; } + +.popover { + max-height: 150px; + overflow-y: scroll; +} diff --git a/src/combobox/combobox.stories.tsx b/src/combobox/combobox.stories.tsx index 7e27203c6..444137579 100644 --- a/src/combobox/combobox.stories.tsx +++ b/src/combobox/combobox.stories.tsx @@ -63,9 +63,7 @@ const team = [ export function ComboboxStory() { const [searchValue, setSearchValue] = useState('') const [selectedValue, setSelectedValue] = useState('') - const [activeId, setActiveId] = useState(null) - - console.log({ activeId }) + const [isOpen, setOpen] = useState(false) const matches = useMemo( () => @@ -75,22 +73,12 @@ export function ComboboxStory() { [searchValue], ) - useEffect( - function updateActiveId() { - console.log({ - searchValue, - matches: JSON.stringify(matches.map((match) => match.name)), - }) - setActiveId(matches[0]?.name) - }, - [searchValue, matches, setActiveId], - ) - const onClose = useCallback( function onClose(open: boolean) { if (!open) { setSearchValue(selectedValue) } + setOpen(open) }, [setSearchValue, selectedValue], ) @@ -103,7 +91,6 @@ export function ComboboxStory() { const onSelect = useCallback( (value: string) => { - console.log({ value }) setSearchValue(value) setSelectedValue(value) }, @@ -114,11 +101,29 @@ export function ComboboxStory() { combobox, value: selectedValue, setValue: onSelect, - defaultActiveId: selectedValue ?? null, - activeId, - setActiveId, + defaultActiveId: selectedValue ?? undefined, }) + const { move } = select + + useEffect( + function focusItemOnSearch() { + if (searchValue) { + move(matches[0]?.name) + } + }, + [searchValue, matches, move], + ) + + useEffect( + function focusItemOnOpen() { + if (isOpen) { + move(selectedValue) + } + }, + [isOpen, selectedValue, move], + ) + return (
@@ -133,7 +138,7 @@ export function ComboboxStory() { store={combobox} gutter={8} sameWidth - className="popover" + className={styles.popover} render={} > {team.map((value) => (