-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathSelector.tsx
More file actions
1687 lines (1586 loc) · 56.4 KB
/
Copy pathSelector.tsx
File metadata and controls
1687 lines (1586 loc) · 56.4 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 Selector.tsx
* @input Uses React, StyleX, usePopover, useTooltip, Icon, InputGroupContext,
* and Selector positioning hooks
* @output Exports Selector component
* @position Core implementation; consumed by index.ts
*
* SYNC: When modified, update:
* - /packages/core/src/Selector/Selector.doc.mjs
* - /packages/core/src/Selector/Selector.test.tsx
* - /packages/core/src/Selector/index.ts
* - /apps/storybook/stories/InputGroup.stories.tsx
* - /packages/cli/assets/templates/blocks/components/Selector/ (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 {useIndicator} from '../Indicator';
import type {IndicatorPosition} from '../Indicator';
import type {IconName} from '../Icon';
import {
Field,
InputClearButton,
inputStatusBorderStyles,
inputStatusHoverShadowStyles,
inputWrapperStyles,
type FieldStatusVariant,
} from '../Field';
import {Divider} from '../Divider';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import type {LayerPlacement} from '../Layer/useLayer';
import {Spinner} from '../Spinner';
import {PanelSearchInput} from '../Field/PanelSearchInput';
import {useAnnounce} from '../hooks/useAnnounce';
import {
colorVars,
sizeVars,
spacingVars,
radiusVars,
durationVars,
easeVars,
typographyVars,
fontWeightVars,
typeScaleVars,
borderVars,
} from '../theme/tokens.stylex';
import type {SelectorOptionType, SelectorOptionData} from './types';
import {
isOptionData,
isDivider,
isSection,
normalizeOption,
getSelectableOptions,
} from './utils';
import {useCombobox, useSelectedItemOffset} from './hooks';
import {useTypeahead} from '../hooks/useTypeahead';
import {useResolvedRequired} from '../hooks/useResolvedRequired';
import {SelectorOption} from './SelectorOption';
import {SelectorRowLayoutContext} from './SelectorRowLayoutContext';
import {getInputARIA, isImeKeyEvent, mergeProps} from '../utils';
import {useSize} from '../SizeContext/SizeContext';
import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
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';
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: {
default: typeScaleVars['--text-label-size'],
'@media (pointer: coarse)': `max(1rem, ${typeScaleVars['--text-label-size']})`,
},
// A FIXED line box, not the ratio: the trigger's padding is derived from
// one line being `--spacing-5` tall, and a ratio makes the line box track
// the font — which the coarse-pointer bump above (and any theme that
// changes `--font-size-base`) then moves, taking the control off its size
// token. The glyphs still grow for touch; only the box they sit in is
// pinned. Item's own rows set their line heights and are unaffected.
lineHeight: spacingVars['--spacing-5'],
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.
// The button must not draw its own :focus-visible outline or the two stack
// into a doubled ring over the trigger.
outline: 'none',
},
triggerPlaceholder: {
color: colorVars['--color-text-secondary'],
},
triggerLabel: {
flexGrow: 1,
minWidth: 0,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
textAlign: 'start',
},
// Inside an InputGroup the group's own height is the row, and the trigger
// takes it: `height: 100%` from `groupStyles.inGroup` can only govern if the
// trigger stops asserting a floor of its own — otherwise a control sized
// above its group (`<InputGroup size="md"><Selector size="lg">`) grows the
// row it was supposed to sit in. The padding goes with it: the row is
// already the size token, and the value box is centred in it.
triggerInGroup: {
minHeight: 0,
paddingBlock: 0,
},
// Wrapper for `renderValue` output. Takes the free width and clips
// horizontally so a long value ellipsizes rather than widening the trigger;
// vertically the content sizes the control, which the size styles below
// handle.
triggerValue: {
flexGrow: 1,
minWidth: 0,
overflow: 'hidden',
textAlign: 'start',
},
// Inside an InputGroup the row height is the group's, so the trigger clamps
// its own value box to that row rather than asking the value to fit it: any
// node is cut off at the row's edge instead of bleeding through the border
// over whatever sits above and below the group. The rows the system draws
// itself never reach the cut — the row-layout context folds them onto one
// line first (SelectorRowLayoutContext).
//
// The clamp is a percentage, not the size token, because a group can be a
// different size than the control inside it; the row is whatever the group
// made it. That needs a definite height to resolve against, which is what
// stretching the button provides.
triggerButtonInGroup: {
alignSelf: 'stretch',
},
triggerValueInGroup: {
maxHeight: '100%',
},
// 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 `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',
paddingBlock: spacingVars['--spacing-1'],
paddingInline: spacingVars['--spacing-1'],
opacity: 1,
transition: `opacity ${durationVars['--duration-fast']}`,
},
dropdownInput: {
// The input trigger's text inset includes its border. Mirror that extra
// pixel in the menu; the borderless ghost variant needs no correction.
paddingInline: `calc(${spacingVars['--spacing-1']} + ${borderVars['--border-width']})`,
},
// Same correction for the search row's gutter, so the search field and the
// option rows share one left edge.
searchRowInput: {
paddingInline: `calc(${spacingVars['--spacing-1']} + ${borderVars['--border-width']})`,
},
dropdownHidden: {
opacity: 0,
transition: 'none',
},
// Popover container (for anchor positioning)
popover: {
minWidth: 'anchor-size(width)',
},
// Empty state
emptyState: {
padding: spacingVars['--spacing-3'],
textAlign: 'center',
color: colorVars['--color-text-secondary'],
fontFamily: typographyVars['--font-family-body'],
fontSize: typeScaleVars['--text-label-size'],
},
// 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',
justifyContent: 'space-between',
gap: spacingVars['--spacing-2'],
width: '100%',
padding: spacingVars['--spacing-2'],
borderRadius: radiusVars['--radius-element'],
fontFamily: typographyVars['--font-family-body'],
fontSize: typeScaleVars['--text-label-size'],
color: colorVars['--color-text-primary'],
backgroundColor: 'transparent',
border: 'none',
cursor: {
default: 'pointer',
':is(:disabled,[aria-disabled="true"])': 'default',
},
textAlign: 'start',
outline: 'none',
},
itemContent: {
display: 'flex',
alignItems: 'center',
gap: spacingVars['--spacing-2'],
flex: 1,
minWidth: 0,
},
// The mark's column, reserved on every row and at either position, so a row
// occupies the same geometry whether or not it is the chosen one — the
// default check draws nothing when unchecked, and without the column a list
// would indent (or truncate) its chosen row differently from the rest.
// `minWidth` rather than `width`: a theme can replace `check` with a larger
// indicator (a radio is 20px at `sm`), and the column has to grow with it.
itemMarkColumn: {
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
minWidth: '1rem',
},
itemCheckmark: {
flexShrink: 0,
width: 16,
height: 16,
color: colorVars['--color-icon-primary'],
},
itemHighlighted: {
backgroundColor: colorVars['--color-overlay-hover'],
},
itemSelected: {
fontWeight: fontWeightVars['--font-weight-medium'],
},
itemDisabled: {
opacity: 0.5,
cursor: 'default',
},
});
// The trigger is sized by PADDING, not by a fixed height, so it is the size
// token plus one text line for each extra line the value uses: 28/32/36 for
// one line, 48/52/56 for two. The token and a text line are both multiples of
// 4, so every trigger lands on the 4px rhythm and lines up with the Buttons
// and inputs beside it. No prop picks the height — the content does, and it
// can only land on the grid.
//
// `--spacing-5` is one line here because `triggerContainer` pins its
// line-height to exactly that; the two must stay in step, which is why both
// read the same token rather than one hardcoding 20px.
const linePad = (token: string) =>
`calc((${token} - ${spacingVars['--spacing-5']} - 2 * ${borderVars['--border-width']}) / 2)`;
const sizeStyles = stylex.create({
sm: {
minHeight: sizeVars['--size-element-sm'],
paddingBlock: linePad(sizeVars['--size-element-sm']),
},
md: {
minHeight: sizeVars['--size-element-md'],
paddingBlock: linePad(sizeVars['--size-element-md']),
},
lg: {
minHeight: sizeVars['--size-element-lg'],
paddingBlock: linePad(sizeVars['--size-element-lg']),
},
});
/**
* Size-specific overrides for dropdown list items.
* Matches the pattern used by DropdownMenuItem so that
* an `sm` selector renders compact list items, `md`/`lg` use
* the base padding defined in `styles.item`.
*/
const itemSizeStyles = stylex.create({
sm: {
paddingBlock: spacingVars['--spacing-1'],
paddingInline: spacingVars['--spacing-2'],
},
md: {
paddingBlock: spacingVars['--spacing-1-5'],
},
lg: {},
});
const STATUS_ICON_MAP: Record<SelectorStatusType, IconName> = {
warning: 'warning',
error: 'error',
success: 'success',
};
const STATUS_ICON_COLOR_MAP: Record<
SelectorStatusType,
'warning' | 'error' | 'success'
> = {
warning: 'warning',
error: 'error',
success: 'success',
};
const STATUS_BUTTON_LABEL_KEY: Record<SelectorStatusType, string> = {
warning: '@astryx.input.statusButton.warning',
error: '@astryx.input.statusButton.error',
success: '@astryx.input.statusButton.success',
};
export type SelectorSize = 'sm' | 'md' | 'lg';
export type SelectorVariant = 'input' | 'ghost';
export type SelectorStatusType = 'warning' | 'error' | 'success';
export interface SelectorStatus {
/**
* The type of status to display.
*/
type: SelectorStatusType;
/**
* Optional message to display below the input.
*/
message?: string;
}
interface SelectorPropsBase<
T extends SelectorOptionType = SelectorOptionType,
> extends Omit<BaseProps, 'onChange' | 'defaultValue'> {
/**
* Label text for the 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
* ```
* <Selector
* label="Owner"
* options={owners}
* isDisabled
* disabledMessage="You need the Editor role to change this"
* />
* ```
*/
disabledMessage?: string;
/**
* The options to display in the selector.
* Can be strings, objects, dividers, or sections.
*/
options: T[];
// value, onChange, changeAction, and hasClear are in the discriminated union below
/**
* 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.
* - 'sm': Compact size
* - 'md': Default size
* @default 'md'
*/
size?: SelectorSize;
/**
* Visual style of the selector trigger.
* - 'input': bordered input-style trigger for forms
* - 'ghost': borderless trigger matching ghost buttons, for toolbars
* @default 'input'
*/
variant?: SelectorVariant;
/**
* Status indicator for the selector.
* When set, displays a colored border and status icon.
* If message is provided, displays a message box below the selector.
*/
status?: SelectorStatus;
/**
* 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. Takes precedence over
* the selected option's own `icon`, which the trigger otherwise renders.
*/
startIcon?: ReactNode | IconType;
/**
* Custom render function for options.
* Only called for selectable options (not dividers/sections).
*/
renderOption?: (option: SelectorOptionData) => ReactNode;
/**
* Custom render function for the selected option inside the closed trigger.
* Only called when something is selected; the placeholder is unaffected.
*
* Passing this does not change the trigger's height — what it draws does. A
* one-line value measures exactly the `size` token, so the control still
* lines up with the Buttons and inputs beside it; each further line of
* content adds one text line. Inside an `InputGroup` the group owns the row
* height: the trigger clamps its value box to that row, so a `SelectorOption`
* folds onto one line and ellipsizes, and anything taller than the row is cut
* off at it rather than bleeding over the rows above and below.
*
* @example
* ```
* renderValue={option => (
* <SelectorOption
* icon={option.icon}
* label={option.label}
* description={option.description}
* />
* )}
* ```
*/
renderValue?: (option: SelectorOptionData) => ReactNode;
/**
* Which edge of the option row carries the selected mark. `start` reserves a
* mark column ahead of every label so they stay aligned, the way a native
* menu does; `end` is the house convention shared with Typeahead and
* CommandPalette.
*
* @default 'end'
*/
indicatorPosition?: IndicatorPosition;
/**
* Whether to show a search input for filtering options.
* @default false
*/
hasSearch?: boolean;
/**
* Placeholder text for the search input.
* @default 'Search...'
*/
searchPlaceholder?: string;
/**
* Position placement relative to the trigger.
*
* Omit to use the selector's default selected-item overlay behavior: the
* selected item is positioned over the trigger and clamped to the viewport.
* Set a placement to opt into explicit layer positioning (for example,
* `placement="above"` for bottom-fixed toolbars).
*/
placement?: LayerPlacement;
/**
* Whether the dropdown starts open on mount.
* Useful for showcases and previews.
* @default false
*/
isDefaultOpen?: boolean;
/**
* The HTML name attribute for form submissions. When set, a hidden input
* carries the selected value under this name, matching how a native
* select serializes.
*/
htmlName?: string;
/**
* Test ID for testing frameworks.
*/
'data-testid'?: string;
}
/**
* Without `hasClear`, the selector always has a string value (or undefined for placeholder).
* With `hasClear`, the value can be `null` and onChange receives `null` on clear.
*/
type SelectorPropsNonClearable<
T extends SelectorOptionType = SelectorOptionType,
> = SelectorPropsBase<T> & {
hasClear?: false;
value?: string;
onChange?: (value: string) => void;
changeAction?: (value: string) => void | Promise<void>;
};
type SelectorPropsClearable<T extends SelectorOptionType = SelectorOptionType> =
SelectorPropsBase<T> & {
/**
* Whether to show a clear button when a value is selected.
* When clicked, resets the value to `null` and returns focus to the trigger.
*
* When enabled, `value` and `onChange` widen to include `null`.
*/
hasClear: true;
value: string | null;
onChange?: (value: string | null) => void;
changeAction?: (value: string | null) => void | Promise<void>;
};
export type SelectorProps<T extends SelectorOptionType = SelectorOptionType> =
SelectorPropsNonClearable<T> | SelectorPropsClearable<T>;
/**
* Default option renderer
*/
function DefaultOption({option}: {option: SelectorOptionData}) {
return (
<SelectorOption
icon={option.icon}
label={option.label ?? option.value}
description={option.description}
/>
);
}
// 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: SelectorOptionData,
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: SelectorOptionData[],
query: string,
): SelectorOptionData[] {
if (!query) {
return items;
}
return items.filter(item => optionMatchesQuery(item, query));
}
/**
* A selector/dropdown component for choosing from a list of options.
*
* @example
* ```
* <Selector
* label="Fruit"
* options={['Apple', 'Banana', 'Orange']}
* value={fruit}
* onChange={setFruit}
* placeholder="Select a fruit..."
* />
* ```
*/
export function Selector<T extends SelectorOptionType>(
props: SelectorProps<T>,
) {
const t = useTranslator();
const {
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,
htmlName,
renderOption,
renderValue,
indicatorPosition = 'end',
hasSearch = false,
searchPlaceholder: searchPlaceholderFromProps,
placement,
isDefaultOpen = false,
'data-testid': testId,
width,
xstyle,
className,
style,
hasClear: hasClearProp,
...rest
} = props as SelectorPropsClearable<T>;
const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});
const placeholder = placeholderFromProps ?? t('@astryx.selector.placeholder');
const searchPlaceholder =
searchPlaceholderFromProps ?? t('@astryx.selector.searchPlaceholder');
const hasClear = hasClearProp === true;
const size = useSize(sizeProp, 'md');
const effectiveStatusVariant =
variant === 'ghost' && statusVariant === 'attached'
? 'detached'
: statusVariant;
// Normalize null to undefined for internal use (null is the clear sentinel)
const normalizedValue = value === null ? undefined : value;
const triggerId = useId();
const listboxId = useId();
const descriptionId = useId();
const statusMessageId = useId();
const inputLabelId = useId();
const searchId = useId();
// Measure from the same outer control that usePopover anchors to; using the
// shorter inner button makes every size's selected row land too low.
const anchorRef = useRef<HTMLDivElement>(null);
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;
const [, startTransition] = useTransition();
const [optimisticValue, setOptimisticValue] = useOptimistic(normalizedValue);
const isBusy = isLoading || optimisticValue !== normalizedValue;
const announce = useAnnounce();
// 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
// useCombobox (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],
);
// Filter items by search query
const filteredItems = useMemo(
() => filterOptionsByQuery(selectableItems, searchQuery),
[selectableItems, searchQuery],
);
// Find selected item and its index for positioning
const selectedItemIndex = useMemo(() => {
return selectableItems.findIndex(item => item.value === optimisticValue);
}, [selectableItems, optimisticValue]);
const selectedItem = useMemo(() => {
return selectedItemIndex >= 0
? selectableItems[selectedItemIndex]
: undefined;
}, [selectableItems, selectedItemIndex]);
// Ref for listbox to measure selected item position
const listboxRef = useRef<HTMLDivElement>(null);
// Typeahead is defined below (it needs the popover), but closing and clearing
// must drop its pending buffer — otherwise a stale prefix survives the reset
// window and poisons the next keystroke ("Dog" then "c" would search "dc").
const resetTypeaheadRef = useRef<() => void>(() => {});
// Layer for dropdown positioning
const handleLayerHide = useCallback(() => {
setSearchQuery('');
resetTypeaheadRef.current();
// 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({
onHide: handleLayerHide,
hasLightDismiss: true,
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: '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.
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.selector.emptySearchResults')
: t('@astryx.selector.resultCount', {count}),
);
},
[announce, selectableItems, t],
);
// Calculate offset to position selected item over trigger. Explicit
// placement opts out of the selector-specific overlay behavior and uses the
// standard layer positioning API instead.
const shouldOverlaySelectedItem = placement == null && !hasSearch;
const {offset: rawOffset, isPositioned: rawIsPositioned} =
useSelectedItemOffset({
isOpen: popover.isOpen && shouldOverlaySelectedItem,
selectedItemIndex,
listboxId,
listboxRef,
anchorRef,
});
const selectedItemOffset = shouldOverlaySelectedItem ? rawOffset : 0;
const isPositioned = shouldOverlaySelectedItem ? rawIsPositioned : true;
const popoverPlacement = placement ?? 'below';
const popoverOffsetStyle: React.CSSProperties | undefined =
selectedItemOffset > 0
? {marginBlockStart: `-${selectedItemOffset}px`}
: undefined;
// Clear the current value. Shared by the clear button and the keyboard
// Delete/Backspace path so clearing is reachable without a mouse.
const clearValue = useCallback(() => {
resetTypeaheadRef.current();
onChange?.(null);
if (changeAction) {
startTransition(async () => {
setOptimisticValue(undefined);
await changeAction(null);
});
}
}, [onChange, changeAction, startTransition, setOptimisticValue]);
// Type-to-find appends to the query rather than replacing it: characters
// typed before focus reaches the search input must not be dropped.
const appendSearchQuery = useCallback((char: string) => {
setSearchQuery(query => query + char);
}, []);
const commitValue = useCallback(