-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathMultiSelector.tsx
More file actions
1729 lines (1612 loc) · 54.1 KB
/
Copy pathMultiSelector.tsx
File metadata and controls
1729 lines (1612 loc) · 54.1 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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Meta Platforms, Inc. and affiliates.
'use client';
/**
* @file MultiSelector.tsx
* @input Uses React, StyleX, usePopover, useTooltip, CheckboxInput, Field, Badge, Icon, InputGroupContext
* @output Exports MultiSelector component
* @position Core implementation; consumed by index.ts
*
* SYNC: When modified, update:
* - /packages/core/src/MultiSelector/MultiSelector.doc.mjs
* - /packages/core/src/MultiSelector/MultiSelector.test.tsx
* - /packages/core/src/MultiSelector/index.ts
* - /apps/storybook/stories/InputGroup.stories.tsx
* - /packages/cli/assets/templates/blocks/components/MultiSelector/ (showcase blocks)
*/
import React, {
useCallback,
useEffect,
useId,
useMemo,
useOptimistic,
useRef,
useState,
useTransition,
type ReactNode,
} from 'react';
import * as stylex from '@stylexjs/stylex';
import {usePopover} from '../Popover/usePopover';
import {useTooltip} from '../Tooltip';
import {Icon, renderIconSlot, type IconType} from '../Icon';
import type {IconName} from '../Icon';
import {
Field,
InputClearButton,
inputStatusBorderStyles,
inputStatusHoverShadowStyles,
inputWrapperStyles,
type FieldStatusVariant,
} from '../Field';
import {Divider} from '../Divider';
import {Spinner} from '../Spinner';
import {PanelSearchInput} from '../Field/PanelSearchInput';
import {CheckboxInput} from '../CheckboxInput';
import type {IndicatorPosition} from '../Indicator';
import {Badge} from '../Badge';
import {
colorVars,
sizeVars,
spacingVars,
radiusVars,
durationVars,
easeVars,
typographyVars,
fontWeightVars,
typeScaleVars,
borderVars,
} from '../theme/tokens.stylex';
import type {
MultiSelectorOptionType,
MultiSelectorOptionData,
MultiSelectorStatus,
} from './types';
import {
isOptionData,
isDivider,
isSection,
normalizeOption,
getSelectableOptions,
} from '../Selector/utils';
import {useMultiCombobox} from './hooks';
import {getInputARIA, isImeKeyEvent, mergeProps} from '../utils';
import {useAnnounce} from '../hooks/useAnnounce';
import {useResolvedRequired} from '../hooks/useResolvedRequired';
import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
import {useSize} from '../SizeContext/SizeContext';
import {themeProps} from '../utils/themeProps';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {stableClassName} from '../naming';
import {groupStyles} from '../InputGroup/groupStyles';
import {useInputGroup} from '../InputGroup/InputGroupContext';
import {VisuallyHidden} from '../VisuallyHidden';
import {useTranslator} from '../i18n';
// Sentinel value for the select-all item in keyboard navigation
const SELECT_ALL_VALUE = '__xds_select_all__';
const styles = stylex.create({
// Trigger container — the enhanced click target wrapping the combobox button and clear button as siblings
triggerContainer: {
position: 'relative',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: spacingVars['--spacing-2'],
width: '100%',
paddingBlock: spacingVars['--spacing-2'],
paddingInline: spacingVars['--spacing-3'],
fontFamily: typographyVars['--font-family-body'],
fontSize: typeScaleVars['--text-label-size'],
lineHeight: typeScaleVars['--text-label-leading'],
color: colorVars['--color-text-primary'],
cursor: {
default: 'pointer',
':is(:disabled,[aria-disabled="true"])': 'default',
},
},
// Trigger button — the actual combobox button, visually integrated with the container
trigger: {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: spacingVars['--spacing-2'],
flexGrow: 1,
flexShrink: 1,
flexBasis: 0,
minWidth: 0,
padding: 0,
margin: 0,
borderWidth: 0,
borderStyle: 'none',
backgroundColor: 'transparent',
fontFamily: 'inherit',
fontSize: 'inherit',
lineHeight: 'inherit',
color: 'inherit',
cursor: {
default: 'pointer',
':is(:disabled,[aria-disabled="true"])': 'default',
},
// The wrapper (inputWrapperStyles.base) renders the focus ring via
// :focus-within when this button is focused, matching
// TextInput/NumberInput/Selector. The button must not draw its own
// :focus-visible outline or the two stack into a doubled ring over the
// trigger.
outline: 'none',
borderRadius: radiusVars['--radius-element'],
},
triggerPlaceholder: {
color: colorVars['--color-text-secondary'],
},
triggerContent: {
display: 'flex',
alignItems: 'center',
gap: spacingVars['--spacing-1'],
flexGrow: 1,
flexShrink: 1,
flexBasis: 0,
minWidth: 0,
overflow: 'hidden',
},
triggerText: {
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
triggerBadges: {
display: 'flex',
flexWrap: 'wrap',
gap: spacingVars['--spacing-1'],
alignItems: 'center',
},
triggerOverflow: {
flexShrink: 0,
fontSize: typeScaleVars['--text-label-size'],
color: colorVars['--color-text-secondary'],
fontWeight: fontWeightVars['--font-weight-medium'],
},
// Only what Icon does not already provide: `size="sm"` gives the 16px box
// and `color` the token, but the glyph still must not shrink inside the flex
// trigger.
triggerIcon: {
flexShrink: 0,
},
// Rotation lives on the chevron glyph itself (passed through `xstyle`), not
// on the layout wrapper above, so the icon's `multi-selector-indicator-icon`
// theme target and the open/closed transform sit on one element — a theme can
// restyle the mark and its rotation through a single selector. The wrapper
// keeps only layout. The status branch renders a different icon, so it never
// picks these up and needs no transition opt-out.
triggerIconRotation: {
transitionProperty: 'transform',
transitionDuration: durationVars['--duration-fast'],
transitionTimingFunction: easeVars['--ease-standard'],
transformOrigin: 'center',
},
triggerIconOpen: {
transform: 'rotate(180deg)',
},
triggerGhost: {
width: 'auto',
borderWidth: 0,
backgroundColor: 'transparent',
backgroundImage: {
default: null,
':hover:where(:not(:disabled,[aria-disabled="true"]))': {
'@media (hover: hover)': `linear-gradient(${colorVars['--color-overlay-hover']}, ${colorVars['--color-overlay-hover']})`,
},
':active': `linear-gradient(${colorVars['--color-overlay-pressed']}, ${colorVars['--color-overlay-pressed']})`,
},
boxShadow: {
default: 'none',
':hover:not(:focus-within):where(:not(:disabled,[aria-disabled="true"]))':
{
'@media (hover: hover)': 'none',
},
':focus-within': 'none',
},
fontWeight: fontWeightVars['--font-weight-medium'],
transitionProperty:
'background-image, background-color, color, opacity, transform',
transform: {
default: 'scale(1)',
':active': 'scale(0.98)',
},
},
triggerGhostDisabled: {
backgroundImage: 'none',
transform: {
default: 'none',
':active': 'none',
},
},
// Clear button
statusButton: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 0,
margin: 0,
borderWidth: 0,
borderStyle: 'none',
backgroundColor: 'transparent',
color: 'inherit',
cursor: {
default: 'pointer',
':is(:disabled,[aria-disabled="true"])': 'default',
},
borderRadius: radiusVars['--radius-element'],
},
// Dropdown container
dropdown: {
boxSizing: 'border-box',
maxHeight: '300px',
overflowY: 'auto',
padding: spacingVars['--spacing-1'],
},
// Popover container (for anchor positioning)
popover: {
minWidth: 'anchor-size(width)',
},
// Select-all wrapper
selectAllWrapper: {
display: 'flex',
alignItems: 'center',
gap: spacingVars['--spacing-2'],
cursor: {
default: 'pointer',
':is(:disabled,[aria-disabled="true"])': 'default',
},
},
// Section heading. Plain secondary text, no rules — the same treatment
// DropdownMenu and CommandPaletteGroup already use for a group heading in a
// panel list. A labeled Divider (line–text–line) reads as a separator, and
// next to the search row's own divider it stacked two rules a few pixels
// apart.
sectionHeading: {
paddingBlock: spacingVars['--spacing-1'],
paddingInline: spacingVars['--spacing-2'],
fontFamily: typographyVars['--font-family-body'],
fontSize: typeScaleVars['--text-supporting-size'],
lineHeight: typeScaleVars['--text-supporting-leading'],
color: colorVars['--color-text-secondary'],
userSelect: 'none',
},
// Divider
divider: {
marginBlock: spacingVars['--spacing-1'],
},
// Individual item
item: {
boxSizing: 'border-box',
display: 'flex',
alignItems: 'center',
gap: spacingVars['--spacing-2'],
width: '100%',
borderRadius: radiusVars['--radius-element'],
cursor: {
default: 'pointer',
':is(:disabled,[aria-disabled="true"])': 'default',
},
// Row typography lives here, not on the label span, so a theme override on
// the row target reaches both the fallback label and renderOption output
// (a declaration on the span would win over the inherited row value).
// Matches Selector, whose option row owns its typography the same way.
fontFamily: typographyVars['--font-family-body'],
fontSize: typeScaleVars['--text-label-size'],
fontWeight: fontWeightVars['--font-weight-medium'],
color: colorVars['--color-text-primary'],
backgroundColor: 'transparent',
border: 'none',
outline: 'none',
},
itemHighlighted: {
backgroundColor: colorVars['--color-overlay-hover'],
},
itemDisabled: {
opacity: 0.5,
color: colorVars['--color-text-disabled'],
cursor: 'default',
},
// Decorative checkbox (non-interactive, purely visual)
checkboxDecorative: {
pointerEvents: 'none',
display: 'flex',
flexShrink: 0,
},
// Pushed to the row's far edge rather than sitting against the label, which
// is what an end-positioned control means here. The row is not
// `space-between` (a truncating label plus a trailing control is what wants
// the auto margin), and `renderOption` content is not wrapped in a growing
// span, so the margin has to live on the checkbox itself.
checkboxDecorativeEnd: {
marginInlineStart: 'auto',
},
// Label text for items (rendered outside checkbox for correct click
// behavior). Typography is inherited from the row; this only handles
// truncation.
itemLabel: {
minWidth: 0,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
// Empty state
emptyState: {
padding: spacingVars['--spacing-3'],
textAlign: 'center',
color: colorVars['--color-text-secondary'],
fontFamily: typographyVars['--font-family-body'],
fontSize: typeScaleVars['--text-label-size'],
},
});
const sizeStyles = stylex.create({
sm: {
height: sizeVars['--size-element-sm'],
},
md: {
height: sizeVars['--size-element-md'],
},
lg: {
height: sizeVars['--size-element-lg'],
},
});
const itemSizeStyles = stylex.create({
sm: {
padding: spacingVars['--spacing-1'],
},
md: {
paddingBlock: spacingVars['--spacing-1-5'],
paddingInline: spacingVars['--spacing-2'],
},
lg: {
padding: spacingVars['--spacing-2'],
},
});
const selectAllSizeStyles = stylex.create({
sm: {
paddingInline: spacingVars['--spacing-1'],
paddingBlock: spacingVars['--spacing-0-5'],
},
md: {
paddingInline: spacingVars['--spacing-2'],
paddingBlock: spacingVars['--spacing-1'],
},
lg: {
paddingInline: spacingVars['--spacing-2'],
paddingBlock: spacingVars['--spacing-1'],
},
});
const STATUS_ICON_MAP: Record<MultiSelectorStatusType, IconName> = {
warning: 'warning',
error: 'error',
success: 'success',
};
const STATUS_ICON_COLOR_MAP: Record<
MultiSelectorStatusType,
'warning' | 'error' | 'success'
> = {
warning: 'warning',
error: 'error',
success: 'success',
};
const STATUS_BUTTON_LABEL_KEY: Record<MultiSelectorStatusType, string> = {
warning: '@astryx.input.statusButton.warning',
error: '@astryx.input.statusButton.error',
success: '@astryx.input.statusButton.success',
};
export type MultiSelectorSize = 'sm' | 'md' | 'lg';
export type MultiSelectorVariant = 'input' | 'ghost';
export type MultiSelectorStatusType = 'warning' | 'error' | 'success';
export type {MultiSelectorStatus};
export interface MultiSelectorProps<
T extends MultiSelectorOptionType = MultiSelectorOptionType,
> extends Omit<BaseProps, 'onChange' | 'defaultValue'> {
/**
* Label text for the multi-selector (always rendered for accessibility).
*/
label: string;
/**
* Whether to visually hide the label (still accessible to screen readers).
* @default false
*/
isLabelHidden?: boolean;
/**
* Description text displayed between the label and selector.
*/
description?: string;
/**
* Whether the field is optional. Mutually exclusive with isRequired.
* @default false
*/
isOptional?: boolean;
/**
* Whether the field is required. Mutually exclusive with isOptional.
* @default false
*/
isRequired?: boolean;
/**
* Whether the selector is disabled.
* @default false
*/
isDisabled?: boolean;
/**
* Explains why the selector is disabled. When set together with
* `isDisabled`, the selector shows a tooltip with this text on hover and
* keyboard focus, and the trigger stays focusable (via `aria-disabled`)
* so the reason is discoverable by keyboard and assistive technology.
* Activation stays blocked.
*
* Use this instead of wrapping a disabled selector in `Tooltip` — disabled
* controls don't emit the pointer events an external tooltip needs.
*
* @example
* ```
* <MultiSelector
* label="Columns"
* options={columns}
* value={selected}
* onChange={setSelected}
* isDisabled
* disabledMessage="Select a table first"
* />
* ```
*/
disabledMessage?: string;
/**
* The options to display in the selector.
* Can be strings, objects, dividers, or sections.
*/
options: T[];
/**
* The currently selected values.
*/
value: string[];
/**
* The HTML name attribute for form submissions. When set, hidden inputs
* carry one entry per selected value under this name, matching how a
* native multi-select serializes.
*/
htmlName?: string;
/**
* Callback when selection changes.
*/
onChange: (value: string[]) => void;
/**
* Async action on change. Fires after onChange.
*/
changeAction?: (value: string[]) => void | Promise<void>;
/**
* Whether the selector is in a loading state.
* @default false
*/
isLoading?: boolean;
/**
* Placeholder text when no value is selected.
* @default 'Select...'
*/
placeholder?: string;
/**
* The size of the selector.
* @default 'md'
*/
size?: MultiSelectorSize;
/**
* Visual style of the selector trigger.
* - 'input': bordered input-style trigger for forms
* - 'ghost': borderless trigger matching ghost buttons, for toolbars
* @default 'input'
*/
variant?: MultiSelectorVariant;
/**
* Status indicator for the selector.
*/
status?: MultiSelectorStatus;
/**
* How the status message is placed relative to the input.
* - 'attached': message overlaps directly below the bordered input (input variant only)
* - 'detached': message floats below as a separate element with spacing
* - 'tooltip': message is exposed from the on-field status icon
* @default 'attached' for input selectors; 'detached' for ghost selectors
*/
statusVariant?: FieldStatusVariant;
/**
* Width of the field. Numbers are treated as pixels, strings are used as-is
* (e.g. `'100%'`). Sizes the whole field (label, control, and status) so they
* stay aligned, unlike setting width via `xstyle`/`className`/`style`.
*/
width?: SizeValue;
/**
* Tooltip text to display in an info icon at the end of the label.
*/
labelTooltip?: string;
/**
* Icon displayed at the start of the selector trigger.
*/
startIcon?: ReactNode | IconType;
/**
* Whether to show a clear button when values are selected.
* When clicked, resets the value to an empty array and returns focus to the trigger.
* @default false
*/
hasClear?: boolean;
/**
* Whether to show a "Select all" checkbox.
* @default false
*/
hasSelectAll?: boolean;
/**
* Label for the select-all checkbox.
* @default 'Select all'
*/
selectAllLabel?: string;
/**
* Whether to show a search input.
* @default false
*/
hasSearch?: boolean;
/**
* Placeholder text for the search input.
* @default 'Search...'
*/
searchPlaceholder?: string;
/**
* How to display selected items in the trigger.
* - 'count': "3 selected"
* - 'labels': "Name, Email, +3"
* - 'badges': [Name] [Email] +2
* @default 'count'
*/
triggerDisplay?: 'count' | 'labels' | 'badges';
/**
* Maximum number of badges to show before showing "+N".
* Only used when triggerDisplay is 'badges'.
* @default 3
*/
maxBadges?: number;
/**
* Custom render function for options.
* Only called for selectable options (not dividers/sections or the select-all row).
*/
renderOption?: (option: MultiSelectorOptionData) => ReactNode;
/**
* Which edge of the option row carries the checkbox.
*
* @default 'start'
*/
indicatorPosition?: IndicatorPosition;
/**
* Whether the dropdown starts open on mount.
* Useful for showcases and previews.
* @default false
*/
isDefaultOpen?: boolean;
/**
* Test ID for testing frameworks.
*/
'data-testid'?: string;
}
// Case-insensitive substring match for a single option. The one predicate used
// by both the flat filter (count + keyboard nav) and the grouped renderer, so
// what is shown while searching stays in lockstep with the announced count.
function optionMatchesQuery(
option: MultiSelectorOptionData,
query: string,
): boolean {
if (!query) {
return true;
}
return (option.label ?? option.value)
.toLowerCase()
.includes(query.toLowerCase());
}
// Case-insensitive substring filter over the selectable options. Shared by the
// `filteredItems` memo (rendering) and the search-change handler, which needs
// the count for the *next* query synchronously to announce it exactly once per
// keystroke rather than reacting to state in an effect.
function filterOptionsByQuery(
items: MultiSelectorOptionData[],
query: string,
): MultiSelectorOptionData[] {
if (!query) {
return items;
}
return items.filter(item => optionMatchesQuery(item, query));
}
/**
* A multi-select dropdown component with checkboxes for choosing
* multiple items from a list of options.
*
* @example
* ```
* <MultiSelector
* label="Columns"
* options={['Name', 'Email', 'Role', 'Status']}
* value={selectedColumns}
* onChange={setSelectedColumns}
* hasSelectAll
* />
* ```
*/
export function MultiSelector<T extends MultiSelectorOptionType>({
label,
isLabelHidden = false,
description,
isOptional = false,
isRequired = false,
isDisabled = false,
disabledMessage,
options,
value,
onChange,
changeAction,
isLoading = false,
placeholder: placeholderFromProps,
size: sizeProp,
variant = 'input',
status,
statusVariant = 'attached',
labelTooltip,
startIcon,
hasClear = false,
hasSelectAll = false,
selectAllLabel: selectAllLabelFromProps,
hasSearch = false,
searchPlaceholder: searchPlaceholderFromProps,
triggerDisplay = 'count',
maxBadges = 3,
renderOption,
indicatorPosition = 'start',
isDefaultOpen = false,
'data-testid': testId,
htmlName,
width,
xstyle,
className,
style,
}: MultiSelectorProps<T>) {
const t = useTranslator();
const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});
const placeholder =
placeholderFromProps ?? t('@astryx.multiSelector.selectPlaceholder');
const selectAllLabel =
selectAllLabelFromProps ?? t('@astryx.multiSelector.selectAll');
const searchPlaceholder =
searchPlaceholderFromProps ?? t('@astryx.multiSelector.searchPlaceholder');
const size = useSize(sizeProp, 'md');
const effectiveStatusVariant =
variant === 'ghost' && statusVariant === 'attached'
? 'detached'
: statusVariant;
const triggerId = useId();
const listboxId = useId();
const descriptionId = useId();
const statusMessageId = useId();
const inputLabelId = useId();
const searchId = useId();
const triggerRef = useRef<HTMLButtonElement>(null);
const searchRef = useRef<HTMLInputElement>(null);
const inputGroup = useInputGroup();
const [searchQuery, setSearchQuery] = useState('');
// A typed query shows the search row's clear (✕) button, which becomes
// the next tab stop after the search input.
const hasQuery = searchQuery.length > 0;
// Snapshot of which values were selected when the dropdown opened.
// Stored as state (not a ref) so sortedItems recomputes exactly once on open,
// then stays frozen until the menu closes.
const [selectedAtOpen, setSelectedAtOpen] = useState<Set<string> | null>(
null,
);
const [, startTransition] = useTransition();
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
const isBusy = isLoading || optimisticValue !== value;
// Disabled-reason tooltip. Disabled controls swallow pointer events, so the
// tooltip listeners attach to the trigger container (which already exists)
// and the trigger button stays perceivable via aria-disabled instead of the
// disabled attribute. Activation is blocked by the isDisabled guards in
// useMultiCombobox (onTriggerClick / onKeyDown).
const showsDisabledMessage = isDisabled && !!disabledMessage;
const disabledMessageTooltip = useTooltip({
placement: 'above',
// The container div is not naturally focusable; focusin bubbles up from
// the trigger button, so always attach focus listeners.
focusTrigger: 'always',
isEnabled: showsDisabledMessage,
});
const statusTooltip = useTooltip({
placement: 'above',
isEnabled: effectiveStatusVariant === 'tooltip' && !!status?.message,
});
const {ariaLabelledBy, ariaDescribedBy} = getInputARIA(
inputLabelId,
[
description ? descriptionId : null,
!inputGroup && effectiveStatusVariant !== 'tooltip' && status?.message
? statusMessageId
: null,
effectiveStatusVariant === 'tooltip' && status?.message
? statusTooltip.describedBy
: null,
showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
],
inputGroup,
);
// Flatten options for keyboard navigation
const selectableItems = useMemo(
() => getSelectableOptions(options),
[options],
);
// Announce selection-count changes politely (comboboxes-7 announce path).
// Toggling options / select-all previously produced no audible feedback.
const announce = useAnnounce();
const announceSelection = useCallback(
(nextValue: string[]) => {
const total = selectableItems.length;
const selectableSet = new Set(selectableItems.map(item => item.value));
const selectedCount = nextValue.filter(v => selectableSet.has(v)).length;
if (selectedCount === 0) {
announce(t('@astryx.multiSelector.selectionCleared'));
} else if (total > 0 && selectedCount === total) {
announce(t('@astryx.multiSelector.allSelected'));
} else {
announce(
t('@astryx.multiSelector.selectionCount', {
count: selectedCount,
total,
}),
);
}
},
[announce, selectableItems, t],
);
// Filter items by search query
const filteredItems = useMemo(
() => filterOptionsByQuery(selectableItems, searchQuery),
[selectableItems, searchQuery],
);
// Single source of truth for item order. Both the hook (keyboard navigation)
// and renderOptions (DOM rendering) consume this list — no independent sorting.
// Selected-at-open items are placed first within each group/section, and the
// same walk applies while searching so group structure survives filtering
// (only matching items are kept; the query is empty in non-search mode).
const sortedItems = useMemo(() => {
const selectedSet = selectedAtOpen ?? new Set<string>();
const result: MultiSelectorOptionData[] = [];
let pendingFlat: MultiSelectorOptionData[] = [];
const orderSelectedFirst = (items: MultiSelectorOptionData[]) => {
const selected = items.filter(item => selectedSet.has(item.value));
const unselected = items.filter(item => !selectedSet.has(item.value));
return [...selected, ...unselected];
};
const flushFlat = () => {
if (pendingFlat.length === 0) {
return;
}
result.push(...orderSelectedFirst(pendingFlat));
pendingFlat = [];
};
for (const option of options) {
if (isDivider(option)) {
flushFlat();
} else if (isSection(option)) {
flushFlat();
const sectionOptions = option.options
.map(opt => normalizeOption(opt))
.filter(opt => optionMatchesQuery(opt, searchQuery));
result.push(...orderSelectedFirst(sectionOptions));
} else if (isOptionData(option)) {
const normalized = normalizeOption(option);
if (optionMatchesQuery(normalized, searchQuery)) {
pendingFlat.push(normalized);
}
}
}
flushFlat();
if (hasSelectAll) {
return [{value: SELECT_ALL_VALUE, label: selectAllLabel}, ...result];
}
return result;
}, [searchQuery, options, selectedAtOpen, hasSelectAll, selectAllLabel]);
// Layer for dropdown positioning
const handleLayerHide = useCallback(() => {
setSearchQuery('');
setSelectedAtOpen(null);
// Clear any lingering result count when the popover closes so stale status
// text does not linger in the a11y tree.
announce('');
triggerRef.current?.focus();
}, [announce]);
const popover = usePopover({
hasLightDismiss: true,
onHide: handleLayerHide,
hasCloseButton: false,
hasAutoFocus: false,
// The popup's own role="listbox" is the exposed semantics; the trigger
// keeps DOM focus, so wrapping it in a modal dialog would misrepresent it.
role: 'none',
// The theme target belongs on the SURFACE that paints the popup, which
// `usePopover` owns — not on the scrolling list inside it.
surfaceTarget: 'multi-selector-popup',
});
// Open dropdown on mount when isDefaultOpen is true
useEffect(() => {
if (isDefaultOpen) {
popover.show();
}
// eslint-disable-next-line @eslint-react/exhaustive-deps -- mount-only: isDefaultOpen is not reactive
}, []);
// Announce the filtered result count from the query-change handler (matching
// BaseTypeahead) rather than a reactive effect: computing the count for the
// next query here fires the announcement exactly once per keystroke and does
// not re-speak on unrelated re-renders. Reuses the announce instance shared
// with the selection-count announcements above.
const handleSearchChange = useCallback(
(nextQuery: string) => {
setSearchQuery(nextQuery);
if (nextQuery.length === 0) {
// Emptying the query clears the region rather than announcing a count.
announce('');
return;
}
const count = filterOptionsByQuery(selectableItems, nextQuery).length;
announce(
count === 0
? t('@astryx.multiSelector.emptySearchResults')
: t('@astryx.multiSelector.resultCount', {count}),
);
},
[announce, selectableItems, t],
);
// Handle toggle
// Clear all selected values. Shared by the clear button and the keyboard
// Delete/Backspace path so clearing is reachable without a mouse.
const clearValues = useCallback(() => {
onChange([]);
announceSelection([]);
if (changeAction) {
startTransition(async () => {
setOptimisticValue([]);
await changeAction([]);
});
}
}, [
onChange,
changeAction,
startTransition,
setOptimisticValue,
announceSelection,
]);
// Whether there is at least one selected value (clearing is meaningful).
const hasValue = optimisticValue.length > 0;
const handleClear = useCallback(
(e: React.MouseEvent) => {
e.stopPropagation(); // Don't open dropdown
clearValues();
},
[clearValues],
);
const handleToggle = useCallback(
(itemValue: string) => {
const newValue = optimisticValue.includes(itemValue)
? optimisticValue.filter(v => v !== itemValue)
: [...optimisticValue, itemValue];
onChange(newValue);
announceSelection(newValue);
if (changeAction) {
startTransition(async () => {
setOptimisticValue(newValue);
await changeAction(newValue);
});
}
},
[
optimisticValue,
onChange,
changeAction,
startTransition,
setOptimisticValue,
announceSelection,
],
);
// Select-all logic
const enabledItems = useMemo(
() => filteredItems.filter(item => !item.disabled),
[filteredItems],
);
const allEnabledSelected = useMemo(
() =>
enabledItems.length > 0 &&