-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathCombobox.tsx
496 lines (468 loc) · 13.8 KB
/
Combobox.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
import { FloatingFocusManager, FloatingPortal } from '@floating-ui/react';
import { useVirtualizer } from '@tanstack/react-virtual';
import cl from 'clsx/lite';
import { forwardRef, useEffect, useId, useRef, useState } from 'react';
import type { InputHTMLAttributes, ReactNode } from 'react';
import type { PortalProps } from '../../../types/Portal';
import { omit, useDebounceCallback } from '../../../utilities';
import { Box } from '../../Box';
import { Spinner } from '../../Spinner';
import type { FormFieldProps } from '../useFormField';
import { useFormField } from '../useFormField';
import { ComboboxContext } from './ComboboxContext';
import { ComboboxIdProvider } from './ComboboxIdContext';
import { ComboboxCustom } from './Custom';
import ComboboxError from './internal/ComboboxError';
import ComboboxInput from './internal/ComboboxInput';
import ComboboxLabel from './internal/ComboboxLabel';
import ComboboxNative from './internal/ComboboxNative';
import type { Option } from './useCombobox';
import { useCombobox } from './useCombobox';
import { useComboboxKeyboard } from './useComboboxKeyboard';
import { useFloatingCombobox } from './useFloatingCombobox';
import { prefix, removePrefix, setReactInputValue } from './utilities';
export type ComboboxProps = {
/**
* Label for the combobox.
*
* Passed label will be encapsulated by a `label` element.
*/
label?: ReactNode;
/**
* Visually hides `label` and `description` (still available for screen readers)
* @default false
*/
hideLabel?: boolean;
/**
* String array of selected options. Contains only one option during single selection mode.
*/
value?: string[];
/**
* String array of initial selected options. Contains only one option during single selection mode.
*/
initialValue?: string[];
/**
* Callback function that is called when the value changes
*/
onValueChange?: (value: string[]) => void;
/**
* Multiple options can be selected
* @default false
*/
multiple?: boolean;
/**
* Name of the value when used in a form
*/
name?: string;
/**
* Exposes the HTML `size` attribute.
* @default 0
*/
htmlSize?: number;
/**
* Hides chips when multiple options are selected
* @default false
*/
hideChips?: boolean;
/**
* Hides the clear button
* @default false
*/
hideClearButton?: boolean;
/**
* Label for the clear button
* @default 'Fjern alt'
*/
clearButtonLabel?: string;
/**
* Enables virtualizing of options list.
* @see https://tanstack.com/virtual
* @default false
*/
virtual?: boolean;
/**
* Value of the input field
*/
inputValue?: string;
/**
* Adds `aria-busy` and displays loading state for the Combobox
* All options will be hidden and replaced with a loading message.
* @default false
*/
loading?: boolean;
/**
* Text to display when the combobox is loading
* @default 'Laster...'
*/
loadingLabel?: string;
/**
* Filter function for filtering the list of options. Return `true` to show option, `false` to hide option.
* @param inputValue
* @param option
* @returns boolean
*
* @default (inputValue, option) => option.value.toLowerCase().startsWith(inputValue.toLowerCase())
*/
filter?: (inputValue: string, option: Option) => boolean;
/**
* Add a screen reader label to the chips
* @param option
* @returns string
*
* @default (option) => 'Slett ' + option.label,
*/
chipSrLabel?: (option: Option) => string;
} & PortalProps &
FormFieldProps &
Omit<InputHTMLAttributes<HTMLInputElement>, 'size'>;
export const ComboboxComponent = forwardRef<HTMLInputElement, ComboboxProps>(
(
{
value,
initialValue = [],
onValueChange,
label,
hideLabel = false,
description,
multiple = false,
disabled = false,
readOnly = false,
hideChips = false,
clearButtonLabel = 'Fjern alt',
hideClearButton = false,
error,
errorId,
id,
name,
portal = true,
htmlSize = 0,
virtual = false,
children,
style,
size = 'md',
loading,
loadingLabel = 'Laster...',
filter,
chipSrLabel = (option) => 'Slett ' + option.label,
className,
...rest
},
forwareddRef,
) => {
const inputRef = useRef<HTMLInputElement>(null);
const portalRef = useRef<HTMLDivElement>(null);
const listRef = useRef<Array<HTMLElement | null>>([]);
const listId = useId();
const [inputValue, setInputValue] = useState<string>(rest.inputValue || '');
useEffect(() => {
if (typeof rest.inputValue === 'string') {
setInputValue(rest.inputValue);
}
}, [rest.inputValue]);
const {
selectedOptions,
options,
restChildren,
interactiveChildren,
customIds,
filteredOptionsChildren,
filteredOptions,
setSelectedOptions,
} = useCombobox({
children,
inputValue,
filter,
multiple,
initialValue,
});
const {
open,
setOpen,
refs,
floatingStyles,
context,
getReferenceProps,
getFloatingProps,
getItemProps,
} = useFloatingCombobox({
listRef,
});
const formFieldProps = useFormField(
{
disabled,
readOnly,
error,
errorId,
size,
description,
id,
},
'combobox',
);
// if value is set, set input value to the label of the value
useEffect(() => {
if (value && value.length > 0 && !multiple) {
const option = options[prefix(value[0])];
inputRef.current &&
setReactInputValue(inputRef.current, option?.label || '');
}
}, [multiple, value, options]);
useEffect(() => {
if (value && Object.keys(options).length >= 0) {
const updatedSelectedOptions = value.map((option) => {
const value = options[prefix(option)];
return value;
});
setSelectedOptions(
updatedSelectedOptions.reduce<{
[key: string]: Option;
}>((acc, value) => {
acc[prefix(value.value)] = value;
return acc;
}, {}),
);
}
}, [multiple, value, options, setSelectedOptions]);
// handle click on option, either select or deselect - Handles single or multiple
const handleSelectOption = (args: {
option: Option | null;
remove?: boolean;
clear?: boolean;
}) => {
const { option, clear, remove } = args;
if (clear) {
setSelectedOptions({});
inputRef.current && setReactInputValue(inputRef.current, '');
onValueChange?.([]);
return;
}
if (!option) return;
if (remove) {
const newSelectedOptions = { ...selectedOptions };
delete newSelectedOptions[prefix(option.value)];
setSelectedOptions(newSelectedOptions);
onValueChange?.(
Object.keys(newSelectedOptions).map((key) => removePrefix(key)),
);
return;
}
const newSelectedOptions = { ...selectedOptions };
if (multiple) {
if (newSelectedOptions[prefix(option.value)]) {
delete newSelectedOptions[prefix(option.value)];
} else {
newSelectedOptions[prefix(option.value)] = option;
}
inputRef.current && setReactInputValue(inputRef.current, '');
inputRef.current?.focus();
} else {
/* clear newSelectedOptions */
for (const key of Object.keys(newSelectedOptions)) {
delete newSelectedOptions[key];
}
newSelectedOptions[prefix(option.value)] = option;
inputRef.current &&
setReactInputValue(inputRef.current, option?.label || '');
// move cursor to the end of the input
setTimeout(() => {
inputRef.current?.setSelectionRange(
option?.label?.length || 0,
option?.label?.length || 0,
);
}, 0);
}
setSelectedOptions(newSelectedOptions);
onValueChange?.(
Object.keys(newSelectedOptions).map((key) => removePrefix(key)),
);
!multiple && setOpen(false);
refs.domReference.current?.focus();
};
const debouncedHandleSelectOption = useDebounceCallback(
handleSelectOption,
50,
);
const handleKeyDown = useComboboxKeyboard({
filteredOptions,
selectedOptions,
readOnly: formFieldProps.readOnly || false,
disabled: disabled,
multiple,
inputValue,
options,
open,
interactiveChildren,
setOpen,
setInputValue,
handleSelectOption: debouncedHandleSelectOption,
});
const rowVirtualizer = useVirtualizer({
count: Object.keys(filteredOptionsChildren).length,
getScrollElement: () => (virtual ? refs.floating.current : null),
estimateSize: () => 70,
measureElement: (elem) => {
return elem.getBoundingClientRect().height;
},
overscan: 7,
});
return (
<ComboboxContext.Provider
value={{
size,
options,
selectedOptions,
multiple,
disabled,
readOnly,
open,
inputRef,
refs,
inputValue,
formFieldProps,
htmlSize,
clearButtonLabel,
customIds,
filteredOptions,
setInputValue,
setOpen,
getReferenceProps,
getItemProps,
/* Recieves the value of the option, and searches for it in our values lookup */
onOptionClick: (value: string) => {
if (readOnly) return;
if (disabled) return;
const option = options[prefix(value)];
debouncedHandleSelectOption({ option: option });
},
handleSelectOption: debouncedHandleSelectOption,
chipSrLabel,
listRef,
forwareddRef,
setListRef: (index: number, node: HTMLElement | null) => {
listRef.current[index] = node;
},
}}
>
<Box
className={cl(
'ds-combobox',
`ds-combobox--${size}`,
disabled && 'ds-combobox__disabled',
className,
)}
style={style}
ref={portalRef}
>
{/* This is only for the Combobox to work in forms */}
{name && (
<ComboboxNative
name={name}
selectedOptions={selectedOptions}
multiple={multiple}
/>
)}
<ComboboxLabel
label={label}
description={description}
size={size}
readOnly={readOnly}
hideLabel={hideLabel}
formFieldProps={formFieldProps}
/>
<ComboboxInput
{...omit(['inputValue'], rest)}
hideClearButton={hideClearButton}
listId={listId}
error={error}
hideChips={hideChips}
handleKeyDown={handleKeyDown}
aria-busy={loading}
/>
<ComboboxError
size={size}
error={error}
formFieldProps={formFieldProps}
/>
</Box>
{/* This is the floating list with options */}
{open && (
<FloatingPortal root={portal ? null : portalRef}>
<FloatingFocusManager
context={context}
initialFocus={-1}
visuallyHiddenDismiss
>
<Box
id={listId}
shadow='md'
borderRadius='md'
borderColor='default'
aria-labelledby={formFieldProps.inputProps.id}
aria-autocomplete='list'
tabIndex={-1}
{...getFloatingProps({
ref: refs.setFloating,
style: {
...floatingStyles,
},
})}
className={cl(
'ds-combobox__options-wrapper',
`ds-combobox--${size}`,
)}
>
{virtual && (
<div
style={{
height: `${rowVirtualizer.getTotalSize()}px`,
width: '100%',
position: 'relative',
}}
>
{/* Render the virtualized rows */}
{rowVirtualizer.getVirtualItems().map((virtualRow) => (
<div
key={virtualRow.index}
ref={rowVirtualizer.measureElement}
data-index={virtualRow.index}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
transform: `translateY(${virtualRow.start}px)`,
}}
>
{filteredOptionsChildren[virtualRow.index]}
</div>
))}
</div>
)}
{loading ? (
<ComboboxCustom className={'ds-combobox__loading'}>
<Spinner title='Laster' size='sm' />
{loadingLabel}
</ComboboxCustom>
) : (
<>
{/* Add the rest of the children */}
{restChildren}
{!virtual && filteredOptionsChildren}
</>
)}
</Box>
</FloatingFocusManager>
</FloatingPortal>
)}
</ComboboxContext.Provider>
);
},
);
export const Combobox = forwardRef<HTMLInputElement, ComboboxProps>(
(props, ref) => (
<ComboboxIdProvider>
<ComboboxComponent {...props} ref={ref} />
</ComboboxIdProvider>
),
);
Combobox.displayName = 'Combobox';