-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathComboboxInput.tsx
168 lines (153 loc) · 5.1 KB
/
ComboboxInput.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import { useMergeRefs } from '@floating-ui/react';
import { ChevronDownIcon, ChevronUpIcon } from '@navikt/aksel-icons';
import cl from 'clsx/lite';
import type { ChangeEvent } from 'react';
import { useContext, useRef } from 'react';
import { omit } from '../../../../utilities';
import { Box } from '../../../Box';
import { Paragraph } from '../../../Typography';
import type { ComboboxProps } from '../Combobox';
import { ComboboxContext } from '../ComboboxContext';
import { useComboboxIdDispatch } from '../ComboboxIdContext';
import { prefix } from '../utilities';
import ComboboxChips from './ComboboxChips';
import ComboboxClearButton from './ComboboxClearButton';
type ComboboxInputProps = {
hideClearButton: ComboboxProps['hideClearButton'];
listId: string;
error: ComboboxProps['error'];
hideChips: NonNullable<ComboboxProps['hideChips']>;
handleKeyDown: (event: React.KeyboardEvent) => void;
} & Omit<React.InputHTMLAttributes<HTMLInputElement>, 'size'>;
const ComboboxInput = ({
hideClearButton,
listId,
error,
hideChips,
handleKeyDown,
...rest
}: ComboboxInputProps) => {
const context = useContext(ComboboxContext);
const idDispatch = useComboboxIdDispatch();
const clearButtonRef = useRef<HTMLButtonElement>(null);
if (!context) {
throw new Error('ComboboxContext is missing');
}
const setActiveIndex = (id: number) => {
idDispatch?.({ type: 'SET_ACTIVE_INDEX', payload: id });
};
const {
forwareddRef,
readOnly,
disabled,
open,
inputRef,
refs,
inputValue,
multiple,
selectedOptions,
formFieldProps,
htmlSize,
options,
setOpen,
getReferenceProps,
setInputValue,
handleSelectOption,
size,
} = context;
const mergedRefs = useMergeRefs([forwareddRef, inputRef]);
// onChange function for the input
const onChange = (event: ChangeEvent<HTMLInputElement>) => {
const value = event.target.value;
setInputValue(value);
setActiveIndex(0);
// check if input value is the same as a label, if so, select it
for (const option of Object.values(options)) {
if (option.label.toLowerCase() === value.toLowerCase()) {
/* if option is already selected, discard selecting it, since it would de-select */
if (selectedOptions[prefix(option.value)]) continue;
handleSelectOption({ option });
}
}
};
const showClearButton =
!hideClearButton && Object.keys(selectedOptions).length > 0;
/* Props from floating-ui */
const props = getReferenceProps({
ref: refs?.setReference,
role: null,
'aria-controls': null,
'aria-expanded': null,
'aria-haspopup': null,
/* If we click the wrapper, toggle open, set index to first option, and focus the input */
onClick(event: React.MouseEvent<HTMLDivElement>) {
if (disabled) return;
if (readOnly) return;
if (clearButtonRef.current?.contains(event.target as Node)) return;
setOpen(!open);
setActiveIndex(0);
inputRef.current?.focus();
},
/* Handles list navigation */
onKeyDown: handleKeyDown,
// preventDefault on keydown to avoid sending in form
onKeyPress(event: React.KeyboardEvent<HTMLDivElement>) {
if (event.key === 'Enter') {
event.preventDefault();
}
},
});
return (
<Paragraph size={size} asChild>
<Box
{...props}
aria-disabled={disabled ? 'true' : undefined}
className={cl(
'ds-textfield__input',
'ds-combobox__input__wrapper',
readOnly && 'ds-combobox--readonly',
error && 'ds-combobox--error',
)}
>
<div className={'ds-combobox__chip-and-input'}>
{/* If the input is in multiple mode, we need to display chips */}
{multiple && !hideChips && <ComboboxChips />}
<Paragraph size={size} asChild>
<input
ref={mergedRefs}
aria-activedescendant={props['aria-activedescendant'] as string}
readOnly={readOnly}
aria-autocomplete='list'
role='combobox'
aria-expanded={open}
aria-controls={listId}
autoComplete='off'
size={htmlSize}
value={inputValue}
{...omit(['style', 'className'], rest)}
{...formFieldProps.inputProps}
className='ds-combobox__input'
onChange={(e) => {
onChange(e);
!open && setOpen(true);
rest.onChange?.(e);
}}
/>
</Paragraph>
</div>
{/* Clear button if we are in multiple mode and have at least one active value */}
{showClearButton && <ComboboxClearButton ref={clearButtonRef} />}
{/* Arrow for combobox. Click is handled by the wrapper */}
<div className={'ds-combobox__arrow'}>
{open ? (
<ChevronUpIcon title='arrow up' fontSize='1.5em' />
) : (
<ChevronDownIcon title='arrow down' fontSize='1.5em' />
)}
</div>
</Box>
</Paragraph>
);
};
ComboboxInput.displayName = 'ComboboxInput';
export default ComboboxInput;