-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathComplexSelector.tsx
More file actions
588 lines (560 loc) · 17.4 KB
/
Copy pathComplexSelector.tsx
File metadata and controls
588 lines (560 loc) · 17.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
// Copyright (c) Meta Platforms, Inc. and affiliates.
'use client';
/**
* @file ComplexSelector.tsx
* @input Uses React, StyleX, Field, Icon slots, Layer positioning, and usePopover
* @output Exports a rich-selector shell with exact token-sized input and ghost triggers, plus an imperative open/close handle
* @position Core implementation; consumed by index.ts
*
* SYNC: When modified, update:
* - /packages/core/src/ComplexSelector/ComplexSelector.doc.mjs
* - /packages/core/src/ComplexSelector/ComplexSelector.test.tsx
* - /packages/core/src/ComplexSelector/index.ts
* - /apps/storybook/stories/ComplexSelector.stories.tsx
* - /packages/cli/assets/templates/blocks/components/ComplexSelector/ (showcase blocks)
*/
import React, {
useCallback,
useId,
useImperativeHandle,
useOptimistic,
useRef,
useTransition,
type ReactNode,
} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import type {BaseProps} from '../BaseProps';
import {Field, inputWrapperStyles, type FieldStatusVariant} from '../Field';
import {Icon, renderIconSlot, type IconType} from '../Icon';
import {Spinner} from '../Spinner';
import {useTranslator} from '../i18n';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer';
import {usePopover} from '../Popover/usePopover';
import {useResolvedRequired} from '../hooks/useResolvedRequired';
import {
colorVars,
durationVars,
easeVars,
fontWeightVars,
radiusVars,
sizeVars,
spacingVars,
typographyVars,
typeScaleVars,
} from '../theme/tokens.stylex';
import {isRenderable, mergeProps} from '../utils';
import {composeEventHandlers} from '../utils/composeEventHandlers';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import type {SizeValue} from '../utils/types';
import {themeProps} from '../utils/themeProps';
const styles = stylex.create({
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']})`,
},
lineHeight: typeScaleVars['--text-label-leading'],
color: colorVars['--color-text-primary'],
cursor: 'pointer',
},
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: 'pointer',
outline: 'none',
borderRadius: radiusVars['--radius-element'],
},
triggerText: {
flexGrow: 1,
minWidth: 0,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
textAlign: 'start',
},
placeholder: {
color: colorVars['--color-text-secondary'],
},
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',
},
},
// Only what Icon does not already provide: `sm` gives the 16px box and
// `color="secondary"` the color, 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
// `complex-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.
triggerIconRotation: {
transitionProperty: 'transform',
transitionDuration: durationVars['--duration-fast'],
transitionTimingFunction: easeVars['--ease-standard'],
transformOrigin: 'center',
},
triggerIconOpen: {
transform: 'rotate(180deg)',
},
popover: {
minWidth: 'anchor-size(width)',
},
content: {
boxSizing: 'border-box',
maxHeight: 'min(480px, calc(100vh - 32px))',
overflow: 'auto',
padding: spacingVars['--spacing-3'],
},
sm: {
height: sizeVars['--size-element-sm'],
},
md: {
height: sizeVars['--size-element-md'],
},
lg: {
height: sizeVars['--size-element-lg'],
},
disabled: {
cursor: 'not-allowed',
},
});
export type ComplexSelectorVariant = 'input' | 'ghost';
export type ComplexSelectorSize = 'sm' | 'md' | 'lg';
export interface ComplexSelectorRenderState {
/** Whether the selector surface is open. */
isOpen: boolean;
/** Whether changeAction/isLoading is pending. */
isBusy: boolean;
/** ID of the trigger button. */
triggerId: string;
/** ID of the popup content container. */
contentId: string;
}
/**
* Imperative control surface for ComplexSelector, accessed via the `handleRef`
* prop. Methods drive the same popover machinery as the built-in trigger, so
* they respect focus restoration, light dismiss, and Escape. Prefer these
* callbacks over mirroring open state in the parent — the selector owns its
* visibility, and imperative calls avoid the focus-management pitfalls of
* syncing an external `isOpen` prop.
*/
export interface ComplexSelectorHandle {
/** Open the selector surface. No-op when disabled or already open. */
open(): void;
/** Close the selector surface. Restores focus to the trigger. */
close(): void;
/** Toggle the selector surface open or closed. */
toggle(): void;
/** Whether the selector surface is currently open. Reads live state. */
isOpen(): boolean;
}
export interface ComplexSelectorStatus {
type: 'warning' | 'error' | 'success';
message?: string;
}
export interface ComplexSelectorProps<Value> extends Omit<
BaseProps<HTMLDivElement>,
'children' | 'onChange'
> {
/** Label text for accessibility and the field label. */
label: string;
/** Current controlled value. */
value: Value;
/** Called when custom content commits a new value. */
onChange?: (value: Value) => void;
/** Optional async action after onChange; drives optimistic UI. */
changeAction?: (value: Value) => void | Promise<void>;
/** Custom selector surface content rendered inside a dialog popover. */
children: (
value: Value,
onChange: (value: Value) => void,
close: () => void,
state: ComplexSelectorRenderState,
) => ReactNode;
/** Label/content shown in the closed trigger. */
triggerLabel?: ReactNode;
/** Placeholder shown when triggerLabel is omitted. */
placeholder?: ReactNode;
/** Whether to visually hide the field label. */
isLabelHidden?: boolean;
/** Helper text displayed below the label. */
description?: string;
/** Marks the field optional. */
isOptional?: boolean;
/** Marks the field required. */
isRequired?: boolean;
/** Disables the selector. */
isDisabled?: boolean;
/** Shows loading state on the trigger. */
isLoading?: boolean;
/** Validation status. */
status?: ComplexSelectorStatus;
/** Status placement. */
statusVariant?: FieldStatusVariant;
/** Tooltip text displayed next to the label. */
labelTooltip?: string;
/** Trigger and field size. */
size?: ComplexSelectorSize;
/** Visual trigger style. Ghost matches toolbar buttons. */
variant?: ComplexSelectorVariant;
/** Icon displayed at the start of the trigger. */
startIcon?: ReactNode | IconType;
/**
* Whether to show the chevron at the end of the trigger. Set false when the
* trigger's own content already reads as "this opens something" — an
* affordance the product supplies itself, for instance.
*
* The chevron is decorative (`aria-hidden`) and sits outside the trigger
* button, so dropping it leaves the accessible name, the focus order, and
* the keyboard behaviour untouched.
*
* @default true
*/
hasChevron?: boolean;
/** Width of the field. */
width?: SizeValue;
/** Popup placement. */
placement?: LayerPlacement;
/** Popup alignment along the placement axis. */
alignment?: LayerAlignment;
/**
* Imperative handle for programmatic open/close control. Exposes open,
* close, toggle, and the isOpen query. Use this instead of mirroring open
* state in the parent — the selector owns its visibility.
*/
handleRef?: React.Ref<ComplexSelectorHandle>;
/** StyleX styles for the popup content container. */
contentXstyle?: StyleXStyles;
/** Test ID for the trigger container. */
'data-testid'?: string;
}
/**
* A selector shell for rich, custom selection surfaces.
*
* ComplexSelector owns the field, trigger, popover, focus restore, and async
* change action flow. Consumers provide the dialog content as a render function,
* using the supplied `value`, `onChange`, and `close` helpers to compose the
* right accessible structure for the custom selector.
*
* @example
* ```
* <ComplexSelector
* label="Fruit"
* value={value}
* onChange={setValue}
* triggerLabel={`${value.fruit} ${value.ripeness}`}>
* {(value, onChange, close) => (
* <FruitGrid
* value={value}
* onChange={nextValue => {
* onChange(nextValue);
* close();
* }}
* />
* )}
* </ComplexSelector>
* ```
*/
export function ComplexSelector<Value>({
label,
value,
onChange,
changeAction,
children,
triggerLabel,
placeholder: placeholderFromProps,
isLabelHidden = false,
description,
isOptional = false,
isRequired = false,
isDisabled = false,
isLoading = false,
status,
statusVariant = 'attached',
labelTooltip,
size = 'md',
variant = 'input',
startIcon,
hasChevron = true,
width,
placement = 'below',
alignment = 'start',
handleRef,
contentXstyle,
xstyle,
className,
style,
'data-testid': testId,
onClick: onClickProp,
...props
}: ComplexSelectorProps<Value>) {
const t = useTranslator();
const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});
const placeholder = placeholderFromProps ?? t('@astryx.selector.placeholder');
const effectiveStatusVariant =
variant === 'ghost' && statusVariant === 'attached'
? 'detached'
: statusVariant;
const triggerId = useId();
const labelId = useId();
const contentId = useId();
const descriptionId = useId();
const statusMessageId = useId();
const ariaDescribedBy =
[
description ? descriptionId : null,
status?.message ? statusMessageId : null,
]
.filter((id): id is string => id != null)
.join(' ') || undefined;
const triggerRef = useRef<HTMLButtonElement>(null);
const lastHideTimeRef = useRef(0);
const [isPending, startTransition] = useTransition();
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
const isBusy = isLoading || isPending;
const handlePopoverHide = useCallback(() => {
lastHideTimeRef.current = Date.now();
triggerRef.current?.focus();
}, []);
const popover = usePopover({
dialogLabel: label,
hasCloseButton: false,
hasAutoFocus: true,
surfaceTarget: 'complex-selector-popup',
onHide: handlePopoverHide,
});
const isOpen = popover.isOpen;
const handleTriggerClick = useCallback(() => {
if (isDisabled || Date.now() - lastHideTimeRef.current < 50) {
return;
}
if (popover.isOpen) {
popover.hide();
} else {
popover.show();
}
}, [isDisabled, popover]);
const close = useCallback(() => {
popover.hide();
}, [popover]);
useImperativeHandle(
handleRef,
() => ({
open: () => {
if (!isDisabled) {
popover.show();
}
},
close: () => popover.hide(),
toggle: () => {
if (isDisabled) {
return;
}
if (popover.isOpen) {
popover.hide();
} else {
popover.show();
}
},
isOpen: () => popover.isOpen,
}),
[isDisabled, popover],
);
const commitValue = useCallback(
(nextValue: Value) => {
onChange?.(nextValue);
if (changeAction) {
startTransition(async () => {
setOptimisticValue(nextValue);
await changeAction(nextValue);
});
}
},
[changeAction, onChange, setOptimisticValue, startTransition],
);
const triggerContent = triggerLabel ?? placeholder;
const startIconSlot = renderIconSlot(startIcon, {
size: 'sm',
color: 'secondary',
});
const content = (
<div id={contentId} {...stylex.props(styles.content, contentXstyle)}>
{children(optimisticValue, commitValue, close, {
isOpen,
isBusy,
triggerId,
contentId,
})}
</div>
);
const selectorContent = (
<>
<div
ref={popover.triggerRef}
data-testid={testId}
{...props}
onClick={composeEventHandlers(onClickProp, handleTriggerClick)}
{...mergeProps(
themeProps('complex-selector', {
variant,
size,
status: status?.type ?? null,
}),
stylex.props(
inputWrapperStyles.base,
styles.triggerContainer,
styles[size],
// The ring belongs to the wrapper (the focusable `<button>` sits
// inside it), but it must still be a KEYBOARD ring: `:focus-within`
// matched a mouse click on the trigger and drew the outline for
// pointer users too. `focusWithin` here is `:has(:focus-visible)`.
focusOutlineStyles.focusWithin,
variant === 'ghost' && styles.triggerGhost,
isDisabled && inputWrapperStyles.disabled,
variant === 'ghost' && isDisabled && styles.triggerGhostDisabled,
isDisabled && styles.disabled,
triggerLabel == null && styles.placeholder,
xstyle,
),
className,
style,
)}>
{isRenderable(startIconSlot) && startIconSlot}
<button
ref={triggerRef}
id={triggerId}
type="button"
aria-haspopup="dialog"
aria-expanded={isOpen}
aria-controls={contentId}
aria-describedby={ariaDescribedBy}
aria-labelledby={labelId}
aria-required={isEffectivelyRequired ? 'true' : undefined}
aria-invalid={status?.type === 'error' ? 'true' : undefined}
aria-busy={isBusy || undefined}
disabled={isDisabled}
onKeyDown={event => {
if (event.key === 'ArrowDown' && !isOpen && !isDisabled) {
event.preventDefault();
popover.show();
}
}}
{...stylex.props(styles.trigger)}>
<span {...stylex.props(styles.triggerText)}>{triggerContent}</span>
</button>
{isBusy && <Spinner size="sm" />}
{hasChevron && (
<Icon
icon="chevronDown"
size="sm"
color="secondary"
// No wrapper: Icon's own span already provides the 16px box (`sm`)
// and the secondary icon color the wrapper used to set, so the glyph
// IS the trigger's icon element — one node carrying the box, the
// color, the rotation, and the theme target.
xstyle={[
styles.triggerIcon,
styles.triggerIconRotation,
isOpen && styles.triggerIconOpen,
]}
{...themeProps('complex-selector-indicator-icon', {
state: isOpen ? 'expanded' : 'collapsed',
})}
/>
)}
</div>
{popover.render(content, {
placement,
alignment,
offset: spacingVars['--spacing-1'],
xstyle: [styles.popover, layerAnimations[placement]],
})}
</>
);
return (
<Field
label={label}
isLabelHidden={isLabelHidden}
description={description}
inputID={triggerId}
descriptionID={description ? descriptionId : undefined}
labelID={labelId}
isOptional={isOptional}
isRequired={isRequired}
isDisabled={isDisabled}
status={
status
? {
type: status.type,
message: status.message,
messageID: status.message ? statusMessageId : undefined,
}
: undefined
}
statusVariant={effectiveStatusVariant}
labelTooltip={labelTooltip}
width={width}>
{selectorContent}
</Field>
);
}
ComplexSelector.displayName = 'ComplexSelector';