Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[selection input] Don't reset selected index when dropdown results don't change #28109

Merged
merged 1 commit into from
Feb 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import {useEffect, useRef} from 'react';

export const usePrevious = <T,>(value: T): T | undefined => {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {SelectionAutoCompleteInputCSS} from './SelectionInputHighlighter';
import {useSelectionInputLintingAndHighlighting} from './useSelectionInputLintingAndHighlighting';
import {useTrackEvent} from '../app/analytics';
import {useDangerousRenderEffect} from '../hooks/useDangerousRenderEffect';
import {usePrevious} from '../hooks/usePrevious';
import {useUpdatingRef} from '../hooks/useUpdatingRef';

import 'codemirror/addon/edit/closebrackets';
Expand Down Expand Up @@ -83,9 +84,23 @@ export const SelectionAutoCompleteInput = ({

const [selectedIndexRef, setSelectedIndex] = useState({current: 0});

// Memoize the stringified results to avoid resetting the selected index down below
const resultsJson = useMemo(() => {
return JSON.stringify(autoCompleteResults?.list.map((l) => l.text));
}, [autoCompleteResults]);

const prevJson = usePrevious(resultsJson);
const prevAutoCompleteResults = usePrevious(autoCompleteResults);

// Handle selection reset
useDangerousRenderEffect(() => {
if (prevAutoCompleteResults?.from !== autoCompleteResults?.from || prevJson !== resultsJson) {
selectedIndexRef.current = 0;
}
}, [resultsJson, autoCompleteResults, prevAutoCompleteResults, prevJson, selectedIndexRef]);

// Handle hiding results
useDangerousRenderEffect(() => {
// Rather then using a useEffect + setState (extra render), we just set the current value directly
selectedIndexRef.current = 0;
if (!autoCompleteResults.list.length && !loading) {
showResults.current = false;
}
Expand Down