Skip to content

Commit

Permalink
fix(CustomSelect): auto scroll only on open
Browse files Browse the repository at this point in the history
  • Loading branch information
BlackySoul committed Jan 22, 2025
1 parent 9205131 commit 5d4e0d5
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions packages/vkui/src/components/CustomSelect/CustomSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,7 @@ export function CustomSelect<OptionInterfaceT extends CustomSelectOptionInterfac
const scrollBoxRef = React.useRef<HTMLDivElement | null>(null);
const selectElRef = useExternRef(getRef);
const optionsWrapperRef = React.useRef<HTMLDivElement>(null);
const scrollPerformedRef = React.useRef(false);

const [focusedOptionIndex, setFocusedOptionIndex] = React.useState<number | undefined>(-1);
const [isControlledOutside, setIsControlledOutside] = React.useState(props.value !== undefined);
Expand Down Expand Up @@ -426,18 +427,27 @@ export function CustomSelect<OptionInterfaceT extends CustomSelectOptionInterfac
[options.length],
);

const setScrollBoxRef = React.useCallback(
(ref: HTMLDivElement | null) => {
scrollBoxRef.current = ref;
const setScrollBoxRef = React.useCallback((ref: HTMLDivElement | null) => {
scrollBoxRef.current = ref;
}, []);

if (ref && selectedOptionIndex !== undefined && isValidIndex(selectedOptionIndex)) {
{
scrollToElement(selectedOptionIndex, true);
}
}
},
[isValidIndex, scrollToElement, selectedOptionIndex],
);
useIsomorphicLayoutEffect(() => {
if (!opened) {
scrollPerformedRef.current = false;
return;
}

if (scrollPerformedRef.current) {
return;
}

const isIndexValid = selectedOptionIndex !== undefined && isValidIndex(selectedOptionIndex);

if (scrollBoxRef.current && isIndexValid) {
scrollPerformedRef.current = true;
scrollToElement(selectedOptionIndex, true);
}
}, [opened, selectedOptionIndex, scrollToElement, isValidIndex]);

const [keyboardInput, setKeyboardInput] = React.useState('');
const resetKeyboardInput = React.useCallback(() => {
Expand Down

0 comments on commit 5d4e0d5

Please sign in to comment.