44 forwardRef ,
55 ReactElement ,
66 RefObject ,
7+ useEffect ,
78 useMemo ,
89} from 'react' ;
910import {
@@ -17,6 +18,7 @@ import {
1718} from 'react-aria' ;
1819import { Item , useComboBoxState } from 'react-stately' ;
1920
21+ import { useEvent } from '../../../_internal/index' ;
2022import { useFieldProps , useFormProps , wrapWithField } from '../../form' ;
2123import { DEFAULT_INPUT_STYLES , INPUT_WRAPPER_STYLES } from '../index' ;
2224import { useProviderProps } from '../../../provider' ;
@@ -318,6 +320,33 @@ export const ComboBox = forwardRef(function ComboBox<T extends object>(
318320 ] ,
319321 ) ;
320322
323+ // If input is not full and the user presses Enter, pick the first option.
324+ let onKeyPress = useEvent ( ( e : KeyboardEvent ) => {
325+ if ( e . key === 'Enter' && ! props . allowsCustomValue && state . isOpen ) {
326+ const option = [ ...state . collection ] [ 0 ] ?. key ;
327+
328+ if ( option ) {
329+ props . onSelectionChange ?.( option ) ;
330+
331+ e . stopPropagation ( ) ;
332+ e . preventDefault ( ) ;
333+ }
334+ }
335+ } ) ;
336+
337+ useEffect ( ( ) => {
338+ ref . current ?. addEventListener ( 'keydown' , onKeyPress , true ) ;
339+
340+ return ( ) => {
341+ ref . current ?. removeEventListener ( 'keydown' , onKeyPress , true ) ;
342+ } ;
343+ } , [ ] ) ;
344+
345+ let allInputProps = useMemo (
346+ ( ) => mergeProps ( inputProps , hoverProps , focusProps ) ,
347+ [ inputProps , hoverProps , focusProps ] ,
348+ ) ;
349+
321350 let comboBoxField = (
322351 < ComboBoxWrapperElement
323352 ref = { wrapperRef }
@@ -333,7 +362,7 @@ export const ComboBox = forwardRef(function ComboBox<T extends object>(
333362 qa = "Input"
334363 autoFocus = { autoFocus }
335364 data-autofocus = { autoFocus ? '' : undefined }
336- { ...mergeProps ( inputProps , hoverProps , focusProps ) }
365+ { ...allInputProps }
337366 ref = { inputRef }
338367 autoComplete = { autoComplete }
339368 styles = { inputStyles }
0 commit comments