@coreui/react-pro 5.17.1 → 5.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/components/autocomplete/CAutocomplete.d.ts +243 -0
  3. package/dist/cjs/components/autocomplete/CAutocomplete.js +306 -0
  4. package/dist/cjs/components/autocomplete/CAutocomplete.js.map +1 -0
  5. package/dist/cjs/components/autocomplete/CAutocompleteOptions.d.ts +17 -0
  6. package/dist/cjs/components/autocomplete/CAutocompleteOptions.js +72 -0
  7. package/dist/cjs/components/autocomplete/CAutocompleteOptions.js.map +1 -0
  8. package/dist/cjs/components/autocomplete/index.d.ts +2 -0
  9. package/dist/cjs/components/autocomplete/types.d.ts +18 -0
  10. package/dist/cjs/components/autocomplete/utils.d.ts +11 -0
  11. package/dist/cjs/components/autocomplete/utils.js +107 -0
  12. package/dist/cjs/components/autocomplete/utils.js.map +1 -0
  13. package/dist/cjs/components/calendar/CCalendarPanel.js +6 -7
  14. package/dist/cjs/components/calendar/CCalendarPanel.js.map +1 -1
  15. package/dist/cjs/components/calendar/utils.d.ts +19 -5
  16. package/dist/cjs/components/calendar/utils.js +20 -9
  17. package/dist/cjs/components/calendar/utils.js.map +1 -1
  18. package/dist/cjs/components/date-range-picker/CDateRangePicker.js +10 -8
  19. package/dist/cjs/components/date-range-picker/CDateRangePicker.js.map +1 -1
  20. package/dist/cjs/components/index.d.ts +1 -0
  21. package/dist/cjs/components/multi-select/CMultiSelect.d.ts +6 -0
  22. package/dist/cjs/components/multi-select/CMultiSelect.js +13 -12
  23. package/dist/cjs/components/multi-select/CMultiSelect.js.map +1 -1
  24. package/dist/cjs/components/multi-select/CMultiSelectOptions.js +6 -5
  25. package/dist/cjs/components/multi-select/CMultiSelectOptions.js.map +1 -1
  26. package/dist/cjs/components/multi-select/CMultiSelectSelection.js +1 -1
  27. package/dist/cjs/components/multi-select/CMultiSelectSelection.js.map +1 -1
  28. package/dist/cjs/components/multi-select/utils.d.ts +0 -2
  29. package/dist/cjs/components/multi-select/utils.js +0 -26
  30. package/dist/cjs/components/multi-select/utils.js.map +1 -1
  31. package/dist/cjs/components/time-picker/CTimePicker.js +15 -1
  32. package/dist/cjs/components/time-picker/CTimePicker.js.map +1 -1
  33. package/dist/cjs/index.js +2 -0
  34. package/dist/cjs/index.js.map +1 -1
  35. package/dist/cjs/utils/getNextSibling.d.ts +2 -0
  36. package/dist/cjs/utils/getNextSibling.js +23 -0
  37. package/dist/cjs/utils/getNextSibling.js.map +1 -0
  38. package/dist/cjs/utils/getPreviousSibling.d.ts +2 -0
  39. package/dist/cjs/utils/getPreviousSibling.js +22 -0
  40. package/dist/cjs/utils/getPreviousSibling.js.map +1 -0
  41. package/dist/cjs/utils/index.d.ts +3 -1
  42. package/dist/esm/components/autocomplete/CAutocomplete.d.ts +243 -0
  43. package/dist/esm/components/autocomplete/CAutocomplete.js +304 -0
  44. package/dist/esm/components/autocomplete/CAutocomplete.js.map +1 -0
  45. package/dist/esm/components/autocomplete/CAutocompleteOptions.d.ts +17 -0
  46. package/dist/esm/components/autocomplete/CAutocompleteOptions.js +70 -0
  47. package/dist/esm/components/autocomplete/CAutocompleteOptions.js.map +1 -0
  48. package/dist/esm/components/autocomplete/index.d.ts +2 -0
  49. package/dist/esm/components/autocomplete/types.d.ts +18 -0
  50. package/dist/esm/components/autocomplete/utils.d.ts +11 -0
  51. package/dist/esm/components/autocomplete/utils.js +96 -0
  52. package/dist/esm/components/autocomplete/utils.js.map +1 -0
  53. package/dist/esm/components/calendar/CCalendarPanel.js +7 -8
  54. package/dist/esm/components/calendar/CCalendarPanel.js.map +1 -1
  55. package/dist/esm/components/calendar/utils.d.ts +19 -5
  56. package/dist/esm/components/calendar/utils.js +20 -9
  57. package/dist/esm/components/calendar/utils.js.map +1 -1
  58. package/dist/esm/components/date-range-picker/CDateRangePicker.js +10 -8
  59. package/dist/esm/components/date-range-picker/CDateRangePicker.js.map +1 -1
  60. package/dist/esm/components/index.d.ts +1 -0
  61. package/dist/esm/components/multi-select/CMultiSelect.d.ts +6 -0
  62. package/dist/esm/components/multi-select/CMultiSelect.js +14 -13
  63. package/dist/esm/components/multi-select/CMultiSelect.js.map +1 -1
  64. package/dist/esm/components/multi-select/CMultiSelectOptions.js +4 -3
  65. package/dist/esm/components/multi-select/CMultiSelectOptions.js.map +1 -1
  66. package/dist/esm/components/multi-select/CMultiSelectSelection.js +1 -1
  67. package/dist/esm/components/multi-select/CMultiSelectSelection.js.map +1 -1
  68. package/dist/esm/components/multi-select/utils.d.ts +0 -2
  69. package/dist/esm/components/multi-select/utils.js +1 -25
  70. package/dist/esm/components/multi-select/utils.js.map +1 -1
  71. package/dist/esm/components/time-picker/CTimePicker.js +15 -1
  72. package/dist/esm/components/time-picker/CTimePicker.js.map +1 -1
  73. package/dist/esm/index.js +1 -0
  74. package/dist/esm/index.js.map +1 -1
  75. package/dist/esm/utils/getNextSibling.d.ts +2 -0
  76. package/dist/esm/utils/getNextSibling.js +18 -0
  77. package/dist/esm/utils/getNextSibling.js.map +1 -0
  78. package/dist/esm/utils/getPreviousSibling.d.ts +2 -0
  79. package/dist/esm/utils/getPreviousSibling.js +18 -0
  80. package/dist/esm/utils/getPreviousSibling.js.map +1 -0
  81. package/dist/esm/utils/index.d.ts +3 -1
  82. package/package.json +10 -10
  83. package/src/components/autocomplete/CAutocomplete.tsx +846 -0
  84. package/src/components/autocomplete/CAutocompleteOptions.tsx +165 -0
  85. package/src/components/autocomplete/__tests__/CAutocomplete.spec.tsx +244 -0
  86. package/src/components/autocomplete/__tests__/CAutocompleteOptions.spec.tsx +210 -0
  87. package/src/components/autocomplete/index.ts +3 -0
  88. package/src/components/autocomplete/types.ts +25 -0
  89. package/src/components/autocomplete/utils.ts +125 -0
  90. package/src/components/calendar/CCalendarPanel.tsx +5 -15
  91. package/src/components/calendar/utils.ts +24 -10
  92. package/src/components/date-range-picker/CDateRangePicker.tsx +11 -7
  93. package/src/components/index.ts +1 -0
  94. package/src/components/multi-select/CMultiSelect.tsx +23 -4
  95. package/src/components/multi-select/CMultiSelectOptions.tsx +8 -5
  96. package/src/components/multi-select/CMultiSelectSelection.tsx +3 -3
  97. package/src/components/multi-select/utils.ts +0 -34
  98. package/src/components/time-picker/CTimePicker.tsx +14 -4
  99. package/src/utils/getNextSibling.ts +18 -0
  100. package/src/utils/getPreviousSibling.ts +18 -0
  101. package/src/utils/index.ts +4 -0
@@ -0,0 +1,846 @@
1
+ import React, {
2
+ FormEvent,
3
+ forwardRef,
4
+ HTMLAttributes,
5
+ ReactNode,
6
+ useEffect,
7
+ useState,
8
+ useRef,
9
+ useMemo,
10
+ useCallback,
11
+ useId,
12
+ } from 'react'
13
+
14
+ import classNames from 'classnames'
15
+ import PropTypes from 'prop-types'
16
+
17
+ import type { Placement } from '@popperjs/core'
18
+
19
+ import { CConditionalPortal } from '../conditional-portal'
20
+ import { CFormControlWrapper, CFormControlWrapperProps } from '../form/CFormControlWrapper'
21
+ import { CAutocompleteOptions } from './CAutocompleteOptions'
22
+
23
+ import { useForkedRef, usePopper } from '../../hooks'
24
+ import { isRTL } from '../../utils'
25
+ import type { Option, OptionsGroup, Search } from './types'
26
+ import {
27
+ filterOptions,
28
+ flattenOptionsArray,
29
+ getOptionLabel,
30
+ getFirstOptionByLabel,
31
+ isGlobalSearch,
32
+ getFirstOptionByValue,
33
+ isExternalSearch,
34
+ } from './utils'
35
+
36
+ export interface CAutocompleteProps
37
+ extends Omit<CFormControlWrapperProps, 'floatingClassName' | 'floatingLabel'>,
38
+ Omit<HTMLAttributes<HTMLDivElement>, 'onChange' | 'onInput'> {
39
+ /**
40
+ * Only allow selection of predefined options.
41
+ * When `true`, users cannot enter custom values that are not in the options list.
42
+ * When `false`, users can enter and select custom values.
43
+ *
44
+ * @default false
45
+ */
46
+ allowOnlyDefinedOptions?: boolean
47
+
48
+ /**
49
+ * A string of all className you want applied to the base component.
50
+ * These classes will be merged with the default React autocomplete classes.
51
+ */
52
+ className?: string
53
+
54
+ /**
55
+ * Enables selection cleaner element.
56
+ * When `true`, displays a clear button that allows users to reset the selection.
57
+ * The cleaner button is only shown when there is a selection and the component is not disabled or read-only.
58
+ *
59
+ * @default false
60
+ */
61
+ cleaner?: boolean
62
+
63
+ /**
64
+ * Whether to clear the internal search state after selecting an option.
65
+ *
66
+ * When set to `true`, the internal search value used for filtering options is cleared
67
+ * after a selection is made. This affects only the component's internal logic.
68
+ *
69
+ * Note: This does **not** clear the visible input field if the component is using external search
70
+ * or is controlled via the `searchValue` prop. In such cases, clearing must be handled externally.
71
+ *
72
+ * @default true
73
+ */
74
+ clearSearchOnSelect?: boolean
75
+
76
+ /**
77
+ * Specifies the DOM element where the dropdown should be rendered when using portal mode.
78
+ * Can be a DOM element reference, DocumentFragment, function that returns an element or null,
79
+ * or null (renders to document body). Works in conjunction with the `portal` prop to control
80
+ * where the portal content is mounted in the DOM tree.
81
+ */
82
+ container?: DocumentFragment | Element | (() => DocumentFragment | Element | null) | null
83
+
84
+ /**
85
+ * Toggle the disabled state for the component.
86
+ * When `true`, the React.js autocomplete is non-interactive and appears visually disabled.
87
+ * Users cannot type, select options, or trigger the dropdown.
88
+ */
89
+ disabled?: boolean
90
+
91
+ /**
92
+ * Highlight options that match the search criteria.
93
+ * When `true`, matching portions of option labels are visually highlighted
94
+ * based on the current search input value.
95
+ *
96
+ * @default false
97
+ */
98
+ highlightOptionsOnSearch?: boolean
99
+
100
+ /**
101
+ * Set the id attribute for the native input element.
102
+ * This id is used for accessibility purposes and form associations.
103
+ * If not provided, a unique id may be generated automatically.
104
+ */
105
+ id?: string
106
+
107
+ /**
108
+ * Show dropdown indicator/arrow button.
109
+ * When `true`, displays a dropdown arrow button that can be clicked
110
+ * to manually show or hide the options dropdown.
111
+ */
112
+ indicator?: boolean
113
+
114
+ /**
115
+ * When set, the options list will have a loading style: loading spinner and reduced opacity.
116
+ * Use this to indicate that options are being fetched asynchronously.
117
+ * The dropdown remains functional but shows visual loading indicators.
118
+ */
119
+ loading?: boolean
120
+
121
+ /**
122
+ * The name attribute for the input element.
123
+ * Used for form submission and identification in form data.
124
+ * Important for proper form handling and accessibility.
125
+ */
126
+ name?: string
127
+
128
+ /**
129
+ * Execute a function when a user changes the selected option.
130
+ * Called with the selected option object or `undefined` when cleared.
131
+ * This is the primary callback for handling selection changes.
132
+ *
133
+ * @param option - The selected option object, or `undefined` if cleared
134
+ */
135
+ onChange?: (option: Option | null) => void
136
+
137
+ /**
138
+ * Execute a function when the filter/search value changes.
139
+ * Called whenever the user types in the search input.
140
+ * Useful for implementing external search functionality or analytics.
141
+ *
142
+ * @param value - The current search input value
143
+ */
144
+ onInput?: (value: string) => void
145
+
146
+ /**
147
+ * The callback is fired when the dropdown requests to be hidden.
148
+ * Called when the dropdown closes due to user interaction, clicks outside,
149
+ * escape key, or programmatic changes.
150
+ */
151
+ onHide?: () => void
152
+
153
+ /**
154
+ * The callback is fired when the dropdown requests to be shown.
155
+ * Called when the dropdown opens due to user interaction, focus,
156
+ * or programmatic changes.
157
+ */
158
+ onShow?: () => void
159
+
160
+ /**
161
+ * List of option elements.
162
+ * Can contain Option objects, OptionsGroup objects, or plain strings.
163
+ * Plain strings are converted to simple Option objects internally.
164
+ * This is a required prop - the React autocomplete needs options to function.
165
+ */
166
+ options: (Option | OptionsGroup | string)[]
167
+
168
+ /**
169
+ * Sets maxHeight of options list.
170
+ * Controls the maximum height of the dropdown options container.
171
+ * Can be a number (pixels) or a CSS length string (e.g., '200px', '10rem').
172
+ * When content exceeds this height, a scrollbar will appear.
173
+ *
174
+ * @default 'auto'
175
+ */
176
+ optionsMaxHeight?: number | string
177
+
178
+ /**
179
+ * Custom template for rendering individual options.
180
+ * Allows complete customization of how each option appears in the dropdown.
181
+ * The function receives an Option object and should return a ReactNode.
182
+ *
183
+ * @param option - The option object to render
184
+ * @returns ReactNode to display for this option
185
+ */
186
+ optionsTemplate?: (option: Option) => ReactNode
187
+
188
+ /**
189
+ * Custom template for rendering option groups.
190
+ * Allows customization of how option group headers appear in the dropdown.
191
+ * The function receives an OptionsGroup object and should return a ReactNode.
192
+ *
193
+ * @param option - The options group object to render
194
+ * @returns ReactNode to display for this group header
195
+ */
196
+ optionsGroupsTemplate?: (option: OptionsGroup) => ReactNode
197
+
198
+ /**
199
+ * Specifies a short hint that is visible in the search input.
200
+ * Displayed when the input is empty to guide user interaction.
201
+ * Standard HTML input placeholder behavior.
202
+ */
203
+ placeholder?: string
204
+
205
+ /**
206
+ * Renders the autocomplete dropdown in a React portal, allowing it to break out of its
207
+ * parent container's styling constraints (like overflow, z-index, or positioning).
208
+ * When enabled, the dropdown is rendered at the document root level, ensuring it appears
209
+ * above other page elements and isn't clipped by parent containers.
210
+ *
211
+ * @default false
212
+ */
213
+ portal?: boolean
214
+
215
+ /**
216
+ * Toggle the readonly state for the component.
217
+ * When `true`, users can view and interact with the dropdown but cannot
218
+ * type in the search input or modify the selection through typing.
219
+ * Selection via clicking options may still be possible.
220
+ */
221
+ readOnly?: boolean
222
+
223
+ /**
224
+ * When it is present, it indicates that the user must choose a value before submitting the form.
225
+ * Adds HTML5 form validation requirement. The form will not submit
226
+ * until a valid selection is made.
227
+ */
228
+ required?: boolean
229
+
230
+ /**
231
+ * Determines whether the selected options should be cleared when the options list is updated.
232
+ * When `true`, any previously selected options will be reset whenever the options
233
+ * list undergoes a change. This ensures that outdated selections are not retained
234
+ * when new options are provided.
235
+ *
236
+ * @default false
237
+ */
238
+ resetSelectionOnOptionsChange?: boolean
239
+
240
+ /**
241
+ * Enables and configures search functionality.
242
+ * - `'external'`: Search is handled externally, filtering is not applied internally
243
+ * - `'global'`: Enables global keyboard search when dropdown is closed
244
+ * - Object with `external` and `global` boolean properties for fine-grained control
245
+ */
246
+ search?: Search
247
+
248
+ /**
249
+ * Sets the label for no results when filtering.
250
+ * - `false`: Don't show any message when no results found
251
+ * - `true`: Show default "No results found" message
252
+ * - `string`: Show custom text message
253
+ * - `ReactNode`: Show custom component/element
254
+ *
255
+ * @default false
256
+ */
257
+ searchNoResultsLabel?: boolean | string | ReactNode
258
+
259
+ /**
260
+ * Show hint options based on the current input value.
261
+ * When `true`, displays a preview/hint of the first matching option
262
+ * as semi-transparent text in the input field, similar to browser autocomplete.
263
+ *
264
+ * @default false
265
+ */
266
+ showHints?: boolean
267
+
268
+ /**
269
+ * Size the component small or large.
270
+ * - `'sm'`: Small size variant
271
+ * - `'lg'`: Large size variant
272
+ * - `undefined`: Default/medium size
273
+ */
274
+ size?: 'sm' | 'lg'
275
+
276
+ /**
277
+ * Sets the initially selected value for the React.js autocomplete component.
278
+ * Can be a string (matched against option labels) or number (matched against option values).
279
+ * The component will attempt to find and select the matching option on mount.
280
+ */
281
+ value?: number | string
282
+
283
+ /**
284
+ * Enable virtual scroller for the options list.
285
+ * When `true`, only visible options are rendered in the DOM for better performance
286
+ * with large option lists. Works in conjunction with `visibleItems` prop.
287
+ *
288
+ * @default false
289
+ */
290
+ virtualScroller?: boolean
291
+
292
+ /**
293
+ * Toggle the visibility of autocomplete dropdown.
294
+ * Controls whether the dropdown is initially visible.
295
+ * The dropdown visibility can still be toggled through user interaction.
296
+ */
297
+ visible?: boolean
298
+
299
+ /**
300
+ * Amount of visible items when virtualScroller is enabled.
301
+ * Determines how many option items are rendered at once when virtual scrolling is active.
302
+ * Higher values show more items but use more memory. Lower values improve performance.
303
+ *
304
+ * @default 10
305
+ */
306
+ visibleItems?: number
307
+ }
308
+
309
+ export const CAutocomplete = forwardRef<HTMLDivElement, CAutocompleteProps>(
310
+ (
311
+ {
312
+ allowOnlyDefinedOptions = false,
313
+ className,
314
+ cleaner = false,
315
+ clearSearchOnSelect = true,
316
+ container,
317
+ disabled,
318
+ feedback,
319
+ feedbackInvalid,
320
+ feedbackValid,
321
+ highlightOptionsOnSearch = false,
322
+ id,
323
+ indicator,
324
+ invalid,
325
+ label,
326
+ loading,
327
+ name,
328
+ onChange,
329
+ onHide,
330
+ onInput,
331
+ onShow,
332
+ options,
333
+ optionsMaxHeight = 'auto',
334
+ optionsTemplate,
335
+ optionsGroupsTemplate,
336
+ placeholder,
337
+ portal = false,
338
+ readOnly,
339
+ required,
340
+ resetSelectionOnOptionsChange = false,
341
+ search,
342
+ searchNoResultsLabel = false,
343
+ showHints = false,
344
+ size,
345
+ text,
346
+ tooltipFeedback,
347
+ valid,
348
+ value,
349
+ virtualScroller,
350
+ visible,
351
+ visibleItems = 10,
352
+ ...rest
353
+ },
354
+ ref
355
+ ) => {
356
+ const autoCompleteRef = useRef<HTMLDivElement>(null)
357
+ const autoCompleteForkedRef = useForkedRef(ref, autoCompleteRef)
358
+
359
+ const dropdownRef = useRef<HTMLDivElement>(null)
360
+ const togglerRef = useRef<HTMLDivElement>(null)
361
+ const inputRef = useRef<HTMLInputElement>(null)
362
+ const inputHintRef = useRef<HTMLInputElement>(null)
363
+ const uniqueId = useId()
364
+
365
+ const { initPopper, destroyPopper } = usePopper()
366
+
367
+ const [_visible, setVisible] = useState(visible)
368
+ const [hint, setHint] = useState<Option | undefined>()
369
+ const [searchValue, setSearchValue] = useState('')
370
+ const [selected, setSelected] = useState<Option | null>(null)
371
+
372
+ const filteredOptions = useMemo(
373
+ () => (isExternalSearch(search) ? options : filterOptions(options, searchValue)),
374
+ [options, searchValue, search]
375
+ )
376
+
377
+ const popperConfig = useMemo(
378
+ () => ({
379
+ placement: (isRTL(autoCompleteRef.current) ? 'bottom-end' : 'bottom-start') as Placement,
380
+ modifiers: [
381
+ {
382
+ name: 'preventOverflow',
383
+ options: {
384
+ boundary: 'clippingParents',
385
+ },
386
+ },
387
+ {
388
+ name: 'offset',
389
+ options: {
390
+ offset: [0, 2],
391
+ },
392
+ },
393
+ ],
394
+ }),
395
+ [autoCompleteRef.current]
396
+ )
397
+
398
+ useEffect(() => {
399
+ if (resetSelectionOnOptionsChange) {
400
+ handleClear()
401
+ }
402
+ }, [options])
403
+
404
+ useEffect(() => {
405
+ if (value && typeof value === 'string') {
406
+ handleSelect(value)
407
+ return
408
+ }
409
+
410
+ if (value && typeof value === 'number') {
411
+ const foundOption = getFirstOptionByValue(value, options)
412
+ if (foundOption) {
413
+ handleSelect(foundOption)
414
+ }
415
+
416
+ return
417
+ }
418
+
419
+ const _selected = flattenOptionsArray(filteredOptions).find(
420
+ (option: Option) => typeof option !== 'string' && option.selected === true
421
+ )
422
+
423
+ if (_selected) {
424
+ handleSelect(_selected)
425
+ }
426
+ }, [options, value])
427
+
428
+ useEffect(() => {
429
+ if (!showHints) {
430
+ return
431
+ }
432
+
433
+ const findOption =
434
+ searchValue.length > 0
435
+ ? filteredOptions.find((option) =>
436
+ getOptionLabel(option).toLowerCase().startsWith(searchValue.toLowerCase())
437
+ )
438
+ : undefined
439
+
440
+ setHint(findOption)
441
+ }, [filteredOptions, searchValue, showHints])
442
+
443
+ useEffect(() => {
444
+ if (
445
+ !searchNoResultsLabel &&
446
+ searchValue.length > 0 &&
447
+ filteredOptions.length === 0 &&
448
+ _visible
449
+ ) {
450
+ handleDropdownHide()
451
+ return
452
+ }
453
+
454
+ if (searchValue.length > 0 && filteredOptions.length > 0 && !_visible) {
455
+ handleDropdownShow()
456
+ }
457
+ }, [filteredOptions])
458
+
459
+ useEffect(() => {
460
+ if (visible === true) {
461
+ handleDropdownShow()
462
+ } else if (visible === false) {
463
+ handleDropdownHide()
464
+ }
465
+ }, [visible])
466
+
467
+ const handleClear = () => {
468
+ if (inputRef.current) {
469
+ inputRef.current.value = ''
470
+ }
471
+
472
+ setSearchValue('')
473
+ setSelected(null)
474
+ onChange?.(null)
475
+ }
476
+
477
+ const handleGlobalSearch = (event: React.KeyboardEvent<HTMLDivElement>) => {
478
+ if (
479
+ isGlobalSearch(search) &&
480
+ inputRef.current &&
481
+ (event.key.length === 1 || event.key === 'Backspace' || event.key === 'Delete')
482
+ ) {
483
+ inputRef.current.focus()
484
+ }
485
+ }
486
+
487
+ const handleInputChange = (event: FormEvent<HTMLInputElement>) => {
488
+ const value = (event.target as HTMLInputElement).value
489
+ handleSearch(value)
490
+
491
+ if (selected !== null) {
492
+ onChange?.(null)
493
+ setSelected(null)
494
+ }
495
+ }
496
+
497
+ const handleInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
498
+ if (event.key === 'Escape') {
499
+ handleDropdownHide()
500
+ return
501
+ }
502
+
503
+ if (
504
+ (event.key === 'Down' || event.key === 'ArrowDown') &&
505
+ inputRef.current?.value.length === inputRef.current?.selectionStart
506
+ ) {
507
+ event.preventDefault()
508
+ handleDropdownShow()
509
+
510
+ const target = event.target as HTMLElement
511
+ const firstOption = target.parentElement?.parentElement?.querySelectorAll(
512
+ '.autocomplete-option'
513
+ )[0] as HTMLElement | null
514
+
515
+ if (firstOption) {
516
+ firstOption.focus()
517
+ }
518
+
519
+ return
520
+ }
521
+
522
+ if (showHints && hint && event.key === 'Tab') {
523
+ event.preventDefault()
524
+ handleSelect(hint)
525
+ handleDropdownHide()
526
+ return
527
+ }
528
+
529
+ if (event.key === 'Enter') {
530
+ const input = event.target as HTMLInputElement
531
+ const foundOptions = getFirstOptionByLabel(input.value, filteredOptions)
532
+ if (foundOptions) {
533
+ handleSelect(foundOptions)
534
+ } else {
535
+ if (!allowOnlyDefinedOptions) {
536
+ handleSelect(input.value)
537
+ }
538
+ }
539
+
540
+ handleDropdownHide()
541
+ return
542
+ }
543
+
544
+ if (event.key === 'Backspace' || event.key === 'Delete') {
545
+ if (selected !== null) {
546
+ setSelected(null)
547
+ onChange?.(null)
548
+ }
549
+
550
+ return
551
+ }
552
+ }
553
+
554
+ const handleKeyUp = useCallback((event: KeyboardEvent) => {
555
+ if (event.key === 'Escape') {
556
+ handleDropdownHide()
557
+ }
558
+
559
+ if (
560
+ autoCompleteRef.current &&
561
+ !autoCompleteRef.current.contains(event.target as HTMLElement)
562
+ ) {
563
+ handleDropdownHide()
564
+ }
565
+ }, [])
566
+
567
+ const handleMouseUp = useCallback((event: Event) => {
568
+ if (
569
+ autoCompleteRef.current &&
570
+ autoCompleteRef.current.contains(event.target as HTMLElement)
571
+ ) {
572
+ return
573
+ }
574
+
575
+ handleDropdownHide()
576
+ }, [])
577
+
578
+ const handleOptionClick = (option: Option) => {
579
+ handleSelect(option)
580
+ handleDropdownHide()
581
+ }
582
+
583
+ const handleSearch = (search: string) => {
584
+ onInput?.(search)
585
+ setSearchValue(search)
586
+ }
587
+
588
+ const handleSelect = (option?: Option | undefined) => {
589
+ if (option && typeof option === 'object' && option.disabled) {
590
+ return
591
+ }
592
+
593
+ if (inputRef.current) {
594
+ inputRef.current.value = option ? getOptionLabel(option) : ''
595
+ }
596
+
597
+ if (clearSearchOnSelect) {
598
+ handleSearch('')
599
+ } else {
600
+ setHint('')
601
+ }
602
+
603
+ setSelected(option ?? null)
604
+ onChange?.(option ?? null)
605
+ }
606
+
607
+ const handleDropdownShow = useCallback(() => {
608
+ if (disabled || readOnly || _visible) {
609
+ return
610
+ }
611
+
612
+ if (
613
+ !isExternalSearch(search) &&
614
+ filteredOptions.length === 0 &&
615
+ searchNoResultsLabel === false
616
+ ) {
617
+ return
618
+ }
619
+
620
+ if (portal && dropdownRef.current && togglerRef.current) {
621
+ dropdownRef.current.style.minWidth = `${(togglerRef.current as HTMLElement).offsetWidth}px`
622
+ }
623
+
624
+ setVisible(true)
625
+ onShow?.()
626
+
627
+ window.addEventListener('mouseup', handleMouseUp)
628
+ window.addEventListener('keyup', handleKeyUp)
629
+
630
+ if (togglerRef.current && dropdownRef.current) {
631
+ setTimeout(() => {
632
+ initPopper(
633
+ togglerRef.current as HTMLDivElement,
634
+ dropdownRef.current as HTMLDivElement,
635
+ popperConfig
636
+ )
637
+ }, 1) // Allow DOM updates to complete before initializing Popper
638
+ }
639
+
640
+ inputRef.current?.focus()
641
+ }, [
642
+ disabled,
643
+ readOnly,
644
+ _visible,
645
+ filteredOptions.length,
646
+ searchNoResultsLabel,
647
+ allowOnlyDefinedOptions,
648
+ onShow,
649
+ handleMouseUp,
650
+ handleKeyUp,
651
+ initPopper,
652
+ popperConfig,
653
+ ])
654
+
655
+ const handleDropdownHide = useCallback(() => {
656
+ setVisible(false)
657
+ onHide?.()
658
+
659
+ window.removeEventListener('mouseup', handleMouseUp)
660
+ window.removeEventListener('keyup', handleKeyUp)
661
+
662
+ destroyPopper()
663
+ inputRef.current?.focus()
664
+ }, [onHide, handleMouseUp, handleKeyUp, destroyPopper])
665
+
666
+ return (
667
+ <CFormControlWrapper
668
+ describedby={rest['aria-describedby']}
669
+ feedback={feedback}
670
+ feedbackInvalid={feedbackInvalid}
671
+ feedbackValid={feedbackValid}
672
+ id={id || `autocomplete-${uniqueId}`}
673
+ invalid={invalid}
674
+ label={label}
675
+ text={text}
676
+ tooltipFeedback={tooltipFeedback}
677
+ valid={valid}
678
+ >
679
+ <div
680
+ className={classNames(
681
+ 'autocomplete',
682
+ {
683
+ [`autocomplete-${size}`]: size,
684
+ disabled,
685
+ 'is-invalid': invalid,
686
+ 'is-valid': valid,
687
+ show: _visible,
688
+ },
689
+ className
690
+ )}
691
+ onKeyDown={handleGlobalSearch}
692
+ ref={autoCompleteForkedRef}
693
+ >
694
+ <div
695
+ className="autocomplete-input-group"
696
+ onClick={() => handleDropdownShow()}
697
+ ref={togglerRef}
698
+ >
699
+ {showHints && searchValue !== '' && (
700
+ <input
701
+ className="autocomplete-input autocomplete-input-hint"
702
+ id={id || `autocomplete-hint-${uniqueId}`}
703
+ autoComplete="off"
704
+ readOnly
705
+ tabIndex={-1}
706
+ aria-hidden="true"
707
+ value={
708
+ hint ? `${searchValue}${getOptionLabel(hint).slice(searchValue.length)}` : ''
709
+ }
710
+ ref={inputHintRef}
711
+ />
712
+ )}
713
+ <input
714
+ type="text"
715
+ className="autocomplete-input"
716
+ disabled={disabled}
717
+ id={id || `autocomplete-${uniqueId}`}
718
+ name={name || `autocomplete-${uniqueId}`}
719
+ onBlur={(event) => {
720
+ event.preventDefault()
721
+ event.stopPropagation()
722
+ if (allowOnlyDefinedOptions && selected === null && filteredOptions.length === 0) {
723
+ handleClear()
724
+ }
725
+ }}
726
+ onChange={handleInputChange}
727
+ onKeyDown={handleInputKeyDown}
728
+ placeholder={placeholder}
729
+ autoComplete="off"
730
+ required={required}
731
+ aria-autocomplete="list"
732
+ aria-expanded={_visible}
733
+ aria-haspopup="listbox"
734
+ {...(portal && { 'aria-owns': `autocomplete-listbox-${uniqueId}` })}
735
+ readOnly={readOnly}
736
+ role="combobox"
737
+ ref={inputRef}
738
+ />
739
+ {(cleaner || indicator) && (
740
+ <div className="autocomplete-buttons">
741
+ {!disabled && !readOnly && cleaner && selected && (
742
+ <button
743
+ type="button"
744
+ className="autocomplete-cleaner"
745
+ onClick={(event) => {
746
+ event.preventDefault()
747
+ event.stopPropagation()
748
+ handleClear()
749
+ }}
750
+ ></button>
751
+ )}
752
+ <button
753
+ type="button"
754
+ className="autocomplete-indicator"
755
+ disabled={
756
+ !(searchNoResultsLabel || filteredOptions.length > 0) &&
757
+ isExternalSearch(search)
758
+ }
759
+ onClick={(event) => {
760
+ event.preventDefault()
761
+ event.stopPropagation()
762
+ if (_visible) {
763
+ handleDropdownHide()
764
+ } else {
765
+ handleDropdownShow()
766
+ }
767
+ }}
768
+ ></button>
769
+ </div>
770
+ )}
771
+ </div>
772
+ <CConditionalPortal container={container} portal={portal}>
773
+ <div
774
+ className={classNames('autocomplete-dropdown', {
775
+ show: portal && _visible,
776
+ })}
777
+ id={`autocomplete-listbox-${uniqueId}`}
778
+ role="listbox"
779
+ aria-labelledby={id || `autocomplete-${uniqueId}`}
780
+ ref={dropdownRef}
781
+ >
782
+ <CAutocompleteOptions
783
+ highlightOptionsOnSearch={highlightOptionsOnSearch}
784
+ loading={loading}
785
+ onOptionClick={(option: Option) =>
786
+ !disabled && !readOnly && handleOptionClick(option)
787
+ }
788
+ options={filteredOptions}
789
+ optionsMaxHeight={optionsMaxHeight}
790
+ optionsTemplate={optionsTemplate}
791
+ optionsGroupsTemplate={optionsGroupsTemplate}
792
+ searchNoResultsLabel={searchNoResultsLabel}
793
+ searchValue={searchValue}
794
+ selected={selected}
795
+ virtualScroller={virtualScroller}
796
+ visibleItems={visibleItems}
797
+ />
798
+ </div>
799
+ </CConditionalPortal>
800
+ </div>
801
+ </CFormControlWrapper>
802
+ )
803
+ }
804
+ )
805
+
806
+ CAutocomplete.propTypes = {
807
+ allowOnlyDefinedOptions: PropTypes.bool,
808
+ className: PropTypes.string,
809
+ clearSearchOnSelect: PropTypes.bool,
810
+ cleaner: PropTypes.bool,
811
+ container: PropTypes.any,
812
+ disabled: PropTypes.bool,
813
+ highlightOptionsOnSearch: PropTypes.bool,
814
+ indicator: PropTypes.bool,
815
+ loading: PropTypes.bool,
816
+ name: PropTypes.string,
817
+ onChange: PropTypes.func,
818
+ onHide: PropTypes.func,
819
+ onInput: PropTypes.func,
820
+ onShow: PropTypes.func,
821
+ options: PropTypes.array.isRequired,
822
+ optionsMaxHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
823
+ optionsTemplate: PropTypes.func,
824
+ optionsGroupsTemplate: PropTypes.func,
825
+ placeholder: PropTypes.string,
826
+ portal: PropTypes.bool,
827
+ required: PropTypes.bool,
828
+ resetSelectionOnOptionsChange: PropTypes.bool,
829
+ search: PropTypes.oneOfType([
830
+ PropTypes.oneOf<'external' | 'global'>(['external', 'global']),
831
+ PropTypes.shape({
832
+ external: PropTypes.bool.isRequired,
833
+ global: PropTypes.bool.isRequired,
834
+ }),
835
+ ]),
836
+ searchNoResultsLabel: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
837
+ showHints: PropTypes.bool,
838
+ size: PropTypes.oneOf(['sm', 'lg']),
839
+ value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
840
+ virtualScroller: PropTypes.bool,
841
+ visible: PropTypes.bool,
842
+ visibleItems: PropTypes.number,
843
+ ...CFormControlWrapper.propTypes,
844
+ }
845
+
846
+ CAutocomplete.displayName = 'CAutocomplete'