@react-stately/combobox 3.13.0 → 3.14.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.
@@ -1,515 +0,0 @@
1
- /*
2
- * Copyright 2020 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
-
13
- import {Collection, CollectionStateBase, FocusStrategy, Key, Node, Selection} from '@react-types/shared';
14
- import {ComboBoxProps, MenuTriggerAction, SelectionMode, ValueType} from '@react-types/combobox';
15
- import {FormValidationState, useFormValidationState} from '@react-stately/form';
16
- import {getChildNodes} from '@react-stately/collections';
17
- import {ListCollection, ListState, useListState} from '@react-stately/list';
18
- import {OverlayTriggerState, useOverlayTriggerState} from '@react-stately/overlays';
19
- import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
20
- import {useControlledState} from '@react-stately/utils';
21
-
22
- export interface ComboBoxState<T, M extends SelectionMode = 'single'> extends ListState<T>, OverlayTriggerState, FormValidationState {
23
- /**
24
- * The key for the first selected item.
25
- * @deprecated
26
- */
27
- readonly selectedKey: Key | null,
28
-
29
- /**
30
- * The default selected key.
31
- * @deprecated
32
- */
33
- readonly defaultSelectedKey: Key | null,
34
- /**
35
- * Sets the selected key.
36
- * @deprecated
37
- */
38
- setSelectedKey(key: Key | null): void,
39
- /** The current combobox value. */
40
- readonly value: ValueType<M>,
41
- /** The default combobox value. */
42
- readonly defaultValue: ValueType<M>,
43
- /** Sets the combobox value. */
44
- setValue(value: Key | readonly Key[] | null): void,
45
- /**
46
- * The value of the first selected item.
47
- * @deprecated
48
- */
49
- readonly selectedItem: Node<T> | null,
50
- /** The value of the selected items. */
51
- readonly selectedItems: Node<T>[],
52
- /** The current value of the combo box input. */
53
- inputValue: string,
54
- /** The default value of the combo box input. */
55
- defaultInputValue: string,
56
- /** Sets the value of the combo box input. */
57
- setInputValue(value: string): void,
58
- /** Selects the currently focused item and updates the input value. */
59
- commit(): void,
60
- /** Controls which item will be auto focused when the menu opens. */
61
- readonly focusStrategy: FocusStrategy | null,
62
- /** Whether the select is currently focused. */
63
- readonly isFocused: boolean,
64
- /** Sets whether the select is focused. */
65
- setFocused(isFocused: boolean): void,
66
- /** Opens the menu. */
67
- open(focusStrategy?: FocusStrategy | null, trigger?: MenuTriggerAction): void,
68
- /** Toggles the menu. */
69
- toggle(focusStrategy?: FocusStrategy | null, trigger?: MenuTriggerAction): void,
70
- /** Resets the input value to the previously selected item's text if any and closes the menu. */
71
- revert(): void
72
- }
73
-
74
- type FilterFn = (textValue: string, inputValue: string) => boolean;
75
-
76
- export interface ComboBoxStateOptions<T, M extends SelectionMode = 'single'> extends Omit<ComboBoxProps<T, M>, 'children'>, CollectionStateBase<T> {
77
- /** The filter function used to determine if a option should be included in the combo box list. */
78
- defaultFilter?: FilterFn,
79
- /** Whether the combo box allows the menu to be open when the collection is empty. */
80
- allowsEmptyCollection?: boolean,
81
- /** Whether the combo box menu should close on blur. */
82
- shouldCloseOnBlur?: boolean
83
- }
84
-
85
- const EMPTY_VALUE: Key[] = [];
86
-
87
- /**
88
- * Provides state management for a combo box component. Handles building a collection
89
- * of items from props and manages the option selection state of the combo box. In addition, it tracks the input value,
90
- * focus state, and other properties of the combo box.
91
- */
92
- export function useComboBoxState<T extends object, M extends SelectionMode = 'single'>(props: ComboBoxStateOptions<T, M>): ComboBoxState<T> {
93
- let {
94
- defaultFilter,
95
- menuTrigger = 'input',
96
- allowsEmptyCollection = false,
97
- allowsCustomValue,
98
- shouldCloseOnBlur = true,
99
- selectionMode = 'single' as SelectionMode
100
- } = props;
101
-
102
- let [showAllItems, setShowAllItems] = useState(false);
103
- let [isFocused, setFocusedState] = useState(false);
104
- let [focusStrategy, setFocusStrategy] = useState<FocusStrategy | null>(null);
105
-
106
- let defaultValue = useMemo(() => {
107
- return props.defaultValue !== undefined ? props.defaultValue : (selectionMode === 'single' ? props.defaultSelectedKey ?? null : []) as ValueType<M>;
108
- }, [props.defaultValue, props.defaultSelectedKey, selectionMode]);
109
- let value = useMemo(() => {
110
- return props.value !== undefined ? props.value : (selectionMode === 'single' ? props.selectedKey : undefined) as ValueType<M>;
111
- }, [props.value, props.selectedKey, selectionMode]);
112
- let [controlledValue, setControlledValue] = useControlledState<Key | readonly Key[] | null>(value, defaultValue, props.onChange as any);
113
- // Only display the first selected item if in single selection mode but the value is an array.
114
- let displayValue: ValueType<M> = selectionMode === 'single' && Array.isArray(controlledValue) ? controlledValue[0] : controlledValue;
115
-
116
- let setValue = (value: Key | Key[] | null) => {
117
- if (selectionMode === 'single') {
118
- let key = Array.isArray(value) ? value[0] ?? null : value;
119
- setControlledValue(key);
120
- if (key !== displayValue) {
121
- props.onSelectionChange?.(key);
122
- }
123
- } else {
124
- let keys: Key[] = [];
125
- if (Array.isArray(value)) {
126
- keys = value;
127
- } else if (value != null) {
128
- keys = [value];
129
- }
130
-
131
- setControlledValue(keys);
132
- }
133
- };
134
-
135
- let {
136
- collection,
137
- selectionManager,
138
- disabledKeys
139
- } = useListState({
140
- ...props,
141
- items: props.items ?? props.defaultItems,
142
- selectionMode,
143
- disallowEmptySelection: selectionMode === 'single',
144
- allowDuplicateSelectionEvents: true,
145
- selectedKeys: useMemo(() => convertValue(displayValue), [displayValue]),
146
- onSelectionChange: (keys: Selection) => {
147
- // impossible, but TS doesn't know that
148
- if (keys === 'all') {
149
- return;
150
- }
151
-
152
- if (selectionMode === 'single') {
153
- let key = keys.values().next().value ?? null;
154
- if (key === displayValue) {
155
- props.onSelectionChange?.(key);
156
- // If key is the same, reset the inputValue and close the menu
157
- // (scenario: user clicks on already selected option)
158
- resetInputValue();
159
- closeMenu();
160
- } else {
161
- setValue(key);
162
- }
163
- } else {
164
- setValue([...keys]);
165
- }
166
- }
167
- });
168
-
169
- let selectedKey = selectionMode === 'single' ? selectionManager.firstSelectedKey : null;
170
- let selectedItems = useMemo(() => {
171
- return [...selectionManager.selectedKeys].map(key => collection.getItem(key)).filter(item => item != null);
172
- }, [selectionManager.selectedKeys, collection]);
173
-
174
- let [inputValue, setInputValue] = useControlledState(
175
- props.inputValue,
176
- getDefaultInputValue(props.defaultInputValue, selectedKey, collection) || '',
177
- props.onInputChange
178
- );
179
- let [initialValue] = useState(displayValue);
180
- let [initialInputValue] = useState(inputValue);
181
-
182
- // Preserve original collection so we can show all items on demand
183
- let originalCollection = collection;
184
- let filteredCollection = useMemo(() => (
185
- // No default filter if items are controlled.
186
- props.items != null || !defaultFilter
187
- ? collection
188
- : filterCollection(collection, inputValue, defaultFilter)
189
- ), [collection, inputValue, defaultFilter, props.items]);
190
- let [lastCollection, setLastCollection] = useState(filteredCollection);
191
-
192
- // Track what action is attempting to open the menu
193
- let menuOpenTrigger = useRef<MenuTriggerAction | undefined>('focus');
194
- let onOpenChange = (open: boolean) => {
195
- if (props.onOpenChange) {
196
- props.onOpenChange(open, open ? menuOpenTrigger.current : undefined);
197
- }
198
-
199
- selectionManager.setFocused(open);
200
- if (!open) {
201
- selectionManager.setFocusedKey(null);
202
- }
203
- };
204
-
205
- let triggerState = useOverlayTriggerState({...props, onOpenChange, isOpen: undefined, defaultOpen: undefined});
206
- let open = (focusStrategy: FocusStrategy | null = null, trigger?: MenuTriggerAction) => {
207
- let displayAllItems = (trigger === 'manual' || (trigger === 'focus' && menuTrigger === 'focus'));
208
- // Prevent open operations from triggering if there is nothing to display
209
- // Also prevent open operations from triggering if items are uncontrolled but defaultItems is empty, even if displayAllItems is true.
210
- // This is to prevent comboboxes with empty defaultItems from opening but allow controlled items comboboxes to open even if the inital list is empty (assumption is user will provide swap the empty list with a base list via onOpenChange returning `menuTrigger` manual)
211
- if (allowsEmptyCollection || filteredCollection.size > 0 || (displayAllItems && originalCollection.size > 0) || props.items) {
212
- if (displayAllItems && !triggerState.isOpen && props.items === undefined) {
213
- // Show all items if menu is manually opened. Only care about this if items are undefined
214
- setShowAllItems(true);
215
- }
216
-
217
- menuOpenTrigger.current = trigger;
218
- setFocusStrategy(focusStrategy);
219
- triggerState.open();
220
- }
221
- };
222
-
223
- let toggle = (focusStrategy: FocusStrategy | null = null, trigger?: MenuTriggerAction) => {
224
- let displayAllItems = (trigger === 'manual' || (trigger === 'focus' && menuTrigger === 'focus'));
225
- // If the menu is closed and there is nothing to display, early return so toggle isn't called to prevent extraneous onOpenChange
226
- if (!(allowsEmptyCollection || filteredCollection.size > 0 || (displayAllItems && originalCollection.size > 0) || props.items) && !triggerState.isOpen) {
227
- return;
228
- }
229
-
230
- if (displayAllItems && !triggerState.isOpen && props.items === undefined) {
231
- // Show all items if menu is toggled open. Only care about this if items are undefined
232
- setShowAllItems(true);
233
- }
234
-
235
- // Only update the menuOpenTrigger if menu is currently closed
236
- if (!triggerState.isOpen) {
237
- menuOpenTrigger.current = trigger;
238
- }
239
-
240
- toggleMenu(focusStrategy);
241
- };
242
-
243
- let updateLastCollection = useCallback(() => {
244
- setLastCollection(showAllItems ? originalCollection : filteredCollection);
245
- }, [showAllItems, originalCollection, filteredCollection]);
246
-
247
- // If menu is going to close, save the current collection so we can freeze the displayed collection when the
248
- // user clicks outside the popover to close the menu. Prevents the menu contents from updating as the menu closes.
249
- let toggleMenu = useCallback((focusStrategy: FocusStrategy | null = null) => {
250
- if (triggerState.isOpen) {
251
- updateLastCollection();
252
- }
253
-
254
- setFocusStrategy(focusStrategy);
255
- triggerState.toggle();
256
- }, [triggerState, updateLastCollection]);
257
-
258
- let closeMenu = useCallback(() => {
259
- if (triggerState.isOpen) {
260
- updateLastCollection();
261
- triggerState.close();
262
- }
263
- }, [triggerState, updateLastCollection]);
264
-
265
- let [lastValue, setLastValue] = useState(inputValue);
266
- let resetInputValue = () => {
267
- let itemText = selectedKey != null ? collection.getItem(selectedKey)?.textValue ?? '' : '';
268
- setLastValue(itemText);
269
- setInputValue(itemText);
270
- };
271
-
272
- let lastValueRef = useRef(displayValue);
273
- let lastSelectedKeyText = useRef(
274
- selectedKey != null ? collection.getItem(selectedKey)?.textValue ?? '' : ''
275
- );
276
- // intentional omit dependency array, want this to happen on every render
277
- // eslint-disable-next-line react-hooks/exhaustive-deps
278
- useEffect(() => {
279
- // Open and close menu automatically when the input value changes if the input is focused,
280
- // and there are items in the collection or allowEmptyCollection is true.
281
- if (
282
- isFocused &&
283
- (filteredCollection.size > 0 || allowsEmptyCollection) &&
284
- !triggerState.isOpen &&
285
- inputValue !== lastValue &&
286
- menuTrigger !== 'manual'
287
- ) {
288
- open(null, 'input');
289
- }
290
-
291
- // Close the menu if the collection is empty. Don't close menu if filtered collection size is 0
292
- // but we are currently showing all items via button press
293
- if (
294
- !showAllItems &&
295
- !allowsEmptyCollection &&
296
- triggerState.isOpen &&
297
- filteredCollection.size === 0
298
- ) {
299
- closeMenu();
300
- }
301
-
302
- // Close when an item is selected.
303
- if (
304
- displayValue != null &&
305
- displayValue !== lastValueRef.current &&
306
- selectionMode === 'single'
307
- ) {
308
- closeMenu();
309
- }
310
-
311
- // Clear focused key when input value changes and display filtered collection again.
312
- if (inputValue !== lastValue) {
313
- selectionManager.setFocusedKey(null);
314
- setShowAllItems(false);
315
-
316
- // Set value to null when the user clears the input.
317
- // If controlled, this is the application developer's responsibility.
318
- if (selectionMode === 'single' && inputValue === '' && (props.inputValue === undefined || value === undefined)) {
319
- setValue(null);
320
- }
321
- }
322
-
323
- // If the value changed, update the input value.
324
- // Do nothing if both inputValue and value are controlled.
325
- // In this case, it's the user's responsibility to update inputValue in onSelectionChange.
326
- if (
327
- displayValue !== lastValueRef.current &&
328
- (props.inputValue === undefined || value === undefined)
329
- ) {
330
- resetInputValue();
331
- } else if (lastValue !== inputValue) {
332
- setLastValue(inputValue);
333
- }
334
-
335
- // Update the inputValue if the selected item's text changes from its last tracked value.
336
- // This is to handle cases where a selectedKey is specified but the items aren't available (async loading) or the selected item's text value updates.
337
- // Only reset if the user isn't currently within the field so we don't erroneously modify user input.
338
- // If inputValue is controlled, it is the user's responsibility to update the inputValue when items change.
339
- let selectedItemText = selectedKey != null ? collection.getItem(selectedKey)?.textValue ?? '' : '';
340
- if (!isFocused && selectedKey != null && props.inputValue === undefined && selectedKey === lastValueRef.current) {
341
- if (lastSelectedKeyText.current !== selectedItemText) {
342
- setLastValue(selectedItemText);
343
- setInputValue(selectedItemText);
344
- }
345
- }
346
-
347
- lastValueRef.current = displayValue;
348
- lastSelectedKeyText.current = selectedItemText;
349
- });
350
-
351
- let validation = useFormValidationState({
352
- ...props,
353
- value: useMemo(() => Array.isArray(displayValue) && displayValue.length === 0 ? null : ({inputValue, value: displayValue as any, selectedKey}), [inputValue, selectedKey, displayValue])
354
- });
355
-
356
- // Revert input value and close menu
357
- let revert = () => {
358
- if (allowsCustomValue && selectedKey == null) {
359
- commitCustomValue();
360
- } else {
361
- commitSelection();
362
- }
363
- };
364
-
365
- let commitCustomValue = () => {
366
- let value = selectionMode === 'multiple' ? EMPTY_VALUE : null;
367
- lastValueRef.current = value as any;
368
- setValue(value);
369
- closeMenu();
370
- };
371
-
372
- let commitSelection = () => {
373
- // If multiple things are controlled, call onSelectionChange
374
- if (value !== undefined && props.inputValue !== undefined) {
375
- props.onSelectionChange?.(selectedKey);
376
- props.onChange?.(displayValue);
377
-
378
- // Stop menu from reopening from useEffect
379
- let itemText = selectedKey != null ? collection.getItem(selectedKey)?.textValue ?? '' : '';
380
- setLastValue(itemText);
381
- closeMenu();
382
- } else {
383
- // If only a single aspect of combobox is controlled, reset input value and close menu for the user
384
- resetInputValue();
385
- closeMenu();
386
- }
387
- };
388
-
389
- const commitValue = () => {
390
- if (allowsCustomValue) {
391
- const itemText = selectedKey != null ? collection.getItem(selectedKey)?.textValue ?? '' : '';
392
- (inputValue === itemText) ? commitSelection() : commitCustomValue();
393
- } else {
394
- // Reset inputValue and close menu
395
- commitSelection();
396
- }
397
- };
398
-
399
- let commit = () => {
400
- if (triggerState.isOpen && selectionManager.focusedKey != null) {
401
- // Reset inputValue and close menu here if the selected key is already the focused key. Otherwise
402
- // fire onSelectionChange to allow the application to control the closing.
403
- if (selectionManager.isSelected(selectionManager.focusedKey) && selectionMode === 'single') {
404
- commitSelection();
405
- } else {
406
- selectionManager.select(selectionManager.focusedKey);
407
- }
408
- } else {
409
- commitValue();
410
- }
411
- };
412
-
413
- let valueOnFocus = useRef(inputValue);
414
- let setFocused = (isFocused: boolean) => {
415
- if (isFocused) {
416
- valueOnFocus.current = inputValue;
417
- if (menuTrigger === 'focus' && !props.isReadOnly) {
418
- open(null, 'focus');
419
- }
420
- } else {
421
- if (shouldCloseOnBlur) {
422
- commitValue();
423
- }
424
-
425
- if (inputValue !== valueOnFocus.current) {
426
- validation.commitValidation();
427
- }
428
- }
429
-
430
- setFocusedState(isFocused);
431
- };
432
-
433
- let displayedCollection = useMemo(() => {
434
- if (triggerState.isOpen) {
435
- if (showAllItems) {
436
- return originalCollection;
437
- } else {
438
- return filteredCollection;
439
- }
440
- } else {
441
- return lastCollection;
442
- }
443
- }, [triggerState.isOpen, originalCollection, filteredCollection, showAllItems, lastCollection]);
444
-
445
- let defaultSelectedKey = props.defaultSelectedKey ?? (selectionMode === 'single' ? initialValue as Key : null);
446
-
447
- return {
448
- ...validation,
449
- ...triggerState,
450
- focusStrategy,
451
- toggle,
452
- open,
453
- close: commitValue,
454
- selectionManager,
455
- value: displayValue as any,
456
- defaultValue: defaultValue ?? initialValue as any,
457
- setValue,
458
- selectedKey,
459
- selectedItems,
460
- defaultSelectedKey,
461
- setSelectedKey: setValue,
462
- disabledKeys,
463
- isFocused,
464
- setFocused,
465
- selectedItem: selectedItems[0] ?? null,
466
- collection: displayedCollection,
467
- inputValue,
468
- defaultInputValue: getDefaultInputValue(props.defaultInputValue, defaultSelectedKey, collection) ?? initialInputValue,
469
- setInputValue,
470
- commit,
471
- revert
472
- };
473
- }
474
-
475
- function filterCollection<T extends object>(collection: Collection<Node<T>>, inputValue: string, filter: FilterFn): Collection<Node<T>> {
476
- return new ListCollection(filterNodes(collection, collection, inputValue, filter));
477
- }
478
-
479
- function filterNodes<T>(collection: Collection<Node<T>>, nodes: Iterable<Node<T>>, inputValue: string, filter: FilterFn): Iterable<Node<T>> {
480
- let filteredNode: Node<T>[] = [];
481
- for (let node of nodes) {
482
- if (node.type === 'section' && node.hasChildNodes) {
483
- let filtered = filterNodes(collection, getChildNodes(node, collection), inputValue, filter);
484
- if ([...filtered].some(node => node.type === 'item')) {
485
- filteredNode.push({...node, childNodes: filtered});
486
- }
487
- } else if (node.type === 'item' && filter(node.textValue, inputValue)) {
488
- filteredNode.push({...node});
489
- } else if (node.type !== 'item') {
490
- filteredNode.push({...node});
491
- }
492
- }
493
- return filteredNode;
494
- }
495
-
496
-
497
- function getDefaultInputValue(defaultInputValue: string | null | undefined, selectedKey: Key | null, collection: Collection<Node<unknown>>) {
498
- if (defaultInputValue == null) {
499
- if (selectedKey != null) {
500
- return collection.getItem(selectedKey)?.textValue ?? '';
501
- }
502
- }
503
-
504
- return defaultInputValue;
505
- }
506
-
507
- function convertValue(value: Key | Key[] | null | undefined) {
508
- if (value === undefined) {
509
- return undefined;
510
- }
511
- if (value === null) {
512
- return [];
513
- }
514
- return Array.isArray(value) ? value : [value];
515
- }