@octanejs/radix 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -0
  3. package/package.json +45 -0
  4. package/src/AccessibleIcon.ts +26 -0
  5. package/src/Accordion.ts +282 -0
  6. package/src/AlertDialog.ts +110 -0
  7. package/src/Arrow.ts +21 -0
  8. package/src/AspectRatio.ts +34 -0
  9. package/src/Avatar.ts +152 -0
  10. package/src/Checkbox.ts +325 -0
  11. package/src/Collapsible.ts +170 -0
  12. package/src/ContextMenu.ts +303 -0
  13. package/src/Dialog.ts +308 -0
  14. package/src/DismissableLayer.ts +413 -0
  15. package/src/DropdownMenu.ts +275 -0
  16. package/src/FocusScope.ts +266 -0
  17. package/src/Form.ts +621 -0
  18. package/src/HoverCard.ts +318 -0
  19. package/src/Label.ts +25 -0
  20. package/src/Menu.ts +1057 -0
  21. package/src/Menubar.ts +572 -0
  22. package/src/NavigationMenu.ts +1236 -0
  23. package/src/OneTimePasswordField.ts +977 -0
  24. package/src/PasswordToggleField.ts +495 -0
  25. package/src/Popover.ts +354 -0
  26. package/src/Popper.ts +401 -0
  27. package/src/Portal.ts +19 -0
  28. package/src/Presence.ts +225 -0
  29. package/src/Primitive.ts +53 -0
  30. package/src/Progress.ts +92 -0
  31. package/src/Radio.ts +262 -0
  32. package/src/RadioGroup.ts +212 -0
  33. package/src/RovingFocusGroup.ts +259 -0
  34. package/src/ScrollArea.ts +966 -0
  35. package/src/Select.ts +1901 -0
  36. package/src/Separator.ts +36 -0
  37. package/src/Slider.ts +745 -0
  38. package/src/Slot.ts +105 -0
  39. package/src/Switch.ts +278 -0
  40. package/src/Tabs.ts +177 -0
  41. package/src/Toast.ts +923 -0
  42. package/src/Toggle.ts +31 -0
  43. package/src/ToggleGroup.ts +157 -0
  44. package/src/Toolbar.ts +130 -0
  45. package/src/Tooltip.ts +669 -0
  46. package/src/VisuallyHidden.ts +29 -0
  47. package/src/collection.ts +97 -0
  48. package/src/compose-event-handlers.ts +15 -0
  49. package/src/compose-refs.ts +53 -0
  50. package/src/context.ts +109 -0
  51. package/src/direction.ts +19 -0
  52. package/src/focus-guards.ts +56 -0
  53. package/src/index.ts +54 -0
  54. package/src/internal.ts +42 -0
  55. package/src/scroll-lock.ts +57 -0
  56. package/src/use-callback-ref.ts +28 -0
  57. package/src/use-effect-event.ts +36 -0
  58. package/src/use-is-hydrated.ts +23 -0
  59. package/src/use-previous.ts +28 -0
  60. package/src/use-size.ts +57 -0
  61. package/src/useControllableState.ts +78 -0
  62. package/src/useId.ts +15 -0
package/src/Select.ts ADDED
@@ -0,0 +1,1901 @@
1
+ // Ported from @radix-ui/react-select (source:
2
+ // .radix-primitives/packages/react/select/src/select.tsx). A `role=combobox` trigger
3
+ // opening a popper- or item-aligned `role=listbox` content over a Collection of items,
4
+ // composing FocusScope + DismissableLayer + focus guards, with typeahead on both the
5
+ // closed trigger and the open content, ItemText portaling of the selected label into
6
+ // the trigger's value node, a detached-fragment mount that keeps items rendered while
7
+ // closed (so labels/native options stay fresh), and — inside a form — a visually hidden
8
+ // native `<select>` "bubble input" so native form machinery (FormData, validation,
9
+ // autofill, change listeners) reflects the state.
10
+ //
11
+ // octane adaptations (documented):
12
+ // - React forwardRef → `ref` destructured from props and composed via useComposedRefs.
13
+ // - `ReactDOM.createPortal` → octane `createPortal`-as-a-value, used both for the
14
+ // detached `DocumentFragment` (SelectContentFragment) and for portaling the selected
15
+ // ItemText into the trigger's value node.
16
+ // - Radix's `RemoveScroll` wrapper (`createSlot('SelectContent.RemoveScroll')`) is
17
+ // replaced by the useScrollLock hook (see scroll-lock.ts); no wrapper Slot needed.
18
+ // - `SelectValue`'s `<React.Fragment key={placeholder|value}>` remount trick is dropped:
19
+ // octane's value-hole reconciliation replaces the placeholder/value content directly.
20
+ // - The bubble `<select>`: React's `defaultValue={selectValue}` + `key={nativeSelectKey}`
21
+ // (re-built so the default option associates) has no octane equivalent (octane has no
22
+ // controlled/default-value model — inputs are native). Instead the select's `value` is
23
+ // synced imperatively: a silent property write whenever the rendered option set changes
24
+ // (mount/late option registration), while actual value CHANGES go through the native
25
+ // `value` setter + a dispatched bubbling `change` event (as in the source) so octane
26
+ // `<form onChange>` observes them. React's synthetic `onChange` on the select is the
27
+ // native `change` event (a `<select>` is not a text input, so no `onInput` remap).
28
+ // - jsdom-environment guards (same class as use-size.ts's ResizeObserver guard; no
29
+ // behavior change in browsers): `hasPointerCapture`/`releasePointerCapture` and
30
+ // `scrollIntoView` are called only when they exist.
31
+ // - Viewport's expand-on-scroll uses the `onScroll` prop directly (octane's runtime
32
+ // capture-delegates the non-bubbling `scroll` event per-element, React 17+
33
+ // semantics). Historical note: an addEventListener workaround predated that runtime
34
+ // from the root and native `scroll` doesn't bubble (nor is `scroll` in the runtime's
35
+ // fix; the Scroll{Up,Down}Button effects keep addEventListener (source parity). Same pattern
36
+ // as the Scroll{Up,Down}Button effects and ScrollArea.
37
+ // - Fragment-position siblings (Root's children+bubble input, ItemText's span+value
38
+ // portal, the bubble select's placeholder option) are emitted as fully-keyed arrays
39
+ // (keyed passthrough `ValueFragment` wrappers / conditional omission instead of null
40
+ // holes) so octane's de-opt list renderer doesn't emit its missing-key warning.
41
+ // - Dev-only warning surfaces are not ported (repo policy: functional outcomes only).
42
+ import {
43
+ createElement,
44
+ createPortal,
45
+ useCallback,
46
+ useEffect,
47
+ useLayoutEffect,
48
+ useMemo,
49
+ useRef,
50
+ useState,
51
+ } from 'octane';
52
+ import { hideOthers } from 'aria-hidden';
53
+
54
+ import { createCollection } from './collection';
55
+ import { composeEventHandlers } from './compose-event-handlers';
56
+ import { useComposedRefs } from './compose-refs';
57
+ import { createContextScope } from './context';
58
+ import { useDirection } from './direction';
59
+ import { DismissableLayer } from './DismissableLayer';
60
+ import { FocusScope } from './FocusScope';
61
+ import { useFocusGuards } from './focus-guards';
62
+ import { S, splitSlot, subSlot } from './internal';
63
+ import * as PopperPrimitive from './Popper';
64
+ import { createPopperScope } from './Popper';
65
+ import { Portal as PortalPrimitive } from './Portal';
66
+ import { Presence } from './Presence';
67
+ import { Primitive } from './Primitive';
68
+ import { useScrollLock } from './scroll-lock';
69
+ import { useCallbackRef } from './use-callback-ref';
70
+ import { usePrevious } from './use-previous';
71
+ import { useControllableState } from './useControllableState';
72
+ import { useId } from './useId';
73
+ import { VISUALLY_HIDDEN_STYLES } from './VisuallyHidden';
74
+
75
+ type Direction = 'ltr' | 'rtl';
76
+
77
+ const OPEN_KEYS = [' ', 'Enter', 'ArrowUp', 'ArrowDown'];
78
+ const SELECTION_KEYS = [' ', 'Enter'];
79
+
80
+ /* -------------------------------------------------------------------------------------------------
81
+ * Select
82
+ * -----------------------------------------------------------------------------------------------*/
83
+
84
+ const SELECT_NAME = 'Select';
85
+
86
+ const [Collection, useCollection, createCollectionScope] = createCollection(SELECT_NAME);
87
+
88
+ const [createSelectContext, createSelectScope] = createContextScope(SELECT_NAME, [
89
+ createCollectionScope,
90
+ createPopperScope,
91
+ ]);
92
+ export { createSelectScope };
93
+ const usePopperScope = createPopperScope();
94
+
95
+ interface SelectContextValue {
96
+ trigger: HTMLElement | null;
97
+ onTriggerChange(node: HTMLElement | null): void;
98
+ valueNode: HTMLElement | null;
99
+ onValueNodeChange(node: HTMLElement | null): void;
100
+ valueNodeHasChildren: boolean;
101
+ onValueNodeHasChildrenChange(hasChildren: boolean): void;
102
+ contentId: string;
103
+ value: string | undefined;
104
+ onValueChange(value: string): void;
105
+ open: boolean;
106
+ required?: boolean;
107
+ onOpenChange(open: boolean): void;
108
+ dir: Direction;
109
+ triggerPointerDownPosRef: { current: { x: number; y: number } | null };
110
+ disabled?: boolean;
111
+ name?: string;
112
+ autoComplete?: string;
113
+ form?: string;
114
+ // Native `<option>` element descriptors registered by mounted ItemTexts.
115
+ nativeOptions: Set<any>;
116
+ nativeSelectKey: string;
117
+ isFormControl: boolean;
118
+ }
119
+
120
+ const [SelectProviderImpl, useSelectContext] = createSelectContext<SelectContextValue>(SELECT_NAME);
121
+
122
+ interface SelectNativeOptionsContextValue {
123
+ onNativeOptionAdd(option: any): void;
124
+ onNativeOptionRemove(option: any): void;
125
+ }
126
+ const [SelectNativeOptionsProvider, useSelectNativeOptionsContext] =
127
+ createSelectContext<SelectNativeOptionsContextValue>(SELECT_NAME);
128
+
129
+ /* -------------------------------------------------------------------------------------------------
130
+ * SelectProvider
131
+ * -----------------------------------------------------------------------------------------------*/
132
+
133
+ const PROVIDER_NAME = 'SelectProvider';
134
+
135
+ export function Provider(props: any): any {
136
+ const slot = S('Select.Provider');
137
+ const {
138
+ __scopeSelect,
139
+ children,
140
+ open: openProp,
141
+ defaultOpen,
142
+ onOpenChange,
143
+ value: valueProp,
144
+ defaultValue,
145
+ onValueChange,
146
+ dir,
147
+ name,
148
+ autoComplete,
149
+ disabled,
150
+ required,
151
+ form,
152
+ // internal render prop used by `Select` (Root) to compose its default parts
153
+ internal_do_not_use_render,
154
+ } = props ?? {};
155
+ const popperScope = usePopperScope(__scopeSelect, subSlot(slot, 'popper'));
156
+ const [trigger, setTrigger] = useState<HTMLElement | null>(null, subSlot(slot, 'trigger'));
157
+ const [valueNode, setValueNode] = useState<HTMLElement | null>(null, subSlot(slot, 'valueNode'));
158
+ const [valueNodeHasChildren, setValueNodeHasChildren] = useState(
159
+ false,
160
+ subSlot(slot, 'hasChildren'),
161
+ );
162
+ const direction = useDirection(dir);
163
+ const [open, setOpen] = useControllableState<boolean>(
164
+ { prop: openProp, defaultProp: defaultOpen ?? false, onChange: onOpenChange },
165
+ subSlot(slot, 'open'),
166
+ );
167
+ const [value, setValue] = useControllableState<string | undefined>(
168
+ { prop: valueProp, defaultProp: defaultValue, onChange: onValueChange },
169
+ subSlot(slot, 'value'),
170
+ );
171
+ const triggerPointerDownPosRef = useRef<{ x: number; y: number } | null>(
172
+ null,
173
+ subSlot(slot, 'pointerPos'),
174
+ );
175
+
176
+ // We set this to true by default so that events bubble to forms without JS (SSR)
177
+ const isFormControl = trigger ? !!form || !!trigger.closest('form') : true;
178
+ const [nativeOptionsSet, setNativeOptionsSet] = useState<Set<any>>(
179
+ new Set(),
180
+ subSlot(slot, 'options'),
181
+ );
182
+ const contentId = useId(subSlot(slot, 'contentId'));
183
+
184
+ // The native `select` only associates the correct default value if the corresponding
185
+ // `option` is rendered as a child **at the same time** as itself. Because it might take
186
+ // a few renders for our items to gather the information to build the native `option`(s),
187
+ // this key tracks the option set (the bubble select re-syncs its value off it).
188
+ const nativeSelectKey = Array.from(nativeOptionsSet)
189
+ .map((option: any) => option?.props?.value)
190
+ .join(';');
191
+
192
+ const handleNativeOptionAdd = useCallback(
193
+ (option: any) => {
194
+ setNativeOptionsSet((prev: Set<any>) => new Set(prev).add(option));
195
+ },
196
+ [],
197
+ subSlot(slot, 'optAdd'),
198
+ );
199
+
200
+ const handleNativeOptionRemove = useCallback(
201
+ (option: any) => {
202
+ setNativeOptionsSet((prev: Set<any>) => {
203
+ const optionsSet = new Set(prev);
204
+ optionsSet.delete(option);
205
+ return optionsSet;
206
+ });
207
+ },
208
+ [],
209
+ subSlot(slot, 'optRemove'),
210
+ );
211
+
212
+ const context: SelectContextValue = {
213
+ required,
214
+ trigger,
215
+ onTriggerChange: setTrigger,
216
+ valueNode,
217
+ onValueNodeChange: setValueNode,
218
+ valueNodeHasChildren,
219
+ onValueNodeHasChildrenChange: setValueNodeHasChildren,
220
+ contentId,
221
+ value,
222
+ onValueChange: setValue as (value: string) => void,
223
+ open,
224
+ onOpenChange: setOpen,
225
+ dir: direction,
226
+ triggerPointerDownPosRef,
227
+ disabled,
228
+ name,
229
+ autoComplete,
230
+ form,
231
+ nativeOptions: nativeOptionsSet,
232
+ nativeSelectKey,
233
+ isFormControl,
234
+ };
235
+
236
+ return createElement(PopperPrimitive.Root, {
237
+ ...popperScope,
238
+ children: createElement(SelectProviderImpl, {
239
+ scope: __scopeSelect,
240
+ ...context,
241
+ children: createElement(Collection.Provider, {
242
+ scope: __scopeSelect,
243
+ children: createElement(SelectNativeOptionsProvider, {
244
+ scope: __scopeSelect,
245
+ onNativeOptionAdd: handleNativeOptionAdd,
246
+ onNativeOptionRemove: handleNativeOptionRemove,
247
+ children: isFunction(internal_do_not_use_render)
248
+ ? internal_do_not_use_render(context)
249
+ : children,
250
+ }),
251
+ }),
252
+ }),
253
+ });
254
+ }
255
+
256
+ /* -------------------------------------------------------------------------------------------------
257
+ * Select (Root)
258
+ * -----------------------------------------------------------------------------------------------*/
259
+
260
+ export function Root(props: any): any {
261
+ const { __scopeSelect, children, ...providerProps } = props ?? {};
262
+ return createElement(Provider, {
263
+ __scopeSelect,
264
+ ...providerProps,
265
+ // Every array entry is keyed (unkeyed/null entries would trip octane's one-time
266
+ // missing-key warning in the de-opt list renderer); `children` rides through a
267
+ // keyed passthrough component, and the bubble input is simply omitted when the
268
+ // select isn't a form control — these are fixed-position siblings.
269
+ internal_do_not_use_render: (context: SelectContextValue) => {
270
+ const nodes: any[] = [createElement(ValueFragment, { key: 'children', children })];
271
+ if (context.isFormControl) {
272
+ nodes.push(createElement(BubbleInput, { key: 'bubble', __scopeSelect }));
273
+ }
274
+ return nodes;
275
+ },
276
+ });
277
+ }
278
+
279
+ /* -------------------------------------------------------------------------------------------------
280
+ * SelectTrigger
281
+ * -----------------------------------------------------------------------------------------------*/
282
+
283
+ const TRIGGER_NAME = 'SelectTrigger';
284
+
285
+ export function Trigger(props: any): any {
286
+ const slot = S('Select.Trigger');
287
+ const { __scopeSelect, disabled = false, ref: forwardedRef, ...triggerProps } = props ?? {};
288
+ const popperScope = usePopperScope(__scopeSelect, subSlot(slot, 'popper'));
289
+ const context = useSelectContext(TRIGGER_NAME, __scopeSelect);
290
+ const isDisabled = context.disabled || disabled;
291
+ const composedRefs = useComposedRefs(
292
+ forwardedRef,
293
+ context.onTriggerChange,
294
+ subSlot(slot, 'refs'),
295
+ );
296
+ const getItems = useCollection(__scopeSelect, subSlot(slot, 'items'));
297
+ const pointerTypeRef = useRef<string>('touch', subSlot(slot, 'pointerType'));
298
+
299
+ const [searchRef, handleTypeaheadSearch, resetTypeahead] = useTypeaheadSearch(
300
+ (search: string) => {
301
+ const enabledItems = getItems().filter((item: any) => !item.disabled);
302
+ const currentItem = enabledItems.find((item: any) => item.value === context.value);
303
+ const nextItem = findNextItem(enabledItems, search, currentItem);
304
+ if (nextItem !== undefined) {
305
+ context.onValueChange(nextItem.value);
306
+ }
307
+ },
308
+ subSlot(slot, 'typeahead'),
309
+ );
310
+
311
+ const handleOpen = (pointerEvent?: MouseEvent | PointerEvent): void => {
312
+ if (!isDisabled) {
313
+ context.onOpenChange(true);
314
+ // reset typeahead when we open
315
+ resetTypeahead();
316
+ }
317
+
318
+ if (pointerEvent) {
319
+ context.triggerPointerDownPosRef.current = {
320
+ x: Math.round(pointerEvent.pageX),
321
+ y: Math.round(pointerEvent.pageY),
322
+ };
323
+ }
324
+ };
325
+
326
+ return createElement(PopperPrimitive.Anchor, {
327
+ asChild: true,
328
+ ...popperScope,
329
+ children: createElement(Primitive.button, {
330
+ type: 'button',
331
+ role: 'combobox',
332
+ 'aria-controls': context.open ? context.contentId : undefined,
333
+ 'aria-expanded': context.open,
334
+ 'aria-required': context.required,
335
+ 'aria-autocomplete': 'none',
336
+ dir: context.dir,
337
+ 'data-state': context.open ? 'open' : 'closed',
338
+ disabled: isDisabled,
339
+ 'data-disabled': isDisabled ? '' : undefined,
340
+ 'data-placeholder': shouldShowPlaceholder(context.value) ? '' : undefined,
341
+ ...triggerProps,
342
+ ref: composedRefs,
343
+ // Enable compatibility with native label or custom `Label` "click" for Safari:
344
+ onClick: composeEventHandlers(triggerProps.onClick, (event: MouseEvent) => {
345
+ // Whilst browsers generally have no issue focusing the trigger when clicking
346
+ // on a label, Safari seems to struggle with the fact that there's no `onClick`.
347
+ // We force `focus` in this case. Note: this doesn't create any other side-effect
348
+ // because we are preventing default in `onPointerDown` so effectively
349
+ // this only runs for a label "click"
350
+ (event.currentTarget as HTMLElement).focus();
351
+
352
+ // Open on click when using a touch or pen device
353
+ if (pointerTypeRef.current !== 'mouse') {
354
+ handleOpen(event);
355
+ }
356
+ }),
357
+ onPointerDown: composeEventHandlers(triggerProps.onPointerDown, (event: PointerEvent) => {
358
+ pointerTypeRef.current = event.pointerType;
359
+
360
+ // prevent implicit pointer capture
361
+ // https://www.w3.org/TR/pointerevents3/#implicit-pointer-capture
362
+ // (guarded: jsdom lacks the pointer-capture APIs)
363
+ const target = event.target as HTMLElement;
364
+ if (
365
+ typeof target.hasPointerCapture === 'function' &&
366
+ target.hasPointerCapture(event.pointerId)
367
+ ) {
368
+ target.releasePointerCapture(event.pointerId);
369
+ }
370
+
371
+ // only call handler if it's the left button (mousedown gets triggered by all mouse buttons)
372
+ // but not when the control key is pressed (avoiding MacOS right click); also not for touch
373
+ // devices because that would open the menu on scroll. (pen devices behave as touch on iOS).
374
+ if (event.button === 0 && event.ctrlKey === false && event.pointerType === 'mouse') {
375
+ handleOpen(event);
376
+ // prevent trigger from stealing focus from the active item after opening.
377
+ event.preventDefault();
378
+ }
379
+ }),
380
+ onKeyDown: composeEventHandlers(triggerProps.onKeyDown, (event: KeyboardEvent) => {
381
+ const isTypingAhead = searchRef.current !== '';
382
+ const isModifierKey = event.ctrlKey || event.altKey || event.metaKey;
383
+ if (!isModifierKey && event.key.length === 1) handleTypeaheadSearch(event.key);
384
+ if (isTypingAhead && event.key === ' ') return;
385
+ if (OPEN_KEYS.includes(event.key)) {
386
+ handleOpen();
387
+ event.preventDefault();
388
+ }
389
+ }),
390
+ }),
391
+ });
392
+ }
393
+
394
+ /* -------------------------------------------------------------------------------------------------
395
+ * SelectValue
396
+ * -----------------------------------------------------------------------------------------------*/
397
+
398
+ const VALUE_NAME = 'SelectValue';
399
+
400
+ export function Value(props: any): any {
401
+ const slot = S('Select.Value');
402
+ // We ignore `className` and `style` as this part shouldn't be styled.
403
+ const {
404
+ __scopeSelect,
405
+ className,
406
+ style,
407
+ children,
408
+ placeholder = '',
409
+ ref: forwardedRef,
410
+ ...valueProps
411
+ } = props ?? {};
412
+ void className;
413
+ void style;
414
+ const context = useSelectContext(VALUE_NAME, __scopeSelect);
415
+ const { onValueNodeHasChildrenChange } = context;
416
+ const hasChildren = children !== undefined;
417
+ const composedRefs = useComposedRefs(
418
+ forwardedRef,
419
+ context.onValueNodeChange,
420
+ subSlot(slot, 'refs'),
421
+ );
422
+
423
+ useLayoutEffect(
424
+ () => {
425
+ onValueNodeHasChildrenChange(hasChildren);
426
+ },
427
+ [onValueNodeHasChildrenChange, hasChildren],
428
+ subSlot(slot, 'e:hasChildren'),
429
+ );
430
+
431
+ const showPlaceholder = shouldShowPlaceholder(context.value);
432
+
433
+ return createElement(Primitive.span, {
434
+ ...valueProps,
435
+ asChild: showPlaceholder ? false : valueProps.asChild,
436
+ ref: composedRefs,
437
+ // we don't want events from the portalled `SelectValue` children to bubble
438
+ // through the item they came from
439
+ style: { pointerEvents: 'none' },
440
+ // The source wraps in `<React.Fragment key={placeholder|value}>`. The component
441
+ // wrapper here doubles as an octane adaptation: it forces the span's children
442
+ // through the BLOCK (marker-delimited) render path, so the ItemText content
443
+ // portal'd into this span from elsewhere isn't swept by the raw host
444
+ // reconciler (see suspected-bug note in the port summary).
445
+ children: createElement(ValueFragment, {
446
+ key: showPlaceholder ? 'placeholder' : 'value',
447
+ children: showPlaceholder ? placeholder : children,
448
+ }),
449
+ });
450
+ }
451
+
452
+ function ValueFragment(props: any): any {
453
+ return props?.children ?? null;
454
+ }
455
+
456
+ /* -------------------------------------------------------------------------------------------------
457
+ * SelectIcon
458
+ * -----------------------------------------------------------------------------------------------*/
459
+
460
+ export function Icon(props: any): any {
461
+ const { __scopeSelect, children, ...iconProps } = props ?? {};
462
+ return createElement(Primitive.span, {
463
+ 'aria-hidden': true,
464
+ ...iconProps,
465
+ children: children || '▼',
466
+ });
467
+ }
468
+
469
+ /* -------------------------------------------------------------------------------------------------
470
+ * SelectPortal
471
+ * -----------------------------------------------------------------------------------------------*/
472
+
473
+ const PORTAL_NAME = 'SelectPortal';
474
+
475
+ interface PortalContextValue {
476
+ forceMount?: true;
477
+ }
478
+ const [PortalProvider, usePortalContext] = createSelectContext<PortalContextValue>(PORTAL_NAME, {
479
+ forceMount: undefined,
480
+ });
481
+
482
+ /**
483
+ * octane children convention: pass enumerable children at a prop/value position
484
+ * (`children={[<Content/>]}`); a function child is portal'd as a single unit.
485
+ */
486
+ export function Portal(props: any): any {
487
+ const { __scopeSelect, forceMount, children, ...portalProps } = props ?? {};
488
+ return createElement(PortalProvider, {
489
+ scope: __scopeSelect,
490
+ forceMount,
491
+ children: createElement(PortalPrimitive, {
492
+ asChild: typeof children !== 'function',
493
+ ...portalProps,
494
+ children,
495
+ }),
496
+ });
497
+ }
498
+
499
+ /* -------------------------------------------------------------------------------------------------
500
+ * SelectContent
501
+ * -----------------------------------------------------------------------------------------------*/
502
+
503
+ const CONTENT_NAME = 'SelectContent';
504
+
505
+ export function Content(props: any): any {
506
+ const slot = S('Select.Content');
507
+ const portalContext = usePortalContext(CONTENT_NAME, props?.__scopeSelect);
508
+ const { forceMount = portalContext.forceMount, ref: forwardedRef, ...contentProps } = props ?? {};
509
+ const context = useSelectContext(CONTENT_NAME, props?.__scopeSelect);
510
+ const [fragment, setFragment] = useState<DocumentFragment | undefined>(
511
+ undefined,
512
+ subSlot(slot, 'fragment'),
513
+ );
514
+
515
+ // setting the fragment in `useLayoutEffect` as `DocumentFragment` doesn't exist on the server
516
+ useLayoutEffect(
517
+ () => {
518
+ setFragment(new DocumentFragment());
519
+ },
520
+ [],
521
+ subSlot(slot, 'e:fragment'),
522
+ );
523
+
524
+ // The `Select` items collect their data (e.g. to build the native `option`s
525
+ // and to display the selected value) by mounting their children. We keep
526
+ // them mounted in a detached fragment whenever the content isn't present so
527
+ // that this data stays up to date even while the select is closed (or
528
+ // animating out).
529
+ return createElement(Presence, {
530
+ present: forceMount || context.open,
531
+ children: ({ present }: { present: boolean }) =>
532
+ present
533
+ ? createElement(ContentImpl, { ...contentProps, ref: forwardedRef })
534
+ : createElement(ContentFragment, { ...contentProps, fragment }),
535
+ });
536
+ }
537
+
538
+ /* -------------------------------------------------------------------------------------------------
539
+ * SelectContentFragment
540
+ * -----------------------------------------------------------------------------------------------*/
541
+
542
+ function ContentFragment(props: any): any {
543
+ const { __scopeSelect, children, fragment, ref: forwardedRef } = props ?? {};
544
+ if (!fragment) return null;
545
+
546
+ return createPortal(
547
+ createElement(SelectContentProvider, {
548
+ scope: __scopeSelect,
549
+ children: createElement(Collection.Slot, {
550
+ scope: __scopeSelect,
551
+ children: createElement('div', { ref: forwardedRef, children }),
552
+ }),
553
+ }),
554
+ // octane's createPortal target is typed as Element; a detached DocumentFragment
555
+ // works identically (appendChild + EventTarget for delegated listeners).
556
+ fragment as any,
557
+ );
558
+ }
559
+
560
+ /* -------------------------------------------------------------------------------------------------
561
+ * SelectContentImpl
562
+ * -----------------------------------------------------------------------------------------------*/
563
+
564
+ const CONTENT_MARGIN = 10;
565
+
566
+ interface SelectContentContextValue {
567
+ content?: HTMLElement | null;
568
+ viewport?: HTMLElement | null;
569
+ onViewportChange?: (node: HTMLElement | null) => void;
570
+ itemRefCallback?: (node: HTMLElement | null, value: string, disabled: boolean) => void;
571
+ selectedItem?: HTMLElement | null;
572
+ onItemLeave?: () => void;
573
+ itemTextRefCallback?: (node: HTMLElement | null, value: string, disabled: boolean) => void;
574
+ focusSelectedItem?: () => void;
575
+ selectedItemText?: HTMLElement | null;
576
+ position?: 'item-aligned' | 'popper';
577
+ isPositioned?: boolean;
578
+ searchRef?: { current: string };
579
+ }
580
+
581
+ const [SelectContentProvider, useSelectContentContext] =
582
+ createSelectContext<SelectContentContextValue>(CONTENT_NAME);
583
+
584
+ const CONTENT_IMPL_NAME = 'SelectContentImpl';
585
+
586
+ function ContentImpl(props: any): any {
587
+ const slot = S('Select.ContentImpl');
588
+ const {
589
+ __scopeSelect,
590
+ position = 'item-aligned',
591
+ onCloseAutoFocus,
592
+ onEscapeKeyDown,
593
+ onPointerDownOutside,
594
+ //
595
+ // PopperContent props
596
+ side,
597
+ sideOffset,
598
+ align,
599
+ alignOffset,
600
+ arrowPadding,
601
+ collisionBoundary,
602
+ collisionPadding,
603
+ sticky,
604
+ hideWhenDetached,
605
+ avoidCollisions,
606
+ //
607
+ ref: forwardedRef,
608
+ ...contentProps
609
+ } = props;
610
+ const context = useSelectContext(CONTENT_NAME, __scopeSelect);
611
+ const [content, setContent] = useState<HTMLElement | null>(null, subSlot(slot, 'content'));
612
+ const [viewport, setViewport] = useState<HTMLElement | null>(null, subSlot(slot, 'viewport'));
613
+ const composedRefs = useComposedRefs(forwardedRef, setContent, subSlot(slot, 'refs'));
614
+ const [selectedItem, setSelectedItem] = useState<HTMLElement | null>(
615
+ null,
616
+ subSlot(slot, 'selItem'),
617
+ );
618
+ const [selectedItemText, setSelectedItemText] = useState<HTMLElement | null>(
619
+ null,
620
+ subSlot(slot, 'selText'),
621
+ );
622
+ const getItems = useCollection(__scopeSelect, subSlot(slot, 'items'));
623
+ const [isPositioned, setIsPositioned] = useState(false, subSlot(slot, 'positioned'));
624
+ const firstValidItemFoundRef = useRef(false, subSlot(slot, 'firstValid'));
625
+
626
+ // aria-hide everything except the content (better supported equivalent to setting aria-modal)
627
+ useEffect(
628
+ () => {
629
+ if (content) return hideOthers(content);
630
+ },
631
+ [content],
632
+ subSlot(slot, 'e:hide'),
633
+ );
634
+
635
+ // Make sure the whole tree has focus guards as our `Select` may be
636
+ // the last element in the DOM (because of the `Portal`)
637
+ useFocusGuards(subSlot(slot, 'guards'));
638
+
639
+ const focusFirst = useCallback(
640
+ (candidates: Array<HTMLElement | null>) => {
641
+ const [firstItem, ...restItems] = getItems().map((item: any) => item.ref.current);
642
+ const [lastItem] = restItems.slice(-1);
643
+
644
+ const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement;
645
+ for (const candidate of candidates) {
646
+ // if focus is already where we want to go, we don't want to keep going through the candidates
647
+ if (candidate === PREVIOUSLY_FOCUSED_ELEMENT) return;
648
+ // (guarded: jsdom lacks scrollIntoView)
649
+ candidate?.scrollIntoView?.({ block: 'nearest' });
650
+ // viewport might have padding so scroll to its edges when focusing first/last items.
651
+ if (candidate === firstItem && viewport) viewport.scrollTop = 0;
652
+ if (candidate === lastItem && viewport) viewport.scrollTop = viewport.scrollHeight;
653
+ candidate?.focus();
654
+ if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT) return;
655
+ }
656
+ },
657
+ [getItems, viewport],
658
+ subSlot(slot, 'focusFirst'),
659
+ );
660
+
661
+ const focusSelectedItem = useCallback(
662
+ () => focusFirst([selectedItem, content]),
663
+ [focusFirst, selectedItem, content],
664
+ subSlot(slot, 'focusSel'),
665
+ );
666
+
667
+ // Since this is not dependent on layout, we want to ensure this runs at the same time as
668
+ // other effects across components. Hence why we don't call `focusSelectedItem` inside `position`.
669
+ useEffect(
670
+ () => {
671
+ if (isPositioned) {
672
+ focusSelectedItem();
673
+ }
674
+ },
675
+ [isPositioned, focusSelectedItem],
676
+ subSlot(slot, 'e:focus'),
677
+ );
678
+
679
+ // prevent selecting items on `pointerup` in some cases after opening from `pointerdown`
680
+ // and close on `pointerup` outside.
681
+ const { onOpenChange, triggerPointerDownPosRef } = context;
682
+ useEffect(
683
+ () => {
684
+ if (content) {
685
+ let pointerMoveDelta = { x: 0, y: 0 };
686
+
687
+ const handlePointerMove = (event: PointerEvent): void => {
688
+ pointerMoveDelta = {
689
+ x: Math.abs(Math.round(event.pageX) - (triggerPointerDownPosRef.current?.x ?? 0)),
690
+ y: Math.abs(Math.round(event.pageY) - (triggerPointerDownPosRef.current?.y ?? 0)),
691
+ };
692
+ };
693
+ const handlePointerUp = (event: PointerEvent): void => {
694
+ // If the pointer hasn't moved by a certain threshold then we prevent selecting item on `pointerup`.
695
+ if (pointerMoveDelta.x <= 10 && pointerMoveDelta.y <= 10) {
696
+ event.preventDefault();
697
+ } else {
698
+ // otherwise, if the event was outside the content, close.
699
+ // `event.target` is retargeted to the shadow host for this
700
+ // document-level listener, so use `composedPath()` which pierces
701
+ // open shadow roots to reliably detect events inside the content.
702
+ if (!event.composedPath().includes(content)) {
703
+ onOpenChange(false);
704
+ }
705
+ }
706
+ document.removeEventListener('pointermove', handlePointerMove);
707
+ triggerPointerDownPosRef.current = null;
708
+ };
709
+
710
+ if (triggerPointerDownPosRef.current !== null) {
711
+ document.addEventListener('pointermove', handlePointerMove);
712
+ document.addEventListener('pointerup', handlePointerUp, { capture: true, once: true });
713
+ }
714
+
715
+ return () => {
716
+ document.removeEventListener('pointermove', handlePointerMove);
717
+ document.removeEventListener('pointerup', handlePointerUp, { capture: true });
718
+ };
719
+ }
720
+ },
721
+ [content, onOpenChange, triggerPointerDownPosRef],
722
+ subSlot(slot, 'e:pointer'),
723
+ );
724
+
725
+ useEffect(
726
+ () => {
727
+ const close = (): void => onOpenChange(false);
728
+ window.addEventListener('blur', close);
729
+ window.addEventListener('resize', close);
730
+ return () => {
731
+ window.removeEventListener('blur', close);
732
+ window.removeEventListener('resize', close);
733
+ };
734
+ },
735
+ [onOpenChange],
736
+ subSlot(slot, 'e:close'),
737
+ );
738
+
739
+ const [searchRef, handleTypeaheadSearch] = useTypeaheadSearch(
740
+ (search: string) => {
741
+ const enabledItems = getItems().filter((item: any) => !item.disabled);
742
+ const currentItem = enabledItems.find(
743
+ (item: any) => item.ref.current === document.activeElement,
744
+ );
745
+ const nextItem = findNextItem(enabledItems, search, currentItem);
746
+ if (nextItem) {
747
+ // Imperative focus during keydown is risky so we defer it (React #20332).
748
+ setTimeout(() => (nextItem.ref.current as HTMLElement | null)?.focus());
749
+ }
750
+ },
751
+ subSlot(slot, 'typeahead'),
752
+ );
753
+
754
+ const itemRefCallback = useCallback(
755
+ (node: HTMLElement | null, value: string, disabled: boolean) => {
756
+ const isFirstValidItem = !firstValidItemFoundRef.current && !disabled;
757
+ const isSelectedItem = context.value !== undefined && context.value === value;
758
+ if (isSelectedItem || isFirstValidItem) {
759
+ setSelectedItem(node);
760
+ if (isFirstValidItem) firstValidItemFoundRef.current = true;
761
+ }
762
+ },
763
+ [context.value],
764
+ subSlot(slot, 'itemRef'),
765
+ );
766
+ const handleItemLeave = useCallback(
767
+ () => content?.focus(),
768
+ [content],
769
+ subSlot(slot, 'itemLeave'),
770
+ );
771
+ const itemTextRefCallback = useCallback(
772
+ (node: HTMLElement | null, value: string, disabled: boolean) => {
773
+ const isFirstValidItem = !firstValidItemFoundRef.current && !disabled;
774
+ const isSelectedItem = context.value !== undefined && context.value === value;
775
+ if (isSelectedItem || isFirstValidItem) {
776
+ setSelectedItemText(node);
777
+ }
778
+ },
779
+ [context.value],
780
+ subSlot(slot, 'itemTextRef'),
781
+ );
782
+
783
+ // Radix wraps the content in `react-remove-scroll` (as a Slot — no wrapper DOM); the
784
+ // octane equivalent is the useScrollLock hook (see scroll-lock.ts).
785
+ useScrollLock(true, subSlot(slot, 'lock'));
786
+
787
+ const SelectPosition = position === 'popper' ? PopperPosition : ItemAlignedPosition;
788
+
789
+ // Silently ignore props that are not supported by `SelectItemAlignedPosition`
790
+ const popperContentProps =
791
+ SelectPosition === PopperPosition
792
+ ? {
793
+ side,
794
+ sideOffset,
795
+ align,
796
+ alignOffset,
797
+ arrowPadding,
798
+ collisionBoundary,
799
+ collisionPadding,
800
+ sticky,
801
+ hideWhenDetached,
802
+ avoidCollisions,
803
+ }
804
+ : {};
805
+
806
+ return createElement(SelectContentProvider, {
807
+ scope: __scopeSelect,
808
+ content,
809
+ viewport,
810
+ onViewportChange: setViewport,
811
+ itemRefCallback,
812
+ selectedItem,
813
+ onItemLeave: handleItemLeave,
814
+ itemTextRefCallback,
815
+ focusSelectedItem,
816
+ selectedItemText,
817
+ position,
818
+ isPositioned,
819
+ searchRef,
820
+ children: createElement(FocusScope, {
821
+ asChild: true,
822
+ // we make sure we're not trapping once it's been closed
823
+ // (closed !== unmounted when animating out)
824
+ trapped: context.open,
825
+ onMountAutoFocus: (event: Event) => {
826
+ // we prevent open autofocus because we manually focus the selected item
827
+ event.preventDefault();
828
+ },
829
+ onUnmountAutoFocus: composeEventHandlers(onCloseAutoFocus, (event: Event) => {
830
+ context.trigger?.focus({ preventScroll: true } as FocusOptions);
831
+ event.preventDefault();
832
+ }),
833
+ children: createElement(DismissableLayer, {
834
+ asChild: true,
835
+ disableOutsidePointerEvents: true,
836
+ onEscapeKeyDown,
837
+ onPointerDownOutside,
838
+ // When focus is trapped, a focusout event may still happen.
839
+ // We make sure we don't trigger our `onDismiss` in such case.
840
+ onFocusOutside: (event: Event) => event.preventDefault(),
841
+ onDismiss: () => context.onOpenChange(false),
842
+ children: createElement(SelectPosition, {
843
+ role: 'listbox',
844
+ id: context.contentId,
845
+ 'data-state': context.open ? 'open' : 'closed',
846
+ dir: context.dir,
847
+ onContextMenu: (event: Event) => event.preventDefault(),
848
+ ...contentProps,
849
+ ...popperContentProps,
850
+ __scopeSelect,
851
+ onPlaced: () => setIsPositioned(true),
852
+ ref: composedRefs,
853
+ style: {
854
+ // flex layout so we can place the scroll buttons properly
855
+ display: 'flex',
856
+ flexDirection: 'column',
857
+ // reset the outline by default as the content MAY get focused
858
+ outline: 'none',
859
+ ...contentProps.style,
860
+ },
861
+ onKeyDown: composeEventHandlers(contentProps.onKeyDown, (event: KeyboardEvent) => {
862
+ const isModifierKey = event.ctrlKey || event.altKey || event.metaKey;
863
+
864
+ // select should not be navigated using tab key so we prevent it
865
+ if (event.key === 'Tab') event.preventDefault();
866
+
867
+ if (!isModifierKey && event.key.length === 1) handleTypeaheadSearch(event.key);
868
+
869
+ if (['ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) {
870
+ const items = getItems().filter((item: any) => !item.disabled);
871
+ let candidateNodes = items.map((item: any) => item.ref.current!);
872
+
873
+ if (['ArrowUp', 'End'].includes(event.key)) {
874
+ candidateNodes = candidateNodes.slice().reverse();
875
+ }
876
+ if (['ArrowUp', 'ArrowDown'].includes(event.key)) {
877
+ const currentElement = event.target as HTMLElement;
878
+ const currentIndex = candidateNodes.indexOf(currentElement);
879
+ candidateNodes = candidateNodes.slice(currentIndex + 1);
880
+ }
881
+
882
+ // Imperative focus during keydown is risky so we defer it (React #20332).
883
+ setTimeout(() => focusFirst(candidateNodes));
884
+
885
+ event.preventDefault();
886
+ }
887
+ }),
888
+ }),
889
+ }),
890
+ }),
891
+ });
892
+ }
893
+
894
+ /* -------------------------------------------------------------------------------------------------
895
+ * SelectItemAlignedPosition
896
+ * -----------------------------------------------------------------------------------------------*/
897
+
898
+ const ITEM_ALIGNED_POSITION_NAME = 'SelectItemAlignedPosition';
899
+
900
+ function ItemAlignedPosition(props: any): any {
901
+ const slot = S('Select.ItemAlignedPosition');
902
+ const { __scopeSelect, onPlaced, ref: forwardedRef, ...popperProps } = props;
903
+ const context = useSelectContext(CONTENT_NAME, __scopeSelect);
904
+ const contentContext = useSelectContentContext(CONTENT_NAME, __scopeSelect);
905
+ const [contentWrapper, setContentWrapper] = useState<HTMLDivElement | null>(
906
+ null,
907
+ subSlot(slot, 'wrapper'),
908
+ );
909
+ const [content, setContent] = useState<HTMLElement | null>(null, subSlot(slot, 'content'));
910
+ const composedRefs = useComposedRefs(forwardedRef, setContent, subSlot(slot, 'refs'));
911
+ const getItems = useCollection(__scopeSelect, subSlot(slot, 'items'));
912
+ const shouldExpandOnScrollRef = useRef(false, subSlot(slot, 'expand'));
913
+ const shouldRepositionRef = useRef(true, subSlot(slot, 'reposition'));
914
+
915
+ const { viewport, selectedItem, selectedItemText, focusSelectedItem } = contentContext;
916
+ const position = useCallback(
917
+ () => {
918
+ if (
919
+ context.trigger &&
920
+ context.valueNode &&
921
+ contentWrapper &&
922
+ content &&
923
+ viewport &&
924
+ selectedItem &&
925
+ selectedItemText
926
+ ) {
927
+ const triggerRect = context.trigger.getBoundingClientRect();
928
+
929
+ // -----------------------------------------------------------------------------------------
930
+ // Horizontal positioning
931
+ // -----------------------------------------------------------------------------------------
932
+ const contentRect = content.getBoundingClientRect();
933
+ const valueNodeRect = context.valueNode.getBoundingClientRect();
934
+ const itemTextRect = selectedItemText.getBoundingClientRect();
935
+
936
+ if (context.dir !== 'rtl') {
937
+ const itemTextOffset = itemTextRect.left - contentRect.left;
938
+ const left = valueNodeRect.left - itemTextOffset;
939
+ const leftDelta = triggerRect.left - left;
940
+ const minContentWidth = triggerRect.width + leftDelta;
941
+ const contentWidth = Math.max(minContentWidth, contentRect.width);
942
+ const rightEdge = window.innerWidth - CONTENT_MARGIN;
943
+ const clampedLeft = clamp(left, [
944
+ CONTENT_MARGIN,
945
+ // Prevents the content from going off the starting edge of the
946
+ // viewport. It may still go off the ending edge, but this can be
947
+ // controlled by the user since they may want to manage overflow in a
948
+ // specific way.
949
+ // https://github.com/radix-ui/primitives/issues/2049
950
+ Math.max(CONTENT_MARGIN, rightEdge - contentWidth),
951
+ ]);
952
+
953
+ contentWrapper.style.minWidth = minContentWidth + 'px';
954
+ contentWrapper.style.left = clampedLeft + 'px';
955
+ } else {
956
+ const itemTextOffset = contentRect.right - itemTextRect.right;
957
+ const right = window.innerWidth - valueNodeRect.right - itemTextOffset;
958
+ const rightDelta = window.innerWidth - triggerRect.right - right;
959
+ const minContentWidth = triggerRect.width + rightDelta;
960
+ const contentWidth = Math.max(minContentWidth, contentRect.width);
961
+ const leftEdge = window.innerWidth - CONTENT_MARGIN;
962
+ const clampedRight = clamp(right, [
963
+ CONTENT_MARGIN,
964
+ Math.max(CONTENT_MARGIN, leftEdge - contentWidth),
965
+ ]);
966
+
967
+ contentWrapper.style.minWidth = minContentWidth + 'px';
968
+ contentWrapper.style.right = clampedRight + 'px';
969
+ }
970
+
971
+ // -----------------------------------------------------------------------------------------
972
+ // Vertical positioning
973
+ // -----------------------------------------------------------------------------------------
974
+ const items = getItems();
975
+ const availableHeight = window.innerHeight - CONTENT_MARGIN * 2;
976
+ const itemsHeight = viewport.scrollHeight;
977
+
978
+ const contentStyles = window.getComputedStyle(content);
979
+ const contentBorderTopWidth = parseInt(contentStyles.borderTopWidth, 10);
980
+ const contentPaddingTop = parseInt(contentStyles.paddingTop, 10);
981
+ const contentBorderBottomWidth = parseInt(contentStyles.borderBottomWidth, 10);
982
+ const contentPaddingBottom = parseInt(contentStyles.paddingBottom, 10);
983
+ const fullContentHeight = contentBorderTopWidth + contentPaddingTop + itemsHeight + contentPaddingBottom + contentBorderBottomWidth; // prettier-ignore
984
+ const minContentHeight = Math.min(selectedItem.offsetHeight * 5, fullContentHeight);
985
+
986
+ const viewportStyles = window.getComputedStyle(viewport);
987
+ const viewportPaddingTop = parseInt(viewportStyles.paddingTop, 10);
988
+ const viewportPaddingBottom = parseInt(viewportStyles.paddingBottom, 10);
989
+
990
+ const topEdgeToTriggerMiddle = triggerRect.top + triggerRect.height / 2 - CONTENT_MARGIN;
991
+ const triggerMiddleToBottomEdge = availableHeight - topEdgeToTriggerMiddle;
992
+
993
+ const selectedItemHalfHeight = selectedItem.offsetHeight / 2;
994
+ const itemOffsetMiddle = selectedItem.offsetTop + selectedItemHalfHeight;
995
+ const contentTopToItemMiddle = contentBorderTopWidth + contentPaddingTop + itemOffsetMiddle;
996
+ const itemMiddleToContentBottom = fullContentHeight - contentTopToItemMiddle;
997
+
998
+ const willAlignWithoutTopOverflow = contentTopToItemMiddle <= topEdgeToTriggerMiddle;
999
+
1000
+ if (willAlignWithoutTopOverflow) {
1001
+ const isLastItem =
1002
+ items.length > 0 && selectedItem === items[items.length - 1]!.ref.current;
1003
+ contentWrapper.style.bottom = 0 + 'px';
1004
+ const viewportOffsetBottom =
1005
+ content.clientHeight - viewport.offsetTop - viewport.offsetHeight;
1006
+ const clampedTriggerMiddleToBottomEdge = Math.max(
1007
+ triggerMiddleToBottomEdge,
1008
+ selectedItemHalfHeight +
1009
+ // viewport might have padding bottom, include it to avoid a scrollable viewport
1010
+ (isLastItem ? viewportPaddingBottom : 0) +
1011
+ viewportOffsetBottom +
1012
+ contentBorderBottomWidth,
1013
+ );
1014
+ const height = contentTopToItemMiddle + clampedTriggerMiddleToBottomEdge;
1015
+ contentWrapper.style.height = height + 'px';
1016
+ } else {
1017
+ const isFirstItem = items.length > 0 && selectedItem === items[0]!.ref.current;
1018
+ contentWrapper.style.top = 0 + 'px';
1019
+ const clampedTopEdgeToTriggerMiddle = Math.max(
1020
+ topEdgeToTriggerMiddle,
1021
+ contentBorderTopWidth +
1022
+ viewport.offsetTop +
1023
+ // viewport might have padding top, include it to avoid a scrollable viewport
1024
+ (isFirstItem ? viewportPaddingTop : 0) +
1025
+ selectedItemHalfHeight,
1026
+ );
1027
+ const height = clampedTopEdgeToTriggerMiddle + itemMiddleToContentBottom;
1028
+ contentWrapper.style.height = height + 'px';
1029
+ viewport.scrollTop = contentTopToItemMiddle - topEdgeToTriggerMiddle + viewport.offsetTop;
1030
+ }
1031
+
1032
+ contentWrapper.style.margin = `${CONTENT_MARGIN}px 0`;
1033
+ contentWrapper.style.minHeight = minContentHeight + 'px';
1034
+ contentWrapper.style.maxHeight = availableHeight + 'px';
1035
+ // -----------------------------------------------------------------------------------------
1036
+
1037
+ onPlaced?.();
1038
+
1039
+ // we don't want the initial scroll position adjustment to trigger "expand on scroll"
1040
+ // so we explicitly turn it on only after they've registered.
1041
+ requestAnimationFrame(() => (shouldExpandOnScrollRef.current = true));
1042
+ }
1043
+ },
1044
+ [
1045
+ getItems,
1046
+ context.trigger,
1047
+ context.valueNode,
1048
+ contentWrapper,
1049
+ content,
1050
+ viewport,
1051
+ selectedItem,
1052
+ selectedItemText,
1053
+ context.dir,
1054
+ onPlaced,
1055
+ ],
1056
+ subSlot(slot, 'position'),
1057
+ );
1058
+
1059
+ useLayoutEffect(() => position(), [position], subSlot(slot, 'e:position'));
1060
+
1061
+ // copy z-index from content to wrapper
1062
+ const [contentZIndex, setContentZIndex] = useState<string | undefined>(
1063
+ undefined,
1064
+ subSlot(slot, 'zIndex'),
1065
+ );
1066
+ useLayoutEffect(
1067
+ () => {
1068
+ if (content) setContentZIndex(window.getComputedStyle(content).zIndex);
1069
+ },
1070
+ [content],
1071
+ subSlot(slot, 'e:zIndex'),
1072
+ );
1073
+
1074
+ // When the viewport becomes scrollable at the top, the scroll up button will mount.
1075
+ // Because it is part of the normal flow, it will push down the viewport, thus throwing our
1076
+ // trigger => selectedItem alignment off by the amount the viewport was pushed down.
1077
+ // We wait for this to happen and then re-run the positining logic one more time to account for it.
1078
+ const handleScrollButtonChange = useCallback(
1079
+ (node: HTMLElement | null) => {
1080
+ if (node && shouldRepositionRef.current === true) {
1081
+ position();
1082
+ focusSelectedItem?.();
1083
+ shouldRepositionRef.current = false;
1084
+ }
1085
+ },
1086
+ [position, focusSelectedItem],
1087
+ subSlot(slot, 'scrollBtn'),
1088
+ );
1089
+
1090
+ return createElement(SelectViewportProvider, {
1091
+ scope: __scopeSelect,
1092
+ contentWrapper,
1093
+ shouldExpandOnScrollRef,
1094
+ onScrollButtonChange: handleScrollButtonChange,
1095
+ children: createElement('div', {
1096
+ ref: setContentWrapper,
1097
+ style: {
1098
+ display: 'flex',
1099
+ flexDirection: 'column',
1100
+ position: 'fixed',
1101
+ zIndex: contentZIndex,
1102
+ },
1103
+ children: createElement(Primitive.div, {
1104
+ ...popperProps,
1105
+ ref: composedRefs,
1106
+ style: {
1107
+ // When we get the height of the content, it includes borders. If we were to set
1108
+ // the height without having `boxSizing: 'border-box'` it would be too big.
1109
+ boxSizing: 'border-box',
1110
+ // We need to ensure the content doesn't get taller than the wrapper
1111
+ maxHeight: '100%',
1112
+ ...popperProps.style,
1113
+ },
1114
+ }),
1115
+ }),
1116
+ });
1117
+ }
1118
+
1119
+ /* -------------------------------------------------------------------------------------------------
1120
+ * SelectPopperPosition
1121
+ * -----------------------------------------------------------------------------------------------*/
1122
+
1123
+ function PopperPosition(props: any): any {
1124
+ const slot = S('Select.PopperPosition');
1125
+ const {
1126
+ __scopeSelect,
1127
+ align = 'start',
1128
+ collisionPadding = CONTENT_MARGIN,
1129
+ ...popperProps
1130
+ } = props ?? {};
1131
+ const popperScope = usePopperScope(__scopeSelect, subSlot(slot, 'popper'));
1132
+
1133
+ return createElement(PopperPrimitive.Content, {
1134
+ ...popperScope,
1135
+ ...popperProps,
1136
+ align,
1137
+ collisionPadding,
1138
+ style: {
1139
+ // Ensure border-box for floating-ui calculations
1140
+ boxSizing: 'border-box',
1141
+ ...popperProps.style,
1142
+ // re-namespace exposed content custom properties
1143
+ '--radix-select-content-transform-origin': 'var(--radix-popper-transform-origin)',
1144
+ '--radix-select-content-available-width': 'var(--radix-popper-available-width)',
1145
+ '--radix-select-content-available-height': 'var(--radix-popper-available-height)',
1146
+ '--radix-select-trigger-width': 'var(--radix-popper-anchor-width)',
1147
+ '--radix-select-trigger-height': 'var(--radix-popper-anchor-height)',
1148
+ },
1149
+ });
1150
+ }
1151
+
1152
+ /* -------------------------------------------------------------------------------------------------
1153
+ * SelectViewport
1154
+ * -----------------------------------------------------------------------------------------------*/
1155
+
1156
+ interface SelectViewportContextValue {
1157
+ contentWrapper?: HTMLElement | null;
1158
+ shouldExpandOnScrollRef?: { current: boolean };
1159
+ onScrollButtonChange?: (node: HTMLElement | null) => void;
1160
+ }
1161
+
1162
+ const [SelectViewportProvider, useSelectViewportContext] =
1163
+ createSelectContext<SelectViewportContextValue>(CONTENT_NAME, {});
1164
+
1165
+ const VIEWPORT_NAME = 'SelectViewport';
1166
+
1167
+ export function Viewport(props: any): any {
1168
+ const slot = S('Select.Viewport');
1169
+ const { __scopeSelect, nonce, ref: forwardedRef, onScroll, ...viewportProps } = props ?? {};
1170
+ const contentContext = useSelectContentContext(VIEWPORT_NAME, __scopeSelect);
1171
+ const viewportContext = useSelectViewportContext(VIEWPORT_NAME, __scopeSelect);
1172
+ const composedRefs = useComposedRefs(
1173
+ forwardedRef,
1174
+ contentContext.onViewportChange,
1175
+ subSlot(slot, 'refs'),
1176
+ );
1177
+ const prevScrollTopRef = useRef(0, subSlot(slot, 'prevScroll'));
1178
+
1179
+ const handleScroll = composeEventHandlers(onScroll, (event: Event) => {
1180
+ const viewport = event.currentTarget as HTMLElement;
1181
+ const { contentWrapper, shouldExpandOnScrollRef } = viewportContext;
1182
+ if (shouldExpandOnScrollRef?.current && contentWrapper) {
1183
+ const scrolledBy = Math.abs(prevScrollTopRef.current - viewport.scrollTop);
1184
+ if (scrolledBy > 0) {
1185
+ const availableHeight = window.innerHeight - CONTENT_MARGIN * 2;
1186
+ const cssMinHeight = parseFloat(contentWrapper.style.minHeight);
1187
+ const cssHeight = parseFloat(contentWrapper.style.height);
1188
+ const prevHeight = Math.max(cssMinHeight, cssHeight);
1189
+
1190
+ if (prevHeight < availableHeight) {
1191
+ const nextHeight = prevHeight + scrolledBy;
1192
+ const clampedNextHeight = Math.min(availableHeight, nextHeight);
1193
+ const heightDiff = nextHeight - clampedNextHeight;
1194
+
1195
+ contentWrapper.style.height = clampedNextHeight + 'px';
1196
+ if (contentWrapper.style.bottom === '0px') {
1197
+ viewport.scrollTop = heightDiff > 0 ? heightDiff : 0;
1198
+ // ensure the content stays pinned to the bottom
1199
+ contentWrapper.style.justifyContent = 'flex-end';
1200
+ }
1201
+ }
1202
+ }
1203
+ }
1204
+ prevScrollTopRef.current = viewport.scrollTop;
1205
+ });
1206
+ return [
1207
+ // Hide scrollbars cross-browser and enable momentum scroll for touch devices
1208
+ createElement('style', {
1209
+ key: 'style',
1210
+ dangerouslySetInnerHTML: {
1211
+ __html: `[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}`,
1212
+ },
1213
+ nonce,
1214
+ }),
1215
+ createElement(Collection.Slot, {
1216
+ key: 'slot',
1217
+ scope: __scopeSelect,
1218
+ children: createElement(Primitive.div, {
1219
+ 'data-radix-select-viewport': '',
1220
+ role: 'presentation',
1221
+ ...viewportProps,
1222
+ ref: composedRefs,
1223
+ onScroll: handleScroll,
1224
+ style: {
1225
+ // we use position: 'relative' here on the `viewport` so that when we call
1226
+ // `selectedItem.offsetTop` in calculations, the offset is relative to the viewport
1227
+ // (independent of the scrollUpButton).
1228
+ position: 'relative',
1229
+ flex: 1,
1230
+ // Viewport should only be scrollable in the vertical direction.
1231
+ // This won't work in vertical writing modes, so we'll need to
1232
+ // revisit this if/when that is supported
1233
+ // https://developer.chrome.com/blog/vertical-form-controls
1234
+ overflow: 'hidden auto',
1235
+ ...viewportProps.style,
1236
+ },
1237
+ }),
1238
+ }),
1239
+ ];
1240
+ }
1241
+
1242
+ /* -------------------------------------------------------------------------------------------------
1243
+ * SelectGroup
1244
+ * -----------------------------------------------------------------------------------------------*/
1245
+
1246
+ const GROUP_NAME = 'SelectGroup';
1247
+
1248
+ interface SelectGroupContextValue {
1249
+ id: string;
1250
+ }
1251
+
1252
+ const [SelectGroupContextProvider, useSelectGroupContext] =
1253
+ createSelectContext<SelectGroupContextValue>(GROUP_NAME);
1254
+
1255
+ export function Group(props: any): any {
1256
+ const slot = S('Select.Group');
1257
+ const { __scopeSelect, ...groupProps } = props ?? {};
1258
+ const groupId = useId(subSlot(slot, 'id'));
1259
+ return createElement(SelectGroupContextProvider, {
1260
+ scope: __scopeSelect,
1261
+ id: groupId,
1262
+ children: createElement(Primitive.div, {
1263
+ role: 'group',
1264
+ 'aria-labelledby': groupId,
1265
+ ...groupProps,
1266
+ }),
1267
+ });
1268
+ }
1269
+
1270
+ /* -------------------------------------------------------------------------------------------------
1271
+ * SelectLabel
1272
+ * -----------------------------------------------------------------------------------------------*/
1273
+
1274
+ const LABEL_NAME = 'SelectLabel';
1275
+
1276
+ export function Label(props: any): any {
1277
+ const { __scopeSelect, ...labelProps } = props ?? {};
1278
+ const groupContext = useSelectGroupContext(LABEL_NAME, __scopeSelect);
1279
+ return createElement(Primitive.div, { id: groupContext.id, ...labelProps });
1280
+ }
1281
+
1282
+ /* -------------------------------------------------------------------------------------------------
1283
+ * SelectItem
1284
+ * -----------------------------------------------------------------------------------------------*/
1285
+
1286
+ const ITEM_NAME = 'SelectItem';
1287
+
1288
+ interface SelectItemContextValue {
1289
+ value: string;
1290
+ disabled: boolean;
1291
+ textId: string;
1292
+ isSelected: boolean;
1293
+ onItemTextChange(node: HTMLElement | null): void;
1294
+ }
1295
+
1296
+ const [SelectItemContextProvider, useSelectItemContext] =
1297
+ createSelectContext<SelectItemContextValue>(ITEM_NAME);
1298
+
1299
+ export function Item(props: any): any {
1300
+ const slot = S('Select.Item');
1301
+ const {
1302
+ __scopeSelect,
1303
+ value,
1304
+ disabled = false,
1305
+ textValue: textValueProp,
1306
+ ref: forwardedRef,
1307
+ ...itemProps
1308
+ } = props ?? {};
1309
+ const context = useSelectContext(ITEM_NAME, __scopeSelect);
1310
+ const contentContext = useSelectContentContext(ITEM_NAME, __scopeSelect);
1311
+ const isSelected = context.value === value;
1312
+ const [textValue, setTextValue] = useState(textValueProp ?? '', subSlot(slot, 'textValue'));
1313
+ const [isFocused, setIsFocused] = useState(false, subSlot(slot, 'focused'));
1314
+ const handleItemRefCallback = useCallbackRef(
1315
+ (node: HTMLElement | null) => contentContext.itemRefCallback?.(node, value, disabled),
1316
+ subSlot(slot, 'refCb'),
1317
+ );
1318
+ const composedRefs = useComposedRefs(forwardedRef, handleItemRefCallback, subSlot(slot, 'refs'));
1319
+ const textId = useId(subSlot(slot, 'textId'));
1320
+ const pointerTypeRef = useRef<string>('touch', subSlot(slot, 'pointerType'));
1321
+
1322
+ const handleSelect = (): void => {
1323
+ if (!disabled) {
1324
+ context.onValueChange(value);
1325
+ context.onOpenChange(false);
1326
+ }
1327
+ };
1328
+
1329
+ return createElement(SelectItemContextProvider, {
1330
+ scope: __scopeSelect,
1331
+ value,
1332
+ disabled,
1333
+ textId,
1334
+ isSelected,
1335
+ onItemTextChange: useCallback(
1336
+ (node: HTMLElement | null) => {
1337
+ setTextValue((prevTextValue: string) => prevTextValue || (node?.textContent ?? '').trim());
1338
+ },
1339
+ [],
1340
+ subSlot(slot, 'textChange'),
1341
+ ),
1342
+ children: createElement(Collection.ItemSlot, {
1343
+ scope: __scopeSelect,
1344
+ value,
1345
+ disabled,
1346
+ textValue,
1347
+ children: createElement(Primitive.div, {
1348
+ role: 'option',
1349
+ 'aria-labelledby': textId,
1350
+ 'data-highlighted': isFocused ? '' : undefined,
1351
+ // `isFocused` caveat fixes stuttering in VoiceOver
1352
+ 'aria-selected': isSelected && isFocused,
1353
+ 'data-state': isSelected ? 'checked' : 'unchecked',
1354
+ 'aria-disabled': disabled || undefined,
1355
+ 'data-disabled': disabled ? '' : undefined,
1356
+ tabIndex: disabled ? undefined : -1,
1357
+ ...itemProps,
1358
+ ref: composedRefs,
1359
+ onFocus: composeEventHandlers(itemProps.onFocus, () => setIsFocused(true)),
1360
+ onBlur: composeEventHandlers(itemProps.onBlur, () => setIsFocused(false)),
1361
+ onClick: composeEventHandlers(itemProps.onClick, () => {
1362
+ // Open on click when using a touch or pen device
1363
+ if (pointerTypeRef.current !== 'mouse') handleSelect();
1364
+ }),
1365
+ onPointerUp: composeEventHandlers(itemProps.onPointerUp, () => {
1366
+ // Using a mouse you should be able to do pointer down, move through
1367
+ // the list, and release the pointer over the item to select it.
1368
+ if (pointerTypeRef.current === 'mouse') handleSelect();
1369
+ }),
1370
+ onPointerDown: composeEventHandlers(itemProps.onPointerDown, (event: PointerEvent) => {
1371
+ pointerTypeRef.current = event.pointerType;
1372
+ }),
1373
+ onPointerMove: composeEventHandlers(itemProps.onPointerMove, (event: PointerEvent) => {
1374
+ // Remember pointer type when sliding over to this item from another one
1375
+ pointerTypeRef.current = event.pointerType;
1376
+ if (disabled) {
1377
+ contentContext.onItemLeave?.();
1378
+ } else if (pointerTypeRef.current === 'mouse') {
1379
+ // even though safari doesn't support this option, it's acceptable
1380
+ // as it only means it might scroll a few pixels when using the pointer.
1381
+ (event.currentTarget as HTMLElement).focus({ preventScroll: true } as FocusOptions);
1382
+ }
1383
+ }),
1384
+ onPointerLeave: composeEventHandlers(itemProps.onPointerLeave, (event: PointerEvent) => {
1385
+ if (event.currentTarget === document.activeElement) {
1386
+ contentContext.onItemLeave?.();
1387
+ }
1388
+ }),
1389
+ onKeyDown: composeEventHandlers(itemProps.onKeyDown, (event: KeyboardEvent) => {
1390
+ const isTypingAhead = contentContext.searchRef?.current !== '';
1391
+ if (isTypingAhead && event.key === ' ') return;
1392
+ if (SELECTION_KEYS.includes(event.key)) handleSelect();
1393
+ // prevent page scroll if using the space key to select an item
1394
+ if (event.key === ' ') event.preventDefault();
1395
+ }),
1396
+ }),
1397
+ }),
1398
+ });
1399
+ }
1400
+
1401
+ /* -------------------------------------------------------------------------------------------------
1402
+ * SelectItemText
1403
+ * -----------------------------------------------------------------------------------------------*/
1404
+
1405
+ const ITEM_TEXT_NAME = 'SelectItemText';
1406
+
1407
+ export function ItemText(props: any): any {
1408
+ const slot = S('Select.ItemText');
1409
+ // We ignore `className` and `style` as this part shouldn't be styled.
1410
+ const { __scopeSelect, className, style, ref: forwardedRef, ...itemTextProps } = props ?? {};
1411
+ void className;
1412
+ void style;
1413
+ const context = useSelectContext(ITEM_TEXT_NAME, __scopeSelect);
1414
+ const contentContext = useSelectContentContext(ITEM_TEXT_NAME, __scopeSelect);
1415
+ const itemContext = useSelectItemContext(ITEM_TEXT_NAME, __scopeSelect);
1416
+ const nativeOptionsContext = useSelectNativeOptionsContext(ITEM_TEXT_NAME, __scopeSelect);
1417
+ const [itemTextNode, setItemTextNode] = useState<HTMLElement | null>(null, subSlot(slot, 'node'));
1418
+ const handleItemTextRefCallback = useCallbackRef(
1419
+ (node: HTMLElement | null) =>
1420
+ contentContext.itemTextRefCallback?.(node, itemContext.value, itemContext.disabled),
1421
+ subSlot(slot, 'textRefCb'),
1422
+ );
1423
+ const composedRefs = useComposedRefs(
1424
+ forwardedRef,
1425
+ setItemTextNode,
1426
+ itemContext.onItemTextChange,
1427
+ handleItemTextRefCallback,
1428
+ subSlot(slot, 'refs'),
1429
+ );
1430
+
1431
+ const textContent = itemTextNode?.textContent;
1432
+ const nativeOption = useMemo(
1433
+ () =>
1434
+ createElement('option', {
1435
+ key: itemContext.value,
1436
+ value: itemContext.value,
1437
+ disabled: itemContext.disabled,
1438
+ children: textContent,
1439
+ }),
1440
+ [itemContext.disabled, itemContext.value, textContent],
1441
+ subSlot(slot, 'option'),
1442
+ );
1443
+
1444
+ const { onNativeOptionAdd, onNativeOptionRemove } = nativeOptionsContext;
1445
+ useLayoutEffect(
1446
+ () => {
1447
+ onNativeOptionAdd(nativeOption);
1448
+ return () => onNativeOptionRemove(nativeOption);
1449
+ },
1450
+ [onNativeOptionAdd, onNativeOptionRemove, nativeOption],
1451
+ subSlot(slot, 'e:option'),
1452
+ );
1453
+
1454
+ return [
1455
+ createElement(Primitive.span, {
1456
+ key: 'text',
1457
+ id: itemContext.textId,
1458
+ ...itemTextProps,
1459
+ ref: composedRefs,
1460
+ }),
1461
+
1462
+ // Portal the select item text into the trigger value node.
1463
+ // When the value is empty we show the placeholder instead, so a
1464
+ // selected "clear" item (empty value) must not portal its text.
1465
+ // Keyed passthrough wrapper: a bare portal/null entry has no `key`, which
1466
+ // would trip octane's one-time missing-key warning for array children.
1467
+ createElement(ValueFragment, {
1468
+ key: 'portal',
1469
+ children:
1470
+ itemContext.isSelected &&
1471
+ context.valueNode &&
1472
+ !context.valueNodeHasChildren &&
1473
+ !shouldShowPlaceholder(context.value)
1474
+ ? createPortal(itemTextProps.children, context.valueNode)
1475
+ : null,
1476
+ }),
1477
+ ];
1478
+ }
1479
+
1480
+ /* -------------------------------------------------------------------------------------------------
1481
+ * SelectItemIndicator
1482
+ * -----------------------------------------------------------------------------------------------*/
1483
+
1484
+ const ITEM_INDICATOR_NAME = 'SelectItemIndicator';
1485
+
1486
+ export function ItemIndicator(props: any): any {
1487
+ const { __scopeSelect, ...itemIndicatorProps } = props ?? {};
1488
+ const itemContext = useSelectItemContext(ITEM_INDICATOR_NAME, __scopeSelect);
1489
+ return itemContext.isSelected
1490
+ ? createElement(Primitive.span, { 'aria-hidden': true, ...itemIndicatorProps })
1491
+ : null;
1492
+ }
1493
+
1494
+ /* -------------------------------------------------------------------------------------------------
1495
+ * SelectScrollUpButton
1496
+ * -----------------------------------------------------------------------------------------------*/
1497
+
1498
+ const SCROLL_UP_BUTTON_NAME = 'SelectScrollUpButton';
1499
+
1500
+ export function ScrollUpButton(props: any): any {
1501
+ const slot = S('Select.ScrollUpButton');
1502
+ const contentContext = useSelectContentContext(SCROLL_UP_BUTTON_NAME, props?.__scopeSelect);
1503
+ const viewportContext = useSelectViewportContext(SCROLL_UP_BUTTON_NAME, props?.__scopeSelect);
1504
+ const [canScrollUp, setCanScrollUp] = useState(false, subSlot(slot, 'canScroll'));
1505
+ const composedRefs = useComposedRefs(
1506
+ props?.ref,
1507
+ viewportContext.onScrollButtonChange,
1508
+ subSlot(slot, 'refs'),
1509
+ );
1510
+
1511
+ useLayoutEffect(
1512
+ () => {
1513
+ if (contentContext.viewport && contentContext.isPositioned) {
1514
+ const viewport = contentContext.viewport;
1515
+ function handleScroll(): void {
1516
+ const canScrollUp = viewport!.scrollTop > 0;
1517
+ setCanScrollUp(canScrollUp);
1518
+ }
1519
+ handleScroll();
1520
+ viewport.addEventListener('scroll', handleScroll);
1521
+ return () => viewport.removeEventListener('scroll', handleScroll);
1522
+ }
1523
+ },
1524
+ [contentContext.viewport, contentContext.isPositioned],
1525
+ subSlot(slot, 'e:scroll'),
1526
+ );
1527
+
1528
+ return canScrollUp
1529
+ ? createElement(ScrollButtonImpl, {
1530
+ ...props,
1531
+ ref: composedRefs,
1532
+ onAutoScroll: () => {
1533
+ const { viewport, selectedItem } = contentContext;
1534
+ if (viewport && selectedItem) {
1535
+ viewport.scrollTop = viewport.scrollTop - selectedItem.offsetHeight;
1536
+ }
1537
+ },
1538
+ })
1539
+ : null;
1540
+ }
1541
+
1542
+ /* -------------------------------------------------------------------------------------------------
1543
+ * SelectScrollDownButton
1544
+ * -----------------------------------------------------------------------------------------------*/
1545
+
1546
+ const SCROLL_DOWN_BUTTON_NAME = 'SelectScrollDownButton';
1547
+
1548
+ export function ScrollDownButton(props: any): any {
1549
+ const slot = S('Select.ScrollDownButton');
1550
+ const contentContext = useSelectContentContext(SCROLL_DOWN_BUTTON_NAME, props?.__scopeSelect);
1551
+ const viewportContext = useSelectViewportContext(SCROLL_DOWN_BUTTON_NAME, props?.__scopeSelect);
1552
+ const [canScrollDown, setCanScrollDown] = useState(false, subSlot(slot, 'canScroll'));
1553
+ const composedRefs = useComposedRefs(
1554
+ props?.ref,
1555
+ viewportContext.onScrollButtonChange,
1556
+ subSlot(slot, 'refs'),
1557
+ );
1558
+
1559
+ useLayoutEffect(
1560
+ () => {
1561
+ if (contentContext.viewport && contentContext.isPositioned) {
1562
+ const viewport = contentContext.viewport;
1563
+ function handleScroll(): void {
1564
+ const maxScroll = viewport!.scrollHeight - viewport!.clientHeight;
1565
+ // we use Math.ceil here because if the UI is zoomed-in
1566
+ // `scrollTop` is not always reported as an integer
1567
+ const canScrollDown = Math.ceil(viewport!.scrollTop) < maxScroll;
1568
+ setCanScrollDown(canScrollDown);
1569
+ }
1570
+ handleScroll();
1571
+ viewport.addEventListener('scroll', handleScroll);
1572
+ return () => viewport.removeEventListener('scroll', handleScroll);
1573
+ }
1574
+ },
1575
+ [contentContext.viewport, contentContext.isPositioned],
1576
+ subSlot(slot, 'e:scroll'),
1577
+ );
1578
+
1579
+ return canScrollDown
1580
+ ? createElement(ScrollButtonImpl, {
1581
+ ...props,
1582
+ ref: composedRefs,
1583
+ onAutoScroll: () => {
1584
+ const { viewport, selectedItem } = contentContext;
1585
+ if (viewport && selectedItem) {
1586
+ viewport.scrollTop = viewport.scrollTop + selectedItem.offsetHeight;
1587
+ }
1588
+ },
1589
+ })
1590
+ : null;
1591
+ }
1592
+
1593
+ function ScrollButtonImpl(props: any): any {
1594
+ const slot = S('Select.ScrollButtonImpl');
1595
+ const { __scopeSelect, onAutoScroll, ref: forwardedRef, ...scrollIndicatorProps } = props ?? {};
1596
+ const contentContext = useSelectContentContext('SelectScrollButton', __scopeSelect);
1597
+ const autoScrollTimerRef = useRef<number | null>(null, subSlot(slot, 'timer'));
1598
+ const getItems = useCollection(__scopeSelect, subSlot(slot, 'items'));
1599
+
1600
+ const clearAutoScrollTimer = useCallback(
1601
+ () => {
1602
+ if (autoScrollTimerRef.current !== null) {
1603
+ window.clearInterval(autoScrollTimerRef.current);
1604
+ autoScrollTimerRef.current = null;
1605
+ }
1606
+ },
1607
+ [],
1608
+ subSlot(slot, 'clear'),
1609
+ );
1610
+
1611
+ useEffect(
1612
+ () => {
1613
+ return () => clearAutoScrollTimer();
1614
+ },
1615
+ [clearAutoScrollTimer],
1616
+ subSlot(slot, 'e:clear'),
1617
+ );
1618
+
1619
+ // When the viewport becomes scrollable on either side, the relevant scroll button will mount.
1620
+ // Because it is part of the normal flow, it will push down (top button) or shrink (bottom button)
1621
+ // the viewport, potentially causing the active item to now be partially out of view.
1622
+ // We re-run the `scrollIntoView` logic to make sure it stays within the viewport.
1623
+ useLayoutEffect(
1624
+ () => {
1625
+ const activeItem = getItems().find(
1626
+ (item: any) => item.ref.current === document.activeElement,
1627
+ );
1628
+ // (guarded: jsdom lacks scrollIntoView)
1629
+ (activeItem?.ref.current as HTMLElement | undefined)?.scrollIntoView?.({ block: 'nearest' });
1630
+ },
1631
+ [getItems],
1632
+ subSlot(slot, 'e:intoView'),
1633
+ );
1634
+
1635
+ return createElement(Primitive.div, {
1636
+ 'aria-hidden': true,
1637
+ ...scrollIndicatorProps,
1638
+ ref: forwardedRef,
1639
+ style: { flexShrink: 0, ...scrollIndicatorProps.style },
1640
+ onPointerDown: composeEventHandlers(scrollIndicatorProps.onPointerDown, () => {
1641
+ if (autoScrollTimerRef.current === null) {
1642
+ autoScrollTimerRef.current = window.setInterval(onAutoScroll, 50);
1643
+ }
1644
+ }),
1645
+ onPointerMove: composeEventHandlers(scrollIndicatorProps.onPointerMove, () => {
1646
+ contentContext.onItemLeave?.();
1647
+ if (autoScrollTimerRef.current === null) {
1648
+ autoScrollTimerRef.current = window.setInterval(onAutoScroll, 50);
1649
+ }
1650
+ }),
1651
+ onPointerLeave: composeEventHandlers(scrollIndicatorProps.onPointerLeave, () => {
1652
+ clearAutoScrollTimer();
1653
+ }),
1654
+ });
1655
+ }
1656
+
1657
+ /* -------------------------------------------------------------------------------------------------
1658
+ * SelectSeparator
1659
+ * -----------------------------------------------------------------------------------------------*/
1660
+
1661
+ export function Separator(props: any): any {
1662
+ const { __scopeSelect, ...separatorProps } = props ?? {};
1663
+ return createElement(Primitive.div, { 'aria-hidden': true, ...separatorProps });
1664
+ }
1665
+
1666
+ /* -------------------------------------------------------------------------------------------------
1667
+ * SelectArrow
1668
+ * -----------------------------------------------------------------------------------------------*/
1669
+
1670
+ const ARROW_NAME = 'SelectArrow';
1671
+
1672
+ export function Arrow(props: any): any {
1673
+ const slot = S('Select.Arrow');
1674
+ const { __scopeSelect, ...arrowProps } = props ?? {};
1675
+ const popperScope = usePopperScope(__scopeSelect, subSlot(slot, 'popper'));
1676
+ const contentContext = useSelectContentContext(ARROW_NAME, __scopeSelect);
1677
+ return contentContext.position === 'popper'
1678
+ ? createElement(PopperPrimitive.Arrow, { ...popperScope, ...arrowProps })
1679
+ : null;
1680
+ }
1681
+
1682
+ /* -------------------------------------------------------------------------------------------------
1683
+ * SelectBubbleInput
1684
+ * -----------------------------------------------------------------------------------------------*/
1685
+
1686
+ const BUBBLE_INPUT_NAME = 'SelectBubbleInput';
1687
+
1688
+ export function BubbleInput(props: any): any {
1689
+ const slot = S('Select.BubbleInput');
1690
+ const { __scopeSelect, ref: forwardedRef, ...selectProps } = props ?? {};
1691
+ const context = useSelectContext(BUBBLE_INPUT_NAME, __scopeSelect);
1692
+ const { value, onValueChange, required, disabled, name, autoComplete, form } = context;
1693
+ const { nativeOptions, nativeSelectKey } = context;
1694
+ const ref = useRef<HTMLSelectElement | null>(null, subSlot(slot, 'ref'));
1695
+ const composedRefs = useComposedRefs(forwardedRef, ref, subSlot(slot, 'refs'));
1696
+ const selectValue = value ?? '';
1697
+ const prevValue = usePrevious(selectValue, subSlot(slot, 'prev'));
1698
+
1699
+ // A consumer may render a `Select.Item` with an empty value to act as a
1700
+ // "clear" option. In that case it already provides a native `<option>` with
1701
+ // an empty value, so we avoid rendering our synthetic placeholder option to
1702
+ // prevent duplicate empty options in the native `select`.
1703
+ const hasEmptyValueOption = Array.from(nativeOptions).some(
1704
+ (option: any) => (option?.props?.value ?? '') === '',
1705
+ );
1706
+
1707
+ // Bubble value change to parents (e.g form change event)
1708
+ useEffect(
1709
+ () => {
1710
+ const select = ref.current;
1711
+ if (!select) return;
1712
+
1713
+ const selectProto = window.HTMLSelectElement.prototype;
1714
+ const descriptor = Object.getOwnPropertyDescriptor(
1715
+ selectProto,
1716
+ 'value',
1717
+ ) as PropertyDescriptor;
1718
+ const setValue = descriptor.set;
1719
+ if (prevValue !== selectValue && setValue) {
1720
+ const event = new Event('change', { bubbles: true });
1721
+ setValue.call(select, selectValue);
1722
+ select.dispatchEvent(event);
1723
+ }
1724
+ },
1725
+ [prevValue, selectValue],
1726
+ subSlot(slot, 'e:bubble'),
1727
+ );
1728
+
1729
+ // octane adaptation: React associates the default value by re-building the keyed
1730
+ // `select` with `defaultValue` each time the option set changes; octane's native-input
1731
+ // model has no defaultValue, so silently sync the `value` property once the rendered
1732
+ // options can represent it (mount + whenever the option set changes).
1733
+ useEffect(
1734
+ () => {
1735
+ const select = ref.current;
1736
+ if (select && select.value !== selectValue) {
1737
+ select.value = selectValue;
1738
+ }
1739
+ },
1740
+ [nativeSelectKey, selectValue],
1741
+ subSlot(slot, 'e:default'),
1742
+ );
1743
+
1744
+ /**
1745
+ * We purposefully use a `select` here to support form autofill as much as
1746
+ * possible.
1747
+ *
1748
+ * We purposefully do not set the `value` attribute here to allow the value
1749
+ * to be set programmatically and bubble to any parent form `onChange` event.
1750
+ *
1751
+ * We use visually hidden styles rather than `display: "none"` because
1752
+ * Safari autofill won't work otherwise.
1753
+ */
1754
+ return createElement(Primitive.select, {
1755
+ 'aria-hidden': true,
1756
+ required,
1757
+ tabIndex: -1,
1758
+ name,
1759
+ autoComplete,
1760
+ disabled,
1761
+ form,
1762
+ // React's synthetic onChange on a `<select>` is the native `change` event.
1763
+ onChange: (event: Event) => onValueChange((event.target as HTMLSelectElement).value),
1764
+ ...selectProps,
1765
+ style: { ...VISUALLY_HIDDEN_STYLES, ...selectProps.style },
1766
+ ref: composedRefs,
1767
+ // All entries keyed, no null holes (a null entry would trip octane's one-time
1768
+ // missing-key warning for array children): the placeholder option is simply
1769
+ // omitted when not needed.
1770
+ children: [
1771
+ ...(shouldShowPlaceholder(value) && !hasEmptyValueOption
1772
+ ? [createElement('option', { key: '__placeholder', value: '' })]
1773
+ : []),
1774
+ ...Array.from(nativeOptions),
1775
+ ],
1776
+ });
1777
+ }
1778
+
1779
+ /* -----------------------------------------------------------------------------------------------*/
1780
+
1781
+ function isFunction(value: unknown): value is (...args: any[]) => any {
1782
+ return typeof value === 'function';
1783
+ }
1784
+
1785
+ function shouldShowPlaceholder(value?: string): boolean {
1786
+ return value === '' || value === undefined;
1787
+ }
1788
+
1789
+ // @radix-ui/number's clamp, inlined.
1790
+ function clamp(value: number, [min, max]: [number, number]): number {
1791
+ return Math.min(max, Math.max(min, value));
1792
+ }
1793
+
1794
+ function useTypeaheadSearch(
1795
+ ...args: any[]
1796
+ ): [{ current: string }, (key: string) => void, () => void] {
1797
+ const [user, slotArg] = splitSlot(args);
1798
+ const slot = slotArg ?? S('Select.useTypeaheadSearch');
1799
+ const onSearchChange = user[0] as (search: string) => void;
1800
+ const handleSearchChange = useCallbackRef(onSearchChange, subSlot(slot, 'change'));
1801
+ const searchRef = useRef('', subSlot(slot, 'search'));
1802
+ const timerRef = useRef(0, subSlot(slot, 'timer'));
1803
+
1804
+ const handleTypeaheadSearch = useCallback(
1805
+ (key: string) => {
1806
+ const search = searchRef.current + key;
1807
+ handleSearchChange(search);
1808
+
1809
+ (function updateSearch(value: string) {
1810
+ searchRef.current = value;
1811
+ window.clearTimeout(timerRef.current);
1812
+ // Reset `searchRef` 1 second after it was last updated
1813
+ if (value !== '') timerRef.current = window.setTimeout(() => updateSearch(''), 1000);
1814
+ })(search);
1815
+ },
1816
+ [handleSearchChange],
1817
+ subSlot(slot, 'handle'),
1818
+ );
1819
+
1820
+ const resetTypeahead = useCallback(
1821
+ () => {
1822
+ searchRef.current = '';
1823
+ window.clearTimeout(timerRef.current);
1824
+ },
1825
+ [],
1826
+ subSlot(slot, 'reset'),
1827
+ );
1828
+
1829
+ useEffect(
1830
+ () => {
1831
+ return () => window.clearTimeout(timerRef.current);
1832
+ },
1833
+ [],
1834
+ subSlot(slot, 'e:timer'),
1835
+ );
1836
+
1837
+ return [searchRef, handleTypeaheadSearch, resetTypeahead];
1838
+ }
1839
+
1840
+ /**
1841
+ * This is the "meat" of the typeahead matching logic. It takes in a list of items,
1842
+ * the search and the current item, and returns the next item (or `undefined`).
1843
+ *
1844
+ * We normalize the search because if a user has repeatedly pressed a character,
1845
+ * we want the exact same behavior as if we only had that one character
1846
+ * (ie. cycle through items starting with that character)
1847
+ *
1848
+ * We also reorder the items by wrapping the array around the current item.
1849
+ * This is so we always look forward from the current item, and picking the first
1850
+ * item will always be the correct one.
1851
+ *
1852
+ * Finally, if the normalized search is exactly one character, we exclude the
1853
+ * current item from the values because otherwise it would be the first to match always
1854
+ * and focus would never move. This is as opposed to the regular case, where we
1855
+ * don't want focus to move if the current item still matches.
1856
+ */
1857
+ function findNextItem<T extends { textValue: string }>(
1858
+ items: T[],
1859
+ search: string,
1860
+ currentItem?: T,
1861
+ ): T | undefined {
1862
+ const isRepeated = search.length > 1 && Array.from(search).every((char) => char === search[0]);
1863
+ const normalizedSearch = isRepeated ? search[0]! : search;
1864
+ const currentItemIndex = currentItem ? items.indexOf(currentItem) : -1;
1865
+ let wrappedItems = wrapArray(items, Math.max(currentItemIndex, 0));
1866
+ const excludeCurrentItem = normalizedSearch.length === 1;
1867
+ if (excludeCurrentItem) wrappedItems = wrappedItems.filter((v) => v !== currentItem);
1868
+ const nextItem = wrappedItems.find((item) =>
1869
+ item.textValue.toLowerCase().startsWith(normalizedSearch.toLowerCase()),
1870
+ );
1871
+ return nextItem !== currentItem ? nextItem : undefined;
1872
+ }
1873
+
1874
+ /**
1875
+ * Wraps an array around itself at a given start index
1876
+ * Example: `wrapArray(['a', 'b', 'c', 'd'], 2) === ['c', 'd', 'a', 'b']`
1877
+ */
1878
+ function wrapArray<T>(array: T[], startIndex: number): T[] {
1879
+ return array.map<T>((_, index) => array[(startIndex + index) % array.length]!);
1880
+ }
1881
+
1882
+ export {
1883
+ Root as Select,
1884
+ Provider as SelectProvider,
1885
+ Trigger as SelectTrigger,
1886
+ Value as SelectValue,
1887
+ Icon as SelectIcon,
1888
+ Portal as SelectPortal,
1889
+ Content as SelectContent,
1890
+ Viewport as SelectViewport,
1891
+ Group as SelectGroup,
1892
+ Label as SelectLabel,
1893
+ Item as SelectItem,
1894
+ ItemText as SelectItemText,
1895
+ ItemIndicator as SelectItemIndicator,
1896
+ ScrollUpButton as SelectScrollUpButton,
1897
+ ScrollDownButton as SelectScrollDownButton,
1898
+ Separator as SelectSeparator,
1899
+ Arrow as SelectArrow,
1900
+ BubbleInput as SelectBubbleInput,
1901
+ };