/* * Copyright 2024 Adobe. All rights reserved. * This file is licensed to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ import { ListBoxSection as AriaListBoxSection, ListBox, ListBoxItem, ListBoxItemProps, ListBoxLoadMoreItem, ListBoxProps, ListBoxSectionProps } from 'react-aria-components/ListBox'; import {PopoverProps as AriaPopoverProps} from 'react-aria-components/Popover'; import { Select as AriaSelect, SelectProps as AriaSelectProps, SelectRenderProps as AriaSelectRenderProps, SelectStateContext, SelectValue } from 'react-aria-components/Select'; import { AsyncLoadable, FocusableRef, FocusableRefValue, GlobalDOMAttributes, HelpTextProps, LoadingState, PressEvent, RefObject, SpectrumLabelableProps } from '@react-types/shared'; import {AvatarContext} from './Avatar'; import {baseColor, focusRing, style} from '../style' with {type: 'macro'}; import {box, iconStyles as checkboxIconStyles} from './Checkbox'; import {Button, ButtonRenderProps} from 'react-aria-components/Button'; import {centerBaseline} from './CenterBaseline'; import { checkbox, checkmark, description, icon, iconCenterWrapper, label, loadingWrapperStyles, progressCircleStyles, sectionHeading } from './Menu'; import CheckmarkIcon from '../ui-icons/Checkmark'; import ChevronIcon from '../ui-icons/Chevron'; import {Collection} from 'react-aria/Collection'; import {ContextValue, DEFAULT_SLOT, Provider} from 'react-aria-components/slots'; import { control, controlBorderRadius, controlFont, field, fieldInput, getAllowedOverrides, StyleProps } from './style-utils' with {type: 'macro'}; import {createHideableComponent} from 'react-aria/private/collections/Hidden'; import {createShadowTreeWalker} from 'react-aria/private/utils/shadowdom/ShadowTreeWalker'; import {css} from '../style/style-macro' with {type: 'macro'}; import {Divider, listbox, listboxHeader, listboxItem, LOADER_ROW_HEIGHTS} from './ComboBox'; import {edgeToText} from '../style/spectrum-theme' with {type: 'macro'}; import {FieldErrorIcon, FieldLabel, HelpText} from './Field'; import {FormContext, useFormProps} from './Form'; import {forwardRefType} from './types'; import {getOwnerDocument} from 'react-aria/private/utils/domHelpers'; import {HeaderContext, HeadingContext, Text, TextContext} from './Content'; import {IconContext} from './Icon'; import intlMessages from '../intl/*.json'; import {isFocusable} from 'react-aria/private/utils/isFocusable'; import {ListLayout} from 'react-stately/useVirtualizerState'; import {mergeStyles} from '../style/runtime'; import {Placement} from 'react-aria-components/Popover'; import {Popover} from './Popover'; import {PressResponder} from 'react-aria/private/interactions/PressResponder'; import {pressScale} from './pressScale'; import {ProgressCircle} from './ProgressCircle'; import React, { createContext, forwardRef, ReactNode, useContext, useEffect, useMemo, useRef, useState } from 'react'; import {useFocusableRef} from './useDOMRef'; import {useGlobalListeners} from 'react-aria/private/utils/useGlobalListeners'; import {useLocale} from 'react-aria/I18nProvider'; import {useLocalizedStringFormatter} from 'react-aria/useLocalizedStringFormatter'; import {useScale} from './utils'; import {useSlotId} from 'react-aria/private/utils/useId'; import {useSpectrumContextProps} from './useSpectrumContextProps'; import {Virtualizer} from 'react-aria-components/Virtualizer'; export interface PickerStyleProps { /** * The size of the Picker. * * @default 'M' */ size?: 'S' | 'M' | 'L' | 'XL'; /** * Whether the picker should be displayed with a quiet style. */ isQuiet?: boolean; } type SelectionMode = 'single' | 'multiple'; export interface PickerProps extends Omit< AriaSelectProps, | 'children' | 'style' | 'className' | 'render' | 'allowsEmptyCollection' | keyof GlobalDOMAttributes >, PickerStyleProps, StyleProps, SpectrumLabelableProps, HelpTextProps, Pick, 'items' | 'dependencies'>, Pick, Pick { /** The contents of the collection. */ children: ReactNode | ((item: T) => ReactNode); /** * Direction the menu will render relative to the Picker. * * @default 'bottom' */ direction?: 'bottom' | 'top'; /** * Alignment of the menu relative to the input target. * * @default 'start' */ align?: 'start' | 'end'; /** * Width of the menu. By default, matches width of the trigger. Note that the minimum width of the * dropdown is always equal to the trigger's width. */ menuWidth?: number; /** The current loading state of the Picker. */ loadingState?: LoadingState; /** * Custom renderer for the picker value. Allows one to provide a custom element to render selected * items. * * @note The returned ReactNode should not have interactable elements as it will break accessibility. */ renderValue?: (selectedItems: T[]) => ReactNode; } interface PickerButtonProps extends PickerStyleProps, ButtonRenderProps {} export const PickerContext = createContext>, FocusableRefValue>>( null ); const inputButton = style({ ...focusRing(), ...control({shape: 'default', icon: true}), ...fieldInput(), outlineStyle: { default: 'none', isFocusVisible: 'solid', isQuiet: 'none' }, position: 'relative', textAlign: 'start', borderStyle: { default: 'none', forcedColors: 'solid' }, borderColor: { forcedColors: { default: 'ButtonText', isDisabled: 'GrayText' } }, transition: 'default', paddingX: { default: 'edge-to-text', isQuiet: 0 }, backgroundColor: { default: baseColor('gray-100'), isOpen: 'gray-200', isDisabled: 'disabled', isQuiet: 'transparent' }, color: { default: baseColor('neutral'), isDisabled: 'disabled' }, maxWidth: { isQuiet: 'max' }, disableTapHighlight: true }); const quietFocusLine = style({ width: 'full', // Use pixels since we are emulating a border. height: '[2px]', position: 'absolute', bottom: 0, borderRadius: 'full', backgroundColor: { default: 'blue-800', forcedColors: 'Highlight' } }); export let menu = style({ outlineStyle: 'none', display: 'grid', width: 'full', gridTemplateColumns: { size: { S: [edgeToText(24), 'auto', 'auto', 'minmax(0, 1fr)', 'auto', 'auto', 'auto', edgeToText(24)], M: [edgeToText(32), 'auto', 'auto', 'minmax(0, 1fr)', 'auto', 'auto', 'auto', edgeToText(32)], L: [edgeToText(40), 'auto', 'auto', 'minmax(0, 1fr)', 'auto', 'auto', 'auto', edgeToText(40)], XL: [edgeToText(48), 'auto', 'auto', 'minmax(0, 1fr)', 'auto', 'auto', 'auto', edgeToText(48)] } }, boxSizing: 'border-box', maxHeight: 'inherit', overflow: 'auto', padding: 8, fontFamily: 'sans', fontSize: controlFont(), gridAutoRows: 'min-content' }); const invalidBorder = style({ ...controlBorderRadius(), position: 'absolute', top: 0, left: 0, bottom: 0, right: 0, pointerEvents: 'none', borderStyle: 'solid', borderWidth: 2, borderColor: baseColor('negative'), transition: 'default' }); const valueStyles = style({ flexGrow: { default: 1, isQuiet: 0 }, truncate: true, display: 'flex', alignItems: 'center', height: '100%' }); const iconStyles = style({ flexShrink: 0, rotate: 90, '--iconPrimary': { type: 'fill', value: 'currentColor' }, color: { isLoading: 'disabled' } }); const avatar = style({ gridArea: 'icon', marginEnd: 'text-to-visual' }); let InternalPickerContext = createContext<{size: 'S' | 'M' | 'L' | 'XL'}>({size: 'M'}); let InsideSelectValueContext = createContext(false); /** * Pickers allow users to choose a single option from a collapsible list of options when space is * limited. */ export const Picker = /*#__PURE__*/ (forwardRef as forwardRefType)(function Picker< T, M extends SelectionMode = 'single' >(props: PickerProps, ref: FocusableRef) { let stringFormatter = useLocalizedStringFormatter(intlMessages, '@react-spectrum/s2'); [props, ref] = useSpectrumContextProps(props, ref, PickerContext); let domRef = useFocusableRef(ref); let formContext = useContext(FormContext); props = useFormProps(props); let { direction = 'bottom', align = 'start', shouldFlip = true, menuWidth, label, description: descriptionMessage, errorMessage, children, items, size = 'M', labelPosition = 'top', labelAlign = 'start', necessityIndicator, UNSAFE_className = '', UNSAFE_style, placeholder = stringFormatter.format('picker.placeholder'), isQuiet, loadingState, renderValue, onLoadMore, ...pickerProps } = props; // Better way to encode this into a style? need to account for flipping let menuOffset: number; if (size === 'S') { menuOffset = 6; } else if (size === 'M') { menuOffset = 6; } else if (size === 'L') { menuOffset = 7; } else { menuOffset = 8; } let renderer; let showButtonSpinner = useMemo(() => loadingState === 'loading', [loadingState]); let spinnerId = useSlotId([showButtonSpinner]); let listBoxLoadingCircle = ( ); if (typeof children === 'function' && items) { renderer = ( <> {children} {listBoxLoadingCircle} ); } else { renderer = ( <> {children} {listBoxLoadingCircle} ); } let scale = useScale(); let {direction: dir} = useLocale(); let RTLFlipOffset = dir === 'rtl' ? -1 : 1; return ( {({isDisabled, isOpen, isFocusVisible, isInvalid, isRequired}) => ( <> {label} } /> {errorMessage}
{renderer}
)}
); }); function PickerProgressCircle(props) { let {id, 'aria-label': ariaLabel} = props; return ( ); } const avatarSize = { S: 16, M: 20, L: 22, XL: 26 } as const; // https://w3c.github.io/aria/#widget_roles let INTERACTIVE_ARIA_ROLES = new Set([ 'application', 'button', 'checkbox', 'combobox', 'gridcell', 'link', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'radio', 'searchbox', 'separator', 'slider', 'spinbutton', 'switch', 'tab', 'textbox', 'treeitem' ]); interface PickerButtonInnerProps extends PickerStyleProps, Omit, Pick, 'loadingState' | 'renderValue'> { loadingCircle: ReactNode; buttonRef: RefObject; } // Needs to be hidable component or otherwise the PressResponder throws a warning when rendered in the fake DOM and tries to register const PickerButton = createHideableComponent(function PickerButton( props: PickerButtonInnerProps ) { let { isOpen, isQuiet, isFocusVisible, size, isInvalid, isDisabled, loadingState, loadingCircle, buttonRef, renderValue } = props; let stringFormatter = useLocalizedStringFormatter(intlMessages, '@react-spectrum/s2'); let renderValueRef = useRef(null); let state = useContext(SelectStateContext)!; useEffect(() => { if (process.env.NODE_ENV === 'production' || !renderValue) { return; } if (!renderValueRef.current) { return; } let doc = getOwnerDocument(renderValueRef.current); let walker = createShadowTreeWalker(doc, renderValueRef.current, NodeFilter.SHOW_ELEMENT, { acceptNode(node: Element) { let role = node.getAttribute('role'); let interactive = isFocusable(node) || (role != null && INTERACTIVE_ARIA_ROLES.has(role)); return interactive ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; } }); let next = walker.nextNode(); if (next) { console.warn("Picker's value should not have interactive children for accessibility."); } }, [state.selectedItems, renderValue]); // For mouse interactions, pickers open on press start. When the popover underlay appears // it covers the trigger button, causing onPressEnd to fire immediately and no press scaling // to occur. We override this by listening for pointerup on the document ourselves. let [isPressed, setPressed] = useState(false); let {addGlobalListener} = useGlobalListeners(); let onPressStart = (e: PressEvent) => { if (e.pointerType !== 'mouse') { return; } setPressed(true); addGlobalListener( document, 'pointerup', () => { setPressed(false); }, {once: true, capture: true} ); }; return ( ); }); export interface PickerItemProps extends Omit< ListBoxItemProps, 'children' | 'style' | 'className' | 'render' | 'onClick' | keyof GlobalDOMAttributes >, StyleProps { children: ReactNode; } const checkmarkIconSize = { S: 'XS', M: 'M', L: 'L', XL: 'XL' } as const; export function PickerItem(props: PickerItemProps): ReactNode { let ref = useRef(null); let isLink = props.href != null; let {size} = useContext(InternalPickerContext); // oxlint-disable react/react-compiler return ( (props.UNSAFE_className || '') + listboxItem({...renderProps, size, isLink}, props.styles) }> {renderProps => { let {children} = props; let checkboxRenderProps = { ...renderProps, size, isFocused: false, isFocusVisible: false, isIndeterminate: false, isReadOnly: false, isInvalid: false, isRequired: false }; return ( {renderProps.selectionMode === 'single' && !isLink && ( )} {renderProps.selectionMode === 'multiple' && !isLink && (
)} {typeof children === 'string' ? {children} : children}
); }}
); // oxlint-enable react/react-compiler } // A Context.Provider that only sets a value if not inside SelectValue. function DefaultProvider({ context, value, children }: { context: React.Context; value: any; children: any; }) { let inSelectValue = useContext(InsideSelectValueContext); if (inSelectValue) { return children; } return {children}; } export interface PickerSectionProps extends Omit< ListBoxSectionProps, 'style' | 'className' | 'render' | keyof GlobalDOMAttributes > {} export function PickerSection(props: PickerSectionProps): ReactNode { let {size} = useContext(InternalPickerContext); return ( <> {props.children} ); }