fix(autocomplete): persist last selected item position (#5286)

* refactor(select): remove unnecessary code

* fix(autocomplete): persist last selected item position

* chore(changeset): add changeset
This commit is contained in:
WK 2025-06-02 00:52:21 +08:00 committed by GitHub
parent 8c2613713a
commit 74e4deca9a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 26 additions and 19 deletions

View File

@ -0,0 +1,6 @@
---
"@heroui/autocomplete": patch
"@heroui/select": patch
---
persist last selected item position (#5282)

View File

@ -349,6 +349,26 @@ export function useAutocomplete<T extends object>(originalProps: UseAutocomplete
state.selectionManager.setFocusedKey(key);
}, [state.collection, state.disabledKeys]);
// scroll the listbox to the selected item
useEffect(() => {
if (state.isOpen && popoverRef.current && listBoxRef.current) {
let selectedItem = listBoxRef.current.querySelector("[aria-selected=true] [data-label=true]");
let scrollShadow = scrollShadowRef.current;
if (selectedItem && scrollShadow && selectedItem.parentElement) {
let scrollShadowRect = scrollShadow?.getBoundingClientRect();
let scrollShadowHeight = scrollShadowRect.height;
scrollShadow.scrollTop =
selectedItem.parentElement.offsetTop -
scrollShadowHeight / 2 +
selectedItem.parentElement.clientHeight / 2;
state.selectionManager.setFocusedKey(state.selectedKey);
}
}
}, [state.isOpen, disableAnimation]);
useEffect(() => {
if (isOpen) {
// apply the same with to the popover as the select

View File

@ -382,25 +382,6 @@ export function useSelect<T extends object>(originalProps: UseSelectProps<T>) {
[objectToDeps(variantProps), isInvalid, labelPlacement, disableAnimation],
);
// scroll the listbox to the selected item
useEffect(() => {
if (state.isOpen && popoverRef.current && listBoxRef.current) {
let selectedItem = listBoxRef.current.querySelector("[aria-selected=true] [data-label=true]");
let scrollShadow = scrollShadowRef.current;
// scroll the listbox to the selected item
if (selectedItem && scrollShadow && selectedItem.parentElement) {
let scrollShadowRect = scrollShadow?.getBoundingClientRect();
let scrollShadowHeight = scrollShadowRect.height;
scrollShadow.scrollTop =
selectedItem.parentElement.offsetTop -
scrollShadowHeight / 2 +
selectedItem.parentElement.clientHeight / 2;
}
}
}, [state.isOpen, disableAnimation]);
usePreventScroll({
isDisabled: !state.isOpen,
});