-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathPicklist.tsx
More file actions
810 lines (741 loc) · 22 KB
/
Picklist.tsx
File metadata and controls
810 lines (741 loc) · 22 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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
import React, {
FC,
CSSProperties,
createContext,
useContext,
useRef,
Ref,
ReactNode,
useId,
useState,
useEffect,
useCallback,
useMemo,
} from 'react';
import classnames from 'classnames';
import { FormElement, FormElementProps } from './FormElement';
import { Icon } from './Icon';
import { AutoAlign, RectangleAlignment } from './AutoAlign';
import { DropdownMenuProps } from './DropdownMenu';
import { registerStyle, isElInChildren } from './util';
import { ComponentSettingsContext } from './ComponentSettings';
import { useControlledValue, useEventCallback, useMergeRefs } from './hooks';
import { createFC } from './common';
import { Bivariant } from './typeUtils';
/**
* Recursively collect option values from PicklistItem components
*/
function collectOptionValues(children: unknown): PicklistValue[] {
return React.Children.map(children, (child) => {
if (!React.isValidElement(child)) {
return [];
}
const props = child.props;
const isPropsObject = typeof props === 'object' && props !== null;
if (!isPropsObject) {
return [];
}
// Recursively check children for nested PicklistItems
if (child.type !== PicklistItem) {
return !('children' in props) ? [] : collectOptionValues(props.children);
}
// Check if this is specifically a PicklistItem component
if (
!('value' in props) ||
(typeof props.value !== 'string' && typeof props.value !== 'number')
) {
return [];
}
// Skip disabled items
if ('disabled' in props && props.disabled === true) {
return [];
}
return [props.value];
}).flat();
}
/**
* Recursively find selected item label from PicklistItem components
*/
function findSelectedItemLabel(
children: unknown,
selectedValue: PicklistValue
): string | number | null {
return (
React.Children.map(children, (child) => {
if (!React.isValidElement(child)) {
return null;
}
const props = child.props;
const isPropsObject = typeof props === 'object' && props !== null;
if (!isPropsObject) {
return null;
}
// Recursively check children for nested PicklistItems
if (child.type !== PicklistItem) {
return !('children' in props)
? null
: findSelectedItemLabel(props.children, selectedValue);
}
// Check if this is specifically a PicklistItem component
if (!('value' in props) || props.value !== selectedValue) {
return null;
}
// Skip disabled items
if ('disabled' in props && props.disabled === true) {
return null;
}
// Safely access label and children properties with proper type checking
const label = 'label' in props ? props.label : undefined;
const itemChildren = 'children' in props ? props.children : undefined;
// Simple type check for React.ReactNode values
const labelValue =
typeof label === 'string' ||
typeof label === 'number' ||
React.isValidElement(label)
? extractTextContent(label)
: undefined;
const childrenValue =
typeof itemChildren === 'string' ||
typeof itemChildren === 'number' ||
React.isValidElement(itemChildren) ||
Array.isArray(itemChildren)
? extractTextContent(itemChildren)
: undefined;
return labelValue || childrenValue;
}).find((result) => result !== null) ?? null
);
}
/**
* Extract text content from React node recursively
*/
function extractTextContent(node: unknown): string | number | null {
if (node == null) {
return null;
}
if (typeof node === 'string' || typeof node === 'number') {
return node;
}
if (typeof node === 'boolean') {
return String(node);
}
if (Array.isArray(node)) {
return node
.map(extractTextContent)
.filter((result) => result !== null)
.join('');
}
if (
React.isValidElement(node) &&
node.props &&
typeof node.props === 'object' &&
'children' in node.props
) {
return extractTextContent(node.props.children);
}
return null;
}
/**
*
*/
type PicklistValue = string | number;
type PicklistValueType<Multi extends boolean | undefined> = Multi extends true
? Array<PicklistValue>
: Multi extends false | undefined
? PicklistValue | null
: Array<PicklistValue> | string | number | null;
/**
*
*/
const PicklistContext = createContext<{
values: PicklistValue[];
multiSelect?: boolean;
onSelect: (value: PicklistValue) => void;
focusedValue?: PicklistValue;
optionIdPrefix: string;
}>({
values: [],
onSelect: () => {
// noop
},
optionIdPrefix: '',
});
/**
*
*/
function useInitComponentStyle() {
useEffect(() => {
registerStyle('picklist', [
['.react-picklist-input:focus-visible', '{ outline: none; }'],
['.react-picklist-input:not(:disabled)', '{ cursor: pointer; }'],
]);
}, []);
}
/**
*
*/
export type PicklistProps<MultiSelect extends boolean | undefined> = {
id?: string;
className?: string;
label?: string;
required?: boolean;
multiSelect?: MultiSelect;
error?: FormElementProps['error'];
cols?: number;
name?: string;
value?: PicklistValueType<MultiSelect>;
defaultValue?: PicklistValueType<MultiSelect>;
selectedText?: string;
optionsSelectedText?: string;
opened?: boolean;
defaultOpened?: boolean;
disabled?: boolean;
menuSize?: DropdownMenuProps['size'];
menuStyle?: CSSProperties;
tooltip?: ReactNode;
tooltipIcon?: string;
elementRef?: Ref<HTMLDivElement>;
inputRef?: Ref<HTMLInputElement>;
dropdownRef?: Ref<HTMLDivElement>;
onValueChange?: Bivariant<
(
newValue: PicklistValueType<MultiSelect>,
prevValue: PicklistValueType<MultiSelect>
) => void
>;
onSelect?: Bivariant<(value: PicklistValue) => void>;
onKeyDown?: (e: React.KeyboardEvent) => void;
onBlur?: () => void;
onComplete?: () => void;
children?: React.ReactNode;
};
/**
*
*/
export const Picklist: (<MultiSelect extends boolean | undefined>(
props: PicklistProps<MultiSelect>
) => ReturnType<FC>) & { isFormElement: boolean } = createFC(
(props) => {
const {
id: id_,
className,
value: value_,
defaultValue,
opened: opened_,
defaultOpened,
multiSelect,
selectedText = '',
optionsSelectedText = '',
menuSize,
menuStyle,
disabled,
label,
required,
error,
cols,
tooltip,
tooltipIcon,
elementRef: elementRef_,
inputRef: inputRef_,
dropdownRef: dropdownRef_,
onSelect,
onComplete,
onValueChange,
onBlur: onBlur_,
onKeyDown: onKeyDown_,
children,
...rprops
} = props;
useInitComponentStyle();
const fallbackId = useId();
const id = id_ ?? fallbackId;
const listboxId = `${id}-listbox`;
const optionIdPrefix = `${useId()}-option`;
const values_: PicklistValue[] | undefined =
typeof value_ === 'undefined'
? undefined
: value_ == null
? []
: Array.isArray(value_)
? value_
: [value_];
const defaultValues: PicklistValue[] | undefined =
typeof defaultValue === 'undefined'
? undefined
: defaultValue == null
? []
: Array.isArray(defaultValue)
? defaultValue
: [defaultValue];
const [values, setValues] = useControlledValue(
values_,
defaultValues ?? []
);
const [opened, setOpened] = useControlledValue(
opened_,
defaultOpened ?? false
);
const [focusedValue, setFocusedValue] = useState<
PicklistValue | undefined
>();
const { getActiveElement } = useContext(ComponentSettingsContext);
// Memoized option values - recursively collected from PicklistItem components (excluding disabled items)
const optionValues = useMemo(() => {
return collectOptionValues(children);
}, [children]);
// Get next option value for keyboard navigation
const getNextValue = useCallback(
(currentValue?: PicklistValue) => {
if (optionValues.length === 0) return undefined;
if (!currentValue) return optionValues[0];
const currentIndex = optionValues.indexOf(currentValue);
return optionValues[
Math.min(currentIndex + 1, optionValues.length - 1)
]; // not wrap around
},
[optionValues]
);
// Get previous option value for keyboard navigation
const getPrevValue = useCallback(
(currentValue?: PicklistValue) => {
if (optionValues.length === 0) return undefined;
if (!currentValue) return optionValues[optionValues.length - 1];
const currentIndex = optionValues.indexOf(currentValue);
return optionValues[Math.max(currentIndex - 1, 0)]; // not wrap around
},
[optionValues]
);
// Scroll focused element into view
const scrollFocusedElementIntoView = useEventCallback(
(nextFocusedValue: PicklistValue | undefined) => {
if (!nextFocusedValue || !dropdownElRef.current) {
return;
}
const dropdownContainer = dropdownElRef.current;
const targetElement = dropdownContainer.querySelector(
`#${CSS.escape(`${optionIdPrefix}-${nextFocusedValue}`)}`
);
if (!(targetElement instanceof HTMLElement)) {
return;
}
targetElement.focus();
}
);
// Set initial focus when dropdown opens
useEffect(() => {
if (opened && !focusedValue) {
// Focus on first selected value or first option
const initialFocus = values.length > 0 ? values[0] : optionValues[0];
setFocusedValue(initialFocus);
scrollFocusedElementIntoView(initialFocus);
} else if (!opened) {
// Reset focus when dropdown closes
setFocusedValue(undefined);
}
}, [
opened,
values,
optionValues,
focusedValue,
scrollFocusedElementIntoView,
]);
const elRef = useRef<HTMLDivElement | null>(null);
const elementRef = useMergeRefs([elRef, elementRef_]);
const comboboxElRef = useRef<HTMLInputElement | null>(null);
const inputRef = useMergeRefs([comboboxElRef, inputRef_]);
const dropdownElRef = useRef<HTMLDivElement | null>(null);
const dropdownRef = useMergeRefs([dropdownElRef, dropdownRef_]);
const setPicklistValues = useEventCallback((newValues: PicklistValue[]) => {
const prevValues = values;
setValues(newValues);
if (onValueChange && prevValues !== newValues) {
if (multiSelect) {
onValueChange(newValues, prevValues);
} else {
onValueChange(
newValues.length > 0 ? newValues[0] : null,
prevValues.length > 0 ? prevValues[0] : null
);
}
}
});
const updateItemValue = useEventCallback((itemValue: PicklistValue) => {
if (multiSelect) {
const newValues = [...values];
// toggle value
if (newValues.indexOf(itemValue) === -1) {
// add value to array
newValues.push(itemValue);
} else {
// remove from array
newValues.splice(newValues.indexOf(itemValue), 1);
}
setPicklistValues(newValues);
} else {
// set only one value
setPicklistValues([itemValue]);
setOpened(false);
setTimeout(() => {
comboboxElRef.current?.focus();
onComplete?.();
}, 10);
}
});
const isFocusedInComponent = useEventCallback(() => {
const targetEl = getActiveElement();
return (
isElInChildren(elRef.current, targetEl) ||
isElInChildren(dropdownElRef.current, targetEl)
);
});
const onClick = useEventCallback(() => {
if (!disabled) {
setOpened((opened) => !opened);
}
});
const onPicklistItemSelect = useEventCallback((value: PicklistValue) => {
updateItemValue(value);
onSelect?.(value);
});
const onBlur = useEventCallback(() => {
setTimeout(() => {
if (!isFocusedInComponent()) {
setOpened(false);
onBlur_?.();
onComplete?.();
}
}, 10);
});
const onKeyDown = useEventCallback((e: React.KeyboardEvent) => {
if (e.keyCode === 40) {
// down
e.preventDefault();
e.stopPropagation();
if (!opened) {
setOpened(true);
} else {
// Navigate to next option
const nextValue = getNextValue(focusedValue);
setFocusedValue(nextValue);
scrollFocusedElementIntoView(nextValue);
}
} else if (e.keyCode === 38) {
// up
e.preventDefault();
e.stopPropagation();
if (!opened) {
setOpened(true);
} else {
// Navigate to previous option
const prevValue = getPrevValue(focusedValue);
setFocusedValue(prevValue);
scrollFocusedElementIntoView(prevValue);
}
} else if (e.keyCode === 9) {
// Tab or Shift+Tab
if (opened) {
e.preventDefault();
e.stopPropagation();
const currentIndex = focusedValue
? optionValues.indexOf(focusedValue)
: -1;
if (e.shiftKey) {
// Shift+Tab - Navigate to previous option or close if at first
if (currentIndex <= 0) {
// At first option or no focus, close the picklist
setOpened(false);
onComplete?.();
} else {
const prevValue = getPrevValue(focusedValue);
setFocusedValue(prevValue);
scrollFocusedElementIntoView(prevValue);
}
} else {
// Tab - Navigate to next option or close if at last
if (currentIndex >= optionValues.length - 1) {
// At last option, close the picklist
setOpened(false);
onComplete?.();
} else {
const nextValue = getNextValue(focusedValue);
setFocusedValue(nextValue);
scrollFocusedElementIntoView(nextValue);
}
}
}
} else if (e.keyCode === 27) {
// ESC
e.preventDefault();
e.stopPropagation();
setOpened(false);
onComplete?.();
} else if (e.keyCode === 13 || e.keyCode === 32) {
// Enter or Space
e.preventDefault();
e.stopPropagation();
if (opened && focusedValue != null) {
// Select focused option
onPicklistItemSelect(focusedValue);
} else {
setOpened((opened) => !opened);
}
}
onKeyDown_?.(e);
});
// Memoized selected item label - displays count for multiple selections, label for single selection, or placeholder text
const selectedItemLabel = useMemo(() => {
// many items selected
if (values.length > 1) {
return optionsSelectedText;
}
// one item
if (values.length === 1) {
const selectedValue = values[0];
const selected = findSelectedItemLabel(children, selectedValue);
return selected || selectedValue;
}
// zero items
return selectedText;
}, [values, optionsSelectedText, selectedText, children]);
const hasValue = values.length > 0;
const portalClassNames = classnames(
className,
'react-slds-picklist',
'slds-combobox_container'
);
const containerClassNames = classnames(portalClassNames, 'slds-size_small');
const comboboxClassNames = classnames(
'slds-combobox',
'slds-dropdown-trigger',
'slds-dropdown-trigger_click',
{
'slds-is-open': opened,
}
);
const inputClassNames = classnames(
'react-picklist-input',
'slds-input_faux',
'slds-combobox__input',
{
'slds-has-focus': opened && !disabled,
'slds-combobox__input-value': hasValue,
'slds-is-disabled': disabled,
}
);
const createDropdownClassNames = useCallback(
(alignment: RectangleAlignment) => {
const [vertAlign, align] = alignment;
return classnames(
'slds-dropdown',
vertAlign ? `slds-dropdown_${vertAlign}` : undefined,
align ? `slds-dropdown_${align}` : undefined,
'slds-dropdown_length-5',
menuSize ? `slds-dropdown_${menuSize}` : 'slds-dropdown_fluid'
);
},
[menuSize]
);
const formElemProps = {
id,
label,
required,
error,
cols,
tooltip,
tooltipIcon,
elementRef,
};
const contextValue = {
values,
multiSelect,
onSelect: onPicklistItemSelect,
focusedValue,
optionIdPrefix,
};
return (
<FormElement {...formElemProps}>
<div className={containerClassNames}>
<div className={comboboxClassNames} ref={elementRef}>
<div
className='slds-combobox__form-element slds-input-has-icon slds-input-has-icon_right'
role='none'
>
<input
type='text'
ref={inputRef}
role='combobox'
tabIndex={disabled ? -1 : 0}
className={inputClassNames}
aria-controls={listboxId}
aria-expanded={opened}
aria-haspopup='listbox'
aria-disabled={disabled}
aria-activedescendant={
focusedValue ? `${optionIdPrefix}-${focusedValue}` : undefined
}
onClick={onClick}
onKeyDown={onKeyDown}
onBlur={onBlur}
{...rprops}
value={selectedItemLabel}
readOnly
disabled={disabled}
/>
<Icon
containerClassName='slds-input__icon slds-input__icon_right'
category='utility'
icon='down'
size='x-small'
textColor='default'
/>
</div>
{opened && (
<AutoAlign
triggerSelector='.react-slds-picklist'
alignmentStyle='menu'
portalClassName={portalClassNames}
size={menuSize}
>
{({ alignment, autoAlignContentRef }) => (
<div
id={listboxId}
className={createDropdownClassNames(alignment)}
role='listbox'
aria-label='Options'
tabIndex={0}
aria-busy={false}
ref={useMergeRefs([dropdownRef, autoAlignContentRef])}
style={menuStyle}
>
<ul
className='slds-listbox slds-listbox_vertical'
role='presentation'
onKeyDown={onKeyDown}
onBlur={onBlur}
>
<PicklistContext.Provider value={contextValue}>
{children}
</PicklistContext.Provider>
</ul>
</div>
)}
</AutoAlign>
)}
</div>
</div>
</FormElement>
);
},
{ isFormElement: true }
);
/**
*
*/
export type PicklistItemProps = {
label?: React.ReactNode;
value?: string | number;
selected?: boolean;
disabled?: boolean;
icon?: string;
iconRight?: string;
divider?: 'top' | 'bottom';
onClick?: (e: React.SyntheticEvent) => void;
children?: React.ReactNode;
};
/**
*
*/
export const PicklistItem: FC<PicklistItemProps> = ({
label,
selected: selected_,
value,
disabled,
icon,
iconRight,
divider,
onClick: onClick_,
children,
}) => {
const { values, multiSelect, onSelect, focusedValue, optionIdPrefix } =
useContext(PicklistContext);
const selected =
selected_ ?? (value != null ? values.indexOf(value) >= 0 : false);
const isFocused = focusedValue === value;
const onClick = useEventCallback((e: React.SyntheticEvent) => {
if (!disabled && value != null) {
onSelect(value);
onClick_?.(e);
}
});
const itemClassNames = classnames(
'slds-media',
'slds-listbox__option',
'slds-listbox__option_plain',
'slds-media_small',
{
'slds-is-selected': selected,
'slds-has-focus': isFocused,
}
);
const listItemClassNames = classnames(
'slds-listbox__item',
divider ? `slds-has-divider_${divider}-space` : undefined
);
const mainListItem = (
<li role='presentation' className={listItemClassNames}>
<div
id={value ? `${optionIdPrefix}-${value}` : undefined}
className={itemClassNames}
role='option'
aria-selected={selected}
aria-checked={multiSelect ? selected : undefined}
aria-disabled={disabled}
tabIndex={disabled ? undefined : 0}
onClick={onClick}
>
<span className='slds-media__figure slds-listbox__option-icon'>
{icon ? (
<Icon
category='utility'
icon={icon}
size='x-small'
textColor='currentColor'
/>
) : selected ? (
<Icon
category='utility'
icon='check'
size='x-small'
textColor='currentColor'
/>
) : null}
</span>
<span className='slds-media__body'>
<span className='slds-truncate' title={String(label || children)}>
{label || children}
</span>
</span>
{iconRight && (
<span className='slds-media__figure slds-media__figure_reverse'>
<Icon
category='utility'
icon={iconRight}
size='x-small'
textColor='currentColor'
/>
</span>
)}
</div>
</li>
);
return (
<>
{divider === 'top' && (
<li className={`slds-has-divider_${divider}-space`} role='separator' />
)}
{mainListItem}
{divider === 'bottom' && (
<li className={`slds-has-divider_${divider}-space`} role='separator' />
)}
</>
);
};