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

Autocomplete: avoid calling setState on input #48565

Merged
merged 1 commit into from
Feb 28, 2023
Merged
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
44 changes: 19 additions & 25 deletions packages/components/src/autocomplete/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -418,53 +418,47 @@ function useAutocomplete( {
};
}

function useLastDifferentValue( value ) {
const history = useRef( new Set() );

history.current.add( value );
youknowriad marked this conversation as resolved.
Show resolved Hide resolved

// Keep the history size to 2.
if ( history.current.size > 2 ) {
history.current.delete( Array.from( history.current )[ 0 ] );
}

return Array.from( history.current )[ 0 ];
}

export function useAutocompleteProps( options ) {
const [ isVisible, setIsVisible ] = useState( false );
const ref = useRef();
const recordAfterInput = useRef();
const onKeyDownRef = useRef();
const { record } = options;
const previousRecord = useLastDifferentValue( record );
const { popover, listBoxId, activeId, onKeyDown } = useAutocomplete( {
...options,
contentRef: ref,
} );
onKeyDownRef.current = onKeyDown;

useEffect( () => {
if ( isVisible ) {
if ( ! recordAfterInput.current ) {
recordAfterInput.current = options.record;
} else if (
recordAfterInput.current.start !== options.record.start ||
recordAfterInput.current.end !== options.record.end
) {
setIsVisible( false );
recordAfterInput.current = null;
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ options.record ] );

const mergedRefs = useMergeRefs( [
ref,
useRefEffect( ( element ) => {
function _onKeyDown( event ) {
onKeyDownRef.current( event );
}
function _onInput() {
// Only show auto complete UI if the user is inputting text.
setIsVisible( true );
recordAfterInput.current = null;
}
element.addEventListener( 'keydown', _onKeyDown );
element.addEventListener( 'input', _onInput );
return () => {
element.removeEventListener( 'keydown', _onKeyDown );
element.removeEventListener( 'input', _onInput );
};
}, [] ),
] );

if ( ! isVisible ) {
// We only want to show the popover if the user has typed something.
const didUserInput = record.text !== previousRecord?.text;

if ( ! didUserInput ) {
return { ref: mergedRefs };
}

Expand Down