import { Adapt, AdaptParent, useAdaptIsActive } from '@tamagui/adapt' import { useComposedRefs } from '@tamagui/compose-refs' import { isWeb, useIsomorphicLayoutEffect } from '@tamagui/constants' import type { GetProps } from '@tamagui/core' import { createChangeEventDetails, createStyledHOC, createStyledContext, styled, Text, View, } from '@tamagui/core' import { FocusScopeController } from '@tamagui/focus-scope' import { registerFocusable } from '@tamagui/focusable' import { withStaticProperties } from '@tamagui/helpers' import { useControllableState } from '@tamagui/use-controllable-state' import type { ControllableStateSetter } from '@tamagui/use-controllable-state' import * as React from 'react' import { SelectItemParentProvider, SelectNativeComponentContext, SelectProvider, SelectZIndexContext, useSelectContext, useSelectItemParentContext, } from './context' import { SelectContent } from './SelectContent' import { SelectInlineImpl } from './SelectImpl' import { SelectItem, useSelectItemContext } from './SelectItem' import { SelectItemText } from './SelectItemText' import { SelectScrollDownButton, SelectScrollUpButton } from './SelectScrollButton' import { SelectTrigger } from './SelectTrigger' import { SelectViewport } from './SelectViewport' import { createSelectItemRegistry, createSelectSelectionController, selectedValuesFromSelection, type SelectMode, type SelectSelection, } from './selectionController' import type { SelectActiveChangeDetails, SelectImplProps, SelectOpenChangeDetails, SelectProps, SelectScopedProps, SelectValueForMode, SelectValueChangeDetails, } from './types' export type SelectValue< Value extends string = string, Multiple extends boolean | undefined = false, > = SelectValueForMode /* ------------------------------------------------------------------------------------------------- * SelectValue * -----------------------------------------------------------------------------------------------*/ const VALUE_NAME = 'SelectValue' export const SelectValueFrame = styled(Text, { displayName: VALUE_NAME, }) export type SelectValueExtraProps = SelectScopedProps<{ placeholder?: React.ReactNode }> export type SelectValueProps = GetProps & SelectValueExtraProps export const SelectValue = createStyledHOC( SelectValueFrame, function SelectValue(propsIn: SelectValueExtraProps, forwardedRef) { const { scope, children: childrenProp, placeholder, ...props }: SelectValueProps = propsIn // We ignore `className` and `style` as this part shouldn't be styled. const context = useSelectContext(scope) const itemParentContext = useSelectItemParentContext(scope) const composedRefs = useComposedRefs( // @ts-ignore react 19 ref type mismatch forwardedRef, context.onValueNodeChange as any ) const isEmptyValue = context.selectedValues.length === 0 // the label comes from the registry, which items fill in after mount and // outside any context value, so this is the one registry subscriber const [, rerender] = React.useReducer((version: number) => version + 1, 0) useIsomorphicLayoutEffect( () => itemParentContext.registry.subscribe(rerender), [itemParentContext.registry] ) // renderValue is synchronous for ssr and lazy item mounting const registeredValue = context.mode === 'multiple' ? context.selectedValues.map((value, index) => ( {index > 0 ? ', ' : null} {itemParentContext.registry.getItem(value)?.label ?? value} )) : (itemParentContext.registry.getItem(context.selectedValues[0])?.label ?? context.value) const children = childrenProp !== undefined ? childrenProp : context.renderValue ? context.renderValue(context.value) : registeredValue const selectValueChildren = isEmptyValue ? (placeholder ?? children) : children return ( {selectValueChildren} ) } ) /* ------------------------------------------------------------------------------------------------- * SelectIcon * -----------------------------------------------------------------------------------------------*/ export const SelectIcon = styled(View, { displayName: 'SelectIcon', // @ts-ignore 'aria-hidden': true, }) /* ------------------------------------------------------------------------------------------------- * SelectItemIndicator * -----------------------------------------------------------------------------------------------*/ export const SelectItemIndicatorFrame = styled(View, { displayName: 'SelectItemIndicator', }) export type SelectItemIndicatorProps = SelectScopedProps< GetProps > export const SelectItemIndicator = createStyledHOC( SelectItemIndicatorFrame, function SelectItemIndicator( props: { scope?: string }, forwardedRef ) { const { scope, ...itemIndicatorProps } = props const context = useSelectItemParentContext(scope) const itemContext = useSelectItemContext(scope) if (context.shouldRenderWebNative) { return null } return itemContext.isSelected ? ( ) : null } ) /* ------------------------------------------------------------------------------------------------- * SelectIndicator * -----------------------------------------------------------------------------------------------*/ export const SelectIndicatorFrame = styled(View, { displayName: 'SelectIndicator', position: 'absolute', top: 0, left: 0, pointerEvents: 'none', zIndex: 10, }) export type SelectIndicatorProps = GetProps export const SelectIndicator = createStyledHOC( SelectIndicatorFrame, function SelectIndicator(propsIn: SelectScopedProps<{}>, forwardedRef) { const { scope, ...props }: SelectScopedProps = propsIn const itemContext = useSelectItemParentContext(scope) const context = useSelectContext(scope) const [layout, setLayout] = React.useState(null) const rafRef = React.useRef(0) useIsomorphicLayoutEffect(() => { const update = (index: number | null) => { if (typeof index !== 'number') return cancelAnimationFrame(rafRef.current) rafRef.current = requestAnimationFrame(() => { const node = itemContext.listRef?.current?.[index] if (node) { setLayout({ width: Math.round(node.offsetWidth), height: Math.round(node.offsetHeight), x: Math.round(node.offsetLeft), y: Math.round(node.offsetTop), }) } }) } // use ref for initial read to avoid depending on state if (context.open && context.activeIndexRef.current !== null) { update(context.activeIndexRef.current) } return itemContext.activeIndexSubscribe(update) }, [context.open, itemContext.listRef]) if (!layout) return null return ( ) } ) /* ------------------------------------------------------------------------------------------------- * SelectGroup * -----------------------------------------------------------------------------------------------*/ const GROUP_NAME = 'SelectGroup' type SelectGroupContextValue = { id: string } const { Provider: SelectGroupContextProvider, useStyledContext: useSelectGroupContext } = createStyledContext({ id: '' }, 'SelectGroup') export const SelectGroupFrame = styled(View, { displayName: GROUP_NAME, }) const NativeSelectFrame = styled(Text, { displayName: 'NativeSelect', render: 'select', }) const NativeSelect = NativeSelectFrame as any type SelectGroupProps = SelectScopedProps> export const SelectGroup = createStyledHOC( SelectGroupFrame, (propsIn: SelectScopedProps<{}>, forwardedRef) => { const props: SelectGroupProps = propsIn const { scope, ...groupProps } = props const groupId = React.useId() const context = useSelectContext(scope) const itemParentContext = useSelectItemParentContext(scope) const StyledNativeSelect = React.useContext(SelectNativeComponentContext) const nativeSelectRef = React.useRef(null) const content = (() => { if (itemParentContext.shouldRenderWebNative) { return ( ) => { const value = context.mode === 'multiple' ? Array.from( event.currentTarget.selectedOptions, (option) => option.value ) : event.currentTarget.value itemParentContext.changeNativeValue(value, event.nativeEvent) }) as any } ref={nativeSelectRef as any} > {props.children} ) } return ( ) })() return ( {content} ) } ) SelectGroup.displayName = GROUP_NAME /* ------------------------------------------------------------------------------------------------- * SelectLabel * -----------------------------------------------------------------------------------------------*/ const LABEL_NAME = 'SelectLabel' export const SelectLabelFrame = styled(Text, { displayName: LABEL_NAME, }) export type SelectLabelProps = SelectScopedProps> export const SelectLabel = createStyledHOC( SelectLabelFrame, (propsIn: SelectScopedProps<{}>, forwardedRef) => { const props: SelectLabelProps = propsIn const { scope, ...labelProps } = props const context = useSelectItemParentContext(scope) const groupContext = useSelectGroupContext(scope) if (context.shouldRenderWebNative) { return null } return ( ) } ) /* ------------------------------------------------------------------------------------------------- * SelectSeparator * -----------------------------------------------------------------------------------------------*/ export const SelectSeparator = styled(View, { displayName: 'SelectSeparator', }) const SelectSheetImpl = (props: SelectImplProps) => { return <>{props.children} } /* ------------------------------------------------------------------------------------------------- * Select * -----------------------------------------------------------------------------------------------*/ export function SelectRoot< Value extends string = string, Multiple extends boolean | undefined = false, >(props: SelectScopedProps>) { const adaptScope = `AdaptSelect${props.scope || ''}` // open state lives here (above AdaptParent) so the Adapt handoff can drive // the adapted Sheet's open/close and unmount timing directly, mirroring Dialog const [open, requestOpenChange] = useControllableState< boolean, SelectOpenChangeDetails >({ prop: props.open, defaultProp: props.defaultOpen || false, onChange: props.onOpenChange as any, }) const handleAdaptOpenChange = React.useCallback( (nextOpen: boolean) => { requestOpenChange( nextOpen, createChangeEventDetails( nextOpen ? 'trigger-press' : 'outside-press' ) as SelectOpenChangeDetails ) }, [requestOpenChange] ) return ( >)} scope={props.scope} adaptScope={adaptScope} open={open} requestOpenChange={requestOpenChange} /> ) } export const Select = withStaticProperties(SelectRoot, { Root: SelectRoot, Adapt: Adapt, Content: SelectContent, Group: SelectGroup, Icon: SelectIcon, Item: SelectItem, ItemIndicator: SelectItemIndicator, ItemText: SelectItemText, Label: SelectLabel, ScrollDownButton: SelectScrollDownButton, ScrollUpButton: SelectScrollUpButton, Separator: SelectSeparator, Trigger: SelectTrigger, Value: SelectValue, Viewport: SelectViewport, Indicator: SelectIndicator, FocusScope: FocusScopeController, }) function useEmitter() { const listenersRef = React.useRef>(new Set()) const emit = React.useCallback((value: A) => { listenersRef.current.forEach((l) => l(value)) }, []) const subscribe = React.useCallback((listener: (val: A) => void) => { listenersRef.current.add(listener) return () => { listenersRef.current.delete(listener) } }, []) return [emit, subscribe] as const } function SelectInner( props: SelectScopedProps> & { adaptScope: string open: boolean requestOpenChange: ControllableStateSetter } ) { const { scope = '', adaptScope, native, children, open, requestOpenChange, defaultOpen: _defaultOpen, onOpenChange: _onOpenChange, value: valueProp, defaultValue, onValueChange, multiple = false, name, form, disablePreventBodyScroll, size: sizeProp = true, onActiveChange, dir, id, renderValue, lazyMount, zIndex, } = props const isAdapted = useAdaptIsActive(adaptScope) const SelectImpl = isAdapted ? SelectSheetImpl : SelectInlineImpl const mode: SelectMode = multiple ? 'multiple' : 'single' const [valueState, requestValueChange] = useControllableState< SelectSelection, SelectValueChangeDetails >({ prop: valueProp as SelectSelection | undefined, defaultProp: (defaultValue ?? (mode === 'multiple' ? [] : '')) as SelectSelection, onChange: onValueChange as any, transition: true, }) const value = React.useMemo( () => mode === 'multiple' ? selectedValuesFromSelection(mode, valueState) : typeof valueState === 'string' ? valueState : '', [mode, valueState] ) const selectedValues = React.useMemo( () => selectedValuesFromSelection(mode, value), [mode, value] ) const [, rerenderRegistry] = React.useReducer((version) => version + 1, 0) const registryRef = React.useRef | null>( null ) if (!registryRef.current) { registryRef.current = createSelectItemRegistry(rerenderRegistry) } const registry = registryRef.current const controllerRef = React.useRef | null>(null) if (!controllerRef.current) { controllerRef.current = createSelectSelectionController({ mode, value, registry, }) } const controller = controllerRef.current controller.setMode(mode) controller.setValue(value) React.useEffect(() => { if (process.env.TAMAGUI_TARGET !== 'native' || !props.id) return return registerFocusable(props.id, { focusAndSelect: () => { requestOpenChange( (current) => !current, createChangeEventDetails('trigger-press') as SelectOpenChangeDetails ) }, focus: () => {}, }) }, [props.id, requestOpenChange]) // the active index is a ref plus an emitter, never React state: hover and // arrow keys must not re-render the list. an item that has to react (focus, // the roving tabindex) subscribes and updates only itself. // null until first open so floating-ui starts from selectedIndex const activeIndexRef = React.useRef(null) const [emitActiveIndex, activeIndexSubscribe] = useEmitter() const selectedIndexRef = React.useRef(null) // a focus-driven scroll makes the browser re-dispatch mousemove under a // pointer that never moved; items compare against this to ignore it const lastPointerRef = React.useRef({ x: -1, y: -1 }) const listContentRef = React.useRef([]) const listRef = React.useRef>([]) const [valueNode, setValueNode] = React.useState(null) const selectedIndex = Math.max(0, controller.selectionAnchorIndex()) listContentRef.current = registry.getTypeaheadLabels() // the registry re-renders this on every registration and node change, so // the list ref (floating-ui's focus target array) mirrors it here const itemNodes = registry.getNodes() listRef.current.length = itemNodes.length for (let i = 0; i < itemNodes.length; i++) listRef.current[i] = itemNodes[i] // Intentionally dependency-less: selectedIndexRef mirrors every render for non-reactive reads. useIsomorphicLayoutEffect(() => { selectedIndexRef.current = selectedIndex }) const shouldRenderWebNative = isWeb && (native === true || native === 'web' || (Array.isArray(native) && native.includes('web'))) const setActiveIndex = React.useCallback( (index: number | null, details?: SelectActiveChangeDetails) => { if (activeIndexRef.current === index) return activeIndexRef.current = index controller.setActiveIndex(index) emitActiveIndex(index) if (typeof index === 'number') { const item = registry.getItems()[index] if (item && details) { onActiveChange?.(item.value, details) } } }, [controller, emitActiveIndex, onActiveChange, registry] ) const activeDetails = React.useCallback( ( reason: SelectActiveChangeDetails['reason'], index: number, event?: unknown ): SelectActiveChangeDetails => ({ reason, event, trigger: undefined, index, }), [] ) const moveActive = React.useCallback( (direction: 1 | -1, event?: unknown) => { const nextIndex = registry.nextEnabledIndex(activeIndexRef.current, direction) if (nextIndex >= 0) { setActiveIndex(nextIndex, activeDetails('keyboard', nextIndex, event)) } }, [activeDetails, registry, setActiveIndex] ) const typeaheadRef = React.useRef({ text: '', timeout: null as any }) const search = React.useCallback( (text: string, event?: unknown) => { clearTimeout(typeaheadRef.current.timeout) typeaheadRef.current.text += text let nextIndex = registry.findTypeaheadIndex( typeaheadRef.current.text, activeIndexRef.current ) if (nextIndex < 0 && typeaheadRef.current.text.length > 1) { typeaheadRef.current.text = text nextIndex = registry.findTypeaheadIndex(text, activeIndexRef.current) } typeaheadRef.current.timeout = setTimeout(() => { typeaheadRef.current.text = '' }, 750) if (nextIndex >= 0) { setActiveIndex(nextIndex, activeDetails('keyboard', nextIndex, event)) } }, [activeDetails, registry, setActiveIndex] ) React.useEffect(() => { return () => clearTimeout(typeaheadRef.current.timeout) }, []) React.useEffect(() => { if (open) { const nextIndex = controller.initialActiveIndex() if (nextIndex >= 0) { setActiveIndex(nextIndex, activeDetails('list-navigation', nextIndex)) } } else { setActiveIndex(null) } }, [open, selectedIndex, registry.getItems().length]) const selectValue = React.useCallback( (nextItemValue: string, details: SelectValueChangeDetails) => { const item = registry.getItem(nextItemValue) if (!item || item.disabled) return controller.setMode(mode) controller.setValue(value) const previousValue = controller.value const nextValue = controller.toggle(nextItemValue) requestValueChange(nextValue, details) if (details.isCanceled) { controller.setValue(previousValue) return } if (controller.shouldCloseOnSelect) { requestOpenChange( false, createChangeEventDetails( details.reason === 'keyboard' ? 'keyboard' : 'item-press', details.event, details.trigger ) as SelectOpenChangeDetails ) } }, [controller, mode, registry, requestOpenChange, requestValueChange, value] ) const changeNativeValue = React.useCallback( (nextValue: SelectSelection, event: unknown) => { const details = createChangeEventDetails( 'native-change', event ) as SelectValueChangeDetails requestValueChange(nextValue, details) if (!details.isCanceled) { controller.setValue(nextValue) } }, [controller, requestValueChange] ) const content = ( {shouldRenderWebNative ? ( children ) : ( {children} )} {isWeb && !shouldRenderWebNative && name ? (mode === 'multiple' ? selectedValues : [value as string]).map((inputValue) => ( )) : null} ) if (zIndex !== undefined) { return ( {content} ) } return content }