Skip to content

Commit

Permalink
Rewrite by deriving from record
Browse files Browse the repository at this point in the history
  • Loading branch information
ellatrix committed Feb 28, 2023
1 parent d116f9f commit ebafb85
Showing 1 changed file with 19 additions and 25 deletions.
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 );

// 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

0 comments on commit ebafb85

Please sign in to comment.