Skip to content

Commit e287d8b

Browse files
committed
fix(ComboBox): allow selecting by enter
1 parent a1db063 commit e287d8b

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

src/components/fields/ComboBox/ComboBox.stories.tsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,11 @@ const TemplateForm: StoryFn<CubeComboBoxProps<any>> = (
4242

4343
return (
4444
<Flow gap="2x">
45-
<Form form={form} defaultValues={{ combobox: 'red' }}>
45+
<Form
46+
form={form}
47+
defaultValues={{ combobox: 'red' }}
48+
onSubmit={(data) => console.log('! submit', data)}
49+
>
4650
<ComboBox name="combobox" {...args}>
4751
<ComboBox.Item key="red">Red</ComboBox.Item>
4852
<ComboBox.Item key="orange">Orange</ComboBox.Item>

src/components/fields/ComboBox/ComboBox.tsx

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
forwardRef,
55
ReactElement,
66
RefObject,
7+
useEffect,
78
useMemo,
89
} from 'react';
910
import {
@@ -17,6 +18,7 @@ import {
1718
} from 'react-aria';
1819
import { Item, useComboBoxState } from 'react-stately';
1920

21+
import { useEvent } from '../../../_internal/index';
2022
import { useFieldProps, useFormProps, wrapWithField } from '../../form';
2123
import { DEFAULT_INPUT_STYLES, INPUT_WRAPPER_STYLES } from '../index';
2224
import { 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

Comments
 (0)