forked from plotly/dash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDropdown.tsx
More file actions
624 lines (579 loc) · 22.7 KB
/
Dropdown.tsx
File metadata and controls
624 lines (579 loc) · 22.7 KB
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
import {isNil, without, append, isEmpty} from 'ramda';
import React, {
useState,
useCallback,
useEffect,
useMemo,
useRef,
MouseEvent,
} from 'react';
import {sanitizeDropdownOptions, filterOptions} from '../utils/dropdownSearch';
import {
CaretDownIcon,
MagnifyingGlassIcon,
Cross1Icon,
} from '@radix-ui/react-icons';
import * as Popover from '@radix-ui/react-popover';
import '../components/css/dropdown.css';
import isEqual from 'react-fast-compare';
import {DetailedOption, DropdownProps, OptionValue} from '../types';
import {
OptionsList,
OptionsListHandle,
OptionLabel,
} from '../utils/optionRendering';
import uuid from 'uniqid';
const Dropdown = (props: DropdownProps) => {
const {
id,
className,
closeOnSelect,
clearable,
debounce,
disabled,
labels,
maxHeight,
multi,
options,
optionHeight,
setProps,
searchable,
search_value,
search_order,
style,
value,
} = props;
const [optionsCheck, setOptionsCheck] = useState<DetailedOption[]>();
const [isOpen, setIsOpen] = useState(false);
const [displayOptions, setDisplayOptions] = useState<DetailedOption[]>([]);
const [val, setVal] = useState<DropdownProps['value']>(value);
const persistentOptions = useRef<DropdownProps['options']>([]);
const dropdownContainerRef = useRef<HTMLButtonElement>(null);
const dropdownContentRef = useRef<HTMLDivElement>(
document.createElement('div')
);
const searchInputRef = useRef<HTMLInputElement>(null);
const optionsListRef = useRef<OptionsListHandle>(null);
const focusedIndexRef = useRef(-1);
const pendingSearchRef = useRef('');
const ctx = window.dash_component_api.useDashContext();
const loading = ctx.useLoading();
// Sync val when external value prop changes
useEffect(() => {
if (!isEqual(value, val)) {
setVal(value);
}
}, [value]);
if (!persistentOptions || !isEqual(options, persistentOptions.current)) {
persistentOptions.current = options;
}
const sanitized = useMemo(
() => sanitizeDropdownOptions(persistentOptions.current),
[persistentOptions.current]
);
const sanitizedOptions = sanitized.options;
const filteredOptions = useMemo(
() =>
searchable
? filterOptions(sanitized, search_value, search_order)
: sanitizedOptions,
[sanitized, searchable, search_value, search_order]
);
const sanitizedValues: OptionValue[] = useMemo(() => {
if (val instanceof Array) {
return val;
}
if (isNil(val)) {
return [];
}
return [val];
}, [val]);
const handleSetProps = useCallback(
(newValue: DropdownProps['value']) => {
if (debounce && isOpen) {
// local only
setVal(newValue);
} else {
setVal(newValue);
setProps({value: newValue});
}
},
[debounce, isOpen, setProps]
);
const updateSelection = useCallback(
(selection: OptionValue[]) => {
if (closeOnSelect !== false) {
setIsOpen(false);
setProps({search_value: undefined});
pendingSearchRef.current = '';
}
if (multi) {
// For multi-select, validate the selection respects clearable rules
if (selection.length === 0) {
// Empty selection: only allow if clearable is true
if (clearable) {
handleSetProps([]);
}
// If clearable is false and trying to set empty, do nothing
// return;
} else {
handleSetProps(selection);
}
} else {
// For single-select, take the first value or null
if (selection.length === 0) {
// Empty selection: only allow if clearable is true
if (clearable) {
handleSetProps(null);
}
// If clearable is false and trying to set empty, do nothing
// return;
} else {
handleSetProps(selection[selection.length - 1]);
}
}
},
[multi, clearable, closeOnSelect, handleSetProps]
);
const onInputChange = useCallback(
search_value => setProps({search_value}),
[]
);
const handleClearSearch = useCallback((e: MouseEvent) => {
if (e.currentTarget instanceof HTMLElement) {
const parentElement = e.currentTarget.parentElement;
parentElement?.querySelector('input')?.focus();
}
setProps({search_value: undefined});
}, []);
useEffect(() => {
if (
!search_value &&
!isNil(sanitizedOptions) &&
optionsCheck !== sanitizedOptions &&
!isNil(value) &&
!isEmpty(value)
) {
const {valueSet} = sanitized;
if (Array.isArray(value)) {
if (multi) {
const invalids = value.filter(v => !valueSet.has(v));
if (invalids.length) {
setProps({value: without(invalids, value)});
}
}
} else {
if (!valueSet.has(value)) {
setProps({value: null});
}
}
setOptionsCheck(sanitizedOptions);
}
}, [sanitizedOptions, optionsCheck, multi, value]);
const displayValue = useMemo(() => {
const labels = sanitizedValues.map((val, i) => {
const option = sanitizedOptions.find(
option => option.value === val
);
return (
<span
key={`${option?.value}-${i}`}
className="dash-dropdown-value-item"
>
{option && <OptionLabel {...option} index={i} />}
</span>
);
});
return labels;
}, [sanitizedOptions, sanitizedValues]);
const canDeselectAll = useMemo(() => {
if (clearable) {
return true;
}
return !sanitizedValues.every(value =>
displayOptions.some(option => option.value === value)
);
}, [clearable, sanitizedValues, displayOptions, search_value]);
const handleClear = useCallback(() => {
const finalValue: DropdownProps['value'] = multi ? [] : null;
handleSetProps(finalValue);
}, [multi, handleSetProps]);
const handleSelectAll = useCallback(() => {
if (multi) {
const allValues = sanitizedValues.concat(
displayOptions
.filter(option => !sanitizedValues.includes(option.value))
.map(option => option.value)
);
handleSetProps(allValues);
}
if (closeOnSelect) {
setIsOpen(false);
}
}, [multi, displayOptions, sanitizedValues, closeOnSelect, handleSetProps]);
const handleDeselectAll = useCallback(() => {
if (multi) {
const withDeselected = sanitizedValues.filter(option => {
return !displayOptions.some(
displayOption => displayOption.value === option
);
});
handleSetProps(withDeselected);
}
if (closeOnSelect) {
setIsOpen(false);
}
}, [multi, displayOptions, sanitizedValues, closeOnSelect, handleSetProps]);
// Sort options when popover opens - selected options first
// Update display options when filtered options or selection changes
useEffect(() => {
if (isOpen) {
let sortedOptions = filteredOptions;
if (multi) {
// Sort filtered options: selected first, then unselected
sortedOptions = [...filteredOptions].sort((a, b) => {
const aSelected = sanitizedValues.includes(a.value);
const bSelected = sanitizedValues.includes(b.value);
if (aSelected && !bSelected) {
return -1;
}
if (!aSelected && bSelected) {
return 1;
}
return 0; // Maintain original order within each group
});
}
setDisplayOptions(sortedOptions);
}
}, [filteredOptions, isOpen]);
// Focus first selected item or search input when dropdown opens.
// Depends on displayOptions so it fires after OptionsList is mounted.
useEffect(() => {
if (!isOpen || pendingSearchRef.current || !displayOptions.length) {
return;
}
// Don't steal focus from the search input during search-driven
// re-renders (displayOptions changes while the user is typing).
if (document.activeElement === searchInputRef.current) {
return;
}
requestAnimationFrame(() => {
if (!multi) {
const selectedValue = sanitizedValues[0];
if (selectedValue) {
const selectedIndex = displayOptions.findIndex(
o => o.value === selectedValue
);
if (selectedIndex >= 0) {
focusedIndexRef.current = selectedIndex;
optionsListRef.current?.focusItem(selectedIndex);
return;
}
}
}
if (searchable) {
searchInputRef.current?.focus();
} else {
focusedIndexRef.current = 0;
optionsListRef.current?.focusItem(0);
}
});
}, [isOpen, multi, displayOptions]);
// Handle keyboard navigation in popover.
// Index -1 = search input, 0..N-1 = option index in displayOptions.
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
const relevantKeys = [
'ArrowDown',
'ArrowUp',
'PageDown',
'PageUp',
'Home',
'End',
];
if (!relevantKeys.includes(e.key)) {
return;
}
if (
['Home', 'End'].includes(e.key) &&
document.activeElement === searchInputRef.current
) {
return;
}
if (displayOptions.length === 0) {
return;
}
e.preventDefault();
const hasSearch = !!searchable;
const current = focusedIndexRef.current;
const maxIndex = displayOptions.length - 1;
const minIndex = hasSearch ? -1 : 0;
let nextIndex: number;
switch (e.key) {
case 'ArrowDown':
nextIndex = current < maxIndex ? current + 1 : minIndex;
break;
case 'ArrowUp':
nextIndex = current > minIndex ? current - 1 : maxIndex;
break;
case 'PageDown':
nextIndex = Math.min(current + 10, maxIndex);
break;
case 'PageUp':
nextIndex = Math.max(current - 10, minIndex);
break;
case 'Home':
nextIndex = minIndex;
break;
case 'End':
nextIndex = maxIndex;
break;
default:
return;
}
focusedIndexRef.current = nextIndex;
if (nextIndex === -1) {
searchInputRef.current?.focus();
dropdownContentRef.current?.scrollTo({top: 0});
} else {
optionsListRef.current?.focusItem(nextIndex);
}
},
[displayOptions.length, searchable]
);
const handleOpenChange = useCallback(
(open: boolean) => {
setIsOpen(open);
focusedIndexRef.current = -1;
if (!open) {
pendingSearchRef.current = '';
const updates: Partial<DropdownProps> = {};
if (!isNil(search_value)) {
updates.search_value = undefined;
}
// Commit debounced value on close only
if (debounce && !isEqual(value, val)) {
updates.value = val;
}
if (Object.keys(updates).length > 0) {
setProps(updates);
}
}
},
[debounce, value, val, search_value, setProps]
);
const accessibleId = id ?? uuid();
const positioningContainerRef = useRef<HTMLDivElement>(null);
const canClearValues = clearable && !disabled && !!sanitizedValues.length;
const popover = (
<Popover.Root open={isOpen} onOpenChange={handleOpenChange}>
<Popover.Trigger asChild>
<button
id={id}
ref={dropdownContainerRef}
disabled={disabled}
type="button"
onKeyDown={e => {
if (['ArrowDown', 'Enter'].includes(e.key)) {
e.preventDefault();
}
}}
onKeyUp={e => {
if (['ArrowDown', 'Enter'].includes(e.key)) {
setIsOpen(true);
}
if (
['Delete', 'Backspace'].includes(e.key) &&
canClearValues
) {
handleClear();
}
if (e.key.length === 1 && searchable) {
pendingSearchRef.current += e.key;
setProps({search_value: pendingSearchRef.current});
setIsOpen(true);
requestAnimationFrame(() =>
searchInputRef.current?.focus()
);
}
}}
className={`dash-dropdown ${className ?? ''}`}
aria-labelledby={`${accessibleId}-value-count ${accessibleId}-value`}
aria-haspopup="listbox"
aria-expanded={isOpen}
data-dash-is-loading={loading || undefined}
>
<span className="dash-dropdown-grid-container dash-dropdown-trigger">
{displayValue.length > 0 && (
<span
id={accessibleId + '-value'}
className="dash-dropdown-value"
>
{displayValue}
</span>
)}
{displayValue.length === 0 && (
<span
id={accessibleId + '-value'}
className="dash-dropdown-value dash-dropdown-placeholder"
>
{props.placeholder}
</span>
)}
{sanitizedValues.length > 1 && (
<span
id={accessibleId + '-value-count'}
className="dash-dropdown-value-count"
>
{labels?.selected_count?.replace(
'{num_selected}',
`${sanitizedValues.length}`
)}
</span>
)}
{canClearValues && (
<a
className="dash-dropdown-clear"
onClick={e => {
e.preventDefault();
handleClear();
}}
title={labels?.clear_selection}
aria-label={labels?.clear_selection}
>
<Cross1Icon />
</a>
)}
<CaretDownIcon className="dash-dropdown-trigger-icon" />
</span>
</button>
</Popover.Trigger>
<Popover.Portal
// container is required otherwise popover will be rendered
// at document root, which may be outside of the Dash app (i.e.
// an embedded app)
container={positioningContainerRef.current}
>
<Popover.Content
ref={dropdownContentRef}
className="dash-dropdown-content"
align="start"
sideOffset={5}
onOpenAutoFocus={e => e.preventDefault()}
onKeyDown={handleKeyDown}
style={{
maxHeight: maxHeight
? `min(${maxHeight}px, calc(100vh - 100px))`
: 'calc(100vh - 100px)',
}}
>
{searchable && (
<div className="dash-dropdown-grid-container dash-dropdown-search-container">
<MagnifyingGlassIcon className="dash-dropdown-search-icon" />
<input
type="search"
className="dash-dropdown-search"
placeholder={labels?.search}
value={search_value || ''}
autoComplete="off"
onChange={e => onInputChange(e.target.value)}
onKeyUp={e => {
if (
!search_value ||
e.key !== 'Enter' ||
!displayOptions.length
) {
return;
}
const firstVal = displayOptions[0].value;
const isSelected =
sanitizedValues.includes(firstVal);
let newSelection;
if (isSelected) {
newSelection = without(
[firstVal],
sanitizedValues
);
} else {
newSelection = append(
firstVal,
sanitizedValues
);
}
updateSelection(newSelection);
}}
ref={searchInputRef}
/>
{search_value && (
<button
type="button"
className="dash-dropdown-clear"
onClick={handleClearSearch}
aria-label={labels?.clear_search}
>
<Cross1Icon />
</button>
)}
</div>
)}
{multi && (
<div className="dash-dropdown-actions">
<button
type="button"
className="dash-dropdown-action-button"
onClick={handleSelectAll}
>
{labels?.select_all}
</button>
{canDeselectAll && (
<button
type="button"
className="dash-dropdown-action-button"
onClick={handleDeselectAll}
>
{labels?.deselect_all}
</button>
)}
</div>
)}
{isOpen && !!displayOptions.length && (
<>
<OptionsList
ref={optionsListRef}
options={displayOptions}
selected={sanitizedValues}
onSelectionChange={updateSelection}
inputType={multi ? 'checkbox' : 'radio'}
className="dash-dropdown-options"
optionClassName="dash-dropdown-option"
optionHeight={
typeof optionHeight === 'number'
? optionHeight
: undefined
}
maxHeight={maxHeight}
/>
</>
)}
{isOpen && search_value && !displayOptions.length && (
<div className="dash-dropdown-options">
<span className="dash-dropdown-option">
{labels?.no_options_found}
</span>
</div>
)}
</Popover.Content>
</Popover.Portal>
</Popover.Root>
);
return (
<div
ref={positioningContainerRef}
className="dash-dropdown-wrapper"
style={style}
>
{popover}
</div>
);
};
export default Dropdown;