diff --git a/packages/react/src/ActionList/TrailingAction.tsx b/packages/react/src/ActionList/TrailingAction.tsx index df3d898593c..3af8a4a9710 100644 --- a/packages/react/src/ActionList/TrailingAction.tsx +++ b/packages/react/src/ActionList/TrailingAction.tsx @@ -1,10 +1,11 @@ import type React from 'react' -import {forwardRef} from 'react' +import {forwardRef, useContext} from 'react' import {Button, IconButton} from '../Button' import type {IconButtonProps} from '../Button/types' import type {ForwardRefComponent as PolymorphicForwardRefComponent} from '../utils/polymorphic' import {clsx} from 'clsx' import classes from './ActionList.module.css' +import {ActionListContainerContext} from './ActionListContainerContext' type ElementProps = | { @@ -34,6 +35,17 @@ export const TrailingAction = forwardRef( {as = 'button', icon, label, href = null, className, style, loading, tooltipDirection = 'w', ...props}, forwardedRef, ) => { + // Use context from ActionList + const {selectionVariant} = useContext(ActionListContainerContext) + // TODO: Rename + const withinMenu = selectionVariant === 'single' || selectionVariant === 'multiple' + + if (withinMenu) { + console.log( + 'Warning: ActionList.TrailingAction should not be used within selectable ActionLists. Please remove it to avoid unexpected behavior.', + ) + } + return ( ) : ( @@ -66,6 +80,7 @@ export const TrailingAction = forwardRef( data-has-label="true" ref={forwardedRef} className={classes.TrailingActionButton} + aria-hidden={withinMenu ? 'true' : undefined} {...props} > {label} diff --git a/packages/react/src/AnchoredOverlay/AnchoredOverlay.test.tsx b/packages/react/src/AnchoredOverlay/AnchoredOverlay.test.tsx index 80bbb333846..4d6a77262f3 100644 --- a/packages/react/src/AnchoredOverlay/AnchoredOverlay.test.tsx +++ b/packages/react/src/AnchoredOverlay/AnchoredOverlay.test.tsx @@ -403,6 +403,31 @@ describe('AnchoredOverlay feature flag specific behavior', () => { expect(anchor!.getAttribute('popovertarget')).toBe(overlay!.getAttribute('id')) }) + it('preserves a consumer ID for the popover and its invoker target', async () => { + render( + + + } + > + + + + , + ) + const dialog = page.getByRole('dialog', {name: 'Custom popover', exact: true}) + await expect.element(dialog).toBeVisible() + expect(dialog.element()).toHaveAttribute('id', 'consumer.popover') + expect(page.getByRole('button', {name: 'Custom anchor', exact: true}).element()).toHaveAttribute( + 'popovertarget', + 'consumer.popover', + ) + expect(dialog.element().matches(':popover-open')).toBe(true) + }) + it('should not set popover attribute on overlay when renderAs is "portal"', () => { const {baseElement} = render( diff --git a/packages/react/src/AnchoredOverlay/AnchoredOverlay.tsx b/packages/react/src/AnchoredOverlay/AnchoredOverlay.tsx index 93741b30be9..3b9e0a368f7 100644 --- a/packages/react/src/AnchoredOverlay/AnchoredOverlay.tsx +++ b/packages/react/src/AnchoredOverlay/AnchoredOverlay.tsx @@ -293,10 +293,11 @@ export const AnchoredOverlay: React.FC= 19 - ? {popoverTarget: popoverId} - : {popovertarget: popoverId} + ? {popoverTarget: overlayId} + : {popovertarget: overlayId} : {} const id = popoverId.replaceAll(':', '_') // popoverId can contain colons which are invalid in CSS custom property names, so we replace them with underscores const anchorName = `--anchored-overlay-anchor-${id}` @@ -396,7 +397,9 @@ export const AnchoredOverlay: React.FC mergedOverlayRef(node)} data-anchor-position={cssAnchorPositioning} data-side={cssAnchorPositioning ? side : position?.anchorSide} diff --git a/packages/react/src/FeatureFlags/DefaultFeatureFlags.ts b/packages/react/src/FeatureFlags/DefaultFeatureFlags.ts index efdd1b66922..b7285bfa21f 100644 --- a/packages/react/src/FeatureFlags/DefaultFeatureFlags.ts +++ b/packages/react/src/FeatureFlags/DefaultFeatureFlags.ts @@ -2,6 +2,9 @@ import {FeatureFlagScope} from './FeatureFlagScope' export const DefaultFeatureFlags = FeatureFlagScope.create({ primer_react_css_anchor_positioning: false, + primer_react_select_panel_composable_adapter: false, + primer_react_select_panel_native_dialog: false, + primer_react_select_panel_native_invokers: false, primer_react_select_panel_fullscreen_on_narrow: false, primer_react_select_panel_legacy_contrast: false, primer_react_select_panel_order_selected_at_top: false, diff --git a/packages/react/src/FilteredActionList/FilteredActionList.tsx b/packages/react/src/FilteredActionList/FilteredActionList.tsx index 1446cd8eb38..66ed2b9e895 100644 --- a/packages/react/src/FilteredActionList/FilteredActionList.tsx +++ b/packages/react/src/FilteredActionList/FilteredActionList.tsx @@ -1,136 +1,50 @@ -import type {ScrollIntoViewOptions} from '@primer/behaviors' +/** Behaviors */ import {scrollIntoView, FocusKeys} from '@primer/behaviors' import type {KeyboardEventHandler, JSX} from 'react' import type React from 'react' -import {forwardRef, useCallback, useEffect, useMemo, useRef, useState} from 'react' -import type {TextInputProps} from '../TextInput' +import {useCallback, useEffect, useMemo, useRef, useState} from 'react' import {ActionList, type ActionListProps} from '../ActionList' -import type {GroupedListProps, ListPropsBase, ItemInput, RenderItemFn} from './' +import type {FilteredActionListProps, ItemInput} from './types' import {useFocusZone} from '../hooks/useFocusZone' import {useId} from '../hooks/useId' import {useProvidedStateOrCreate} from '../hooks/useProvidedStateOrCreate' import useScrollFlash from '../hooks/useScrollFlash' import {VisuallyHidden} from '../VisuallyHidden' -import type {FilteredActionListLoadingType} from './FilteredActionListLoaders' import {FilteredActionListLoadingTypes, FilteredActionListBodyLoader} from './FilteredActionListLoaders' import classes from './FilteredActionList.module.css' import Checkbox from '../Checkbox' import {ActionListContainerContext} from '../ActionList/ActionListContainerContext' -import {isValidElementType} from 'react-is' import {useAnnouncements} from './useAnnouncements' import {clsx} from 'clsx' import {useVirtualizer} from '@tanstack/react-virtual' import {useMergedRefs} from '../hooks' -import {FilteredActionListInput} from './FilteredActionListInput' - -const menuScrollMargins: ScrollIntoViewOptions = {startMargin: 0, endMargin: 8} - -export interface FilteredActionListProps extends Partial>, ListPropsBase { - loading?: boolean - loadingType?: FilteredActionListLoadingType - placeholderText?: string - filterValue?: string - onFilterChange: (value: string, e: React.ChangeEvent | null) => void - onListContainerRefChanged?: (ref: HTMLElement | null) => void - onInputRefChanged?: (ref: React.RefObject) => void - /** - * A ref assigned to the scrollable container wrapping the ActionList - */ - scrollContainerRef?: React.Ref - textInputProps?: Partial> - inputRef?: React.RefObject - message?: React.ReactNode - messageText?: { - title: string - description: string - } - className?: string - announcementsEnabled?: boolean - fullScreenOnNarrow?: boolean - onSelectAllChange?: (checked: boolean) => void - /** - * Additional props to pass to the underlying ActionList component. - */ - actionListProps?: Partial - /** - * Determines how keyboard focus behaves when navigating beyond the first or last item in the list. - * - * - `'stop'`: Focus will stop at the first or last item; further navigation in that direction will not move focus. - * - `'wrap'`: Focus will wrap around to the opposite end of the list when navigating past the boundaries (e.g., pressing Down on the last item moves focus to the first). - * - * @default 'wrap' - */ - focusOutBehavior?: 'stop' | 'wrap' - /** - * Callback function that is called when the active descendant changes. - * - * @param newActiveDescendant - The new active descendant element. - * @param previousActiveDescendant - The previous active descendant element. - * @param directlyActivated - Whether the active descendant was directly activated (e.g., by a keyboard event). - */ - onActiveDescendantChanged?: ( - newActiveDescendant: HTMLElement | undefined, - previousActiveDescendant: HTMLElement | undefined, - directlyActivated: boolean, - ) => void - /** - * Private API for use internally only. Adds the ability to switch between - * `active-descendant` and roving tabindex. - * - * By default, FilteredActionList uses `aria-activedescendant` to manage focus. - * - * Roving tabindex is an alternative focus management method that moves - * focus to the list items themselves instead of keeping focus on the input. - * - * Improper usage can lead to inaccessible experiences, so this prop should be used with caution. - * - * For usage, refer to the documentation: - * - * WAI-ARIA `aria-activedescendant`: https://www.w3.org/TR/wai-aria-1.2/#aria-activedescendant - * - * Roving Tabindex: https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/#kbd_roving_tabindex - * - * @default 'active-descendant' - */ - _PrivateFocusManagement?: 'roving-tabindex' | 'active-descendant' - /** - * If true, disables selecting items when hovering over them with the mouse. - */ - disableSelectOnHover?: boolean - /** - * If true, focus remains where it was and the user must interact to move focus. - * If false, sets initial focus to the first item in the list when rendered, enabling keyboard navigation immediately. - */ - setInitialFocus?: boolean - /** - * Set to true to allow focus to move to elements that are dynamically prepended to the container. - * Default is false. - */ - focusPrependedElements?: boolean - /** - * Determines the scroll behavior of the container when an item is focused. - * - * @default 'auto' - */ - scrollBehavior?: ScrollBehavior - /** - * If true, enables client-side list virtualization. Only the visible items (plus a small - * overscan buffer) are rendered in the DOM, dramatically improving performance for large lists. - * - * This is a purely client-side optimization — it does not require server-side pagination. - * The consumer can still pass all items at once; the component will only render what is visible. - * - * Recommended for lists with more than 100 items. - * - * Note: Has no effect when `groupMetadata` is provided, as grouped lists are - * typically small enough not to need virtualization. - * - * @default false - */ - virtualized?: boolean +import {FilteredActionListInput, type FilteredActionListInputProps} from './FilteredActionListInput' + +import {MappedActionListItem} from './components/MappedActionListItem' +import {menuScrollMargins} from './utils' +import {activateDescendant} from '../internal/hooks/useListboxFocus' + +export type {FilteredActionListProps} from './types' + +interface FilteredActionListRenderers { + Input?: React.ComponentType + List?: React.ComponentType & React.RefAttributes> + Item?: typeof MappedActionListItem +} + +function getDefaultItemKey(item: ItemInput, index: number) { + return item.id?.toString() ?? index.toString() +} + +export function FilteredActionList(props: FilteredActionListProps): JSX.Element { + return } -export function FilteredActionList({ +// Share the compatibility behavior without requiring its configured renderer. +export function FilteredActionListContent({ + components, + getItemKey = getDefaultItemKey, + componentName = 'FilteredActionList', loading = false, placeholderText, filterValue: externalFilterValue, @@ -161,7 +75,14 @@ export function FilteredActionList({ scrollBehavior, virtualized = false, ...listProps -}: FilteredActionListProps): JSX.Element { +}: FilteredActionListProps & { + components?: FilteredActionListRenderers + getItemKey?: (item: ItemInput, index: number) => string + componentName?: 'FilteredActionList' | 'SelectPanel.Collection' +}): JSX.Element { + const Input = components?.Input ?? FilteredActionListInput + const List = components?.List ?? ActionList + const Item = components?.Item ?? MappedActionListItem if (__DEV__) { if (virtualized && groupMetadata?.length) { // eslint-disable-next-line no-console @@ -177,6 +98,7 @@ export function FilteredActionList({ const isVirtualized = virtualized && !groupMetadata?.length const [filterValue, setInternalFilterValue] = useProvidedStateOrCreate(externalFilterValue, undefined, '') + const onInputChange = useCallback( (e: React.ChangeEvent) => { const value = e.target.value @@ -262,16 +184,10 @@ export function FilteredActionList({ const onInputKeyPress: KeyboardEventHandler = useCallback( (event: React.KeyboardEvent) => { - if (event.key === 'Enter' && activeDescendantRef.current) { - event.preventDefault() - event.nativeEvent.stopImmediatePropagation() - - // Forward Enter key press to active descendant so that item gets activated - const activeDescendantEvent = new KeyboardEvent(event.type, event.nativeEvent) - activeDescendantRef.current.dispatchEvent(activeDescendantEvent) - } + if (components && (event.defaultPrevented || !activeDescendantRef.current?.isConnected)) return + activateDescendant(event, activeDescendantRef.current) }, - [activeDescendantRef], + [activeDescendantRef, components], ) const listContainerRefCallback = useCallback( @@ -305,7 +221,7 @@ export function FilteredActionList({ // so guard against `items[index]` being undefined. const item = items[index] as ItemInput | undefined if (!item) return index.toString() - return item.key ?? item.id?.toString() ?? index.toString() + return item.key ?? getItemKey(item, index) }, measureElement: el => (el as HTMLElement).scrollHeight, }) @@ -449,9 +365,9 @@ export function FilteredActionList({ {group.header?.title ? group.header.title : `Group ${group.groupId}`} {getItemListForEachGroup(group.groupId).map(({key: itemKey, ...item}, itemIndex) => { - const key = itemKey ?? item.id?.toString() ?? itemIndex.toString() + const key = itemKey ?? getItemKey(item, itemIndex) return ( - { - const key = itemKey ?? item.id?.toString() ?? index.toString() + const key = itemKey ?? getItemKey(item, index) return ( - { - const key = itemKey ?? item.id?.toString() ?? index.toString() + const key = itemKey ?? getItemKey(item, index) return ( - {renderListItems()} - + ) // Use ActionListContainerContext.Provider only for the old behavior (when feature flag is disabled) @@ -564,9 +481,9 @@ export function FilteredActionList({ ref={inputAndListContainerRef} className={clsx(className, classes.Root)} data-testid="filtered-action-list" - data-component="FilteredActionList" + data-component={componentName} > - ) } -const MappedActionListItem = forwardRef((item, ref) => { - // keep backward compatibility for renderItem - // escape hatch for custom Item rendering - if (typeof item.renderItem === 'function') return item.renderItem(item) - - const { - id, - description, - descriptionVariant, - text, - trailingVisual: TrailingVisual, - leadingVisual: LeadingVisual, - trailingText, - trailingIcon: TrailingIcon, - onAction, - children, - ...rest - } = item - - return ( - | React.KeyboardEvent) => { - if (typeof onAction === 'function') - onAction(item, e as React.MouseEvent | React.KeyboardEvent) - }} - data-id={id} - ref={ref} - {...rest} - > - {LeadingVisual ? ( - - - - ) : null} - {children} - {text} - {description ? {description} : null} - {TrailingVisual ? ( - - {typeof TrailingVisual !== 'string' && isValidElementType(TrailingVisual) ? ( - - ) : ( - TrailingVisual - )} - - ) : TrailingIcon || trailingText ? ( - - {trailingText} - {TrailingIcon && } - - ) : null} - - ) -}) - FilteredActionList.displayName = 'FilteredActionList' diff --git a/packages/react/src/FilteredActionList/FilteredActionListInput.tsx b/packages/react/src/FilteredActionList/FilteredActionListInput.tsx index 8c3ffe8db03..823d1f7dc1f 100644 --- a/packages/react/src/FilteredActionList/FilteredActionListInput.tsx +++ b/packages/react/src/FilteredActionList/FilteredActionListInput.tsx @@ -1,10 +1,16 @@ -import type React from 'react' +import React from 'react' import {clsx} from 'clsx' import TextInput from '../TextInput' import type {TextInputProps} from '../TextInput' import classes from './FilteredActionList.module.css' +import {useMergedRefs} from '../hooks/useMergedRefs' + +const DefaultInput = React.forwardRef(function DefaultInput(props, ref) { + return +}) export interface FilteredActionListInputProps extends Partial> { + InputComponent?: React.ComponentType> inputRef: React.Ref onInputChange?: (e: React.ChangeEvent) => void onInputFocus?: React.FocusEventHandler @@ -19,6 +25,7 @@ export interface FilteredActionListInputProps extends Partial(inputRef, undefined) return (
- & React.RefAttributes> +} + +export const MappedActionListItem = forwardRef< + HTMLLIElement, + ItemInput & {renderItem?: RenderItemFn} & MappedActionListItemRenderers +>(({ItemComponent = ActionList.Item, ...item}, ref) => { + // keep backward compatibility for renderItem + // escape hatch for custom Item rendering + if (typeof item.renderItem === 'function') return item.renderItem(item) + + const { + id, + description, + descriptionVariant, + text, + trailingVisual, + leadingVisual, + trailingText, + trailingIcon, + onAction, + children, + ...rest + } = item + + return ( + | React.KeyboardEvent) => { + if (typeof onAction === 'function') + onAction(item, e as React.MouseEvent | React.KeyboardEvent) + }} + data-id={id} + ref={ref} + {...rest} + > + {renderActionListItemContent({ + text, + description, + descriptionVariant, + leadingVisual, + trailingVisual, + trailingIcon, + trailingText, + children, + })} + + ) +}) diff --git a/packages/react/src/FilteredActionList/index.ts b/packages/react/src/FilteredActionList/index.ts index db6bba0b3c6..d71bb1b139c 100644 --- a/packages/react/src/FilteredActionList/index.ts +++ b/packages/react/src/FilteredActionList/index.ts @@ -2,11 +2,11 @@ import {FilteredActionList as FilteredList} from './FilteredActionList' import {FilteredActionListInput} from './FilteredActionListInput' import {FilteredActionListBodyLoader} from './FilteredActionListLoaders' -export type {FilteredActionListProps} from './FilteredActionList' export type {FilteredActionListInputProps} from './FilteredActionListInput' export {FilteredActionListLoadingTypes} from './FilteredActionListLoaders' export type { + FilteredActionListProps, FilteredActionListItemProps as ItemProps, ItemInput, GroupedListProps, diff --git a/packages/react/src/FilteredActionList/types.ts b/packages/react/src/FilteredActionList/types.ts index 7ae5343d46b..c824dbb33c6 100644 --- a/packages/react/src/FilteredActionList/types.ts +++ b/packages/react/src/FilteredActionList/types.ts @@ -1,8 +1,11 @@ import type {Key} from 'react' import type {Merge} from '../utils/polymorphic' import type {Group} from '../ActionList/Group' +import type {ActionListProps} from '../ActionList' import type {ActionListGroupProps} from '../deprecated' import type {AriaRole} from '../utils/types' +import type {FilteredActionListLoadingType} from './FilteredActionListLoaders' +import type {TextInputProps} from '../TextInput' // eslint-disable-next-line @typescript-eslint/no-explicit-any export type RenderItemFn = (props: FilteredActionListItemProps) => React.ReactElement @@ -186,3 +189,108 @@ export interface ListPropsBase { */ showItemDividers?: boolean } + +export interface FilteredActionListProps extends Partial>, ListPropsBase { + loading?: boolean + loadingType?: FilteredActionListLoadingType + placeholderText?: string + filterValue?: string + onFilterChange: (value: string, e: React.ChangeEvent | null) => void + onListContainerRefChanged?: (ref: HTMLElement | null) => void + onInputRefChanged?: (ref: React.RefObject) => void + /** + * A ref assigned to the scrollable container wrapping the ActionList + */ + scrollContainerRef?: React.Ref + textInputProps?: Partial> + inputRef?: React.RefObject + message?: React.ReactNode + messageText?: { + title: string + description: string + } + className?: string + announcementsEnabled?: boolean + fullScreenOnNarrow?: boolean + onSelectAllChange?: (checked: boolean) => void + /** + * Additional props to pass to the underlying ActionList component. + */ + actionListProps?: Partial + /** + * Determines how keyboard focus behaves when navigating beyond the first or last item in the list. + * + * - `'stop'`: Focus will stop at the first or last item; further navigation in that direction will not move focus. + * - `'wrap'`: Focus will wrap around to the opposite end of the list when navigating past the boundaries (e.g., pressing Down on the last item moves focus to the first). + * + * @default 'wrap' + */ + focusOutBehavior?: 'stop' | 'wrap' + /** + * Callback function that is called when the active descendant changes. + * + * @param newActiveDescendant - The new active descendant element. + * @param previousActiveDescendant - The previous active descendant element. + * @param directlyActivated - Whether the active descendant was directly activated (e.g., by a keyboard event). + */ + onActiveDescendantChanged?: ( + newActiveDescendant: HTMLElement | undefined, + previousActiveDescendant: HTMLElement | undefined, + directlyActivated: boolean, + ) => void + /** + * Private API for use internally only. Adds the ability to switch between + * `active-descendant` and roving tabindex. + * + * By default, FilteredActionList uses `aria-activedescendant` to manage focus. + * + * Roving tabindex is an alternative focus management method that moves + * focus to the list items themselves instead of keeping focus on the input. + * + * Improper usage can lead to inaccessible experiences, so this prop should be used with caution. + * + * For usage, refer to the documentation: + * + * WAI-ARIA `aria-activedescendant`: https://www.w3.org/TR/wai-aria-1.2/#aria-activedescendant + * + * Roving Tabindex: https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/#kbd_roving_tabindex + * + * @default 'active-descendant' + */ + _PrivateFocusManagement?: 'roving-tabindex' | 'active-descendant' + /** + * If true, disables selecting items when hovering over them with the mouse. + */ + disableSelectOnHover?: boolean + /** + * If true, focus remains where it was and the user must interact to move focus. + * If false, sets initial focus to the first item in the list when rendered, enabling keyboard navigation immediately. + */ + setInitialFocus?: boolean + /** + * Set to true to allow focus to move to elements that are dynamically prepended to the container. + * Default is false. + */ + focusPrependedElements?: boolean + /** + * Determines the scroll behavior of the container when an item is focused. + * + * @default 'auto' + */ + scrollBehavior?: ScrollBehavior + /** + * If true, enables client-side list virtualization. Only the visible items (plus a small + * overscan buffer) are rendered in the DOM, dramatically improving performance for large lists. + * + * This is a purely client-side optimization — it does not require server-side pagination. + * The consumer can still pass all items at once; the component will only render what is visible. + * + * Recommended for lists with more than 100 items. + * + * Note: Has no effect when `groupMetadata` is provided, as grouped lists are + * typically small enough not to need virtualization. + * + * @default false + */ + virtualized?: boolean +} diff --git a/packages/react/src/FilteredActionList/utils.ts b/packages/react/src/FilteredActionList/utils.ts new file mode 100644 index 00000000000..56e3b823aa8 --- /dev/null +++ b/packages/react/src/FilteredActionList/utils.ts @@ -0,0 +1,3 @@ +import type {ScrollIntoViewOptions} from '@primer/behaviors' + +export const menuScrollMargins: ScrollIntoViewOptions = {startMargin: 0, endMargin: 8} diff --git a/packages/react/src/SelectPanel/ConfiguredSelectPanelAdapter.tsx b/packages/react/src/SelectPanel/ConfiguredSelectPanelAdapter.tsx new file mode 100644 index 00000000000..acea0063db9 --- /dev/null +++ b/packages/react/src/SelectPanel/ConfiguredSelectPanelAdapter.tsx @@ -0,0 +1,39 @@ +import React from 'react' +import {FilteredActionListContent} from '../FilteredActionList/FilteredActionList' +import type {FilteredActionListProps, ItemInput} from '../FilteredActionList' +import {FilteredActionListInput, type FilteredActionListInputProps} from '../FilteredActionList/FilteredActionListInput' +import {MappedActionListItem} from '../FilteredActionList/components/MappedActionListItem' +import {SelectPanelItemBase, SelectPanelListBase, SelectPanelSearchInputBase} from './SelectPanelParts' +import {useMergedRefs} from '../hooks/useMergedRefs' +import {useSelectPanelContext} from './SelectPanelContext' + +function ConfiguredSearchInput(props: FilteredActionListInputProps) { + const {registerInput} = useSelectPanelContext() + const ref = useMergedRefs(props.inputRef, registerInput) + return +} + +const ConfiguredItem: typeof MappedActionListItem = React.forwardRef(function ConfiguredItem(props, ref) { + return +}) + +const components = { + Input: ConfiguredSearchInput, + List: SelectPanelListBase, + Item: ConfiguredItem, +} + +function getItemKey(item: ItemInput, index: number) { + return item.id === undefined ? index.toString() : `${typeof item.id}:${item.id}` +} + +export function ConfiguredSelectPanelCollection(props: FilteredActionListProps) { + return ( + + ) +} diff --git a/packages/react/src/SelectPanel/SelectPanel.compatibility.stories.tsx b/packages/react/src/SelectPanel/SelectPanel.compatibility.stories.tsx new file mode 100644 index 00000000000..e3f49d27b38 --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanel.compatibility.stories.tsx @@ -0,0 +1,116 @@ +import type {Meta, StoryObj} from '@storybook/react-vite' +import {expect, fireEvent, waitFor, within} from 'storybook/test' +import {FeatureFlags} from '../FeatureFlags' +import {Default as ConfiguredExample} from './SelectPanel.stories' +import {SingleSelectModal, MultiSelectModal, WithExternalAnchor, WithMessage} from './SelectPanel.features.stories' + +const examples = { + Default: ConfiguredExample, + SingleSelectModal, + MultiSelectModal, + WithExternalAnchor, + WithMessage, +} + +const meta = { + title: 'Components/SelectPanel/Configured Adapter', + args: {composable: true, nativeDialog: false, nativeInvokers: false, example: 'Default'}, + argTypes: { + composable: {control: 'boolean'}, + nativeDialog: {control: 'boolean'}, + nativeInvokers: {control: 'boolean'}, + example: {control: 'select', options: Object.keys(examples)}, + }, + render: ({composable, nativeDialog, nativeInvokers, example}) => { + const Example = examples[example] + return ( + + + + ) + }, + parameters: { + docs: { + description: { + component: + 'Reuses the existing configured examples, unchanged. Controls reset the example. Turning composable off restores the original configured selection rules, heading and message markup, collection renderer, and AnchoredOverlay host, even if the native flags are on. Explicit compositions are unaffected. Native dialog requires both composable and nativeDialog plus dialog and popover support; invokers additionally require nativeInvokers and command support. Native anchored panels are non-modal top-layer popovers; modal, bottom-sheet, and fullscreen variants retain native modality. Save/Cancel and narrow defaults are retained. Non-default positioning strategies, including opposite-side, and unsupported reflow and focus opt-outs use the legacy host.', + }, + }, + }, +} satisfies Meta<{composable: boolean; nativeDialog: boolean; nativeInvokers: boolean; example: keyof typeof examples}> + +export default meta + +export const Default: StoryObj = { + play: async ({canvas, canvasElement, userEvent, args}) => { + if (args.example !== 'Default') return + await userEvent.click(canvas.getByRole('button', {name: /bug/})) + const body = within(canvasElement.ownerDocument.body) + const input = await body.findByRole('combobox', {name: 'Filter items'}) + await waitFor(() => expect(input).toHaveFocus()) + await expect( + input.closest( + args.composable ? '[data-component="SelectPanel.Collection"]' : '[data-component="FilteredActionList"]', + ), + ).toBeInTheDocument() + await userEvent.type(input, 'enhancement') + await expect(body.getAllByRole('option')).toHaveLength(1) + await userEvent.click(body.getByRole('option', {name: /enhancement/})) + await expect(body.getByRole('option', {name: /enhancement/})).toHaveAttribute('aria-selected', 'true') + const dialog = body.getByRole('dialog') + if (dialog instanceof HTMLDialogElement && dialog.matches(':modal')) { + // Storybook's synthetic keyboard events cannot invoke the browser's + // dialog cancel action. Real Escape is covered by the browser tests. + fireEvent(dialog, new Event('cancel', {cancelable: true})) + } else { + await userEvent.keyboard('{Escape}') + } + if (dialog instanceof HTMLDialogElement) { + await waitFor(() => expect(dialog).not.toBeVisible()) + } else { + await waitFor(() => expect(body.queryByRole('dialog')).not.toBeInTheDocument()) + } + }, +} + +export const Legacy: StoryObj = { + ...Default, + args: {composable: false, nativeDialog: true, nativeInvokers: true}, +} + +export const NativeDialog: StoryObj = { + ...Default, + args: {nativeDialog: true}, +} + +export const NativeInvokers: StoryObj = { + ...Default, + args: {nativeDialog: true, nativeInvokers: true}, +} + +export const Messages: StoryObj = { + args: {example: 'WithMessage'}, +} + +export const ModalTransaction: StoryObj = { + args: {example: 'SingleSelectModal', nativeDialog: true, nativeInvokers: true}, + play: async ({canvas, canvasElement, userEvent}) => { + const body = within(canvasElement.ownerDocument.body) + await userEvent.click(canvas.getByRole('button', {name: 'Select labels'})) + await userEvent.click(body.getByRole('option', {name: /enhancement/})) + await expect(body.getByRole('dialog')).toBeVisible() + await userEvent.click(body.getByRole('button', {name: 'Cancel'})) + await expect(canvas.getByRole('button', {name: 'Select labels'})).toHaveFocus() + await userEvent.click(canvas.getByRole('button', {name: 'Select labels'})) + await expect(body.getByRole('option', {name: /enhancement/})).toHaveAttribute('aria-selected', 'false') + await userEvent.click(body.getByRole('option', {name: /enhancement/})) + await userEvent.click(body.getByRole('button', {name: 'Save'})) + await expect(canvas.getByRole('button', {name: 'enhancement'})).toHaveFocus() + }, +} diff --git a/packages/react/src/SelectPanel/SelectPanel.compatibility.test.tsx b/packages/react/src/SelectPanel/SelectPanel.compatibility.test.tsx new file mode 100644 index 00000000000..379b9d40f31 --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanel.compatibility.test.tsx @@ -0,0 +1,780 @@ +import React from 'react' +import {act, render} from '@testing-library/react' +import {afterAll, afterEach, describe, expect, it, vi} from 'vitest' +import {page, userEvent} from 'vitest/browser' +import axe from 'axe-core' +import BaseStyles from '../BaseStyles' +import {ThemeProvider} from '../ThemeProvider' +import {FeatureFlags} from '../FeatureFlags' +import {SelectPanel, type SelectPanelProps} from './SelectPanel' +import {Button} from '../Button' +// eslint-disable-next-line import/no-namespace -- Enumerate story exports so new configured examples are included automatically. +import * as defaultStories from './SelectPanel.stories' +// eslint-disable-next-line import/no-namespace +import * as featureStories from './SelectPanel.features.stories' +// eslint-disable-next-line import/no-namespace +import * as exampleStories from './SelectPanel.examples.stories' +// eslint-disable-next-line import/no-namespace +import * as devStories from './SelectPanel.dev.stories' + +function isStoryComponent(value: unknown): value is React.ComponentType> { + return typeof value === 'function' +} + +function cancelItemAction(_item: unknown, event: React.SyntheticEvent) { + event.preventDefault() +} + +function cancelClick(event: React.MouseEvent) { + event.preventDefault() +} + +function isStoryObject( + value: unknown, +): value is {render: React.ComponentType>; args?: Record} { + return typeof value === 'object' && value !== null && 'render' in value && isStoryComponent(value.render) +} + +const storyGroups = [ + ['Default', defaultStories], + ['Features', featureStories], + ['Examples', exampleStories], + ['Dev', devStories], +] as const + +afterAll(async () => { + await page.viewport(1280, 720) +}) + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +const platforms = [ + {dialog: false, invokers: false}, + {dialog: true, invokers: false}, + {dialog: true, invokers: true}, +] + +describe.each(platforms)('Configured adapter with $dialog dialog / $invokers invokers', flags => { + describe.each([1280, 390])('at %ipx', width => { + describe.each(storyGroups)('%s stories', (_group, stories) => { + for (const [name, Story] of Object.entries(stories)) { + if (name === 'default') continue + it(`opens every configured panel in ${name} without falling back`, async () => { + await page.viewport(width, 900) + const story = isStoryComponent(Story) + ? React.createElement(Story) + : isStoryObject(Story) + ? React.createElement(Story.render, Story.args) + : undefined + expect(story, `${name} must be a renderable configured story`).toBeDefined() + const {container} = render( + + + + {story} + + + , + ) + const triggers = Array.from( + container.querySelectorAll( + name === 'WithExternalAnchor' ? 'button' : 'button[aria-haspopup]', + ), + ) + expect(triggers.length).toBeGreaterThan(0) + for (const trigger of triggers) { + await userEvent.click(trigger) + const collection = page.getByTestId('filtered-action-list') + await expect.element(collection).toHaveAttribute('data-component', 'SelectPanel.Collection') + await expect.element(collection.getByRole('combobox')).toBeVisible() + expect(document.querySelector('[data-component="FilteredActionList"]')).toBeNull() + await userEvent.keyboard('{Escape}') + await expect.element(collection).not.toBeInTheDocument() + } + }) + } + }) + }) +}) + +describe('Configured adapter compatibility boundaries', () => { + it('does not change the explicit composition API', async () => { + const onSelectedChange = vi.fn() + render( + + + + + One + + + , + ) + await expect.element(page.getByLabelText('Search', {exact: true})).toBeVisible() + await userEvent.click(page.getByRole('option', {name: 'One'})) + expect(onSelectedChange).toHaveBeenCalledExactlyOnceWith(['one']) + expect(document.querySelector('[data-component="SelectPanel.Collection"]')).toBeNull() + }) + + it('uses the original configured renderer when the flag is omitted', async () => { + render() + await userEvent.click(page.getByRole('button', {name: /bug/})) + await expect + .element(page.getByTestId('filtered-action-list')) + .toHaveAttribute('data-component', 'FilteredActionList') + }) + + // Only adapter keys distinguish numeric and string IDs with the same string representation. + it.each([ + {composable: false, stringId: '2'}, + {composable: true, stringId: '2'}, + {composable: true, stringId: '1'}, + ])( + 'preserves item identity and filtered-out selections with adapter=$composable and string ID=$stringId', + async ({composable, stringId}) => { + const hidden = {id: 'hidden', text: 'Hidden selection'} + const anonymous = {text: 'No ID'} + const numeric = {id: 1, text: 'Numeric ID'} + const string = {id: stringId, text: 'String ID'} + const items = [anonymous, numeric, string] + const onSelectedChange = vi.fn<(items: SelectPanelProps['items']) => void>() + function Example() { + const [selected, setSelected] = React.useState([hidden]) + const [filter, setFilter] = React.useState('') + return ( + {}} + selected={selected} + onSelectedChange={(next: SelectPanelProps['items']) => { + onSelectedChange(next) + setSelected(next) + }} + items={items.filter(item => item.text.includes(filter))} + onFilterChange={setFilter} + /> + ) + } + render( + + + , + ) + for (const item of items) { + await userEvent.click(page.getByRole('option', {name: item.text, exact: true})) + } + const selected = onSelectedChange.mock.lastCall?.[0] + expect(selected).toHaveLength(4) + for (const [index, item] of [hidden, ...items].entries()) { + expect(selected?.[index]).toBe(item) + } + const input = page.getByRole('combobox') + await userEvent.fill(input, 'Numeric') + await userEvent.click(page.getByRole('option', {name: 'Numeric ID', exact: true})) + expect(onSelectedChange).toHaveBeenLastCalledWith([hidden, anonymous, string]) + await userEvent.clear(input) + await expect + .element(page.getByRole('option', {name: 'No ID', exact: true})) + .toHaveAttribute('aria-selected', 'true') + await expect + .element(page.getByRole('option', {name: 'String ID', exact: true})) + .toHaveAttribute('aria-selected', 'true') + }, + ) + + it('allows item actions to cancel pointer and active-descendant keyboard selection', async () => { + const onSelectedChange = vi.fn() + const onAction = vi.fn(cancelItemAction) + render( + + {}} + items={[{id: 'one', text: 'One', onAction}]} + selected={[]} + onSelectedChange={onSelectedChange} + onFilterChange={() => {}} + /> + , + ) + await userEvent.click(page.getByRole('option', {name: 'One', exact: true})) + await userEvent.click(page.getByRole('combobox')) + await userEvent.keyboard('{ArrowDown}{Enter}') + expect(onAction).toHaveBeenCalledTimes(2) + expect(onSelectedChange).not.toHaveBeenCalled() + await expect.element(page.getByRole('option', {name: 'One', exact: true})).toHaveAttribute('aria-selected', 'false') + }) + + it('keeps native-host experiments off when the configured adapter is disabled', async () => { + render( + + + , + ) + await userEvent.click(page.getByRole('button', {name: /bug/})) + expect(page.getByRole('dialog').element()).not.toBeInstanceOf(HTMLDialogElement) + await expect + .element(page.getByTestId('filtered-action-list')) + .toHaveAttribute('data-component', 'FilteredActionList') + }) + + function configured(children: React.ReactNode, {adapter = true, dialog = true, invokers = false} = {}) { + return ( + + + + {children} + + + + ) + } + + const choices = [{id: 1, text: 'One'}, {text: 'No ID'}, {id: 'disabled', text: 'Disabled', disabled: true}] + const configuredTrigger = () => page.getByRole('button', {name: 'Choose', exact: true}) + const configuredSearch = () => page.getByRole('combobox', {name: 'Filter items', exact: true}) + + describe.each([false, true])('Configured native compatibility with invokers=%s', invokers => { + it.each(['anchored', 'modal'] as const)( + 'matches the composable %s backdrop, modality and dismissal', + async variant => { + await page.viewport(1280, 900) + const composed = render( + configured( + + + Choices + + + , + {invokers}, + ), + ) + const expectedBackdrop = getComputedStyle(page.getByRole('dialog').element(), '::backdrop').backgroundColor + if (variant === 'anchored') expect(expectedBackdrop).toBe('rgba(0, 0, 0, 0)') + else expect(expectedBackdrop).not.toBe('rgba(0, 0, 0, 0)') + composed.unmount() + + const Example = variant === 'modal' ? featureStories.SingleSelectModal : defaultStories.Default + render(configured(, {invokers})) + const button = page.getByRole('button', {name: variant === 'modal' ? 'Select labels' : /bug/, exact: true}) + await userEvent.click(button) + const host = page.getByRole('dialog').element() + if (!(host instanceof HTMLDialogElement)) throw new Error('Expected the configured native dialog') + expect(host.matches(':modal')).toBe(variant === 'modal') + expect(host.matches(':popover-open')).toBe(variant === 'anchored') + expect(getComputedStyle(host, '::backdrop').backgroundColor).toBe(expectedBackdrop) + await userEvent.keyboard('{Escape}') + await expect.poll(() => host.matches(':modal, :popover-open')).toBe(false) + await expect.element(button).toHaveFocus() + }, + ) + + it('uses the shared non-modal host and preserves object identity and callback order', async () => { + await page.viewport(1280, 900) + const calls: unknown[] = [] + function Example() { + const [open, setOpen] = React.useState(false) + const [selected, setSelected] = React.useState() + return ( + { + calls.push([value, reason]) + setOpen(value) + }} + selected={selected} + onSelectedChange={(item: SelectPanelProps['items'][number] | undefined) => { + calls.push(item) + setSelected(item) + }} + items={choices} + onFilterChange={() => {}} + placeholder="Choose" + renderAnchor={props => } + /> + ) + } + render(configured(, {invokers})) + const button = configuredTrigger() + expect(button.element().hasAttribute('command')).toBe(invokers) + const host = document.querySelector('dialog') + expect(host).toBeInstanceOf(HTMLDialogElement) + expect(document.querySelector('[data-component="SelectPanel.Collection"]')).toBeNull() + await userEvent.click(button) + await expect.poll(() => host?.matches(':popover-open')).toBe(true) + await expect.element(configuredSearch()).toHaveFocus() + await userEvent.click(page.getByRole('option', {name: 'No ID', exact: true})) + await expect.poll(() => host?.matches(':popover-open')).toBe(false) + expect(calls).toEqual([[true, 'anchor-click'], choices[1], [false, 'selection']]) + expect(calls[1]).toBe(choices[1]) + await expect.element(button).toHaveFocus() + expect(document.querySelector('[data-component="SelectPanel.Collection"]')).toBeNull() + }) + + it('reconciles refused open, selection close, Escape, and native close commands', async () => { + const onOpenChange = vi.fn() + const onSelectedChange = vi.fn() + const onCancel = vi.fn() + const picker = (open: boolean) => + configured( + {}} + />, + {invokers}, + ) + const {rerender} = render(picker(false)) + await userEvent.click(configuredTrigger()) + await expect.poll(() => onOpenChange.mock.calls.length).toBe(1) + const host = document.querySelector('dialog') + await expect.poll(() => host?.open).toBe(false) + rerender(picker(true)) + await expect.poll(() => host?.matches(':modal')).toBe(true) + await userEvent.keyboard('{Escape}') + expect(host?.matches(':modal')).toBe(true) + expect(onOpenChange).toHaveBeenLastCalledWith(false, 'escape') + expect(onCancel).not.toHaveBeenCalled() + await userEvent.click(page.getByRole('button', {name: 'Cancel and close', exact: true})) + await expect.poll(() => onOpenChange.mock.calls.length).toBe(3) + expect(onOpenChange).toHaveBeenLastCalledWith(false, 'cancel') + expect(onCancel).toHaveBeenCalledOnce() + await expect.poll(() => host?.matches(':modal')).toBe(true) + await userEvent.click(page.getByRole('option', {name: 'No ID', exact: true})) + expect(onSelectedChange).not.toHaveBeenCalled() + await userEvent.click(page.getByRole('button', {name: 'Save', exact: true})) + expect(onSelectedChange).toHaveBeenCalledExactlyOnceWith(choices[1]) + expect(onOpenChange).toHaveBeenLastCalledWith(false, 'selection') + expect(host?.matches(':modal')).toBe(true) + }) + + it('preserves single modal draft Save/Cancel and configured dismissal reasons', async () => { + await page.viewport(1280, 900) + const calls: unknown[] = [] + function Example() { + const [open, setOpen] = React.useState(false) + const [selected, setSelected] = React.useState(choices[0]) + return ( + { + calls.push([value, reason]) + setOpen(value) + }} + onCancel={() => calls.push('cancel')} + selected={selected} + onSelectedChange={(item: SelectPanelProps['items'][number] | undefined) => { + calls.push(item) + setSelected(item) + }} + onFilterChange={() => {}} + renderAnchor={props => } + items={choices} + /> + ) + } + render(configured(, {invokers})) + await userEvent.click(configuredTrigger()) + const host = document.querySelector('dialog') + await userEvent.click(page.getByRole('option', {name: 'No ID', exact: true})) + expect(calls).toEqual([[true, 'anchor-click']]) + expect(host?.matches(':modal')).toBe(true) + await userEvent.click(page.getByRole('button', {name: 'Cancel', exact: true})) + expect(calls).toEqual([[true, 'anchor-click'], 'cancel', [false, 'cancel']]) + await userEvent.click(configuredTrigger()) + await expect + .element(page.getByRole('option', {name: 'One', exact: true})) + .toHaveAttribute('aria-selected', 'true') + await userEvent.click(page.getByRole('option', {name: 'No ID', exact: true})) + await userEvent.click(page.getByRole('button', {name: 'Save', exact: true})) + expect(calls.slice(-2)).toEqual([choices[1], [false, 'selection']]) + expect(calls[calls.length - 2]).toBe(choices[1]) + await expect.poll(() => host?.open).toBe(false) + await userEvent.click(configuredTrigger()) + await userEvent.click(page.getByRole('dialog'), {position: {x: -10, y: -10}, force: true}) + expect(calls.slice(-2)).toEqual(['cancel', [false, 'click-outside']]) + await expect.poll(() => host?.open).toBe(false) + }) + + it('retains filtered-out multiple selections and skips disabled options', async () => { + const hidden = {id: 'hidden', text: 'Hidden'} + const onSelectedChange = vi.fn() + function Example() { + const [selected, setSelected] = React.useState([hidden]) + return ( + {}} + selected={selected} + onSelectedChange={(next: SelectPanelProps['items']) => { + onSelectedChange(next) + setSelected(next) + }} + items={choices} + onFilterChange={() => {}} + /> + ) + } + render(configured(, {invokers})) + await expect.element(configuredSearch()).toHaveFocus() + await userEvent.keyboard('{ArrowDown}{ArrowDown}{ArrowDown}{Enter}') + expect(onSelectedChange).toHaveBeenCalledExactlyOnceWith([hidden, choices[0]]) + expect(onSelectedChange.mock.calls[0][0][0]).toBe(hidden) + expect(onSelectedChange.mock.calls[0][0][1]).toBe(choices[0]) + expect(document.querySelector('dialog')?.matches(':popover-open')).toBe(true) + }) + + it('supports external anchors without injecting invoker behavior', async () => { + render(configured(, {invokers})) + const button = page.getByRole('button', {name: /bug/}) + expect(button.element()).not.toHaveAttribute('command') + await userEvent.click(button) + await expect.element(configuredSearch()).toHaveFocus() + expect(document.querySelector('dialog')?.matches(':popover-open')).toBe(true) + await userEvent.keyboard('{Escape}') + await expect.element(button).toHaveFocus() + }) + + it('preserves configured widths, heights, surface props, refs and dismissal overrides', async () => { + await page.viewport(1280, 900) + const ref = React.createRef() + const onEscape = vi.fn() + const onClickOutside = vi.fn() + render( + configured( + {}} + onOpenChange={() => {}} + selected={[]} + onSelectedChange={() => {}} + items={Array.from({length: 100}, (_, id) => ({id, text: `Item ${id}`}))} + onFilterChange={() => {}} + width="large" + height="medium" + overlayProps={{ + ref, + id: 'configured-native', + 'aria-label': 'Custom name', + onEscape, + onClickOutside, + className: 'custom-surface', + style: {borderWidth: 3}, + maxHeight: 'small', + }} + />, + {invokers}, + ), + ) + const dialog = page.getByRole('dialog', {name: 'Custom name', exact: true}) + await expect.element(configuredSearch()).toHaveFocus() + expect(dialog.element()).toHaveAttribute('id', 'configured-native') + expect(dialog.element()).toHaveAttribute('aria-modal', 'true') + expect(ref.current).toHaveClass('custom-surface') + expect(ref.current?.style.borderWidth).toBe('3px') + expect(Math.round(ref.current?.getBoundingClientRect().width ?? 0)).toBe(480) + expect(Math.round(ref.current?.getBoundingClientRect().height ?? 0)).toBe(256) + const last = page.getByRole('option', {name: 'Item 99', exact: true}) + await userEvent.click(last) + expect(last.element().getBoundingClientRect().bottom).toBeLessThanOrEqual( + dialog.element().getBoundingClientRect().bottom, + ) + await userEvent.keyboard('{Escape}') + expect(onEscape).toHaveBeenCalledOnce() + await userEvent.click(page.getByRole('dialog'), {position: {x: -10, y: -10}, force: true}) + expect(onClickOutside).toHaveBeenCalledOnce() + expect(document.querySelector('dialog')?.matches(':modal')).toBe(true) + }) + }) + + describe('Configured native gates and fallbacks', () => { + it('keeps a configured modal centered on narrow screens when fullscreen is disabled', async () => { + await page.viewport(390, 844) + render( + + {configured( + {}} + onCancel={() => {}} + selected={undefined} + onSelectedChange={() => {}} + items={choices} + onFilterChange={() => {}} + />, + )} + , + ) + const dialog = page.getByRole('dialog') + await expect.element(dialog).toHaveAttribute('data-variant', 'modal') + await expect + .poll(() => { + const rect = dialog.element().getBoundingClientRect() + return {x: Math.round(rect.left + rect.width / 2), y: Math.round(rect.top + rect.height / 2)} + }) + .toEqual({x: 195, y: 422}) + }) + + it('reconciles a refused responsive native close command without canceling the modal draft', async () => { + await page.viewport(390, 844) + const onOpenChange = vi.fn() + const onCancel = vi.fn() + const onSelectedChange = vi.fn() + const showModal = vi.spyOn(HTMLDialogElement.prototype, 'showModal') + render( + + {configured( + {}} + />, + {invokers: true}, + )} + , + ) + const host = document.querySelector('dialog') + const commands: string[] = [] + host?.addEventListener('command', event => { + if (event instanceof CommandEvent && event.isTrusted) commands.push(event.command) + }) + await userEvent.click(page.getByRole('option', {name: 'No ID', exact: true})) + const close = page.getByRole('button', {name: 'Cancel and close', exact: true}) + await expect.element(close).toHaveAttribute('command', 'close') + await userEvent.click(close) + await expect.poll(() => onOpenChange.mock.calls.length).toBe(1) + await expect.poll(() => host?.matches(':modal')).toBe(true) + expect(commands).toEqual(['close']) + expect(showModal).toHaveBeenCalledTimes(2) + expect(onCancel).toHaveBeenCalledOnce() + expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false, 'cancel') + expect(onSelectedChange).not.toHaveBeenCalled() + await expect + .element(page.getByRole('option', {name: 'No ID', exact: true})) + .toHaveAttribute('aria-selected', 'true') + }) + + it.each([ + {dialog: false, invokers: false}, + {dialog: false, invokers: true}, + ])('keeps the part-backed legacy host with $dialog dialog / $invokers invokers', async flags => { + render(configured(, flags)) + await userEvent.click(page.getByRole('button', {name: /bug/})) + expect(document.querySelector('dialog')).toBeNull() + await expect + .element(page.getByTestId('filtered-action-list')) + .toHaveAttribute('data-component', 'SelectPanel.Collection') + }) + + it('falls back to the part-backed host without native dialog support', async () => { + vi.stubGlobal('HTMLDialogElement', undefined) + render(configured(, {invokers: true})) + const button = page.getByRole('button', {name: /bug/}) + expect(button.element()).not.toHaveAttribute('command') + await userEvent.click(button) + expect(document.querySelector('dialog')).toBeNull() + await expect + .element(page.getByTestId('filtered-action-list')) + .toHaveAttribute('data-component', 'SelectPanel.Collection') + }) + + it('retains native dialog with JavaScript controls without command support', async () => { + vi.stubGlobal('CommandEvent', undefined) + render(configured(, {invokers: true})) + const button = page.getByRole('button', {name: /bug/}) + expect(button.element()).not.toHaveAttribute('command') + await userEvent.click(button) + expect(document.querySelector('dialog')?.matches(':popover-open')).toBe(true) + }) + + it.each([ + {height: 'initial' as const}, + {overlayProps: {height: 'initial' as const}}, + {overlayProps: {preventFocusOnOpen: true}}, + {overlayProps: {preventFocusOnClose: true}}, + {overlayProps: {top: 20}}, + {overlayProps: {style: {position: 'fixed' as const, top: 20}}}, + {overlayProps: {preventOverflow: false}}, + {overlayProps: {ignoreClickRefs: [React.createRef()]}}, + {cssAnchorPositioningSettings: {fallbackStrategy: 'none' as const}}, + {cssAnchorPositioningSettings: {fallbackStrategy: 'opposite-side' as const}}, + ])('retains the legacy implementation for unsupported meaningful props: %j', async props => { + render( + configured( + {}} + selected={[]} + onSelectedChange={() => {}} + items={choices} + onFilterChange={() => {}} + />, + {invokers: true}, + ), + ) + expect(document.querySelector('dialog')).toBeNull() + await expect + .element(page.getByTestId('filtered-action-list')) + .toHaveAttribute('data-component', 'SelectPanel.Collection') + }) + + it.each([false, true])('keeps configured narrow defaults with fullscreen=%s', async fullscreen => { + await page.viewport(390, 844) + const overflow = document.body.style.overflow + const {unmount} = render( + + {configured(, {invokers: true})} + , + ) + await userEvent.click(page.getByRole('button', {name: /bug/})) + const host = document.querySelector('dialog') + expect(host?.matches(':modal')).toBe(fullscreen) + expect(host?.matches(':popover-open')).toBe(!fullscreen) + expect(host).toHaveAttribute('data-variant', fullscreen ? 'fullscreen' : 'anchored') + expect(getComputedStyle(page.getByRole('dialog').element(), '::backdrop').backgroundColor).toBe( + 'rgba(0, 0, 0, 0)', + ) + if (fullscreen) expect(Math.round(host?.getBoundingClientRect().height ?? 0)).toBe(844) + await expect.poll(() => document.body.style.overflow).toBe(fullscreen ? 'hidden' : overflow) + unmount() + expect(document.body.style.overflow).toBe(overflow) + }) + + it('preserves custom non-button anchors, keyboard reasons and canceled/disabled clicks', async () => { + await page.viewport(1280, 900) + const onOpenChange = vi.fn() + const picker = (anchor: NonNullable) => + configured( + {}} + onFilterChange={() => {}} + renderAnchor={anchor} + />, + {invokers: true}, + ) + const {rerender} = render( + picker(props => ( + + )), + ) + act(() => + configuredTrigger() + .element() + .dispatchEvent(new MouseEvent('click', {bubbles: true})), + ) + expect(onOpenChange).not.toHaveBeenCalled() + rerender( + picker(props => ( + + )), + ) + await userEvent.click(configuredTrigger()) + expect(onOpenChange).not.toHaveBeenCalled() + rerender( + picker(props => ( + + Choose + + )), + ) + const link = page.getByRole('link', {name: 'Choose', exact: true}) + expect(link.element()).not.toHaveAttribute('command') + await userEvent.click(link) + expect(onOpenChange).toHaveBeenLastCalledWith(true, 'anchor-click') + act(() => link.element().focus()) + await userEvent.keyboard('{Enter}') + expect(onOpenChange).toHaveBeenLastCalledWith(true, 'anchor-key-press') + }) + }) + + it.each(platforms)( + 'retains combobox semantics and passes accessibility checks with dialog=$dialog / invokers=$invokers', + async flags => { + render( + + + + + + + , + ) + await userEvent.click(page.getByRole('button', {name: /Select options/})) + const input = page.getByRole('combobox') + const list = page.getByRole('listbox') + await expect.element(input).toHaveFocus() + expect(input.element().getAttribute('aria-controls')).toBe(list.element().id) + await userEvent.keyboard('{ArrowDown}') + await expect.element(input).toHaveAttribute('aria-activedescendant') + // The native host is opaque immediately; its BaseOverlay surface owns + // the entrance animation. Audit the settled colors, not the fade-in. + const dialog = page.getByRole('dialog').element() + const surface = dialog instanceof HTMLDialogElement ? dialog.firstElementChild : dialog + if (!surface) throw new Error('Expected the visible configured panel surface') + await expect.poll(() => getComputedStyle(surface).opacity).toBe('1') + const results = await axe.run(document.body, { + runOnly: {type: 'tag', values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa']}, + }) + expect( + results.violations.map(({id, nodes}) => ({ + id, + nodes: nodes.map(({html, failureSummary}) => ({html, failureSummary})), + })), + ).toEqual([]) + }, + ) +}) diff --git a/packages/react/src/SelectPanel/SelectPanel.composition.stories.module.css b/packages/react/src/SelectPanel/SelectPanel.composition.stories.module.css new file mode 100644 index 00000000000..66e79ae30b9 --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanel.composition.stories.module.css @@ -0,0 +1,54 @@ +.Story { + display: flex; + align-items: flex-start; + flex-direction: column; + gap: var(--base-size-8); +} + +.Form { + display: flex; + min-height: 0; + max-height: inherit; + flex-direction: column; +} + +.Footer { + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: var(--base-size-8); +} + +.FooterActions { + display: flex; + gap: var(--base-size-8); +} + +.ActionHeader { + align-items: center; + gap: var(--base-size-8); +} + +.HeaderCopy { + min-width: 0; +} + +.HeaderActions { + display: flex; + align-items: center; + gap: var(--base-size-8); + flex-shrink: 0; +} + +.Muted { + font-size: var(--text-body-size-small); + color: var(--fgColor-muted); +} + +.InlinePanel { + width: 24rem; + max-width: 100%; + background-color: var(--bgColor-default); + border: var(--borderWidth-thin) solid var(--borderColor-default); + border-radius: var(--borderRadius-medium); +} diff --git a/packages/react/src/SelectPanel/SelectPanel.composition.stories.tsx b/packages/react/src/SelectPanel/SelectPanel.composition.stories.tsx new file mode 100644 index 00000000000..c38d623adc3 --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanel.composition.stories.tsx @@ -0,0 +1,458 @@ +import {InfoIcon, TagIcon, TriangleDownIcon} from '@primer/octicons-react' +import type {Meta} from '@storybook/react-vite' +import {useRef, useState, type RefObject} from 'react' +import {ActionList} from '../ActionList' +import {Button} from '../Button' +import {Dialog} from '../Dialog/Dialog' +import {useOnOutsideClick} from '../hooks/useOnOutsideClick' +import FormControl from '../FormControl' +import {SelectPanel, type SelectPanelValue} from '../SelectPanel' +import classes from './SelectPanel.composition.stories.module.css' + +const meta = { + title: 'Components/SelectPanel/Composition', + component: SelectPanel.Root, +} satisfies Meta + +export default meta + +interface LabelOption { + id: SelectPanelValue + name: string + description: string + disabled?: boolean +} + +const items: LabelOption[] = [ + {id: 'bug', name: 'Bug', description: 'Something is not working'}, + {id: 'enhancement', name: 'Enhancement', description: 'A new feature or request'}, + {id: 'design', name: 'Design', description: 'Interface and interaction design'}, + {id: 'accessibility', name: 'Accessibility', description: 'Usable by everyone'}, + { + id: 'archived', + name: 'Archived', + description: 'This label is no longer available', + disabled: true, + }, +] + +const groups = [ + {label: 'Issue type', items: items.slice(0, 2)}, + {label: 'Area', items: items.slice(2)}, +] + +function filterItems(options: LabelOption[], filter: string) { + const query = filter.trim().toLowerCase() + return options.filter(item => `${item.name} ${item.description}`.toLowerCase().includes(query)) +} + +function selectionLabel(selected: SelectPanelValue[]) { + return ( + items + .filter(item => selected.includes(item.id)) + .map(item => item.name) + .join(', ') || 'None' + ) +} + +function LabelItem({option}: {option: LabelOption}) { + return ( + + + + + {option.name} + {option.description} + + ) +} + +function NoResults() { + return ( + + Try searching for a different name or description. + + ) +} + +function CustomLayoutExample({ + transactional = false, + focusStrategy, +}: { + transactional?: boolean + focusStrategy?: React.ComponentProps['focusStrategy'] +}) { + const [open, setOpen] = useState(false) + const [committed, setCommitted] = useState(['bug']) + const [draft, setDraft] = useState(['bug']) + const [filter, setFilter] = useState('') + const filteredGroups = groups + .map(group => ({...group, items: filterItems(group.items, filter)})) + .filter(group => group.items.length > 0) + const resultCount = filteredGroups.reduce((count, group) => count + group.items.length, 0) + + return ( +
+ { + if (nextOpen) { + setDraft([...committed]) + setFilter('') + } + setOpen(nextOpen) + }} + selectionMode="multiple" + selected={draft} + onSelectedChange={setDraft} + onSubmit={values => setCommitted([...values])} + onCancel={() => setDraft([...committed])} + onDismiss={() => { + if (transactional) setDraft([...committed]) + else setCommitted([...draft]) + }} + filterValue={filter} + onFilterChange={setFilter} + > +
+ ) +} + +export const CustomLayout = () => + +CustomLayout.parameters = { + docs: { + description: { + story: + 'V1-style multi-selection: Escape, outside click, and Done apply the current selection. Search keeps focus while the active result changes.', + }, + }, +} + +export const ExplicitApplyCancel = () => + +ExplicitApplyCancel.parameters = { + docs: { + description: { + story: + 'An explicit transactional alternative, not the default: Save commits the draft; Cancel, Escape, and outside click discard it.', + }, + }, +} + +export const RovingFocus = () => + +RovingFocus.parameters = { + docs: { + description: { + story: + 'Opt into focusStrategy="roving" to move DOM focus into list options. Save-on-dismiss behavior is unchanged.', + }, + }, +} + +export const HeaderActions = () => { + const [selected, setSelected] = useState(['bug']) + + return ( +
+ + + Labels with header actions ({selected.length}) + + + + +
+ Choose labels + + Pick labels individually or select all enabled labels. + +
+
+ + +
+
+ + {items.map(item => ( + + ))} + +
+
+
+

Selected labels: {selectionLabel(selected)}

+
+ ) +} + +HeaderActions.parameters = { + docs: { + description: { + story: + 'Compose ordinary buttons and SelectPanel.CloseButton inside SelectPanel.Header. Select all updates the selection without dismissing the picker; the close button dismisses it and returns focus to the trigger. No header-actions prop or special slot is needed.', + }, + }, +} + +function LabelDetails({item, returnFocusRef}: {item: LabelOption; returnFocusRef: RefObject}) { + const [open, setOpen] = useState(false) + return ( + <> + setOpen(true)}]} + > + {item.name} + {item.description} + + {open ? setOpen(false)} /> : null} + + ) +} + +function LabelDetailsDialog({ + item, + returnFocusRef, + onClose, +}: { + item: LabelOption + returnFocusRef: RefObject + onClose: () => void +}) { + const dialogRef = useRef(null) + const backRef = useRef(null) + // Register this portaled dialog above the parent picker's outside-click handler. + useOnOutsideClick({ + containerRef: dialogRef, + onClickOutside: event => { + event.preventDefault() + onClose() + }, + }) + return ( + +

Inspecting a label does not select it. Close this dialog to return to search with the same active label.

+ + + +
+ ) +} + +export const ListWithNestedDetails = () => { + const searchRef = useRef(null) + const [selected, setSelected] = useState([]) + const [filter, setFilter] = useState('') + const filteredItems = filterItems(items, filter) + + return ( + + + Labels with details ({selected.length}) + + + + +
+ Choose labels + + Select a label, or press Cmd/Ctrl+Shift+U to open its details. Escape returns to search. + +
+
+ + + {filteredItems.map(item => ( + + ))} + + {filteredItems.length === 0 && } + + {selected.length} selected + +
+
+
+ ) +} + +export const WithoutSearchInput = () => { + const [selected, setSelected] = useState([]) + + return ( + + + {selected.length > 0 ? selectionLabel(selected) : 'Choose a label'} + + + + + Choose a label + + + {items.map(item => ( + + ))} + + + + + ) +} + +export const InlineList = () => { + const [selected, setSelected] = useState([]) + const [filter, setFilter] = useState('') + const filteredItems = filterItems(items, filter) + + return ( + + + +
+ Primary label + + This picker stays in the page without a trigger or overlay. + +
+
+ + + {filteredItems.map(item => ( + + ))} + + {filteredItems.length === 0 && } + + Selected: {selectionLabel(selected)} + +
+
+ ) +} + +export const ResponsiveImmediateSelection = () => { + const [selected, setSelected] = useState([]) + const [filter, setFilter] = useState('') + const filteredItems = filterItems(items, filter) + + return ( + + Primary label + + + {selected.length > 0 ? selectionLabel(selected) : 'Choose a primary label'} + + + + +
+ Choose a primary label + Selection applies immediately and closes this dialog. +
+ +
+ + + {filteredItems.map(item => ( + + ))} + + {filteredItems.length === 0 && } +
+
+
+ The selected label is applied immediately. +
+ ) +} diff --git a/packages/react/src/SelectPanel/SelectPanel.composition.test.tsx b/packages/react/src/SelectPanel/SelectPanel.composition.test.tsx new file mode 100644 index 00000000000..327554e6bad --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanel.composition.test.tsx @@ -0,0 +1,947 @@ +import React from 'react' +import {act, fireEvent, render, screen, waitFor, within} from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import {describe, expect, it, vi} from 'vitest' +import BaseStyles from '../BaseStyles' +import {BookIcon} from '@primer/octicons-react' +import axe from 'axe-core' +import {ActionList} from '../ActionList' +import FormControl from '../FormControl' +import {SelectPanel, type SelectPanelRootProps, type SelectPanelValue} from '.' + +const items = [ + {id: 'apple', text: 'Apple'}, + {id: 'banana', text: 'Banana'}, + {id: 'cherry', text: 'Cherry', disabled: true}, +] + +function Picker(props: SelectPanelRootProps) { + return ( + + + Choose fruit + + + + Fruit picker + Choose your favorite fruit + + + + {items.map(item => ( + + {item.text} + + ))} + + + + + + + + + ) +} + +describe('SelectPanel composition', () => { + it('connects the trigger, panel, description, input, and collection', async () => { + const user = userEvent.setup() + render() + const trigger = screen.getByRole('button', {name: 'Choose fruit'}) + expect(trigger).toHaveAttribute('aria-haspopup', 'dialog') + expect(trigger).toHaveAttribute('aria-expanded', 'false') + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + + await user.click(trigger) + const dialog = screen.getByRole('dialog', {name: 'Fruit picker'}) + const input = screen.getByRole('textbox', {name: 'Filter fruit'}) + const list = screen.getByRole('listbox', {name: 'Fruit'}) + expect(dialog).toHaveAccessibleDescription('Choose your favorite fruit') + expect(trigger).toHaveAttribute('aria-controls', dialog.id) + expect(input).toHaveAttribute('aria-controls', list.id) + expect(input).not.toHaveAttribute('aria-expanded') + expect(dialog).toHaveAttribute('aria-modal', 'true') + expect(within(dialog).getByRole('heading', {level: 1})).toHaveTextContent('Fruit picker') + await waitFor(() => expect(input).toHaveFocus()) + + await user.keyboard('{Escape}') + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + await waitFor(() => expect(trigger).toHaveFocus()) + }) + + it('moves DOM focus into the list and wraps arrow navigation at its boundaries', async () => { + const user = userEvent.setup() + const onSelectedChange = vi.fn() + render() + await user.click(screen.getByRole('button', {name: 'Choose fruit'})) + const input = screen.getByRole('textbox') + await waitFor(() => expect(input).toHaveFocus()) + const firstOption = screen.getByRole('option', {name: 'Apple'}) + expect(input).not.toHaveAttribute('aria-activedescendant') + await user.keyboard('{ArrowDown}') + expect(firstOption).toHaveFocus() + await user.keyboard('{Enter}') + expect(onSelectedChange).toHaveBeenLastCalledWith(['apple']) + expect(firstOption).toHaveAttribute('aria-selected', 'true') + expect(firstOption).toHaveFocus() + expect(screen.getByRole('listbox')).toHaveAttribute('aria-multiselectable', 'true') + + await user.keyboard('{ArrowDown}') + expect(screen.getByRole('option', {name: 'Banana'})).toHaveFocus() + await user.keyboard('{ArrowDown}') + expect(firstOption).toHaveFocus() + await user.keyboard('{ArrowUp}') + expect(screen.getByRole('option', {name: 'Banana'})).toHaveFocus() + await user.keyboard('{ArrowUp}') + expect(firstOption).toHaveFocus() + expect(onSelectedChange).toHaveBeenCalledTimes(1) + await user.tab({shift: true}) + expect(input).toHaveFocus() + await user.keyboard('{ArrowUp}') + expect(input).toHaveFocus() + }) + + it.each([1, 2])('wraps among %i available options without a search input', async count => { + const user = userEvent.setup() + const onSelectedChange = vi.fn() + render( + + + + Unavailable first item + + + {items.slice(0, count).map(item => ( + + {item.text} + + ))} + + + + Unavailable last item + + + , + ) + const first = screen.getByRole('option', {name: 'Apple'}) + const last = screen.getByRole('option', {name: items[count - 1].text}) + act(() => last.focus()) + + await user.keyboard('{ArrowDown}') + expect(first).toHaveFocus() + expect(screen.getByRole('listbox').querySelectorAll('[role="option"][tabindex="0"]')).toHaveLength(1) + await user.keyboard('{ArrowUp}') + expect(last).toHaveFocus() + expect(screen.getByRole('listbox').querySelectorAll('[role="option"][tabindex="0"]')).toHaveLength(1) + + await user.keyboard('{Home}{Home}') + expect(first).toHaveFocus() + await user.keyboard('{End}{End}') + expect(last).toHaveFocus() + expect(onSelectedChange).not.toHaveBeenCalled() + }) + + it('does not close a single-selection panel unless close-on-select is enabled', async () => { + const user = userEvent.setup() + const onSubmit = vi.fn() + render() + await user.click(screen.getByRole('option', {name: 'Apple'})) + expect(screen.getByRole('option', {name: 'Apple'})).toHaveAttribute('aria-selected', 'true') + expect(screen.getByRole('dialog')).toBeInTheDocument() + expect(onSubmit).not.toHaveBeenCalled() + }) + + it('closes after single selection and restores trigger focus', async () => { + const user = userEvent.setup() + const onSelectedChange = vi.fn() + const onOpenChange = vi.fn() + render() + const trigger = screen.getByRole('button', {name: 'Choose fruit'}) + await user.click(trigger) + await user.click(screen.getByRole('option', {name: 'Banana'})) + expect(onSelectedChange).toHaveBeenLastCalledWith(['banana']) + expect(onOpenChange).toHaveBeenLastCalledWith(false, 'selection') + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() + await waitFor(() => expect(trigger).toHaveFocus()) + }) + + it('treats controlled selection changes as requests', async () => { + const user = userEvent.setup() + const onSelectedChange = vi.fn() + const {rerender} = render( + , + ) + await user.click(screen.getByRole('option', {name: 'Apple'})) + expect(onSelectedChange).toHaveBeenCalledWith(['apple']) + expect(screen.getByRole('option', {name: 'Apple'})).toHaveAttribute('aria-selected', 'false') + + rerender() + expect(screen.getByRole('option', {name: 'Apple'})).toHaveAttribute('aria-selected', 'true') + }) + + it('does not restore focus when a controlled owner rejects dismissal', async () => { + const user = userEvent.setup() + const onOpenChange = vi.fn() + render() + const input = screen.getByRole('textbox') + await waitFor(() => expect(input).toHaveFocus()) + await user.keyboard('{Escape}') + expect(onOpenChange).toHaveBeenCalledWith(false, 'escape') + expect(screen.getByRole('dialog')).toBeInTheDocument() + expect(input).toHaveFocus() + }) + + it('does not select disabled items', async () => { + const user = userEvent.setup() + const onSelectedChange = vi.fn() + render() + await user.click(screen.getByRole('option', {name: 'Cherry'})) + expect(onSelectedChange).not.toHaveBeenCalled() + expect(screen.getByRole('dialog')).toBeInTheDocument() + }) + + it('keeps item ARIA state consistent with root selection and disabled behavior', async () => { + const user = userEvent.setup() + const onSelectedChange = vi.fn() + render( + + + + Apple + + + Banana + + + Cherry + + + , + ) + expect(screen.getByRole('option', {name: 'Apple'})).toHaveAttribute('aria-selected', 'true') + for (const name of ['Banana', 'Cherry']) { + const option = screen.getByRole('option', {name}) + expect(option).toHaveAttribute('aria-disabled', 'true') + expect(option).toHaveAttribute('tabindex', '-1') + await user.click(option) + } + expect(onSelectedChange).not.toHaveBeenCalled() + }) + + it('does not leave disabled options in the Tab order', async () => { + const user = userEvent.setup() + render() + const input = screen.getByRole('textbox') + await waitFor(() => expect(input).toHaveFocus()) + expect(screen.getByRole('option', {name: 'Cherry'})).toHaveAttribute('tabindex', '-1') + await user.tab() + expect(screen.getByRole('option', {name: 'Apple'})).toHaveFocus() + await user.tab() + expect(screen.getByRole('button', {name: 'Close'})).toHaveFocus() + await user.tab({shift: true}) + expect(screen.getByRole('option', {name: 'Apple'})).toHaveFocus() + }) + + it('refreshes navigation when an existing option becomes enabled or disabled', async () => { + const user = userEvent.setup() + function DynamicOptions({disabled}: {disabled: boolean}) { + return ( + + + + + Apple + + Banana + + + ) + } + const {rerender} = render() + const input = screen.getByRole('textbox') + await user.click(input) + await user.keyboard('{ArrowDown}') + const banana = screen.getByRole('option', {name: 'Banana'}) + expect(banana).toHaveFocus() + + rerender() + const apple = screen.getByRole('option', {name: 'Apple'}) + await waitFor(() => expect(apple).toHaveAttribute('tabindex', '-1')) + await user.keyboard('{ArrowUp}') + expect(apple).toHaveFocus() + + rerender() + await waitFor(() => expect(banana).toHaveFocus()) + expect(apple).toHaveAttribute('tabindex', '-1') + expect(input).not.toHaveAttribute('aria-activedescendant') + await user.tab({shift: true}) + expect(input).toHaveFocus() + rerender() + await waitFor(() => expect(apple).not.toHaveAttribute('aria-disabled', 'true')) + await user.keyboard('{ArrowDown}') + expect(apple).toHaveFocus() + expect(banana).toHaveAttribute('tabindex', '-1') + }) + + it('repairs removed list focus without stealing focus from search or after an explicit blur', async () => { + const user = userEvent.setup() + function DynamicList({values}: {values: string[]}) { + return ( + + + + {values.map(value => ( + + {value} + + ))} + + + ) + } + const {rerender} = render() + await user.click(screen.getByRole('option', {name: 'Banana'})) + rerender() + await waitFor(() => expect(screen.getByRole('option', {name: 'Apple'})).toHaveFocus()) + rerender() + await waitFor(() => expect(screen.getByRole('textbox')).toHaveFocus()) + + rerender() + expect(screen.getByRole('textbox')).toHaveFocus() + await user.keyboard('{ArrowDown}{ArrowDown}') + expect(screen.getByRole('option', {name: 'Banana'})).toHaveFocus() + await user.click(screen.getByRole('textbox')) + rerender() + await waitFor(() => expect(screen.getByRole('option')).toHaveAttribute('tabindex', '0')) + expect(screen.getByRole('textbox')).toHaveFocus() + + await user.keyboard('{ArrowDown}') + act(() => screen.getByRole('option').blur()) + rerender() + await waitFor(() => expect(document.body).toHaveFocus()) + }) + + it('lets input and collection handlers cancel navigation', async () => { + const user = userEvent.setup() + const cancel = (event: React.KeyboardEvent) => event.preventDefault() + render( + + + + Apple + Banana + + , + ) + await user.click(screen.getByRole('textbox')) + await user.keyboard('{ArrowDown}') + expect(screen.getByRole('textbox')).toHaveFocus() + await user.click(screen.getByRole('option', {name: 'Apple'})) + await user.keyboard('{ArrowDown}') + expect(screen.getByRole('option', {name: 'Apple'})).toHaveFocus() + }) + + it('does not filter externally supplied results a second time', () => { + render() + expect(screen.getAllByRole('option')).toHaveLength(3) + expect(screen.getByRole('textbox')).toHaveValue('server-side query') + }) + + it('supports wrapped parts, custom labels, refs, and inline composition', async () => { + const user = userEvent.setup() + const inputRef = React.createRef() + const listRef = React.createRef() + const itemRef = React.createRef() + const WrappedInput = () => + render( + + + + + Custom apple + + + , + ) + expect(inputRef.current).toBe(screen.getByRole('textbox')) + expect(inputRef.current).toHaveAttribute('aria-controls', 'custom-list') + expect(listRef.current).toBe(screen.getByRole('listbox', {name: 'Inline fruit'})) + expect(listRef.current).toHaveClass('custom-list') + expect(itemRef.current).toBe(screen.getByRole('option', {name: 'Custom apple'})) + expect(itemRef.current).toHaveClass('custom-item') + await user.click(itemRef.current!) + expect(itemRef.current).toHaveAttribute('aria-selected', 'true') + }) + + it('preserves row visual slots and accessible descriptions', () => { + render( + + + + + + + Book + Reference + + + , + ) + expect(screen.getByRole('option', {name: 'Book'})).toHaveAccessibleDescription('Reference') + expect(screen.getByText('Reference')).toBeInTheDocument() + }) + + it('honors canceled item handlers for pointer and keyboard activation', async () => { + const user = userEvent.setup() + const onSelectedChange = vi.fn() + const onSelect = vi.fn((event: React.MouseEvent | React.KeyboardEvent) => event.preventDefault()) + render( + + + + + Apple + + + , + ) + await user.click(screen.getByRole('option')) + await user.click(screen.getByRole('textbox')) + await user.keyboard('{ArrowDown}{Enter}') + expect(onSelect).toHaveBeenCalledTimes(2) + expect(onSelectedChange).not.toHaveBeenCalled() + }) + + it('merges a custom trigger ref and honors canceled trigger activation', async () => { + const user = userEvent.setup() + const ref = React.createRef() + const onOpenChange = vi.fn() + render( + + event.preventDefault()} + render={props => } + /> + , + ) + const trigger = screen.getByRole('button', {name: 'Custom trigger'}) + expect(ref.current).toBe(trigger) + await user.click(trigger) + expect(onOpenChange).not.toHaveBeenCalled() + expect(trigger).toHaveAttribute('aria-expanded', 'false') + }) + + it('links a trigger to a custom overlay id', async () => { + const user = userEvent.setup() + render( + + Open custom panel + + + + , + ) + const trigger = screen.getByRole('button', {name: 'Open custom panel'}) + await user.click(trigger) + expect(screen.getByRole('dialog', {name: 'Custom panel'})).toHaveAttribute('id', 'custom-panel') + expect(trigger).toHaveAttribute('aria-controls', 'custom-panel') + }) + + it('uses FormControl labeling and descriptions without sharing the filter id or required state', async () => { + const user = userEvent.setup() + render( + + Fruit + Choose a favorite + + Choose fruit + + Pick fruit + + + Apple + + + + , + ) + const trigger = screen.getByLabelText(/^Fruit/) + expect(trigger).toHaveAttribute('id', 'fruit-field') + expect(trigger).toHaveAccessibleDescription('Choose a favorite') + await user.click(trigger) + const input = screen.getByRole('textbox', {name: 'Filter fruit'}) + expect(input).not.toHaveAttribute('id', trigger.id) + expect(input).not.toHaveAttribute('required') + expect(input).not.toHaveAccessibleDescription('Choose a favorite') + expect(screen.getByRole('heading', {name: 'Pick fruit', level: 1})).toBeInTheDocument() + }) + + it('inherits FormControl disabled state and keeps inline heading levels configurable', async () => { + const user = userEvent.setup() + const onOpenChange = vi.fn() + render( + + Fruit + + Choose fruit + Inline fruit + + , + ) + const trigger = screen.getByLabelText(/^Fruit/) + expect(trigger).toBeDisabled() + await user.click(trigger) + expect(onOpenChange).not.toHaveBeenCalled() + expect(screen.getByRole('heading', {name: 'Inline fruit', level: 3})).toBeInTheDocument() + }) +}) + +function NestedPicker({ + showRow = true, + onSelectedChange, +}: { + showRow?: boolean + onSelectedChange?: (values: SelectPanelValue[]) => void +}) { + return ( + + + Open parent + + + Parent picker + + {showRow && } + + + + + ) +} + +function NestedItem() { + const [open, setOpen] = React.useState(false) + const itemRef = React.useRef(null) + const titleRef = React.useRef(null) + return ( + <> + setOpen(true)}]} + > + Apple + + + + + + Apple information + +

Details are independent of selection.

+ +
+
+
+ + ) +} + +describe('SelectPanel nested layers', () => { + it('opens nested details directly from the item shortcut and restores item focus', async () => { + const user = userEvent.setup() + const onSelectedChange = vi.fn() + render() + await user.click(screen.getByRole('button', {name: 'Open parent'})) + await user.keyboard('{ArrowDown}') + const item = screen.getByRole('option', {name: 'Apple'}) + expect(item).toHaveFocus() + await user.keyboard('{Control>}{Shift>}u{/Shift}{/Control}') + const child = screen.getByRole('dialog', {name: 'Apple information'}) + await waitFor(() => expect(within(child).getByRole('heading', {name: 'Apple information'})).toHaveFocus()) + expect(onSelectedChange).not.toHaveBeenCalled() + await user.keyboard('{Escape}') + await waitFor(() => expect(item).toHaveFocus()) + }) + + it('keeps selection and query intact and dismisses only the child on Escape', async () => { + const user = userEvent.setup() + const onSelectedChange = vi.fn() + render() + await user.click(screen.getByRole('button', {name: 'Open parent'})) + await user.type(screen.getByRole('textbox'), 'apple') + const action = screen.getByTitle('Apple details') + const item = screen.getByRole('option', {name: 'Apple'}) + await user.click(action) + const child = screen.getByRole('dialog', {name: 'Apple information'}) + await waitFor(() => expect(within(child).getByRole('heading', {name: 'Apple information'})).toHaveFocus()) + expect(onSelectedChange).not.toHaveBeenCalled() + + await user.keyboard('{Escape}') + expect(screen.queryByRole('dialog', {name: 'Apple information'})).not.toBeInTheDocument() + expect(screen.getByRole('dialog', {name: 'Parent picker'})).toBeInTheDocument() + expect(screen.getByRole('textbox', {name: 'Parent filter'})).toHaveValue('apple') + await waitFor(() => expect(item).toHaveFocus()) + }) + + describe('SelectPanel item secondary actions', () => { + it('has no WCAG A/AA violations or focusable descendants in options with pointer actions', async () => { + render( + + + + + Primer + + + + , + ) + const option = screen.getByRole('option', {name: 'Primer'}) + expect( + option.querySelectorAll('button, a[href], input, select, textarea, [tabindex], [contenteditable="true"]'), + ).toHaveLength(0) + const result = await axe.run(screen.getByRole('listbox'), { + runOnly: {type: 'tag', values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa']}, + }) + expect(result.violations).toEqual([]) + }) + + it('preserves trailing metadata and its visual-slot props alongside secondary actions', () => { + render( + + + + Primer + + TypeScript + + + + , + ) + const option = screen.getByRole('option', {name: 'Primer TypeScript'}) + const metadata = within(option).getByText('TypeScript') + expect(metadata).toHaveAttribute('data-anatomy', 'Item.trailingVisual') + expect(metadata).toHaveClass('metadata-slot') + expect(metadata.querySelector('[data-component="SelectPanel.Item.SecondaryAction"]')).not.toBeNull() + expect(option.querySelectorAll('button, [tabindex]')).toHaveLength(0) + }) + + it('preserves the native option height when adding pointer actions', () => { + render( + + + + + Apple + + Banana + + + , + ) + expect(screen.getByRole('option', {name: 'Apple'}).getBoundingClientRect().height).toBe( + screen.getByRole('option', {name: 'Banana'}).getBoundingClientRect().height, + ) + }) + + function ActionPicker({ + actions = [{label: 'Inspect Apple', icon: BookIcon, onClick: vi.fn()}], + onSelectedChange = vi.fn(), + itemProps = {}, + }: { + actions?: React.ComponentProps['secondaryActions'] + onSelectedChange?: (values: SelectPanelValue[]) => void + itemProps?: Partial> + }) { + return ( + + + Open actions + + Fruit actions + + + + Apple + A tasty fruit + + Banana + + + + + + ) + } + + it.each(['metaKey', 'ctrlKey'])( + 'executes a sole action directly with %s and keeps selection intact', + async modifier => { + const user = userEvent.setup() + const onAction = vi.fn() + const onSelectedChange = vi.fn() + render( + , + ) + await user.click(screen.getByRole('button', {name: 'Open actions'})) + await user.keyboard('{ArrowDown}') + const item = screen.getByRole('option', {name: 'Apple'}) + expect(item).toHaveAccessibleDescription(expect.stringContaining('A tasty fruit')) + expect(item).toHaveAccessibleDescription(expect.stringContaining('Cmd/Ctrl+Shift+U')) + expect(item).toHaveAttribute('aria-keyshortcuts', 'Meta+Shift+U Control+Shift+U') + fireEvent.keyDown(item, {key: 'U', shiftKey: true, [modifier]: true}) + expect(onAction).toHaveBeenCalledOnce() + expect(onSelectedChange).not.toHaveBeenCalled() + expect(item).toHaveFocus() + expect(screen.queryByRole('dialog', {name: 'Supplemental actions'})).not.toBeInTheDocument() + expect(screen.getByRole('dialog', {name: 'Fruit actions'})).toBeInTheDocument() + }, + ) + + it('keeps hidden pointer actions out of the tab order, name, and list navigation', async () => { + const user = userEvent.setup() + const onAction = vi.fn() + const onSelectedChange = vi.fn() + render( + , + ) + await user.click(screen.getByRole('button', {name: 'Open actions'})) + await user.tab() + const apple = screen.getByRole('option', {name: 'Apple'}) + const banana = screen.getByRole('option', {name: 'Banana'}) + const pointerAction = screen.getByTitle('Inspect Apple') + expect(apple).toHaveFocus() + expect(pointerAction).not.toHaveAttribute('tabindex') + expect(pointerAction).toHaveAttribute('data-component', 'SelectPanel.Item.SecondaryAction') + expect(pointerAction).toHaveAttribute('aria-hidden', 'true') + expect(screen.queryByRole('button', {name: 'Inspect Apple'})).not.toBeInTheDocument() + await user.keyboard('{ArrowRight}') + expect(apple).toHaveFocus() + await user.keyboard('{End}') + expect(banana).toHaveFocus() + expect(apple).toHaveAttribute('tabindex', '-1') + expect(banana).toHaveAttribute('tabindex', '0') + await user.tab() + expect(screen.getByRole('button', {name: 'After list'})).toHaveFocus() + await user.tab({shift: true}) + expect(banana).toHaveFocus() + await user.click(pointerAction) + expect(onAction).toHaveBeenCalledOnce() + expect(apple).toHaveFocus() + expect(onSelectedChange).not.toHaveBeenCalled() + expect(screen.getByRole('dialog', {name: 'Fruit actions'})).toBeInTheDocument() + }) + + it('opens supplemental actions for multiple actions and returns focus after activation', async () => { + const user = userEvent.setup() + const inspect = vi.fn() + const edit = vi.fn() + const onSelectedChange = vi.fn() + render( + , + ) + await user.click(screen.getByRole('button', {name: 'Open actions'})) + await user.keyboard('{ArrowDown}{Control>}{Shift>}u{/Shift}{/Control}') + const dialog = screen.getByRole('dialog', {name: 'Supplemental actions'}) + await waitFor(() => expect(within(dialog).getByRole('button', {name: 'Inspect Apple'})).toHaveFocus()) + const editButton = within(dialog).getByRole('button', {name: 'Edit Apple'}) + await user.click(editButton) + expect(edit).toHaveBeenCalledOnce() + expect(inspect).not.toHaveBeenCalled() + expect(onSelectedChange).not.toHaveBeenCalled() + expect(screen.queryByRole('dialog', {name: 'Supplemental actions'})).not.toBeInTheDocument() + expect(screen.getByRole('dialog', {name: 'Fruit actions'})).toBeInTheDocument() + await waitFor(() => expect(screen.getByRole('option', {name: 'Apple'})).toHaveFocus()) + }) + + it('dismisses only supplemental actions on Escape and restores the item', async () => { + const user = userEvent.setup() + render( + , + ) + await user.click(screen.getByRole('button', {name: 'Open actions'})) + await user.keyboard('{ArrowDown}{Meta>}{Shift>}u{/Shift}{/Meta}') + const dialog = screen.getByRole('dialog', {name: 'Supplemental actions'}) + await waitFor(() => expect(within(dialog).getByRole('button', {name: 'Inspect'})).toHaveFocus()) + await user.keyboard('{Escape}') + expect(screen.queryByRole('dialog', {name: 'Supplemental actions'})).not.toBeInTheDocument() + expect(screen.getByRole('dialog', {name: 'Fruit actions'})).toBeInTheDocument() + await waitFor(() => expect(screen.getByRole('option', {name: 'Apple'})).toHaveFocus()) + await user.keyboard('{Escape}') + expect(screen.queryByRole('dialog', {name: 'Fruit actions'})).not.toBeInTheDocument() + }) + + it('focuses an enabled supplemental action and activates it by keyboard without selecting', async () => { + const user = userEvent.setup() + const disabledAction = vi.fn() + const onAction = vi.fn() + const onSelectedChange = vi.fn() + render( + , + ) + await user.click(screen.getByRole('button', {name: 'Open actions'})) + await user.keyboard('{ArrowDown}{Control>}{Shift>}u{/Shift}{/Control}') + const dialog = screen.getByRole('dialog', {name: 'Supplemental actions'}) + expect(within(dialog).getByRole('button', {name: 'Unavailable action'})).toHaveAttribute('aria-disabled', 'true') + await waitFor(() => expect(within(dialog).getByRole('button', {name: 'Inspect Apple'})).toHaveFocus()) + await user.keyboard('{Enter}') + expect(onAction).toHaveBeenCalledOnce() + expect(disabledAction).not.toHaveBeenCalled() + expect(onSelectedChange).not.toHaveBeenCalled() + expect(screen.queryByRole('dialog', {name: 'Supplemental actions'})).not.toBeInTheDocument() + await waitFor(() => expect(screen.getByRole('option', {name: 'Apple'})).toHaveFocus()) + }) + + it('dismisses only the supplemental dialog when clicking outside it', async () => { + const user = userEvent.setup() + render( + , + ) + await user.click(screen.getByRole('button', {name: 'Open actions'})) + await user.keyboard('{ArrowDown}{Control>}{Shift>}u{/Shift}{/Control}') + const dialog = screen.getByRole('dialog', {name: 'Supplemental actions'}) + await waitFor(() => expect(within(dialog).getByRole('button', {name: 'Inspect'})).toHaveFocus()) + await user.click(screen.getByRole('textbox', {name: 'Filter actions'})) + expect(screen.queryByRole('dialog', {name: 'Supplemental actions'})).not.toBeInTheDocument() + expect(screen.getByRole('dialog', {name: 'Fruit actions'})).toBeInTheDocument() + await waitFor(() => expect(screen.getByRole('option', {name: 'Apple'})).toHaveFocus()) + }) + + it('prevents keys on pointer-only buttons from selecting their item', async () => { + const user = userEvent.setup() + const onSelectedChange = vi.fn() + render() + await user.click(screen.getByRole('button', {name: 'Open actions'})) + const pointerAction = screen.getByTitle('Inspect Apple') + fireEvent.keyDown(pointerAction, {key: 'Enter'}) + fireEvent.keyPress(pointerAction, {key: 'Enter', charCode: 13}) + expect(onSelectedChange).not.toHaveBeenCalled() + expect(screen.getByRole('dialog', {name: 'Fruit actions'})).toBeInTheDocument() + }) + + it.each([{disabled: true}, {'aria-disabled': true}, {loading: true}, {inactiveText: 'Not available'}])( + 'does not activate secondary actions on unavailable items: %j', + async itemProps => { + const user = userEvent.setup() + const onAction = vi.fn() + render( + , + ) + await user.click(screen.getByRole('button', {name: 'Open actions'})) + const item = screen.getAllByRole('option')[0] + fireEvent.keyDown(item, {key: 'u', shiftKey: true, ctrlKey: true}) + const pointerAction = screen.queryByTitle('Inspect Apple') + if (pointerAction) { + expect(pointerAction).toHaveAttribute('data-disabled', 'true') + fireEvent.click(pointerAction) + } + expect(onAction).not.toHaveBeenCalled() + expect(item).not.toHaveAttribute('aria-keyshortcuts') + if ('disabled' in itemProps || 'aria-disabled' in itemProps) { + await user.keyboard('{ArrowDown}') + expect(screen.getByRole('option', {name: 'Banana'})).toHaveFocus() + expect(item).toHaveAttribute('tabindex', '-1') + } + }, + ) + + it('respects disabled actions, consumer cancellation, modifiers, and repeat', async () => { + const user = userEvent.setup() + const onAction = vi.fn() + const onKeyDown = vi.fn((event: React.KeyboardEvent) => event.preventDefault()) + const {rerender} = render( + , + ) + await user.click(screen.getByRole('button', {name: 'Open actions'})) + const item = screen.getByRole('option', {name: 'Apple'}) + fireEvent.keyDown(item, {key: 'u', shiftKey: true, ctrlKey: true}) + expect(onKeyDown).toHaveBeenCalled() + expect(onAction).not.toHaveBeenCalled() + rerender() + fireEvent.keyDown(item, {key: 'u', shiftKey: true, ctrlKey: true, altKey: true}) + fireEvent.keyDown(item, {key: 'u', shiftKey: true, ctrlKey: true, repeat: true}) + fireEvent.keyDown(item, {key: 'u', ctrlKey: true}) + expect(onAction).not.toHaveBeenCalled() + rerender() + fireEvent.keyDown(item, {key: 'u', shiftKey: true, ctrlKey: true}) + expect(screen.getByTitle('Inspect Apple')).toHaveAttribute('data-disabled', 'true') + expect(onAction).not.toHaveBeenCalled() + }) + }) + + it('does not dismiss a parent when interacting inside its portaled child', async () => { + const user = userEvent.setup() + render() + await user.click(screen.getByRole('button', {name: 'Open parent'})) + await user.click(screen.getByTitle('Apple details')) + await user.click(screen.getByText('Details are independent of selection.')) + expect(screen.getByRole('dialog', {name: 'Parent picker'})).toBeInTheDocument() + expect(screen.getByRole('dialog', {name: 'Apple information'})).toBeInTheDocument() + }) + + it('returns to the parent input if the invoking row is removed', async () => { + const user = userEvent.setup() + const {rerender} = render() + await user.click(screen.getByRole('button', {name: 'Open parent'})) + await user.click(screen.getByTitle('Apple details')) + expect(screen.getByRole('dialog', {name: 'Apple information'})).toBeInTheDocument() + rerender() + expect(screen.queryByRole('dialog', {name: 'Apple information'})).not.toBeInTheDocument() + await waitFor(() => expect(screen.getByRole('textbox', {name: 'Parent filter'})).toHaveFocus()) + }) +}) diff --git a/packages/react/src/SelectPanel/SelectPanel.examples.stories.tsx b/packages/react/src/SelectPanel/SelectPanel.examples.stories.tsx index 7434581cee8..b264c8f576e 100644 --- a/packages/react/src/SelectPanel/SelectPanel.examples.stories.tsx +++ b/packages/react/src/SelectPanel/SelectPanel.examples.stories.tsx @@ -724,7 +724,7 @@ export const VirtualizedConsumerSide = () => { [virtualizer], )} focusOutBehavior="stop" - scrollContainerRef={node => setScrollContainer(node)} + scrollContainerRef={setScrollContainer} actionListProps={{ style: renderSubset ? { diff --git a/packages/react/src/SelectPanel/SelectPanel.focus.test.tsx b/packages/react/src/SelectPanel/SelectPanel.focus.test.tsx new file mode 100644 index 00000000000..3e4a303d8f7 --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanel.focus.test.tsx @@ -0,0 +1,319 @@ +import {act, fireEvent, render} from '@testing-library/react' +import {InfoIcon} from '@primer/octicons-react' +import {describe, expect, it, vi} from 'vitest' +import {page, userEvent} from 'vitest/browser' +import type {ComponentProps} from 'react' +import axe from 'axe-core' +import BaseStyles from '../BaseStyles' +import {SelectPanel, type SelectPanelRootProps} from '.' +import {CustomLayout, ExplicitApplyCancel, ResponsiveImmediateSelection} from './SelectPanel.composition.stories' + +const fruit = [ + {value: 'apple', label: 'Apple'}, + {value: 'banana', label: 'Banana', disabled: true}, + {value: 'cherry', label: 'Cherry'}, +] + +function FocusPicker({ + options = fruit, + search = true, + inputProps, + listProps, + ...props +}: SelectPanelRootProps & { + options?: {value: string; label: string; disabled?: boolean; hidden?: boolean}[] + search?: boolean + inputProps?: ComponentProps + listProps?: ComponentProps +}) { + return ( + + + {search && } + + {options.map(option => ( + + ))} + + + + + ) +} + +const input = () => page.getByRole('combobox', {name: 'Filter fruit', exact: true}) +const option = (name: string) => page.getByRole('option', {name, exact: true}) + +describe('SelectPanel focus strategies', () => { + it('defaults to a combobox that activates the first result with Enter without moving DOM focus', async () => { + const onSelectedChange = vi.fn() + render() + await userEvent.click(input()) + expect(input().element()).toHaveAttribute('aria-controls', page.getByRole('listbox').element().id) + expect(input().element()).toHaveAttribute('aria-expanded', 'true') + expect(input().element()).toHaveAttribute('aria-autocomplete', 'list') + expect(input().element()).toHaveAttribute('aria-activedescendant', option('Apple').element().id) + for (const name of ['Apple', 'Banana', 'Cherry']) expect(option(name).element()).toHaveAttribute('tabindex', '-1') + await userEvent.keyboard('{Enter}') + expect(onSelectedChange).toHaveBeenCalledExactlyOnceWith(['apple']) + expect(input().element()).toHaveFocus() + expect(option('Apple').element()).toHaveAttribute('aria-selected', 'true') + fireEvent.keyDown(input().element(), {key: 'Enter', repeat: true}) + expect(onSelectedChange).toHaveBeenCalledTimes(1) + await userEvent.keyboard(' ') + expect(input().element()).toHaveValue(' ') + expect(onSelectedChange).toHaveBeenCalledTimes(1) + }) + + it('wraps active results, skips disabled options, and preserves text-editing keys', async () => { + render() + await userEvent.click(input()) + await userEvent.keyboard('{ArrowDown}') + expect(input().element()).toHaveAttribute('aria-activedescendant', option('Cherry').element().id) + expect(option('Cherry').element()).toHaveAttribute('data-is-active-descendant', 'activated-directly') + await userEvent.keyboard('{Home}{End}') + expect(input().element()).toHaveAttribute('aria-activedescendant', option('Cherry').element().id) + await userEvent.keyboard('{ArrowDown}') + expect(input().element()).toHaveAttribute('aria-activedescendant', option('Apple').element().id) + await userEvent.keyboard('{ArrowUp}{Enter}') + expect(input().element()).toHaveFocus() + expect(option('Cherry').element()).toHaveAttribute('aria-selected', 'true') + expect(option('Banana').element()).toHaveAttribute('aria-selected', 'false') + await userEvent.tab() + expect(page.getByRole('button', {name: 'After picker'}).element()).toHaveFocus() + expect(input().element()).not.toHaveAttribute('aria-activedescendant') + expect(option('Cherry').element()).not.toHaveAttribute('data-is-active-descendant') + }) + + it('repairs filtered, disabled, hidden, and empty results without stealing search focus', async () => { + const {rerender} = render() + await userEvent.click(input()) + await userEvent.keyboard('{ArrowDown}') + rerender() + await expect.element(input()).toHaveAttribute('aria-activedescendant', option('Apple').element().id) + expect(input().element()).toHaveFocus() + rerender() + await expect.element(input()).toHaveAttribute('aria-activedescendant', option('Cherry').element().id) + rerender( + , + ) + await expect.element(input()).toHaveAttribute('aria-activedescendant', option('Apple').element().id) + rerender() + await expect.element(input()).not.toHaveAttribute('aria-activedescendant') + await userEvent.keyboard('{ArrowDown}{Enter}') + expect(input().element()).toHaveFocus() + rerender() + await expect.element(input()).toHaveAttribute('aria-activedescendant', option('Cherry').element().id) + await userEvent.keyboard('{Enter}') + expect(option('Cherry').element()).toHaveAttribute('aria-selected', 'true') + }) + + it('honors canceled search navigation and does not activate during IME composition', async () => { + const onSelectedChange = vi.fn() + const onKeyDown = vi.fn(event => event.preventDefault()) + const {rerender} = render() + await userEvent.click(input()) + await userEvent.keyboard('{ArrowDown}{Enter}') + expect(input().element()).toHaveAttribute('aria-activedescendant', option('Apple').element().id) + expect(onSelectedChange).not.toHaveBeenCalled() + rerender() + fireEvent.keyDown(input().element(), {key: 'ArrowDown', isComposing: true}) + fireEvent.keyDown(input().element(), {key: 'Enter', isComposing: true}) + fireEvent.keyDown(input().element(), {key: 'ArrowDown', altKey: true}) + expect(input().element()).toHaveAttribute('aria-activedescendant', option('Apple').element().id) + expect(onSelectedChange).not.toHaveBeenCalled() + }) + + it('honors canceled item activation forwarded from the input', async () => { + const onSelectedChange = vi.fn() + const onSelect = vi.fn(event => event.preventDefault()) + render( + + + + + Apple + + + , + ) + await userEvent.click(input()) + await userEvent.keyboard('{Enter}') + expect(onSelect).toHaveBeenCalledTimes(1) + expect(onSelectedChange).not.toHaveBeenCalled() + expect(input().element()).toHaveFocus() + }) + + it('keeps focus in search for pointer selection and updates the active result', async () => { + render() + await userEvent.click(input()) + await userEvent.click(option('Cherry')) + expect(input().element()).toHaveFocus() + expect(input().element()).toHaveAttribute('aria-activedescendant', option('Cherry').element().id) + expect(option('Cherry').element()).toHaveAttribute('aria-selected', 'true') + await userEvent.keyboard('{Enter}') + expect(option('Cherry').element()).toHaveAttribute('aria-selected', 'false') + }) + + it('supports explicit roving focus and falls back to roving without a search input', async () => { + const {rerender} = render() + const textbox = page.getByRole('textbox', {name: 'Filter fruit', exact: true}) + await userEvent.click(textbox) + await userEvent.keyboard('{ArrowDown}') + expect(option('Apple').element()).toHaveFocus() + expect(textbox.element()).not.toHaveAttribute('aria-activedescendant') + await userEvent.keyboard('{ArrowDown}{Enter}') + expect(option('Cherry').element()).toHaveFocus() + expect(option('Cherry').element()).toHaveAttribute('aria-selected', 'true') + rerender() + await expect.element(option('Cherry')).toHaveAttribute('tabindex', '0') + act(() => option('Apple').element().focus()) + await userEvent.keyboard('{ArrowUp}') + expect(option('Cherry').element()).toHaveFocus() + }) + + it('uses a roving tab stop by default for a searchless list', async () => { + render() + expect(option('Apple').element()).toHaveAttribute('tabindex', '0') + act(() => option('Apple').element().focus()) + await userEvent.keyboard('{ArrowUp}{Enter}') + expect(option('Cherry').element()).toHaveFocus() + expect(option('Cherry').element()).toHaveAttribute('aria-selected', 'true') + expect(option('Banana').element()).toHaveAttribute('tabindex', '-1') + }) + + it('keeps the collection keyboard-accessible when search is disabled and restores virtual focus when enabled', async () => { + const {rerender} = render() + await expect.element(option('Apple')).toHaveAttribute('tabindex', '0') + await userEvent.click(option('Apple')) + expect(option('Apple').element()).toHaveFocus() + await userEvent.keyboard('{ArrowDown}') + expect(option('Cherry').element()).toHaveFocus() + rerender() + await userEvent.click(input()) + await expect.element(option('Cherry')).toHaveAttribute('tabindex', '-1') + expect(input().element()).toHaveAttribute('aria-activedescendant', option('Cherry').element().id) + rerender() + await expect.element(option('Cherry')).toHaveAttribute('tabindex', '0') + expect(input().element()).not.toHaveAttribute('aria-activedescendant') + }) + + it('cleans up active-descendant relationships when switching strategy', async () => { + const {rerender} = render() + await userEvent.click(input()) + await userEvent.keyboard('{ArrowDown}') + rerender() + const textbox = page.getByRole('textbox', {name: 'Filter fruit', exact: true}) + expect(textbox.element()).not.toHaveAttribute('aria-activedescendant') + expect(option('Cherry').element()).not.toHaveAttribute('data-is-active-descendant') + expect(textbox.element()).toHaveFocus() + await userEvent.keyboard('{ArrowDown}') + expect(option('Apple').element()).toHaveFocus() + }) + + it('opens supplemental actions from the active result and restores input focus', async () => { + const onAction = vi.fn() + render( + + + + + + Apple + + + + , + ) + await userEvent.click(input()) + await userEvent.keyboard('{Control>}{Shift>}u{/Shift}{/Control}') + await expect.element(page.getByRole('dialog', {name: 'Supplemental actions'})).toBeVisible() + await userEvent.keyboard('{Escape}') + await expect.element(input()).toHaveFocus() + expect(input().element()).toHaveAttribute('aria-activedescendant', option('Apple').element().id) + expect(onAction).not.toHaveBeenCalled() + }) + + it('has no detectable accessibility violations with an active result', async () => { + const {container} = render() + await userEvent.click(input()) + const result = await axe.run(container, {rules: {'color-contrast': {enabled: false}}}) + expect(result.violations).toEqual([]) + }) +}) + +describe('SelectPanel story save policies', () => { + it('supports type-and-Enter quick selection with closeOnSelect in the single-selection story', async () => { + render( + + + , + ) + const trigger = page.getByRole('button', {name: 'Primary label', exact: true}) + await userEvent.click(trigger) + const search = page.getByRole('combobox', {name: 'Filter primary labels', exact: true}) + await userEvent.fill(search, 'Accessibility') + await expect + .element(search) + .toHaveAttribute( + 'aria-activedescendant', + page.getByRole('option', {name: 'Accessibility', exact: true}).element().id, + ) + await userEvent.keyboard('{Enter}') + await expect.element(page.getByRole('dialog')).not.toBeInTheDocument() + await expect.element(trigger).toHaveFocus() + expect(trigger.element()).toHaveTextContent('Accessibility') + }) + + it.each(['escape', 'outside', 'done'] as const)('applies the primary story selection on %s', async gesture => { + await page.viewport(1200, 900) + render( + + + , + ) + await userEvent.click(page.getByRole('button', {name: 'Labels (1)', exact: true})) + const search = page.getByRole('combobox') + await userEvent.fill(search, 'Enhancement') + await userEvent.keyboard('{Enter}') + expect(search.element()).toHaveFocus() + expect(page.getByText('Saved labels: Bug', {exact: true}).element()).toBeVisible() + if (gesture === 'escape') await userEvent.keyboard('{Escape}') + else if (gesture === 'outside') await userEvent.click(document.body, {position: {x: 1100, y: 800}, force: true}) + else await userEvent.click(page.getByRole('button', {name: 'Done', exact: true})) + await expect.element(page.getByText('Saved labels: Bug, Enhancement', {exact: true})).toBeVisible() + await userEvent.click(page.getByRole('button', {name: 'Labels (2)', exact: true})) + expect(page.getByRole('option', {name: /Enhancement/}).element()).toHaveAttribute('aria-selected', 'true') + }) + + it('keeps explicit Save/Cancel opt-in and discards that story draft on dismissal', async () => { + render( + + + , + ) + await userEvent.click(page.getByRole('button', {name: 'Labels (1)', exact: true})) + await userEvent.fill(page.getByRole('combobox'), 'Enhancement') + await userEvent.keyboard('{Enter}{Escape}') + await expect.element(page.getByText('Saved labels: Bug', {exact: true})).toBeVisible() + await userEvent.click(page.getByRole('button', {name: 'Labels (1)', exact: true})) + expect(page.getByRole('option', {name: /Enhancement/}).element()).toHaveAttribute('aria-selected', 'false') + await userEvent.fill(page.getByRole('combobox'), 'Enhancement') + await userEvent.keyboard('{Enter}') + await userEvent.click(page.getByRole('button', {name: 'Save', exact: true})) + await expect.element(page.getByText('Saved labels: Bug, Enhancement', {exact: true})).toBeVisible() + }) +}) diff --git a/packages/react/src/SelectPanel/SelectPanel.module.css b/packages/react/src/SelectPanel/SelectPanel.module.css index 7fc46e2b1fb..afb729bd95a 100644 --- a/packages/react/src/SelectPanel/SelectPanel.module.css +++ b/packages/react/src/SelectPanel/SelectPanel.module.css @@ -88,6 +88,13 @@ border-top-color: var(--borderColor-default); } +.ItemActions { + display: inline-flex; + height: var(--control-medium-lineBoxHeight); + pointer-events: auto; + align-items: center; +} + .FilteredActionList { /* inheriting height and maxHeight ensures that the FilteredActionList is never taller than the Overlay (which would break scrolling the items) */ @@ -95,7 +102,8 @@ max-height: inherit; } -.Message { +.Message, +.Loading { display: flex; height: 100%; padding: var(--base-size-24); @@ -105,13 +113,67 @@ align-items: center; flex-grow: 1; gap: var(--base-size-4); +} +.Message { a { color: inherit; text-decoration: underline; } } +.MessageContent { + display: flex; + flex-direction: column; + align-items: center; + gap: var(--base-size-4); +} + +.Message:where([data-size='inline']), +.Loading:where([data-size='inline']) { + height: auto; + padding: var(--base-size-8) var(--base-size-16); + text-align: left; + flex-grow: 0; + gap: var(--base-size-8); +} + +.Message:where([data-size='inline']) { + display: grid; + grid-template-columns: minmax(0, 1fr); + align-items: start; + + &:where([data-has-icon]) { + grid-template-columns: auto minmax(0, 1fr); + } + + .MessageContent { + grid-column: -2 / -1; + align-items: flex-start; + } + + .MessageIcon { + grid-column: 1; + grid-row: 1; + margin-bottom: 0; + } + + .MessageAction { + grid-column: -2 / -1; + margin-top: 0; + } +} + +.Loading:where([data-size='inline']) { + flex-direction: row; + justify-content: flex-start; +} + +.Message:where([hidden]), +.Loading:where([hidden]) { + display: none; +} + .MessageTitle { font-size: var(--text-body-size-medium); font-weight: var(--base-text-weight-semibold); @@ -234,3 +296,14 @@ .TextInput { margin: var(--base-size-8); } + +.SearchInput { + min-width: 0; + max-width: calc(100% - var(--base-size-16)); +} + +.List { + min-height: 0; + overflow: auto; + flex: 1; +} diff --git a/packages/react/src/SelectPanel/SelectPanel.platform.stories.tsx b/packages/react/src/SelectPanel/SelectPanel.platform.stories.tsx new file mode 100644 index 00000000000..55d0625ee2f --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanel.platform.stories.tsx @@ -0,0 +1,193 @@ +import {useState} from 'react' +import type {Meta, StoryObj} from '@storybook/react-vite' +import {expect, waitFor} from 'storybook/test' +import {Button} from '../Button' +import {FeatureFlags} from '../FeatureFlags' +import {SelectPanel} from './SelectPanel' +import {nativeSelectPanelCapabilities} from './platform/NativeSelectPanelContext' +import {PlatformSelectPanel} from './platform/PlatformSelectPanel' + +interface PlatformStoryArgs { + nativeDialog: boolean + invokers: boolean +} + +const meta = { + title: 'Components/SelectPanel/Platform', + args: { + nativeDialog: false, + invokers: false, + }, + argTypes: { + nativeDialog: { + control: 'boolean', + description: 'Opt into the internal primer_react_select_panel_native_dialog adapter for composable parts.', + }, + invokers: { + control: 'boolean', + description: 'Opt into primer_react_select_panel_native_invokers when the native dialog is enabled.', + }, + }, + parameters: { + docs: { + description: { + component: + 'Web platform proofs of concept. Native dialog and invoker adapters are internal implementations of the composable parts, enabled by default-off feature flags. These stories use local Controls to override the global toolbar flags. Toggle the controls to compare with the existing overlay; unsupported browser features display an explicit fallback notice.', + }, + }, + }, +} satisfies Meta + +export default meta +type Story = StoryObj + +export const Popover: Story = { + parameters: { + controls: {exclude: ['nativeDialog', 'invokers']}, + docs: { + description: { + story: + 'Uses SelectPanel.Overlay renderAs="popover" with the CSS anchor positioning flag enabled. The story-only fixture sets overlayProps._PrivateDisablePortal only when the native popover is active. The picker remains inline in the DOM and renders in the browser top layer without an overlay portal; the shared backdrop still uses a portal. React still owns visibility, focus trapping, and dismissal. Unsupported and narrow fullscreen presentations retain the portal fallback.', + }, + source: { + // eslint-disable-next-line github/unescaped-html-literal -- Storybook displays this JSX as code, not HTML. + code: ` + +`, + }, + }, + }, + render: () => ( + +

+ renderAs="popover" opts into a manual, top-layer popover when native CSS anchor + positioning is available, without portaling the picker content. +

+ +
+ ), +} + +export const NativeDialog: Story = { + args: {nativeDialog: true}, + parameters: { + controls: {exclude: ['invokers']}, + docs: { + description: { + story: + 'Opt-in native adapter. showModal() supplies focus containment, top-layer rendering, and an inert background. Disable nativeDialog in Controls to compare with the existing SelectPanel overlay. The same default-off flag works in ordinary composition stories.', + }, + }, + }, + render: ({nativeDialog}) => ( + +

+ An internal <dialog> host reuses the same SelectPanel search, list, items, and selection + state. Toggle nativeDialog in Controls to compare implementations. +

+ +
+ ), +} + +function NativeAnchoredPicker() { + const [filter, setFilter] = useState('') + return ( + + Choose labels + + + + Native labels + + + + + {['Bug', 'Enhancement', 'Accessibility'] + .filter(label => label.toLowerCase().includes(filter.toLowerCase())) + .map(label => ( + + {label} + + ))} + + + + + ) +} + +export const NativeAnchored: Story = { + args: {nativeDialog: true, invokers: true}, + parameters: { + docs: { + description: { + story: + 'Anchored native panels use a manual top-layer popover with dialog semantics, without making the page inert or locking background scrolling. Tab can leave the panel, Escape dismisses it, and clicking a background control preserves its focus. Native invokers use toggle-popover and hide-popover, not show-modal. Turning nativeDialog off retains the compatibility implementation.', + }, + }, + }, + render: ({nativeDialog, invokers}) => ( + +
+ +

Open the picker, then scroll the page, Tab outside it, or activate the background action.

+ +
+
+ ), + play: async ({canvas, userEvent, args}) => { + if (!args.nativeDialog || nativeSelectPanelCapabilities() === 'unsupported') return + const trigger = canvas.getByRole('button', {name: 'Choose labels'}) + await userEvent.click(trigger) + await waitFor(() => expect(trigger).toHaveAttribute('aria-expanded', 'true')) + const dialog = canvas.getByRole('dialog', {name: 'Native labels'}) + await expect(dialog).not.toHaveAttribute('aria-modal') + const background = canvas.getByRole('button', {name: 'Background action'}) + await userEvent.click(background) + await waitFor(() => expect(trigger).toHaveAttribute('aria-expanded', 'false')) + await expect(background).toHaveFocus() + }, +} + +export const Invokers: Story = { + args: {nativeDialog: true, invokers: true}, + parameters: { + docs: { + description: { + story: + 'Opt-in native command/commandfor buttons target a persistently mounted dialog. The browser performs show-modal and close; the adapter synchronizes those commands with SelectPanel state. Disable invokers to retain the native dialog with JavaScript activation, or disable nativeDialog to return to the existing overlay.', + }, + }, + }, + render: ({nativeDialog, invokers}) => ( + +

+ Native command="show-modal" and command="close" buttons target the + dialog using commandfor. Toggle invokers in Controls to compare activation paths. +

+ +
+ ), +} diff --git a/packages/react/src/SelectPanel/SelectPanel.playground.stories.tsx b/packages/react/src/SelectPanel/SelectPanel.playground.stories.tsx new file mode 100644 index 00000000000..16b24cc3c13 --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanel.playground.stories.tsx @@ -0,0 +1,26 @@ +import type {Meta} from '@storybook/react-vite' +import {SelectPanelDemo} from './playground/SelectPanelDemo' +import {SelectPanelPlayground} from './playground/SelectPanelPlayground' +import {StorybookPreview, StorybookPreviewSurface} from './playground/StorybookPreview' +import skinSource from './playground/SelectPanelDemo.module.css?raw' + +const meta = { + title: 'Components/SelectPanel/Playground', + parameters: { + layout: 'fullscreen', + controls: {disable: true}, + }, + globals: { + showSurroundingElements: false, + }, +} satisfies Meta + +export default meta + +export const Playground = () => ( + } /> +) + +Playground.globals = {colorScheme: 'dark'} + +export const PreviewSurface = () => } /> diff --git a/packages/react/src/SelectPanel/SelectPanel.ref-selector.stories.module.css b/packages/react/src/SelectPanel/SelectPanel.ref-selector.stories.module.css new file mode 100644 index 00000000000..81a42f708be --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanel.ref-selector.stories.module.css @@ -0,0 +1,39 @@ +.Content { + min-height: 0; + max-height: min(var(--overlay-height-xlarge), calc(100dvh - var(--base-size-64))); + + @media screen and (--viewportRange-narrow) { + max-height: 100dvh; + } +} + +.Header { + align-items: center; + padding-bottom: var(--base-size-8); +} + +.Tabs { + flex-shrink: 0; + border-top: var(--borderWidth-thin) solid var(--borderColor-default); +} + +.TabPanel:not([hidden]) { + display: flex; + min-height: 0; + overflow: auto; + flex: 1; + flex-direction: column; +} + +.List { + padding-block: var(--base-size-8); +} + +.Footer { + padding: 0; + flex-shrink: 0; +} + +.FooterList { + width: 100%; +} diff --git a/packages/react/src/SelectPanel/SelectPanel.ref-selector.stories.tsx b/packages/react/src/SelectPanel/SelectPanel.ref-selector.stories.tsx new file mode 100644 index 00000000000..e073792d194 --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanel.ref-selector.stories.tsx @@ -0,0 +1,166 @@ +import {GitBranchIcon, TagIcon, TriangleDownIcon} from '@primer/octicons-react' +import type {Meta, StoryObj} from '@storybook/react-vite' +import {useState} from 'react' +import {ActionList} from '../ActionList' +import {UnderlinePanels} from '../experimental' +import Label from '../Label' +import {SelectPanel, type SelectPanelValue} from '../SelectPanel' +import classes from './SelectPanel.ref-selector.stories.module.css' + +const refTypes = [ + { + value: 'branch', + label: 'Branches', + placeholder: 'Find or create a branch...', + href: 'https://github.com/primer/react/branches', + names: [ + 'main', + 'mattcosta7-breadcrumbs-resize-perf', + 'mattcosta7-actionlist-treeview-invalidation-fix', + 'liuliu/fix-selectpanel-announcement', + 'joshfarrant/segmentedcontrol-reintroduction', + 'joshfarrant/impeccable', + 'joshfarrant/detached-anchor-aria-fix', + 'joshblack/react-compiler-token-remove-button', + ], + }, + { + value: 'tag', + label: 'Tags', + placeholder: 'Search or create a new tag', + href: 'https://github.com/primer/react/tags', + names: [ + 'v36.14.0', + 'v36.7.1', + 'v36.7.0', + 'v36.6.0', + 'v36.5.0', + 'v36.4.0', + 'v36.3.1', + 'v36.3.0', + 'v36.2.0', + 'v36.1.0', + ], + }, +] as const + +export function RefSelectorExample() { + const [open, setOpen] = useState(false) + const [refType, setRefType] = useState('branch') + const [selected, setSelected] = useState(['branch:main']) + const [filter, setFilter] = useState('') + const selectedType = refTypes.find(type => type.names.some(name => selected.includes(`${type.value}:${name}`)))! + const selectedName = selectedType.names.find(name => selected.includes(`${selectedType.value}:${name}`))! + const activeType = refTypes.find(type => type.value === refType)! + const query = filter.trim().toLowerCase() + + return ( + { + if (nextOpen) { + setFilter('') + setRefType(selectedType.value) + } + setOpen(nextOpen) + }} + selectionMode="single" + closeOnSelect + selected={selected} + onSelectedChange={values => { + // A repository always has a current ref, even when its selected row is activated again. + if (values.length > 0) setSelected(values) + }} + filterValue={filter} + onFilterChange={setFilter} + > + + {selectedName} + + + + + Switch branches/tags + + + + setRefType(value)} + > + {refTypes.map(type => ( + + {type.label} + + ))} + {refTypes.map(type => { + const results = type.names.filter(name => name.toLowerCase().includes(query)) + return ( + + {refType === type.value ? ( + results.length > 0 ? ( + + {results.map(name => ( + + {name} + {type.value === 'branch' && name === 'main' ? ( + // eslint-disable-next-line primer-react/direct-slot-children -- SelectPanel.Item forwards ActionList slots. + + + + ) : null} + + ))} + + ) : ( + + Try a different name. + + ) + ) : null} + + ) + })} + + + + + View all {activeType.label.toLowerCase()} + + + + + + + ) +} + +const meta = { + title: 'Components/SelectPanel/Composition/RefSelector', + component: SelectPanel.Root, + excludeStories: ['RefSelectorExample'], + parameters: { + controls: {disable: true}, + }, +} satisfies Meta + +export default meta + +type Story = StoryObj + +export const Default: Story = { + render: () => , + parameters: { + docs: { + description: { + story: + 'A branch/tag picker composed entirely from the existing SelectPanel API and UnderlinePanels, with repository navigation in a separate footer ActionList. Search, the active tab, and the current ref are application-owned. Static fixtures demonstrate filtering and single selection; branch/tag creation and repository requests are intentionally out of scope.', + }, + }, + }, +} diff --git a/packages/react/src/SelectPanel/SelectPanel.ref-selector.test.tsx b/packages/react/src/SelectPanel/SelectPanel.ref-selector.test.tsx new file mode 100644 index 00000000000..55bb2991a0c --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanel.ref-selector.test.tsx @@ -0,0 +1,111 @@ +import {render} from '@testing-library/react' +import {describe, expect, it} from 'vitest' +import {page, userEvent} from 'vitest/browser' +import BaseStyles from '../BaseStyles' +import {RefSelectorExample} from './SelectPanel.ref-selector.stories' + +function renderExample() { + render( + + + , + ) +} + +describe('SelectPanel RefSelector example', () => { + it('filters branches and tags, recovers from no results, and maintains the active collection relationship', async () => { + renderExample() + await userEvent.click(page.getByRole('button', {name: 'main', exact: true})) + const search = page.getByRole('combobox', {name: 'Find a branch or tag'}) + await expect.element(search).toHaveFocus() + await expect + .element(page.getByRole('option', {name: 'main default', exact: true})) + .toHaveAttribute('aria-selected', 'true') + + await userEvent.fill(search, 'NO-MATCH') + await expect.element(page.getByText('No branches found')).toBeVisible() + await expect.element(page.getByRole('listbox')).not.toBeInTheDocument() + await expect.element(search).not.toHaveAttribute('aria-controls') + await userEvent.fill(search, ' IMPECCABLE ') + await expect.element(page.getByRole('option', {name: 'joshfarrant/impeccable', exact: true})).toBeVisible() + expect(page.getByRole('option').all()).toHaveLength(1) + + await userEvent.clear(search) + await userEvent.click(page.getByRole('tab', {name: /^Branches\b/})) + await userEvent.keyboard('{ArrowRight}') + await expect.element(page.getByRole('tab', {name: /^Tags\b/})).toHaveAttribute('aria-selected', 'true') + await expect.element(search).toHaveAttribute('placeholder', 'Search or create a new tag') + expect(page.getByRole('listbox').all()).toHaveLength(1) + await expect + .element(search) + .toHaveAttribute('aria-controls', page.getByRole('listbox', {name: 'Tags'}).element().id) + await userEvent.fill(search, 'v36.7') + expect(page.getByRole('option').all()).toHaveLength(2) + await userEvent.fill(search, 'NO-MATCH') + await expect.element(page.getByText('No tags found')).toBeVisible() + await userEvent.clear(search) + await expect.element(page.getByRole('option', {name: 'v36.14.0', exact: true})).toBeVisible() + }) + + it('selects with the keyboard, returns focus, and cannot deselect the current ref', async () => { + renderExample() + await userEvent.click(page.getByRole('button', {name: 'main', exact: true})) + const search = page.getByRole('combobox', {name: 'Find a branch or tag'}) + await userEvent.fill(search, 'impeccable') + const option = page.getByRole('option', {name: 'joshfarrant/impeccable', exact: true}) + await userEvent.keyboard('{ArrowDown}') + await expect.element(search).toHaveAttribute('aria-activedescendant', option.element().id) + await userEvent.keyboard('{Enter}') + await expect.element(page.getByRole('dialog')).not.toBeInTheDocument() + const trigger = page.getByRole('button', {name: 'joshfarrant/impeccable', exact: true}) + await expect.element(trigger).toHaveFocus() + await userEvent.click(trigger) + await expect.element(search).toHaveValue('') + await expect.element(option).toHaveAttribute('aria-selected', 'true') + await userEvent.click(option) + await expect.element(page.getByRole('dialog')).not.toBeInTheDocument() + await expect.element(trigger).toHaveFocus() + await userEvent.click(trigger) + await expect.element(option).toHaveAttribute('aria-selected', 'true') + }) + + it('keeps selection independent of the tab and updates the trigger and footer when a tag is chosen', async () => { + renderExample() + await userEvent.click(page.getByRole('button', {name: 'main', exact: true})) + const footer = page.getByRole('list') + const branchesLink = footer.getByRole('link', {name: 'View all branches'}) + await expect.element(branchesLink).toHaveAttribute('href', 'https://github.com/primer/react/branches') + expect(page.getByRole('listbox').element()).not.toContainElement(branchesLink.element()) + await userEvent.click(page.getByRole('tab', {name: /^Tags\b/})) + await expect + .element(footer.getByRole('link', {name: 'View all tags'})) + .toHaveAttribute('href', 'https://github.com/primer/react/tags') + const tag = page.getByRole('option', {name: 'v36.14.0', exact: true}) + await expect.element(tag).toHaveAttribute('aria-selected', 'false') + await userEvent.click(tag) + await expect.element(page.getByRole('dialog')).not.toBeInTheDocument() + const trigger = page.getByRole('button', {name: 'v36.14.0', exact: true}) + await expect.element(trigger).toHaveFocus() + await userEvent.click(trigger) + await expect.element(page.getByRole('tab', {name: /^Tags\b/})).toHaveAttribute('aria-selected', 'true') + await expect.element(tag).toHaveAttribute('aria-selected', 'true') + await userEvent.click(page.getByRole('tab', {name: /^Branches\b/})) + await expect + .element(page.getByRole('option', {name: 'main default', exact: true})) + .toHaveAttribute('aria-selected', 'false') + }) + + it.each(['close button', 'Escape'] as const)('dismisses using %s and restores focus', async method => { + renderExample() + const trigger = page.getByRole('button', {name: 'main', exact: true}) + await userEvent.click(trigger) + await expect.element(page.getByRole('combobox')).toHaveFocus() + if (method === 'close button') { + await userEvent.click(page.getByRole('button', {name: 'Close', exact: true})) + } else { + await userEvent.keyboard('{Escape}') + } + await expect.element(page.getByRole('dialog')).not.toBeInTheDocument() + await expect.element(trigger).toHaveFocus() + }) +}) diff --git a/packages/react/src/SelectPanel/SelectPanel.rollback.test.tsx b/packages/react/src/SelectPanel/SelectPanel.rollback.test.tsx new file mode 100644 index 00000000000..8683f972156 --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanel.rollback.test.tsx @@ -0,0 +1,169 @@ +import React from 'react' +import {render} from '@testing-library/react' +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest' +import {page, userEvent} from 'vitest/browser' +import {FeatureFlags} from '../FeatureFlags' +import {getLiveRegion} from '../live-region/__tests__/test-helpers' +import {SelectPanel} from './SelectPanel' +import {SelectPanelMessage} from './SelectPanelMessage' + +describe.each([false, true])('configured SelectPanel rollback with adapter=%s', composable => { + function withFlags(children: React.ReactNode) { + return {children} + } + + beforeEach(() => { + document.body.appendChild(document.createElement('live-region')) + }) + + afterEach(() => { + getLiveRegion().remove() + }) + + it('gates named-message markup and live-region announcements', () => { + const ref = React.createRef() + render( + withFlags( + Retry} + > + Please try again. + , + ), + ) + + const message = ref.current + const title = page.getByText('Search unavailable', {exact: true}).element() + const body = page.getByText('Please try again.', {exact: true}).element() + expect(title.parentElement === message).toBe(!composable) + expect(body.parentElement).toBe(title.parentElement) + expect(page.getByRole('button', {name: 'Retry'}).element().closest('[data-component="SelectPanel.Message"]')).toBe( + message, + ) + if (composable) { + expect(message).toHaveAttribute('data-size', 'full') + expect(getLiveRegion().getMessage('polite')).toContain('Search unavailable') + expect(getLiveRegion().getMessage('polite')).not.toContain('Retry') + } else { + expect(message).not.toHaveAttribute('data-size') + expect(getLiveRegion().getMessage('polite')).toBe('') + } + }) + + it('always uses the new message part for explicit composition', () => { + render( + withFlags( + + Try another query. + , + ), + ) + expect(page.getByTestId('message').element()).toHaveAttribute('data-size', 'full') + expect(getLiveRegion().getMessage('polite')).toContain('No matches') + }) + + it('preserves configured headings while gating message markup', async () => { + render( + withFlags( + {}} + items={[]} + loading={false} + selected={[]} + onSelectedChange={() => {}} + onFilterChange={() => {}} + title="Choose labels" + subtitle="Labels for this issue" + message={{variant: 'error', title: 'Search unavailable', body: 'Please try again.'}} + />, + ), + ) + await expect.element(page.getByRole('heading', {name: 'Choose labels', level: 1})).toBeVisible() + const title = page.getByText('Search unavailable', {exact: true}).element() + const message = title.closest('[data-component="SelectPanel.Message"]') + expect(title.parentElement === message).toBe(!composable) + expect(page.getByRole('dialog').element()).toHaveAttribute( + 'aria-describedby', + page.getByText('Labels for this issue', {exact: true}).element().id, + ) + }) + + it('preserves reference-based anchored single selection until opted in', async () => { + const selected = {id: 'one', text: 'One'} + const item = {...selected} + const onSelectedChange = vi.fn() + const onOpenChange = vi.fn() + render( + withFlags( + {}} + />, + ), + ) + await userEvent.click(page.getByRole('option', {name: 'One', exact: true})) + expect(onSelectedChange).toHaveBeenCalledExactlyOnceWith(composable ? undefined : item) + expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false, 'selection') + }) + + it('preserves legacy ID comparison for modal drafts until opted in', async () => { + const first = {text: 'First'} + const second = {text: 'Second'} + const onSelectedChange = vi.fn() + const onOpenChange = vi.fn() + render( + withFlags( + {}} + items={[first, second]} + selected={first} + onSelectedChange={onSelectedChange} + onFilterChange={() => {}} + />, + ), + ) + await userEvent.click(page.getByRole('option', {name: 'Second', exact: true})) + expect(onSelectedChange).not.toHaveBeenCalled() + await userEvent.click(page.getByRole('button', {name: 'Save', exact: true})) + expect(onSelectedChange).toHaveBeenCalledExactlyOnceWith(composable ? second : undefined) + expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false, 'selection') + }) +}) + +it('retains the original overlay even when native flags are enabled without the adapter', async () => { + render( + + {}} + items={[{id: 'one', text: 'One'}]} + selected={[]} + onSelectedChange={() => {}} + onFilterChange={() => {}} + /> + , + ) + const dialog = page.getByRole('dialog') + await expect.element(dialog).toBeVisible() + expect(dialog.element()).not.toBeInstanceOf(HTMLDialogElement) + expect(dialog.element()).not.toHaveAttribute('aria-modal') + expect(page.getByRole('heading', {name: 'Select items', level: 1}).element()).toBeVisible() + expect(page.getByTestId('filtered-action-list').element()).toHaveAttribute('data-component', 'FilteredActionList') +}) diff --git a/packages/react/src/SelectPanel/SelectPanel.test.tsx b/packages/react/src/SelectPanel/SelectPanel.test.tsx index 6e4054a89e2..825c8f47655 100644 --- a/packages/react/src/SelectPanel/SelectPanel.test.tsx +++ b/packages/react/src/SelectPanel/SelectPanel.test.tsx @@ -1,5 +1,5 @@ -import {act, render, waitFor} from '@testing-library/react' -import {describe, expect, it, beforeEach, vi} from 'vitest' +import {act, render as rtlRender, waitFor} from '@testing-library/react' +import {describe, expect, it, beforeEach, afterAll, vi} from 'vitest' import {page, userEvent} from 'vitest/browser' import React from 'react' import {SelectPanel, type SelectPanelProps, type ItemInput, type GroupedListProps} from '../SelectPanel' @@ -44,2384 +44,2332 @@ export function getLiveRegion(): LiveRegionElement { throw new Error('No live-region found') } -const getFocusManagement = (flag?: boolean) => { - // true = 'use roving tabindex' - // false = 'use aria-activedescendant' - return flag ? 'roving-tabindex' : 'active-descendant' -} +describe.each([false, true])('Configured SelectPanel (composable adapter: %s)', composable => { + beforeEach(async () => { + await page.viewport(1280, 900) + }) + afterAll(async () => { + await page.viewport(1280, 720) + }) -const renderWithProp = (element: React.ReactElement, flag?: boolean) => { - return render(React.cloneElement(element, {_PrivateFocusManagement: getFocusManagement(flag)})) -} + const render = (ui: React.ReactNode) => + rtlRender(ui, { + wrapper: ({children}) => ( + {children} + ), + }) -const items: SelectPanelProps['items'] = [ - { - text: 'item one', - }, - { - text: 'item two', - }, - { - text: 'item three', - }, -] - -function BasicSelectPanel(passthroughProps: Record) { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) - - const onSelectedChange = (selected: SelectPanelProps['items']) => { - setSelected(selected) + const getFocusManagement = (flag?: boolean) => { + // true = 'use roving tabindex' + // false = 'use aria-activedescendant' + return flag ? 'roving-tabindex' : 'active-descendant' } - return ( - { - setFilter(value) - }} - open={open} - onOpenChange={isOpen => { - setOpen(isOpen) - }} - {...passthroughProps} - /> - ) -} - -globalThis.Element.prototype.scrollTo = vi.fn() + const renderWithProp = (element: React.ReactElement, flag?: boolean) => { + return render(React.cloneElement(element, {_PrivateFocusManagement: getFocusManagement(flag)})) + } -describe('SelectPanel state synchronization', () => { - const synchronizedItems: ItemInput[] = [ - {id: 'one', text: 'item one'}, - {id: 'two', text: 'item two'}, - {id: 'three', text: 'item three'}, + const items: SelectPanelProps['items'] = [ + { + text: 'item one', + }, + { + text: 'item two', + }, + { + text: 'item three', + }, ] - const selectedItems = [synchronizedItems[1]] - - function MultiSelectPanel({ - items: panelItems, - loading, - onOpenChange = () => {}, - open, - }: { - items: ItemInput[] - loading?: boolean - onOpenChange?: SelectPanelProps['onOpenChange'] - open: boolean - }) { - return ( - {}} - onFilterChange={() => {}} - loading={loading} - open={open} - onOpenChange={onOpenChange} - /> - ) - } - function SingleSelectModal({ - onSelectedChange = () => {}, - open, - selected, - }: { - onSelectedChange?: (selected: ItemInput | undefined) => void - open: boolean - selected: ItemInput | undefined - }) { + function BasicSelectPanel(passthroughProps: Record) { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) + + const onSelectedChange = (selected: SelectPanelProps['items']) => { + setSelected(selected) + } + return ( {}} + filterValue={filter} + onFilterChange={value => { + setFilter(value) + }} open={open} - onOpenChange={() => {}} - variant="modal" - onCancel={() => {}} + onOpenChange={isOpen => { + setOpen(isOpen) + }} + {...passthroughProps} /> ) } - it('does not commit a follow-up update when mounted closed with preloaded items', async () => { - const [Wrap, counter] = createRenderCounter() - - render( - - - , - ) - await act(async () => {}) - - expect(counter.mountCount).toBe(1) - expect(counter.updateCount).toBe(0) - }) + globalThis.Element.prototype.scrollTo = vi.fn() - it('orders the selected item in the opening commit and focuses the filter input', async () => { - const committedOrders: string[][] = [] - const recordOrder = () => { - const order = Array.from(document.querySelectorAll('[role="option"]'), option => - option.textContent.trim(), + describe('SelectPanel state synchronization', () => { + const synchronizedItems: ItemInput[] = [ + {id: 'one', text: 'item one'}, + {id: 'two', text: 'item two'}, + {id: 'three', text: 'item three'}, + ] + const selectedItems = [synchronizedItems[1]] + + function MultiSelectPanel({ + items: panelItems, + loading, + onOpenChange = () => {}, + open, + }: { + items: ItemInput[] + loading?: boolean + onOpenChange?: SelectPanelProps['onOpenChange'] + open: boolean + }) { + return ( + {}} + onFilterChange={() => {}} + loading={loading} + open={open} + onOpenChange={onOpenChange} + /> ) - - if (order.length > 0) { - committedOrders.push(order) - } } - const renderPanel = (open: boolean) => ( - - - - - - ) - const {rerender} = render(renderPanel(false)) - - await act(async () => {}) - committedOrders.length = 0 - rerender(renderPanel(true)) - await act(async () => {}) - expect(committedOrders.length).toBeGreaterThan(0) - expect(committedOrders.every(order => order[0] === 'item two')).toBe(true) - await expect.element(page.getByLabelText('Filter items')).toHaveFocus() - }) - - it('commits item arrival once while closed', async () => { - const [Wrap, counter] = createRenderCounter() - const renderPanel = (panelItems: ItemInput[]) => ( - - - - ) - const {rerender} = render(renderPanel([])) - - await act(async () => {}) - counter.reset() - rerender(renderPanel(synchronizedItems)) - await act(async () => {}) - - expect(counter.updateCount).toBe(1) - expect(counter.nestedUpdateCount).toBe(0) - }) - - it('orders arriving items without replacing or blurring the filter input', async () => { - const committedOrders: string[][] = [] - const recordOrder = () => { - const order = Array.from(document.querySelectorAll('[role="option"]'), option => - option.textContent.trim(), + function SingleSelectModal({ + onSelectedChange = () => {}, + open, + selected, + }: { + onSelectedChange?: (selected: ItemInput | undefined) => void + open: boolean + selected: ItemInput | undefined + }) { + return ( + {}} + open={open} + onOpenChange={() => {}} + variant="modal" + onCancel={() => {}} + /> ) - - if (order.length > 0) { - committedOrders.push(order) - } } - const renderPanel = (panelItems: ItemInput[]) => ( - - - - - - ) - const {rerender} = render(renderPanel([])) - - const input = page.getByLabelText('Filter items') - await expect.element(input).toHaveFocus() - const inputElement = input.element() - committedOrders.length = 0 - rerender(renderPanel(synchronizedItems)) - await act(async () => {}) - - expect(committedOrders.length).toBeGreaterThan(0) - expect(committedOrders.every(order => order[0] === 'item two')).toBe(true) - expect(page.getByLabelText('Filter items').element()).toBe(inputElement) - await expect.element(input).toHaveFocus() - }) - - it('commits a controlled modal selection change once while closed', async () => { - const [Wrap, counter] = createRenderCounter() - const renderPanel = (selected: ItemInput) => ( - - - - ) - const {rerender} = render(renderPanel(synchronizedItems[0])) - await act(async () => {}) - counter.reset() - rerender(renderPanel(synchronizedItems[1])) - await act(async () => {}) + it('does not commit a follow-up update when mounted closed with preloaded items', async () => { + const [Wrap, counter] = createRenderCounter() - expect(counter.updateCount).toBe(1) - expect(counter.nestedUpdateCount).toBe(0) - }) + render( + + + , + ) + await act(async () => {}) - it('resets modal intermediate selection across close and controlled selection changes', async () => { - const onSelectedChange = vi.fn() - const renderPanel = (open: boolean, selected: ItemInput) => ( - - ) - const {rerender} = render(renderPanel(true, synchronizedItems[0])) - - await expect.element(page.getByLabelText('Filter items')).toHaveFocus() - await userEvent.click(page.getByRole('option', {name: 'item two'})) - await expect.element(page.getByRole('option', {name: 'item two'})).toHaveAttribute('aria-selected', 'true') - expect(onSelectedChange).not.toHaveBeenCalled() - - rerender(renderPanel(false, synchronizedItems[0])) - rerender(renderPanel(true, synchronizedItems[0])) - await expect.element(page.getByLabelText('Filter items')).toHaveFocus() - await expect.element(page.getByRole('option', {name: 'item one'})).toHaveAttribute('aria-selected', 'true') - - const input = page.getByLabelText('Filter items') - const inputElement = input.element() - rerender(renderPanel(true, synchronizedItems[2])) - await expect.element(page.getByRole('option', {name: 'item three'})).toHaveAttribute('aria-selected', 'true') - expect(page.getByLabelText('Filter items').element()).toBe(inputElement) - await expect.element(input).toHaveFocus() - - await userEvent.click(page.getByRole('button', {name: 'Save'})) - expect(onSelectedChange).toHaveBeenCalledWith(synchronizedItems[2]) - }) + expect(counter.mountCount).toBe(1) + expect(counter.updateCount).toBe(0) + }) - it('announces internally managed loading when opened', async () => { - vi.useFakeTimers() - for (const element of document.querySelectorAll('live-region')) { - element.remove() - } - const liveRegion = document.createElement('live-region') as LiveRegionElement - document.body.appendChild(liveRegion) + it('orders the selected item in the opening commit and focuses the filter input', async () => { + const committedOrders: string[][] = [] + const recordOrder = () => { + const order = Array.from(document.querySelectorAll('[role="option"]'), option => + option.textContent.trim(), + ) - try { - function LoadingPanel() { - const [open, setOpen] = React.useState(false) - return + if (order.length > 0) { + committedOrders.push(order) + } } + const renderPanel = (open: boolean) => ( + + + + + + ) + const {rerender} = render(renderPanel(false)) - render() - await userEvent.click(page.getByRole('button', {name: 'item two'})) - await act(async () => { - await vi.runAllTimersAsync() - }) + await act(async () => {}) + committedOrders.length = 0 + rerender(renderPanel(true)) + await act(async () => {}) - expect(liveRegion.getMessage('polite')).toBe('Loading.') - } finally { - vi.useRealTimers() - } - }) -}) + expect(committedOrders.length).toBeGreaterThan(0) + expect(committedOrders.every(order => order[0] === 'item two')).toBe(true) + await expect.element(page.getByLabelText('Filter items')).toHaveFocus() + }) -for (const usingRemoveActiveDescendant of [false, true]) { - describe('SelectPanel', () => { - implementsClassName(props => , classes.FilteredActionList) - it('should render an anchor to open the select panel using `placeholder`', async () => { - renderWithProp() + it('commits item arrival once while closed', async () => { + const [Wrap, counter] = createRenderCounter() + const renderPanel = (panelItems: ItemInput[]) => ( + + + + ) + const {rerender} = render(renderPanel([])) - await expect.element(page.getByText('Select items', {exact: true})).toBeInTheDocument() + await act(async () => {}) + counter.reset() + rerender(renderPanel(synchronizedItems)) + await act(async () => {}) - const trigger = page.getByRole('button', { - name: 'Select items', - }) - await expect.element(trigger).toHaveAttribute('aria-haspopup', 'true') - await expect.element(trigger).toHaveAttribute('aria-expanded', 'false') + expect(counter.updateCount).toBe(1) + expect(counter.nestedUpdateCount).toBe(0) }) - it('should call onActiveDescendantChanged when using keyboard while focusing on an item', async () => { - // jest function - const onActiveDescendantChanged = vi.fn() - - render() + it('orders arriving items without replacing or blurring the filter input', async () => { + const committedOrders: string[][] = [] + const recordOrder = () => { + const order = Array.from(document.querySelectorAll('[role="option"]'), option => + option.textContent.trim(), + ) - await userEvent.click(page.getByText('Select items', {exact: true})) + if (order.length > 0) { + committedOrders.push(order) + } + } + const renderPanel = (panelItems: ItemInput[]) => ( + + + + + + ) + const {rerender} = render(renderPanel([])) - await userEvent.keyboard('{ArrowDown}') - expect(onActiveDescendantChanged).toHaveBeenCalled() + const input = page.getByLabelText('Filter items') + await expect.element(input).toHaveFocus() + const inputElement = input.element() + committedOrders.length = 0 + rerender(renderPanel(synchronizedItems)) + await act(async () => {}) + + expect(committedOrders.length).toBeGreaterThan(0) + expect(committedOrders.every(order => order[0] === 'item two')).toBe(true) + expect(page.getByLabelText('Filter items').element()).toBe(inputElement) + await expect.element(input).toHaveFocus() }) - it('should open the select panel when activating the trigger', async () => { - renderWithProp(, usingRemoveActiveDescendant) + it('commits a controlled modal selection change once while closed', async () => { + const [Wrap, counter] = createRenderCounter() + const renderPanel = (selected: ItemInput) => ( + + + + ) + const {rerender} = render(renderPanel(synchronizedItems[0])) - await userEvent.click(page.getByText('Select items', {exact: true})) + await act(async () => {}) + counter.reset() + rerender(renderPanel(synchronizedItems[1])) + await act(async () => {}) - // Verify that the button has `aria-expanded="true"` after opening - const trigger = page.getByRole('button', { - name: 'Select items', - }) - await expect.element(trigger).toHaveAttribute('aria-expanded', 'true') + expect(counter.updateCount).toBe(1) + expect(counter.nestedUpdateCount).toBe(0) + }) - // Verify that the input and listbox are in the document - await expect.element(page.getByPlaceholder('Filter items')).toBeInTheDocument() - await expect.element(page.getByRole('listbox')).toBeInTheDocument() + it('resets modal intermediate selection across close and controlled selection changes', async () => { + const onSelectedChange = vi.fn() + const renderPanel = (open: boolean, selected: ItemInput) => ( + + ) + const {rerender} = render(renderPanel(true, synchronizedItems[0])) - // The input box must have focus - expect(document.activeElement?.tagName.toLowerCase()).toBe('input') - }) + await expect.element(page.getByLabelText('Filter items')).toHaveFocus() + await userEvent.click(page.getByRole('option', {name: 'item two'})) + await expect.element(page.getByRole('option', {name: 'item two'})).toHaveAttribute('aria-selected', 'true') + expect(onSelectedChange).not.toHaveBeenCalled() - it('should close the select panel when pressing Escape', async () => { - renderWithProp(, usingRemoveActiveDescendant) + rerender(renderPanel(false, synchronizedItems[0])) + rerender(renderPanel(true, synchronizedItems[0])) + await expect.element(page.getByLabelText('Filter items')).toHaveFocus() + await expect.element(page.getByRole('option', {name: 'item one'})).toHaveAttribute('aria-selected', 'true') - await userEvent.click(page.getByText('Select items', {exact: true})) - await userEvent.keyboard('{Escape}') + const input = page.getByLabelText('Filter items') + const inputElement = input.element() + rerender(renderPanel(true, synchronizedItems[2])) + await expect.element(page.getByRole('option', {name: 'item three'})).toHaveAttribute('aria-selected', 'true') + expect(page.getByLabelText('Filter items').element()).toBe(inputElement) + await expect.element(input).toHaveFocus() - await expect.element(page.getByRole('button', {name: 'Select items'})).toHaveFocus() - await expect.element(page.getByRole('button', {name: 'Select items'})).toHaveAttribute('aria-expanded', 'false') + await userEvent.click(page.getByRole('button', {name: 'Save'})) + expect(onSelectedChange).toHaveBeenCalledWith(synchronizedItems[2]) }) - it('should close the select panel when clicking outside of the select panel', async () => { - render( - <> - - - , - ) + it('announces internally managed loading when opened', async () => { + vi.useFakeTimers() + for (const element of document.querySelectorAll('live-region')) { + element.remove() + } + const liveRegion = document.createElement('live-region') as LiveRegionElement + document.body.appendChild(liveRegion) + + try { + function LoadingPanel() { + const [open, setOpen] = React.useState(false) + return + } - await userEvent.click(page.getByText('Select items', {exact: true})) - await userEvent.click(page.getByText('outer button', {exact: true})) + render() + await userEvent.click(page.getByRole('button', {name: 'item two'})) + await act(async () => { + await vi.runAllTimersAsync() + }) - await expect.element(page.getByRole('button', {name: 'Select items'})).toHaveAttribute('aria-expanded', 'false') + expect(liveRegion.getMessage('polite')).toBe('Loading.') + } finally { + vi.useRealTimers() + } }) + }) - it('should open a dialog that is labelled by `title` and described by `subtitle`', async () => { - renderWithProp(, usingRemoveActiveDescendant) + for (const usingRemoveActiveDescendant of [false, true]) { + describe('SelectPanel', () => { + implementsClassName(props => , classes.FilteredActionList) + it('should render an anchor to open the select panel using `placeholder`', async () => { + renderWithProp() - await userEvent.click(page.getByText('Select items', {exact: true})) + await expect.element(page.getByText('Select items', {exact: true})).toBeInTheDocument() - await expect - .element( - page.getByRole('dialog', { - name: 'test title', - }), - ) - .toBeInTheDocument() - await expect.element(page.getByRole('dialog', {name: 'test title'})).toHaveAccessibleDescription('test subtitle') - }) + const trigger = page.getByRole('button', { + name: 'Select items', + }) + await expect.element(trigger).toHaveAttribute('aria-haspopup', 'true') + await expect.element(trigger).toHaveAttribute('aria-expanded', 'false') + }) - it('should call `onOpenChange` when opening and closing the dialog', async () => { - const onOpenChange = vi.fn() + it('should call onActiveDescendantChanged when using keyboard while focusing on an item', async () => { + // jest function + const onActiveDescendantChanged = vi.fn() - function SelectPanelOpenChange() { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) + render() - const onSelectedChange = (selected: SelectPanelProps['items']) => { - setSelected(selected) - } + await userEvent.click(page.getByText('Select items', {exact: true})) - return ( - <> - - { - setFilter(value) - }} - open={open} - onOpenChange={(...args) => { - onOpenChange(...args) - setOpen(args[0]) - }} - /> - - ) - } + await userEvent.keyboard('{ArrowDown}') + expect(onActiveDescendantChanged).toHaveBeenCalled() + }) - renderWithProp(, usingRemoveActiveDescendant) + it('should open the select panel when activating the trigger', async () => { + renderWithProp(, usingRemoveActiveDescendant) - // Open by click - await userEvent.click(page.getByText('Select items', {exact: true})) - expect(onOpenChange).toHaveBeenLastCalledWith(true, 'anchor-click') + await userEvent.click(page.getByText('Select items', {exact: true})) - // Close by click on anchor - await userEvent.click(page.getByText('Select items', {exact: true})) - expect(onOpenChange).toHaveBeenLastCalledWith(false, 'anchor-click') + // Verify that the button has `aria-expanded="true"` after opening + const trigger = page.getByRole('button', { + name: 'Select items', + }) + await expect.element(trigger).toHaveAttribute('aria-expanded', 'true') - // Open by button activation - // RTL's type() clicked the target before typing. - await userEvent.click(page.getByText('Select items', {exact: true})) - await userEvent.keyboard('{Space}') - expect(onOpenChange).toHaveBeenLastCalledWith(true, 'anchor-click') + // Verify that the input and listbox are in the document + await expect.element(page.getByPlaceholder('Filter items')).toBeInTheDocument() + await expect.element(page.getByRole('listbox')).toBeInTheDocument() - // Close by Escape key - await userEvent.keyboard('{Escape}') - expect(onOpenChange).toHaveBeenLastCalledWith(false, 'escape') + // The input box must have focus + expect(document.activeElement?.tagName.toLowerCase()).toBe('input') + }) - // Close by click outside - await userEvent.click(page.getByText('Select items', {exact: true})) - await userEvent.click(page.getByText('Outside of select panel', {exact: true})) - expect(onOpenChange).toHaveBeenLastCalledWith(false, 'click-outside') - }) + it('should close the select panel when pressing Escape', async () => { + renderWithProp(, usingRemoveActiveDescendant) - it('should label the list by title unless a aria-label is explicitly passed', async () => { - renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) - await expect.element(page.getByRole('listbox', {name: 'test title'})).toBeInTheDocument() - }) + await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.keyboard('{Escape}') - it('should label the list by aria-label when explicitly passed', async () => { - renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) - await expect.element(page.getByRole('listbox', {name: 'Custom label'})).toBeInTheDocument() - }) + await expect.element(page.getByRole('button', {name: 'Select items'})).toHaveFocus() + await expect.element(page.getByRole('button', {name: 'Select items'})).toHaveAttribute('aria-expanded', 'false') + }) - it('should focus the filter input on open', async () => { - // This panel contains another focusable thing (the IconButton) that should not receive focus - // when the panel opens. - renderWithProp( - {}} - onFilterChange={() => {}} - onSelectedChange={() => {}} - open={true} - items={items} - selected={[]} - placeholder="Select items" - placeholderText="Filter items" - title={ -
- - Title -
- } - />, - usingRemoveActiveDescendant, - ) + it('should close the select panel when clicking outside of the select panel', async () => { + render( + <> + + + , + ) - await userEvent.click(page.getByText('Select items', {exact: true})) - await expect.element(page.getByLabelText('Filter items')).toHaveFocus() - }) + await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('outer button', {exact: true})) + + await expect.element(page.getByRole('button', {name: 'Select items'})).toHaveAttribute('aria-expanded', 'false') + }) - describe('selection', () => { - it('should select an active option when activated', async () => { + it('should open a dialog that is labelled by `title` and described by `subtitle`', async () => { renderWithProp(, usingRemoveActiveDescendant) await userEvent.click(page.getByText('Select items', {exact: true})) - await userEvent.keyboard('{Enter}') await expect .element( - page.getByRole('option', { - name: 'item one', + page.getByRole('dialog', { + name: 'test title', }), ) - .toHaveAttribute('aria-selected', 'true') - - await userEvent.keyboard('{Enter}') + .toBeInTheDocument() await expect - .element( - page.getByRole('option', { - name: 'item one', - }), - ) - .toHaveAttribute('aria-selected', 'false') + .element(page.getByRole('dialog', {name: 'test title'})) + .toHaveAccessibleDescription('test subtitle') + }) - await userEvent.click(page.getByText('item one', {exact: true})) - await expect - .element( - page.getByRole('option', { - name: 'item one', - }), - ) - .toHaveAttribute('aria-selected', 'true') + it('should call `onOpenChange` when opening and closing the dialog', async () => { + const onOpenChange = vi.fn() - await userEvent.click(page.getByRole('option', {name: 'item one'})) - await expect - .element( - page.getByRole('option', { - name: 'item one', - }), + function SelectPanelOpenChange() { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) + + const onSelectedChange = (selected: SelectPanelProps['items']) => { + setSelected(selected) + } + + return ( + <> + + { + setFilter(value) + }} + open={open} + onOpenChange={(...args) => { + onOpenChange(...args) + setOpen(args[0]) + }} + /> + ) - .toHaveAttribute('aria-selected', 'false') - }) + } - it('should support navigating through items with ArrowUp and ArrowDown', async () => { - renderWithProp(, usingRemoveActiveDescendant) + renderWithProp(, usingRemoveActiveDescendant) + // Open by click await userEvent.click(page.getByText('Select items', {exact: true})) + expect(onOpenChange).toHaveBeenLastCalledWith(true, 'anchor-click') - if (usingRemoveActiveDescendant) { - await expect.element(page.elementLocator(document.activeElement!)).toHaveAttribute('role', 'combobox') + // Close by click on anchor + await userEvent.click(page.getByText('Select items', {exact: true})) + expect(onOpenChange).toHaveBeenLastCalledWith(false, 'anchor-click') - await userEvent.keyboard('{ArrowDown}') - await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item one') + // Open by button activation + // RTL's type() clicked the target before typing. + await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.keyboard('{Space}') + expect(onOpenChange).toHaveBeenLastCalledWith(true, 'anchor-click') - await userEvent.keyboard('{ArrowDown}') - await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item two') + // Close by Escape key + await userEvent.keyboard('{Escape}') + expect(onOpenChange).toHaveBeenLastCalledWith(false, 'escape') - await userEvent.keyboard('{ArrowDown}') - await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item three') + // Close by click outside + await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Outside of select panel', {exact: true})) + expect(onOpenChange).toHaveBeenLastCalledWith(false, 'click-outside') + }) - // At end of list, should wrap to the beginning - await userEvent.keyboard('{ArrowDown}') - await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item one') + it('should label the list by title unless a aria-label is explicitly passed', async () => { + renderWithProp(, usingRemoveActiveDescendant) + await userEvent.click(page.getByText('Select items', {exact: true})) + await expect.element(page.getByRole('listbox', {name: 'test title'})).toBeInTheDocument() + }) - // At beginning of list, ArrowUp should wrap to the end - await userEvent.keyboard('{ArrowUp}') - await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item three') + it('should label the list by aria-label when explicitly passed', async () => { + renderWithProp(, usingRemoveActiveDescendant) + await userEvent.click(page.getByText('Select items', {exact: true})) + await expect.element(page.getByRole('listbox', {name: 'Custom label'})).toBeInTheDocument() + }) - await userEvent.keyboard('{ArrowUp}') - await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item two') + it('should focus the filter input on open', async () => { + // This panel contains another focusable thing (the IconButton) that should not receive focus + // when the panel opens. + renderWithProp( + {}} + onFilterChange={() => {}} + onSelectedChange={() => {}} + open={true} + items={items} + selected={[]} + placeholder="Select items" + placeholderText="Filter items" + title={ +
+ + Title +
+ } + />, + usingRemoveActiveDescendant, + ) - await userEvent.keyboard('{ArrowUp}') - await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item one') - } else { - // First item by default should be the active element - await expect - .element(page.elementLocator(document.activeElement!)) - .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item one'}).element().id) + await userEvent.click(page.getByText('Select items', {exact: true})) + await expect.element(page.getByLabelText('Filter items')).toHaveFocus() + }) - await userEvent.keyboard('{ArrowDown}') - await expect - .element(page.elementLocator(document.activeElement!)) - .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item two'}).element().id) + describe('selection', () => { + it('should select an active option when activated', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.keyboard('{ArrowDown}') - await expect - .element(page.elementLocator(document.activeElement!)) - .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item three'}).element().id) + await userEvent.click(page.getByText('Select items', {exact: true})) - // At end of list, should wrap to the beginning - await userEvent.keyboard('{ArrowDown}') + await userEvent.keyboard('{Enter}') await expect - .element(page.elementLocator(document.activeElement!)) - .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item one'}).element().id) - - // At beginning of list, ArrowUp should wrap to the end - await userEvent.keyboard('{ArrowUp}') + .element( + page.getByRole('option', { + name: 'item one', + }), + ) + .toHaveAttribute('aria-selected', 'true') + + await userEvent.keyboard('{Enter}') await expect - .element(page.elementLocator(document.activeElement!)) - .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item three'}).element().id) - - await userEvent.keyboard('{ArrowUp}') + .element( + page.getByRole('option', { + name: 'item one', + }), + ) + .toHaveAttribute('aria-selected', 'false') + + await userEvent.click(page.getByText('item one', {exact: true})) await expect - .element(page.elementLocator(document.activeElement!)) - .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item two'}).element().id) - - await userEvent.keyboard('{ArrowUp}') + .element( + page.getByRole('option', { + name: 'item one', + }), + ) + .toHaveAttribute('aria-selected', 'true') + + await userEvent.click(page.getByRole('option', {name: 'item one'})) await expect - .element(page.elementLocator(document.activeElement!)) - .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item one'}).element().id) - } - }) - - it('should support navigating through items with PageDown and PageUp', async () => { - renderWithProp(, usingRemoveActiveDescendant) + .element( + page.getByRole('option', { + name: 'item one', + }), + ) + .toHaveAttribute('aria-selected', 'false') + }) - await userEvent.click(page.getByText('Select items', {exact: true})) + it('should support navigating through items with ArrowUp and ArrowDown', async () => { + renderWithProp(, usingRemoveActiveDescendant) + + await userEvent.click(page.getByText('Select items', {exact: true})) + + if (usingRemoveActiveDescendant) { + await expect.element(page.elementLocator(document.activeElement!)).toHaveAttribute('role', 'combobox') + + await userEvent.keyboard('{ArrowDown}') + await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item one') + + await userEvent.keyboard('{ArrowDown}') + await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item two') + + await userEvent.keyboard('{ArrowDown}') + await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item three') + + // At end of list, should wrap to the beginning + await userEvent.keyboard('{ArrowDown}') + await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item one') + + // At beginning of list, ArrowUp should wrap to the end + await userEvent.keyboard('{ArrowUp}') + await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item three') + + await userEvent.keyboard('{ArrowUp}') + await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item two') + + await userEvent.keyboard('{ArrowUp}') + await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item one') + } else { + // First item by default should be the active element + await expect + .element(page.elementLocator(document.activeElement!)) + .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item one'}).element().id) + + await userEvent.keyboard('{ArrowDown}') + await expect + .element(page.elementLocator(document.activeElement!)) + .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item two'}).element().id) + + await userEvent.keyboard('{ArrowDown}') + await expect + .element(page.elementLocator(document.activeElement!)) + .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item three'}).element().id) + + // At end of list, should wrap to the beginning + await userEvent.keyboard('{ArrowDown}') + await expect + .element(page.elementLocator(document.activeElement!)) + .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item one'}).element().id) + + // At beginning of list, ArrowUp should wrap to the end + await userEvent.keyboard('{ArrowUp}') + await expect + .element(page.elementLocator(document.activeElement!)) + .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item three'}).element().id) + + await userEvent.keyboard('{ArrowUp}') + await expect + .element(page.elementLocator(document.activeElement!)) + .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item two'}).element().id) + + await userEvent.keyboard('{ArrowUp}') + await expect + .element(page.elementLocator(document.activeElement!)) + .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item one'}).element().id) + } + }) - if (usingRemoveActiveDescendant) { - await userEvent.keyboard('{ArrowDown}') + it('should support navigating through items with PageDown and PageUp', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item one') + await userEvent.click(page.getByText('Select items', {exact: true})) - await userEvent.keyboard('{PageDown}') + if (usingRemoveActiveDescendant) { + await userEvent.keyboard('{ArrowDown}') - await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item three') + await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item one') - await userEvent.keyboard('{PageUp}') + await userEvent.keyboard('{PageDown}') - await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item one') - } else { - // First item by default should be the active element - await expect - .element(page.elementLocator(document.activeElement!)) - .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item one'}).element().id) + await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item three') - await userEvent.keyboard('{PageDown}') + await userEvent.keyboard('{PageUp}') - await expect - .element(page.elementLocator(document.activeElement!)) - .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item three'}).element().id) + await expect.element(page.elementLocator(document.activeElement!)).toHaveAccessibleName('item one') + } else { + // First item by default should be the active element + await expect + .element(page.elementLocator(document.activeElement!)) + .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item one'}).element().id) - await userEvent.keyboard('{PageUp}') - await expect - .element(page.elementLocator(document.activeElement!)) - .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item one'}).element().id) - } - }) + await userEvent.keyboard('{PageDown}') - it('should select an item (by item.id) even when items are defined in the component', async () => { - function Fixture() { - // items are defined in the same scope as selection, so they could rerender and create new object references - // We use item.id to track selection - const items: SelectPanelProps['items'] = [ - {id: 'one', text: 'item one'}, - {id: 'two', text: 'item two'}, - {id: 'three', text: 'item three'}, - ] + await expect + .element(page.elementLocator(document.activeElement!)) + .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item three'}).element().id) - const [open, setOpen] = React.useState(false) - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - - return ( - - ) - } - - renderWithProp(, usingRemoveActiveDescendant) - - await userEvent.click(page.getByText('Select items', {exact: true})) - - await userEvent.click(page.getByText('item one', {exact: true})) - await expect.element(page.getByRole('option', {name: 'item one'})).toHaveAttribute('aria-selected', 'true') - - await userEvent.click(page.getByText('item two', {exact: true})) - await expect.element(page.getByRole('option', {name: 'item two'})).toHaveAttribute('aria-selected', 'true') - - await userEvent.click(page.getByRole('option', {name: 'item one'})) - await expect.element(page.getByRole('option', {name: 'item one'})).toHaveAttribute('aria-selected', 'false') - }) - }) + await userEvent.keyboard('{PageUp}') + await expect + .element(page.elementLocator(document.activeElement!)) + .toHaveAttribute('aria-activedescendant', page.getByRole('option', {name: 'item one'}).element().id) + } + }) - function FilterableSelectPanel({textInputProps}: Pick) { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) + it('should select an item (by item.id) even when items are defined in the component', async () => { + function Fixture() { + // items are defined in the same scope as selection, so they could rerender and create new object references + // We use item.id to track selection + const items: SelectPanelProps['items'] = [ + {id: 'one', text: 'item one'}, + {id: 'two', text: 'item two'}, + {id: 'three', text: 'item three'}, + ] + + const [open, setOpen] = React.useState(false) + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + + return ( + + ) + } - const onSelectedChange = (selected: SelectPanelProps['items']) => { - setSelected(selected) - } + renderWithProp(, usingRemoveActiveDescendant) - return ( - item.text?.includes(filter))} - placeholder="Select items" - placeholderText="Filter items" - textInputProps={textInputProps} - selected={selected} - onSelectedChange={onSelectedChange} - filterValue={filter} - onFilterChange={value => { - setFilter(value) - }} - open={open} - onOpenChange={isOpen => { - setOpen(isOpen) - }} - _PrivateFocusManagement={usingRemoveActiveDescendant ? 'roving-tabindex' : 'active-descendant'} - /> - ) - } + await userEvent.click(page.getByText('Select items', {exact: true})) - const SelectPanelWithCustomMessages: React.FC<{ - items: SelectPanelProps['items'] - withAction?: boolean - onAction?: () => void - }> = ({items, withAction = false, onAction}) => { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) - - const onSelectedChange = (selected: SelectPanelProps['items']) => { - setSelected(selected) - } + await userEvent.click(page.getByText('item one', {exact: true})) + await expect.element(page.getByRole('option', {name: 'item one'})).toHaveAttribute('aria-selected', 'true') - const emptyMessage = { - variant: 'empty' as const, - title: "You haven't created any projects yet", - body: 'Start your first project to organise your issues', - ...(withAction && { - action: ( - - ), - }), - } + await userEvent.click(page.getByText('item two', {exact: true})) + await expect.element(page.getByRole('option', {name: 'item two'})).toHaveAttribute('aria-selected', 'true') - const noResultsMessage = (filter: string) => ({ - variant: 'empty' as const, - title: `No language found for ${filter}`, - body: 'Adjust your search term to find other languages', + await userEvent.click(page.getByRole('option', {name: 'item one'})) + await expect.element(page.getByRole('option', {name: 'item one'})).toHaveAttribute('aria-selected', 'false') + }) }) - const filteredItems = items.filter(item => item.text?.includes(filter)) + function FilterableSelectPanel({textInputProps}: Pick) { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - function getMessage() { - if (filteredItems.length === 0 && !filter) { - return emptyMessage - } - if (filteredItems.length === 0 && filter) { - return noResultsMessage(filter) + const onSelectedChange = (selected: SelectPanelProps['items']) => { + setSelected(selected) } - return undefined - } - - return ( - { - setFilter(value) - }} - open={open} - onOpenChange={isOpen => { - setOpen(isOpen) - }} - message={getMessage()} - /> - ) - } - - function NoItemAvailableSelectPanel() { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) - - const onSelectedChange = (selected: SelectPanelProps['items']) => { - setSelected(selected) - } - - const items: SelectPanelProps['items'] = [] - - return ( - item.text?.includes(filter))} - placeholder="Select items" - placeholderText="Filter items" - selected={selected} - onSelectedChange={onSelectedChange} - filterValue={filter} - onFilterChange={value => { - setFilter(value) - }} - open={open} - onOpenChange={isOpen => { - setOpen(isOpen) - }} - /> - ) - } - - describe('filtering', () => { - it('should filter the list of items when the user types into the input', async () => { - renderWithProp(, usingRemoveActiveDescendant) - - await userEvent.click(page.getByText('Select items', {exact: true})) - - expect(page.getByRole('option').elements()).toHaveLength(3) - - await userEvent.type(page.getByRole('combobox'), 'two') - expect(page.getByRole('option').elements()).toHaveLength(1) - }) - }) - describe.each([ - {name: 'absent', flags: {}, contrast: false}, - {name: 'false', flags: {primer_react_select_panel_legacy_contrast: false}, contrast: false}, - {name: 'true', flags: {primer_react_select_panel_legacy_contrast: true}, contrast: true}, - ])('legacy contrast flag $name', ({flags, contrast}) => { - it('should set the default background without changing filtering or focus', async () => { - render( - - - , + return ( + item.text?.includes(filter))} + placeholder="Select items" + placeholderText="Filter items" + textInputProps={textInputProps} + selected={selected} + onSelectedChange={onSelectedChange} + filterValue={filter} + onFilterChange={value => { + setFilter(value) + }} + open={open} + onOpenChange={isOpen => { + setOpen(isOpen) + }} + _PrivateFocusManagement={usingRemoveActiveDescendant ? 'roving-tabindex' : 'active-descendant'} + /> ) + } - await userEvent.click(page.getByRole('button', {name: 'Select items'})) + const SelectPanelWithCustomMessages: React.FC<{ + items: SelectPanelProps['items'] + withAction?: boolean + onAction?: () => void + }> = ({items, withAction = false, onAction}) => { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - const input = page.getByLabelText('Filter items') - const wrapper = input.element().closest('[data-component="TextInput"]') - if (!wrapper) { - throw new Error('Expected a TextInput wrapper') + const onSelectedChange = (selected: SelectPanelProps['items']) => { + setSelected(selected) } - await expect.element(wrapper).toBeInTheDocument() - expect(wrapper.hasAttribute('data-contrast')).toBe(contrast) - await expect.element(input).toBeEnabled() - await expect.element(input).toHaveFocus() - await userEvent.type(input, 'two') - await expect.element(input).toHaveValue('two') - expect(page.getByRole('option').elements()).toHaveLength(1) - await expect.element(page.getByRole('option', {name: 'item two'})).toBeInTheDocument() - - await userEvent.keyboard('{Escape}') - await expect.element(input).not.toBeInTheDocument() - await expect.element(page.getByRole('button', {name: 'Select items'})).toHaveFocus() - }) + const emptyMessage = { + variant: 'empty' as const, + title: "You haven't created any projects yet", + body: 'Start your first project to organise your issues', + ...(withAction && { + action: ( + + ), + }), + } - it.each([true, false, undefined])('should preserve explicit contrast=%s', async explicitContrast => { - render( - - - , - ) + const noResultsMessage = (filter: string) => ({ + variant: 'empty' as const, + title: `No language found for ${filter}`, + body: 'Adjust your search term to find other languages', + }) - await userEvent.click(page.getByRole('button', {name: 'Select items'})) + const filteredItems = items.filter(item => item.text?.includes(filter)) - const input = page.getByLabelText('Filter items') - const wrapper = input.element().closest('[data-component="TextInput"]') - if (!wrapper) { - throw new Error('Expected a TextInput wrapper') + function getMessage() { + if (filteredItems.length === 0 && !filter) { + return emptyMessage + } + if (filteredItems.length === 0 && filter) { + return noResultsMessage(filter) + } + return undefined } - await expect.element(wrapper).toBeInTheDocument() - expect(wrapper.hasAttribute('data-contrast')).toBe(explicitContrast === true) - await expect.element(input).toBeEnabled() - await expect.element(input).toHaveFocus() - await userEvent.type(input, 'two') - await expect.element(input).toHaveValue('two') - await expect.element(page.getByRole('option', {name: 'item two'})).toBeInTheDocument() - }) - }) - - it('should update contrast with the flag while preserving the input, filter, and focus', async () => { - const textInputProps = {'aria-label': 'Search items'} - const panel = - const {rerender} = render( - {panel}, - ) - - await userEvent.click(page.getByRole('button', {name: 'Select items'})) - const input = page.getByLabelText('Search items') - const inputElement = input.element() - const wrapper = inputElement.closest('[data-component="TextInput"]') - if (!wrapper) { - throw new Error('Expected a TextInput wrapper') - } - await expect.element(wrapper).toBeInTheDocument() - expect(wrapper.hasAttribute('data-contrast')).toBe(false) - await userEvent.type(input, 'two') - for (const legacyContrast of [true, false]) { - rerender( - {panel}, + return ( + { + setFilter(value) + }} + open={open} + onOpenChange={isOpen => { + setOpen(isOpen) + }} + message={getMessage()} + /> ) - - expect(page.getByLabelText('Search items').element()).toBe(inputElement) - expect(wrapper.hasAttribute('data-contrast')).toBe(legacyContrast) - await expect.element(input).toBeEnabled() - await expect.element(input).toHaveValue('two') - await expect.element(input).toHaveFocus() - expect(page.getByRole('option').elements()).toHaveLength(1) - await expect.element(page.getByRole('option', {name: 'item two'})).toBeInTheDocument() } - await userEvent.clear(input) - expect(page.getByRole('option').elements()).toHaveLength(3) - }) + function NoItemAvailableSelectPanel() { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - describe('screen reader announcements', () => { - beforeEach(() => { - const liveRegion = document.createElement('live-region') - document.body.appendChild(liveRegion) - }) + const onSelectedChange = (selected: SelectPanelProps['items']) => { + setSelected(selected) + } - function LoadingSelectPanel({ - initialLoadingType = 'spinner', - items = [], - }: { - initialLoadingType?: InitialLoadingType - items?: SelectPanelProps['items'] - }) { - const [open, setOpen] = React.useState(false) + const items: SelectPanelProps['items'] = [] return ( item.text?.includes(filter))} placeholder="Select items" + placeholderText="Filter items" + selected={selected} + onSelectedChange={onSelectedChange} + filterValue={filter} + onFilterChange={value => { + setFilter(value) + }} open={open} - items={items} - onFilterChange={() => {}} - selected={[]} - onSelectedChange={() => {}} onOpenChange={isOpen => { setOpen(isOpen) }} - initialLoadingType={initialLoadingType} /> ) } - it('displays a loading spinner on first open', async () => { - renderWithProp(, usingRemoveActiveDescendant) + describe('filtering', () => { + it('should filter the list of items when the user types into the input', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - await expect.element(page.getByTestId('filtered-action-list-spinner')).toBeInTheDocument() + expect(page.getByRole('option').elements()).toHaveLength(3) + + await userEvent.type(page.getByRole('combobox'), 'two') + expect(page.getByRole('option').elements()).toHaveLength(1) + }) }) - it('displays a loading skeleton on first open', async () => { - renderWithProp(, usingRemoveActiveDescendant) + describe.each([ + {name: 'absent', flags: {}, contrast: false}, + {name: 'false', flags: {primer_react_select_panel_legacy_contrast: false}, contrast: false}, + {name: 'true', flags: {primer_react_select_panel_legacy_contrast: true}, contrast: true}, + ])('legacy contrast flag $name', ({flags, contrast}) => { + it('should set the default background without changing filtering or focus', async () => { + render( + + + , + ) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByRole('button', {name: 'Select items'})) - await expect.element(page.getByTestId('filtered-action-list-skeleton')).toBeInTheDocument() - }) + const input = page.getByLabelText('Filter items') + const wrapper = input.element().closest('[data-component="TextInput"]') + if (!wrapper) { + throw new Error('Expected a TextInput wrapper') + } + await expect.element(wrapper).toBeInTheDocument() + expect(wrapper.hasAttribute('data-contrast')).toBe(contrast) + await expect.element(input).toBeEnabled() + await expect.element(input).toHaveFocus() + + await userEvent.type(input, 'two') + await expect.element(input).toHaveValue('two') + expect(page.getByRole('option').elements()).toHaveLength(1) + await expect.element(page.getByRole('option', {name: 'item two'})).toBeInTheDocument() + + await userEvent.keyboard('{Escape}') + await expect.element(input).not.toBeInTheDocument() + await expect.element(page.getByRole('button', {name: 'Select items'})).toHaveFocus() + }) - it('displays a loading spinner in the text input if items are already loaded', async () => { - renderWithProp(, usingRemoveActiveDescendant) + it.each([true, false, undefined])('should preserve explicit contrast=%s', async explicitContrast => { + render( + + + , + ) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByRole('button', {name: 'Select items'})) - expect(page.getByRole('option').elements()).toHaveLength(3) + const input = page.getByLabelText('Filter items') + const wrapper = input.element().closest('[data-component="TextInput"]') + if (!wrapper) { + throw new Error('Expected a TextInput wrapper') + } + await expect.element(wrapper).toBeInTheDocument() + expect(wrapper.hasAttribute('data-contrast')).toBe(explicitContrast === true) + await expect.element(input).toBeEnabled() + await expect.element(input).toHaveFocus() + await userEvent.type(input, 'two') + await expect.element(input).toHaveValue('two') + await expect.element(page.getByRole('option', {name: 'item two'})).toBeInTheDocument() + }) + }) - // since the test component never repopulates the panel's list of items, the panel will - // enter the loading state after the following line executes and stay there indefinitely - await userEvent.type(page.getByRole('combobox'), 'two') + it('should update contrast with the flag while preserving the input, filter, and focus', async () => { + const textInputProps = {'aria-label': 'Search items'} + const panel = + const {rerender} = render( + {panel}, + ) - // The aria-describedby attribute is only available if the icon is present. The input - // field has a role of combobox. - await expect.element(page.getByRole('combobox')).toHaveAttribute('aria-describedby') - }) + await userEvent.click(page.getByRole('button', {name: 'Select items'})) + const input = page.getByLabelText('Search items') + const inputElement = input.element() + const wrapper = inputElement.closest('[data-component="TextInput"]') + if (!wrapper) { + throw new Error('Expected a TextInput wrapper') + } + await expect.element(wrapper).toBeInTheDocument() + expect(wrapper.hasAttribute('data-contrast')).toBe(false) + await userEvent.type(input, 'two') - it('should announce initially focused item', async () => { - renderWithProp(, usingRemoveActiveDescendant) + for (const legacyContrast of [true, false]) { + rerender( + {panel}, + ) - await userEvent.click(page.getByText('Select items', {exact: true})) - await expect.element(page.getByLabelText('Filter items')).toHaveFocus() + expect(page.getByLabelText('Search items').element()).toBe(inputElement) + expect(wrapper.hasAttribute('data-contrast')).toBe(legacyContrast) + await expect.element(input).toBeEnabled() + await expect.element(input).toHaveValue('two') + await expect.element(input).toHaveFocus() + expect(page.getByRole('option').elements()).toHaveLength(1) + await expect.element(page.getByRole('option', {name: 'item two'})).toBeInTheDocument() + } - // we wait because announcement is intentionally updated after a timeout to not interrupt user input - await waitFor( - async () => { - if (usingRemoveActiveDescendant) { - expect(getLiveRegion().getMessage('polite')!.trim()).toEqual('3 items available, 0 selected.') - } else { - expect(getLiveRegion().getMessage('polite')!.trim()).toEqual( - 'Filter items, filter text box and list of items, Focused item: item one, not selected, 1 of 3', - ) - } - }, - {timeout: 3000}, - ) + await userEvent.clear(input) + expect(page.getByRole('option').elements()).toHaveLength(3) }) - it('should announce notice text', async () => { - function SelectPanelWithNotice() { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) + describe('screen reader announcements', () => { + beforeEach(() => { + const liveRegion = document.createElement('live-region') + document.body.appendChild(liveRegion) + }) - const onSelectedChange = (selected: SelectPanelProps['items']) => { - setSelected(selected) - } + function LoadingSelectPanel({ + initialLoadingType = 'spinner', + items = [], + }: { + initialLoadingType?: InitialLoadingType + items?: SelectPanelProps['items'] + }) { + const [open, setOpen] = React.useState(false) return ( { - setFilter(value) - }} open={open} + items={items} + onFilterChange={() => {}} + selected={[]} + onSelectedChange={() => {}} onOpenChange={isOpen => { setOpen(isOpen) }} - notice={{ - text: 'This is a notice', - variant: 'warning', - }} + initialLoadingType={initialLoadingType} /> ) } - renderWithProp(, usingRemoveActiveDescendant) + it('displays a loading spinner on first open', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) - await expect.element(page.getByLabelText('Filter items')).toHaveFocus() + await userEvent.click(page.getByText('Select items', {exact: true})) - expect(getLiveRegion().getMessage('polite').trim()).toContain('This is a notice') - }) + await expect.element(page.getByTestId('filtered-action-list-spinner')).toBeInTheDocument() + }) - it('should announce filtered results', async () => { - renderWithProp(, usingRemoveActiveDescendant) + it('displays a loading skeleton on first open', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) - await expect.element(page.getByLabelText('Filter items')).toHaveFocus() + await userEvent.click(page.getByText('Select items', {exact: true})) - await waitFor( - async () => { - if (usingRemoveActiveDescendant) { - expect(getLiveRegion().getMessage('polite')!.trim()).toEqual('3 items available, 0 selected.') - } else { - expect(getLiveRegion().getMessage('polite')!.trim()).toEqual( - 'Filter items, filter text box and list of items, Focused item: item one, not selected, 1 of 3', - ) - } - }, - {timeout: 3000}, // increased timeout because we don't want the test to compare with previous announcement - ) + await expect.element(page.getByTestId('filtered-action-list-skeleton')).toBeInTheDocument() + }) - await userEvent.type(page.getByRole('combobox'), 'o') - expect(page.getByRole('option').elements()).toHaveLength(2) - - await waitFor( - async () => { - if (usingRemoveActiveDescendant) { - expect(getLiveRegion().getMessage('polite')).toBe('2 items available, 0 selected.') - } else { - expect(getLiveRegion().getMessage('polite')).toBe( - 'List updated, Focused item: item one, not selected, 1 of 2', - ) - } - }, - {timeout: 3000}, // increased timeout because we don't want the test to compare with previous announcement - ) + it('displays a loading spinner in the text input if items are already loaded', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.type(page.getByRole('combobox'), 'ne') // now: one - expect(page.getByRole('option').elements()).toHaveLength(1) - - await waitFor( - async () => { - if (usingRemoveActiveDescendant) { - expect(getLiveRegion().getMessage('polite')!.trim()).toBe('1 item available, 0 selected.') - } else { - expect(getLiveRegion().getMessage('polite').trim()).toBe( - 'List updated, Focused item: item one, not selected, 1 of 1', - ) - } - }, - {timeout: 3000}, - ) - }) + await userEvent.click(page.getByText('Select items', {exact: true})) - it('should announce default empty message when no results are available (no custom message is provided)', async () => { - renderWithProp(, usingRemoveActiveDescendant) + expect(page.getByRole('option').elements()).toHaveLength(3) - await userEvent.click(page.getByText('Select items', {exact: true})) + // since the test component never repopulates the panel's list of items, the panel will + // enter the loading state after the following line executes and stay there indefinitely + await userEvent.type(page.getByRole('combobox'), 'two') - await userEvent.type(page.getByRole('combobox'), 'zero') - await expect.element(page.getByRole('option')).not.toBeInTheDocument() + // The aria-describedby attribute is only available if the icon is present. The input + // field has a role of combobox. + await expect.element(page.getByRole('combobox')).toHaveAttribute('aria-describedby') + }) - await waitFor( - async () => { - if (usingRemoveActiveDescendant) { - expect(getLiveRegion().getMessage('polite')!.trim()).toBe('No items available.') - } else { - expect(getLiveRegion().getMessage('polite').trim()).toBe('No items available.') + it('should announce initially focused item', async () => { + renderWithProp(, usingRemoveActiveDescendant) + + await userEvent.click(page.getByText('Select items', {exact: true})) + await expect.element(page.getByLabelText('Filter items')).toHaveFocus() + + // we wait because announcement is intentionally updated after a timeout to not interrupt user input + await waitFor( + async () => { + if (usingRemoveActiveDescendant) { + expect(getLiveRegion().getMessage('polite')!.trim()).toEqual('3 items available, 0 selected.') + } else { + expect(getLiveRegion().getMessage('polite')!.trim()).toEqual( + 'Filter items, filter text box and list of items, Focused item: item one, not selected, 1 of 3', + ) + } + }, + {timeout: 3000}, + ) + }) + + it('should announce notice text', async () => { + function SelectPanelWithNotice() { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) + + const onSelectedChange = (selected: SelectPanelProps['items']) => { + setSelected(selected) } - }, - {timeout: 3000}, - ) - }) - it('should announce custom empty message when no results are available', async () => { - function SelectPanelWithCustomEmptyMessage() { - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) + return ( + { + setFilter(value) + }} + open={open} + onOpenChange={isOpen => { + setOpen(isOpen) + }} + notice={{ + text: 'This is a notice', + variant: 'warning', + }} + /> + ) + } - return ( - { - setFilter(value) - }} - filterValue={filter} - selected={[]} - onSelectedChange={() => {}} - onOpenChange={isOpen => { - setOpen(isOpen) - }} - message={{ - title: 'Nothing found', - body: `There's nothing here.`, - variant: 'empty', - }} - /> + renderWithProp(, usingRemoveActiveDescendant) + + await userEvent.click(page.getByText('Select items', {exact: true})) + await expect.element(page.getByLabelText('Filter items')).toHaveFocus() + + expect(getLiveRegion().getMessage('polite').trim()).toContain('This is a notice') + }) + + it('should announce filtered results', async () => { + renderWithProp(, usingRemoveActiveDescendant) + + await userEvent.click(page.getByText('Select items', {exact: true})) + await expect.element(page.getByLabelText('Filter items')).toHaveFocus() + + await waitFor( + async () => { + if (usingRemoveActiveDescendant) { + expect(getLiveRegion().getMessage('polite')!.trim()).toEqual('3 items available, 0 selected.') + } else { + expect(getLiveRegion().getMessage('polite')!.trim()).toEqual( + 'Filter items, filter text box and list of items, Focused item: item one, not selected, 1 of 3', + ) + } + }, + {timeout: 3000}, // increased timeout because we don't want the test to compare with previous announcement ) - } - renderWithProp(, usingRemoveActiveDescendant) + await userEvent.type(page.getByRole('combobox'), 'o') + expect(page.getByRole('option').elements()).toHaveLength(2) + + await waitFor( + async () => { + if (usingRemoveActiveDescendant) { + expect(getLiveRegion().getMessage('polite')).toBe('2 items available, 0 selected.') + } else { + expect(getLiveRegion().getMessage('polite')).toBe( + 'List updated, Focused item: item one, not selected, 1 of 2', + ) + } + }, + {timeout: 3000}, // increased timeout because we don't want the test to compare with previous announcement + ) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.type(page.getByRole('combobox'), 'ne') // now: one + expect(page.getByRole('option').elements()).toHaveLength(1) + + await waitFor( + async () => { + if (usingRemoveActiveDescendant) { + expect(getLiveRegion().getMessage('polite')!.trim()).toBe('1 item available, 0 selected.') + } else { + expect(getLiveRegion().getMessage('polite').trim()).toBe( + 'List updated, Focused item: item one, not selected, 1 of 1', + ) + } + }, + {timeout: 3000}, + ) + }) - await userEvent.type(page.getByRole('combobox'), 'zero') - await expect.element(page.getByRole('option')).not.toBeInTheDocument() + it('should announce default empty message when no results are available (no custom message is provided)', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await waitFor( - async () => { - if (usingRemoveActiveDescendant) { - expect(getLiveRegion().getMessage('polite')!.trim()).toBe("Nothing found. There's nothing here.") - } else { - expect(getLiveRegion().getMessage('polite').trim()).toBe("Nothing found. There's nothing here.") - } - }, - {timeout: 3000}, - ) - }) + await userEvent.click(page.getByText('Select items', {exact: true})) - it('should accept a className to style the component', async () => { - renderWithProp(, usingRemoveActiveDescendant) + await userEvent.type(page.getByRole('combobox'), 'zero') + await expect.element(page.getByRole('option')).not.toBeInTheDocument() - await userEvent.click(page.getByText('Select items', {exact: true})) + await waitFor( + async () => { + if (usingRemoveActiveDescendant) { + expect(getLiveRegion().getMessage('polite')!.trim()).toBe('No items available.') + } else { + expect(getLiveRegion().getMessage('polite').trim()).toBe('No items available.') + } + }, + {timeout: 3000}, + ) + }) - await expect.element(page.getByTestId('filtered-action-list')).toHaveClass('test-class') - }) - }) + it('should announce custom empty message when no results are available', async () => { + function SelectPanelWithCustomEmptyMessage() { + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) + + return ( + { + setFilter(value) + }} + filterValue={filter} + selected={[]} + onSelectedChange={() => {}} + onOpenChange={isOpen => { + setOpen(isOpen) + }} + message={{ + title: 'Nothing found', + body: `There's nothing here.`, + variant: 'empty', + }} + /> + ) + } - describe('Empty state', () => { - it('should display the default empty state message when there is no matching item after filtering (No custom message is provided)', async () => { - renderWithProp(, usingRemoveActiveDescendant) + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - expect(page.getByRole('option').elements()).toHaveLength(3) + await userEvent.type(page.getByRole('combobox'), 'zero') + await expect.element(page.getByRole('option')).not.toBeInTheDocument() - await userEvent.type(page.getByRole('combobox'), 'something') - await expect.element(page.getByText('No items available', {exact: true})).toBeInTheDocument() - }) + await waitFor( + async () => { + if (usingRemoveActiveDescendant) { + expect(getLiveRegion().getMessage('polite')!.trim()).toBe("Nothing found. There's nothing here.") + } else { + expect(getLiveRegion().getMessage('polite').trim()).toBe("Nothing found. There's nothing here.") + } + }, + {timeout: 3000}, + ) + }) - it('should display the default empty state message when there is no item after the initial load (No custom message is provided)', async () => { - renderWithProp(, usingRemoveActiveDescendant) + it('should accept a className to style the component', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) - await expect.element(page.getByTestId('filtered-action-list-spinner')).toBeInTheDocument() - await userEvent.keyboard('{Escape}') - await userEvent.click(page.getByText('Select items', {exact: true})) - await expect.element(page.getByText('No items available', {exact: true})).toBeInTheDocument() + await userEvent.click(page.getByText('Select items', {exact: true})) + + await expect.element(page.getByTestId('filtered-action-list')).toHaveClass('test-class') + }) }) - it('should display the custom empty state message when there is no matching item after filtering', async () => { - renderWithProp( - , - usingRemoveActiveDescendant, - ) - await userEvent.click(page.getByText('Select items', {exact: true})) + describe('Empty state', () => { + it('should display the default empty state message when there is no matching item after filtering (No custom message is provided)', async () => { + renderWithProp(, usingRemoveActiveDescendant) - expect(page.getByRole('option').elements()).toHaveLength(3) + await userEvent.click(page.getByText('Select items', {exact: true})) - await userEvent.type(page.getByRole('combobox'), 'something') - await expect.element(page.getByText('No language found for something', {exact: true})).toBeInTheDocument() - await expect - .element(page.getByText('Adjust your search term to find other languages', {exact: true})) - .toBeInTheDocument() - }) + expect(page.getByRole('option').elements()).toHaveLength(3) - it('should display the custom empty state message when there is no item after the initial load', async () => { - renderWithProp(, usingRemoveActiveDescendant) + await userEvent.type(page.getByRole('combobox'), 'something') + await expect.element(page.getByText('No items available', {exact: true})).toBeInTheDocument() + }) - await userEvent.click(page.getByText('Select items', {exact: true})) - await expect.element(page.getByText("You haven't created any projects yet", {exact: true})).toBeInTheDocument() - await expect - .element(page.getByText('Start your first project to organise your issues', {exact: true})) - .toBeInTheDocument() + it('should display the default empty state message when there is no item after the initial load (No custom message is provided)', async () => { + renderWithProp(, usingRemoveActiveDescendant) + + await userEvent.click(page.getByText('Select items', {exact: true})) + await expect.element(page.getByTestId('filtered-action-list-spinner')).toBeInTheDocument() + await userEvent.keyboard('{Escape}') + await userEvent.click(page.getByText('Select items', {exact: true})) + await expect.element(page.getByText('No items available', {exact: true})).toBeInTheDocument() + }) + it('should display the custom empty state message when there is no matching item after filtering', async () => { + renderWithProp( + , + usingRemoveActiveDescendant, + ) + + await userEvent.click(page.getByText('Select items', {exact: true})) + + expect(page.getByRole('option').elements()).toHaveLength(3) + + await userEvent.type(page.getByRole('combobox'), 'something') + await expect.element(page.getByText('No language found for something', {exact: true})).toBeInTheDocument() + await expect + .element(page.getByText('Adjust your search term to find other languages', {exact: true})) + .toBeInTheDocument() + }) + + it('should display the custom empty state message when there is no item after the initial load', async () => { + renderWithProp(, usingRemoveActiveDescendant) + + await userEvent.click(page.getByText('Select items', {exact: true})) + await expect + .element(page.getByText("You haven't created any projects yet", {exact: true})) + .toBeInTheDocument() + await expect + .element(page.getByText('Start your first project to organise your issues', {exact: true})) + .toBeInTheDocument() + }) + + it('should display action button in custom empty state message', async () => { + const handleAction = vi.fn() + + renderWithProp( + , + usingRemoveActiveDescendant, + ) + + await userEvent.click(page.getByText('Select items', {exact: true})) + await expect + .element(page.getByText("You haven't created any projects yet", {exact: true})) + .toBeInTheDocument() + await expect + .element(page.getByText('Start your first project to organise your issues', {exact: true})) + .toBeInTheDocument() + + // Check that action button is in the document + const actionButton = page.getByTestId('create-project-action') + await expect.element(actionButton).toBeInTheDocument() + await expect.element(actionButton).toHaveTextContent('Create new project') + + // Test that action button is clickable + await userEvent.click(actionButton) + expect(handleAction).toHaveBeenCalledTimes(1) + }) }) - it('should display action button in custom empty state message', async () => { - const handleAction = vi.fn() + describe('with footer', () => { + function SelectPanelWithFooter() { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - renderWithProp( - , - usingRemoveActiveDescendant, - ) + const onSelectedChange = (selected: SelectPanelProps['items']) => { + setSelected(selected) + } - await userEvent.click(page.getByText('Select items', {exact: true})) - await expect.element(page.getByText("You haven't created any projects yet", {exact: true})).toBeInTheDocument() - await expect - .element(page.getByText('Start your first project to organise your issues', {exact: true})) - .toBeInTheDocument() + return ( + test footer
} + items={items} + placeholder="Select items" + placeholderText="Filter items" + selected={selected} + onSelectedChange={onSelectedChange} + filterValue={filter} + onFilterChange={value => { + setFilter(value) + }} + open={open} + onOpenChange={isOpen => { + setOpen(isOpen) + }} + /> + ) + } - // Check that action button is in the document - const actionButton = page.getByTestId('create-project-action') - await expect.element(actionButton).toBeInTheDocument() - await expect.element(actionButton).toHaveTextContent('Create new project') + it('should render the provided `footer` at the bottom of the dialog', async () => { + renderWithProp(, usingRemoveActiveDescendant) - // Test that action button is clickable - await userEvent.click(actionButton) - expect(handleAction).toHaveBeenCalledTimes(1) + await userEvent.click(page.getByText('Select items', {exact: true})) + await expect.element(page.getByText('test footer', {exact: true})).toBeInTheDocument() + }) }) - }) - describe('with footer', () => { - function SelectPanelWithFooter() { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') + const listOfItems: Array = [ + { + id: '1', + key: 1, + text: 'Item 1', + groupId: '1', + }, + { + id: '2', + key: 2, + text: 'Item 2', + groupId: '1', + }, + { + id: '3', + key: 3, + text: 'Item 3', + groupId: '2', + }, + { + id: '4', + key: 4, + text: 'Item 4', + groupId: '3', + }, + ] + + const groupMetadata: GroupedListProps['groupMetadata'] = [ + {groupId: '1', header: {title: 'Group title 1'}}, + {groupId: '2', header: {title: 'Group title 2'}}, + {groupId: '3', header: {title: 'Group title 3'}}, + ] + + function SelectPanelWithGroups() { + const [selectedItems, setSelectedItems] = React.useState([]) const [open, setOpen] = React.useState(false) + const [filter, setFilter] = React.useState('') - const onSelectedChange = (selected: SelectPanelProps['items']) => { - setSelected(selected) + const onSelectedChange = (selections: ItemInput[]) => { + setSelectedItems(selections) } return ( test footer} - items={items} - placeholder="Select items" + groupMetadata={groupMetadata} placeholderText="Filter items" - selected={selected} + placeholder="Select items" + items={listOfItems} + selected={selectedItems} onSelectedChange={onSelectedChange} - filterValue={filter} - onFilterChange={value => { - setFilter(value) - }} open={open} onOpenChange={isOpen => { setOpen(isOpen) }} + filterValue={filter} + onFilterChange={value => { + setFilter(value) + }} /> ) } - it('should render the provided `footer` at the bottom of the dialog', async () => { - renderWithProp(, usingRemoveActiveDescendant) - - await userEvent.click(page.getByText('Select items', {exact: true})) - await expect.element(page.getByText('test footer', {exact: true})).toBeInTheDocument() - }) - }) - - const listOfItems: Array = [ - { - id: '1', - key: 1, - text: 'Item 1', - groupId: '1', - }, - { - id: '2', - key: 2, - text: 'Item 2', - groupId: '1', - }, - { - id: '3', - key: 3, - text: 'Item 3', - groupId: '2', - }, - { - id: '4', - key: 4, - text: 'Item 4', - groupId: '3', - }, - ] + describe('with groups', () => { + it('should render groups with items', async () => { + renderWithProp(, usingRemoveActiveDescendant) - const groupMetadata: GroupedListProps['groupMetadata'] = [ - {groupId: '1', header: {title: 'Group title 1'}}, - {groupId: '2', header: {title: 'Group title 2'}}, - {groupId: '3', header: {title: 'Group title 3'}}, - ] + await userEvent.click(page.getByText('Select items', {exact: true})) + const listbox = page.getByRole('listbox') + await expect.element(listbox).toBeInTheDocument() + await expect.element(listbox).toHaveAttribute('aria-multiselectable', 'true') - function SelectPanelWithGroups() { - const [selectedItems, setSelectedItems] = React.useState([]) - const [open, setOpen] = React.useState(false) - const [filter, setFilter] = React.useState('') + // listbox should has 3 groups and each have heading + const groups = page.getByRole('group').elements() + expect(groups).toHaveLength(3) + await expect.element(groups[0]).toHaveAttribute('aria-label', 'Group title 1') + await expect.element(groups[1]).toHaveAttribute('aria-label', 'Group title 2') + await expect.element(groups[2]).toHaveAttribute('aria-label', 'Group title 3') - const onSelectedChange = (selections: ItemInput[]) => { - setSelectedItems(selections) - } + expect(page.getByRole('option').elements()).toHaveLength(4) + }) + it('should select items within groups', async () => { + renderWithProp(, usingRemoveActiveDescendant) - return ( - { - setOpen(isOpen) - }} - filterValue={filter} - onFilterChange={value => { - setFilter(value) - }} - /> - ) - } + await userEvent.click(page.getByText('Select items', {exact: true})) - describe('with groups', () => { - it('should render groups with items', async () => { - renderWithProp(, usingRemoveActiveDescendant) + // Select the first item + await userEvent.click(page.getByRole('option', {name: 'Item 1'})) + await expect + .element( + page.getByRole('option', { + name: 'Item 1', + }), + ) + .toHaveAttribute('aria-selected', 'true') + + await userEvent.click(page.getByRole('option', {name: 'Item 3'})) + await expect + .element( + page.getByRole('option', { + name: 'Item 3', + }), + ) + .toHaveAttribute('aria-selected', 'true') + + await userEvent.click(page.getByRole('option', {name: 'Item 4'})) + await expect + .element( + page.getByRole('option', { + name: 'Item 4', + }), + ) + .toHaveAttribute('aria-selected', 'true') + }) + }) - await userEvent.click(page.getByText('Select items', {exact: true})) - const listbox = page.getByRole('listbox') - await expect.element(listbox).toBeInTheDocument() - await expect.element(listbox).toHaveAttribute('aria-multiselectable', 'true') + describe('As Modal', () => { + it('selections render as radios when variant modal and single select', async () => { + renderWithProp( + {}} selected={undefined} />, + usingRemoveActiveDescendant, + ) - // listbox should has 3 groups and each have heading - const groups = page.getByRole('group').elements() - expect(groups).toHaveLength(3) - await expect.element(groups[0]).toHaveAttribute('aria-label', 'Group title 1') - await expect.element(groups[1]).toHaveAttribute('aria-label', 'Group title 2') - await expect.element(groups[2]).toHaveAttribute('aria-label', 'Group title 3') + await userEvent.click(page.getByText('Select items', {exact: true})) - expect(page.getByRole('option').elements()).toHaveLength(4) - }) - it('should select items within groups', async () => { - renderWithProp(, usingRemoveActiveDescendant) + expect(page.getByRole('radio', {includeHidden: true}).elements()).toHaveLength(items.length) - await userEvent.click(page.getByText('Select items', {exact: true})) + await expect.element(page.getByRole('button', {name: 'Save'})).toBeInTheDocument() + await expect.element(page.getByRole('button', {name: 'Cancel', exact: true})).toBeInTheDocument() + }) + it('save and oncancel buttons are present when variant modal', async () => { + renderWithProp( {}} />, usingRemoveActiveDescendant) - // Select the first item - await userEvent.click(page.getByRole('option', {name: 'Item 1'})) - await expect - .element( - page.getByRole('option', { - name: 'Item 1', - }), - ) - .toHaveAttribute('aria-selected', 'true') + await userEvent.click(page.getByText('Select items', {exact: true})) - await userEvent.click(page.getByRole('option', {name: 'Item 3'})) - await expect - .element( - page.getByRole('option', { - name: 'Item 3', - }), - ) - .toHaveAttribute('aria-selected', 'true') + await expect.element(page.getByRole('button', {name: 'Save'})).toBeInTheDocument() + await expect.element(page.getByRole('button', {name: 'Cancel', exact: true})).toBeInTheDocument() + }) - await userEvent.click(page.getByRole('option', {name: 'Item 4'})) - await expect - .element( - page.getByRole('option', { - name: 'Item 4', - }), - ) - .toHaveAttribute('aria-selected', 'true') - }) - }) + it('locks body scroll when modal is open', async () => { + renderWithProp( {}} />, usingRemoveActiveDescendant) - describe('As Modal', () => { - it('selections render as radios when variant modal and single select', async () => { - renderWithProp( - {}} selected={undefined} />, - usingRemoveActiveDescendant, - ) + expect(document.body.style.overflow).not.toBe('hidden') - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - expect(page.getByRole('radio', {includeHidden: true}).elements()).toHaveLength(items.length) + await waitFor(() => { + expect(document.body.style.overflow).toBe('hidden') + }) + }) - await expect.element(page.getByRole('button', {name: 'Save'})).toBeInTheDocument() - await expect.element(page.getByRole('button', {name: 'Cancel'})).toBeInTheDocument() - }) - it('save and oncancel buttons are present when variant modal', async () => { - renderWithProp( {}} />, usingRemoveActiveDescendant) + it('restores body scroll when modal is closed', async () => { + renderWithProp( {}} />, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) + await waitFor(() => { + expect(document.body.style.overflow).toBe('hidden') + }) - await expect.element(page.getByRole('button', {name: 'Save'})).toBeInTheDocument() - await expect.element(page.getByRole('button', {name: 'Cancel'})).toBeInTheDocument() + await userEvent.click(page.getByRole('button', {name: 'Cancel', exact: true})) + await waitFor(() => { + expect(document.body.style.overflow).not.toBe('hidden') + }) + }) }) - it('locks body scroll when modal is open', async () => { - renderWithProp( {}} />, usingRemoveActiveDescendant) + describe('sorting', () => { + const items = [ + { + text: 'item one', + id: '3', + }, + { + text: 'item two', + id: '1', + selected: true, + }, + { + text: 'item three', + id: '2', + }, + ] - expect(document.body.style.overflow).not.toBe('hidden') + it('should render selected items at the top by default when FF on', async () => { + renderWithProp( + + + , + usingRemoveActiveDescendant, + ) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('item two', {exact: true})) // item two is selected so that's what the anchor text is - await waitFor(() => { - expect(document.body.style.overflow).toBe('hidden') + const options = page.getByRole('option').elements() + await expect.element(options[0]).toHaveTextContent('item two') // item two is selected + await expect.element(options[1]).toHaveTextContent('item one') + await expect.element(options[2]).toHaveTextContent('item three') }) - }) + it('should not render selected items at the top by default when FF off', async () => { + renderWithProp( + + + , + usingRemoveActiveDescendant, + ) - it('restores body scroll when modal is closed', async () => { - renderWithProp( {}} />, usingRemoveActiveDescendant) + await userEvent.click(page.getByText('item two', {exact: true})) // item two is selected so that's what the anchor text is - await userEvent.click(page.getByText('Select items', {exact: true})) - await waitFor(() => { - expect(document.body.style.overflow).toBe('hidden') + const options = page.getByRole('option').elements() + await expect.element(options[0]).toHaveTextContent('item one') + await expect.element(options[1]).toHaveTextContent('item two') // item two is selected + await expect.element(options[2]).toHaveTextContent('item three') }) + it('should not render selected items at the top when showSelectedOptionsFirst set to false', async () => { + renderWithProp( + , + usingRemoveActiveDescendant, + ) - await userEvent.click(page.getByRole('button', {name: 'Cancel'})) - await waitFor(() => { - expect(document.body.style.overflow).not.toBe('hidden') + await userEvent.click(page.getByText('item two', {exact: true})) // item two is selected so that's what the anchor text is + + const options = page.getByRole('option').elements() + await expect.element(options[0]).toHaveTextContent('item one') + await expect.element(options[1]).toHaveTextContent('item two') // item two is selected + await expect.element(options[2]).toHaveTextContent('item three') }) }) - }) - describe('sorting', () => { - const items = [ - { - text: 'item one', - id: '3', - }, - { - text: 'item two', - id: '1', - selected: true, - }, - { - text: 'item three', - id: '2', - }, - ] - - it('should render selected items at the top by default when FF on', async () => { - renderWithProp( - - - , - usingRemoveActiveDescendant, - ) - - await userEvent.click(page.getByText('item two', {exact: true})) // item two is selected so that's what the anchor text is - - const options = page.getByRole('option').elements() - await expect.element(options[0]).toHaveTextContent('item two') // item two is selected - await expect.element(options[1]).toHaveTextContent('item one') - await expect.element(options[2]).toHaveTextContent('item three') - }) - it('should not render selected items at the top by default when FF off', async () => { - renderWithProp( - - - , - usingRemoveActiveDescendant, - ) - - await userEvent.click(page.getByText('item two', {exact: true})) // item two is selected so that's what the anchor text is - - const options = page.getByRole('option').elements() - await expect.element(options[0]).toHaveTextContent('item one') - await expect.element(options[1]).toHaveTextContent('item two') // item two is selected - await expect.element(options[2]).toHaveTextContent('item three') - }) - it('should not render selected items at the top when showSelectedOptionsFirst set to false', async () => { - renderWithProp( - , - usingRemoveActiveDescendant, - ) - - await userEvent.click(page.getByText('item two', {exact: true})) // item two is selected so that's what the anchor text is + describe('disableFullscreenOnNarrow prop', () => { + const renderSelectPanelWithFlags = (flags: Record, props: Record = {}) => { + return renderWithProp( + + + , + usingRemoveActiveDescendant, + ) + } - const options = page.getByRole('option').elements() - await expect.element(options[0]).toHaveTextContent('item one') - await expect.element(options[1]).toHaveTextContent('item two') // item two is selected - await expect.element(options[2]).toHaveTextContent('item three') - }) - }) + // Create a single-select version to test ResponsiveCloseButton behavior + function SingleSelectPanel(passthroughProps: Record) { + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - describe('disableFullscreenOnNarrow prop', () => { - const renderSelectPanelWithFlags = (flags: Record, props: Record = {}) => { - return renderWithProp( - - - , - usingRemoveActiveDescendant, - ) - } + return ( + {}} + filterValue={filter} + onFilterChange={value => { + setFilter(value) + }} + open={open} + onOpenChange={open => setOpen(open)} + {...passthroughProps} + /> + ) + } - // Create a single-select version to test ResponsiveCloseButton behavior - function SingleSelectPanel(passthroughProps: Record) { - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) + it('should opt out of fullscreen when disableFullscreenOnNarrow=true even when feature flag is enabled', async () => { + renderSelectPanelWithFlags( + { + primer_react_select_panel_fullscreen_on_narrow: true, + }, + {disableFullscreenOnNarrow: true}, + ) - return ( - {}} - filterValue={filter} - onFilterChange={value => { - setFilter(value) - }} - open={open} - onOpenChange={open => setOpen(open)} - {...passthroughProps} - /> - ) - } + await userEvent.click(page.getByText('Select an item', {exact: true})) - it('should opt out of fullscreen when disableFullscreenOnNarrow=true even when feature flag is enabled', async () => { - renderSelectPanelWithFlags( - { - primer_react_select_panel_fullscreen_on_narrow: true, - }, - {disableFullscreenOnNarrow: true}, - ) + // When disableFullscreenOnNarrow=true, the ResponsiveCloseButton should not be present + // even when the feature flag is enabled, indicating no fullscreen behavior + const responsiveCloseButton = page.getByRole('button', {name: 'Cancel and close'}) + await expect.element(responsiveCloseButton).not.toBeInTheDocument() + }) - await userEvent.click(page.getByText('Select an item', {exact: true})) + it('should use fullscreen behavior when disableFullscreenOnNarrow=false and feature flag is enabled', async () => { + await page.viewport(320, 568) + renderSelectPanelWithFlags( + { + primer_react_select_panel_fullscreen_on_narrow: true, + }, + {disableFullscreenOnNarrow: false}, + ) - // When disableFullscreenOnNarrow=true, the ResponsiveCloseButton should not be present - // even when the feature flag is enabled, indicating no fullscreen behavior - const responsiveCloseButton = page.getByRole('button', {name: 'Cancel and close'}) - await expect.element(responsiveCloseButton).not.toBeInTheDocument() - }) + await userEvent.click(page.getByText('Select an item', {exact: true})) - it('should use fullscreen behavior when disableFullscreenOnNarrow=false and feature flag is enabled', async () => { - renderSelectPanelWithFlags( - { - primer_react_select_panel_fullscreen_on_narrow: true, - }, - {disableFullscreenOnNarrow: false}, - ) + // When feature flag is true and disableFullscreenOnNarrow is false, the ResponsiveCloseButton should be present + // indicating fullscreen behavior is active + const responsiveCloseButton = page.getByRole('button', {name: 'Cancel and close'}) + await expect.element(responsiveCloseButton).toBeInTheDocument() + }) - await userEvent.click(page.getByText('Select an item', {exact: true})) + it('should default to feature flag value when disableFullscreenOnNarrow is undefined', async () => { + // Test with feature flag disabled + renderSelectPanelWithFlags({ + primer_react_select_panel_fullscreen_on_narrow: false, + }) - // When feature flag is true and disableFullscreenOnNarrow is false, the ResponsiveCloseButton should be present - // indicating fullscreen behavior is active - const responsiveCloseButton = page.getByRole('button', {name: 'Cancel and close'}) - await expect.element(responsiveCloseButton).toBeInTheDocument() - }) + await userEvent.click(page.getByText('Select an item', {exact: true})) - it('should default to feature flag value when disableFullscreenOnNarrow is undefined', async () => { - // Test with feature flag disabled - renderSelectPanelWithFlags({ - primer_react_select_panel_fullscreen_on_narrow: false, + // When feature flag is false and disableFullscreenOnNarrow is undefined, + // the ResponsiveCloseButton should not be present + const responsiveCloseButton = page.getByRole('button', {name: 'Cancel and close'}) + await expect.element(responsiveCloseButton).not.toBeInTheDocument() }) - - await userEvent.click(page.getByText('Select an item', {exact: true})) - - // When feature flag is false and disableFullscreenOnNarrow is undefined, - // the ResponsiveCloseButton should not be present - const responsiveCloseButton = page.getByRole('button', {name: 'Cancel and close'}) - await expect.element(responsiveCloseButton).not.toBeInTheDocument() }) - }) - describe('Select all', () => { - function SelectAllSelectPanel({showSelectAll = true}: {showSelectAll?: boolean} = {}) { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) + describe('Select all', () => { + function SelectAllSelectPanel({showSelectAll = true}: {showSelectAll?: boolean} = {}) { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - const onSelectedChange = (selected: SelectPanelProps['items']) => { - setSelected(selected) - } + const onSelectedChange = (selected: SelectPanelProps['items']) => { + setSelected(selected) + } - return ( - { - setFilter(value) - }} - open={open} - onOpenChange={isOpen => { - setOpen(isOpen) - }} - showSelectAll={showSelectAll} - /> - ) - } + return ( + { + setFilter(value) + }} + open={open} + onOpenChange={isOpen => { + setOpen(isOpen) + }} + showSelectAll={showSelectAll} + /> + ) + } - it('should render a Select All checkbox when showSelectAll is true', async () => { - renderWithProp(, usingRemoveActiveDescendant) + it('should render a Select All checkbox when showSelectAll is true', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - await expect.element(page.getByText('Select all', {exact: true})).toBeInTheDocument() - await expect.element(page.getByRole('checkbox', {name: 'Select all'})).toBeInTheDocument() - await expect.element(page.getByRole('checkbox', {name: 'Select all'})).not.toBeChecked() - }) + await expect.element(page.getByText('Select all', {exact: true})).toBeInTheDocument() + await expect.element(page.getByRole('checkbox', {name: 'Select all'})).toBeInTheDocument() + await expect.element(page.getByRole('checkbox', {name: 'Select all'})).not.toBeChecked() + }) - it('should not render a Select All checkbox when showSelectAll is false', async () => { - renderWithProp(, usingRemoveActiveDescendant) + it('should not render a Select All checkbox when showSelectAll is false', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - await expect.element(page.getByText('Select all', {exact: true})).not.toBeInTheDocument() - await expect.element(page.getByRole('checkbox', {name: 'Select all'})).not.toBeInTheDocument() - }) + await expect.element(page.getByText('Select all', {exact: true})).not.toBeInTheDocument() + await expect.element(page.getByRole('checkbox', {name: 'Select all'})).not.toBeInTheDocument() + }) - it('should select all items when the Select All checkbox is clicked', async () => { - renderWithProp(, usingRemoveActiveDescendant) + it('should select all items when the Select All checkbox is clicked', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - await userEvent.click(page.getByRole('checkbox', {name: 'Select all'})) + await userEvent.click(page.getByRole('checkbox', {name: 'Select all'})) - // All options should now be selected - for (const item of items) { - await expect.element(page.getByRole('option', {name: item.text})).toHaveAttribute('aria-selected', 'true') - } - }) + // All options should now be selected + for (const item of items) { + await expect.element(page.getByRole('option', {name: item.text})).toHaveAttribute('aria-selected', 'true') + } + }) - it('should deselect all items when the Deselect All checkbox is clicked', async () => { - renderWithProp(, usingRemoveActiveDescendant) + it('should deselect all items when the Deselect All checkbox is clicked', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - // First select all - await userEvent.click(page.getByRole('checkbox', {name: 'Select all'})) + // First select all + await userEvent.click(page.getByRole('checkbox', {name: 'Select all'})) - // Then deselect all - await userEvent.click(page.getByRole('checkbox', {name: 'Deselect all'})) + // Then deselect all + await userEvent.click(page.getByRole('checkbox', {name: 'Deselect all'})) - // All options should now be deselected - for (const item of items) { - if (item.text) { - await expect.element(page.getByRole('option', {name: item.text})).toHaveAttribute('aria-selected', 'false') + // All options should now be deselected + for (const item of items) { + if (item.text) { + await expect + .element(page.getByRole('option', {name: item.text})) + .toHaveAttribute('aria-selected', 'false') + } } - } - }) + }) - it('should update Select All checkbox to indeterminate state when some items (but not all) are selected', async () => { - renderWithProp(, usingRemoveActiveDescendant) + it('should update Select All checkbox to indeterminate state when some items (but not all) are selected', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - // Select only one item - await userEvent.click(page.getByText('item one', {exact: true})) + // Select only one item + await userEvent.click(page.getByText('item one', {exact: true})) - // Check that Select All is in indeterminate state - const selectAllCheckbox = page.getByRole('checkbox', {name: 'Select all'}) - await expect.element(selectAllCheckbox).not.toBeChecked() - expect(selectAllCheckbox.element()).toHaveProperty('indeterminate', true) - }) + // Check that Select All is in indeterminate state + const selectAllCheckbox = page.getByRole('checkbox', {name: 'Select all'}) + await expect.element(selectAllCheckbox).not.toBeChecked() + expect(selectAllCheckbox.element()).toHaveProperty('indeterminate', true) + }) - it('should update Select All checkbox to checked when all items are selected manually', async () => { - renderWithProp(, usingRemoveActiveDescendant) + it('should update Select All checkbox to checked when all items are selected manually', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - // Select all items individually - for (const item of items) { - if (item.text) { - await userEvent.click(page.getByText(item.text, {exact: true})) + // Select all items individually + for (const item of items) { + if (item.text) { + await userEvent.click(page.getByText(item.text, {exact: true})) + } } - } - // Check that Deselect All is checked - await expect.element(page.getByRole('checkbox', {name: 'Deselect all'})).toBeChecked() - }) + // Check that Deselect All is checked + await expect.element(page.getByRole('checkbox', {name: 'Deselect all'})).toBeChecked() + }) - it('should update Select All checkbox label to "Deselect all" when all items are selected', async () => { - renderWithProp(, usingRemoveActiveDescendant) + it('should update Select All checkbox label to "Deselect all" when all items are selected', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - // Select all items - await userEvent.click(page.getByRole('checkbox', {name: 'Select all'})) + // Select all items + await userEvent.click(page.getByRole('checkbox', {name: 'Select all'})) - // Check that the label has changed to "Deselect all" - await expect.element(page.getByText('Deselect all', {exact: true})).toBeInTheDocument() - await expect.element(page.getByRole('checkbox', {name: 'Deselect all'})).toBeInTheDocument() - }) + // Check that the label has changed to "Deselect all" + await expect.element(page.getByText('Deselect all', {exact: true})).toBeInTheDocument() + await expect.element(page.getByRole('checkbox', {name: 'Deselect all'})).toBeInTheDocument() + }) - it('should apply Select All only to filtered items and maintain selection state when filters are cleared', async () => { - function FilterableSelectAllPanel() { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) + it('should apply Select All only to filtered items and maintain selection state when filters are cleared', async () => { + function FilterableSelectAllPanel() { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - const onSelectedChange = (selected: SelectPanelProps['items']) => { - setSelected(selected) + const onSelectedChange = (selected: SelectPanelProps['items']) => { + setSelected(selected) + } + + return ( + item.text?.includes(filter))} + placeholder="Select items" + placeholderText="Filter items" + selected={selected} + onSelectedChange={onSelectedChange} + filterValue={filter} + onFilterChange={value => { + setFilter(value) + }} + open={open} + onOpenChange={isOpen => { + setOpen(isOpen) + }} + showSelectAll={true} + /> + ) } - return ( - item.text?.includes(filter))} - placeholder="Select items" - placeholderText="Filter items" - selected={selected} - onSelectedChange={onSelectedChange} - filterValue={filter} - onFilterChange={value => { - setFilter(value) - }} - open={open} - onOpenChange={isOpen => { - setOpen(isOpen) - }} - showSelectAll={true} - /> - ) - } + renderWithProp(, usingRemoveActiveDescendant) - renderWithProp(, usingRemoveActiveDescendant) + await userEvent.click(page.getByText('Select items', {exact: true})) - await userEvent.click(page.getByText('Select items', {exact: true})) + // Filter to only show "item one" + await userEvent.type(page.getByLabelText('Filter items'), 'one') - // Filter to only show "item one" - await userEvent.type(page.getByLabelText('Filter items'), 'one') + // Only "item one" should be visible + expect(page.getByRole('option').elements()).toHaveLength(1) + await expect.element(page.getByText('item one', {exact: true})).toBeInTheDocument() - // Only "item one" should be visible - expect(page.getByRole('option').elements()).toHaveLength(1) - await expect.element(page.getByText('item one', {exact: true})).toBeInTheDocument() + // Select all (which is just the one visible item) + await userEvent.click(page.getByRole('checkbox', {name: 'Select all'})) - // Select all (which is just the one visible item) - await userEvent.click(page.getByRole('checkbox', {name: 'Select all'})) + // The visible item should be selected + await expect.element(page.getByRole('option', {name: 'item one'})).toHaveAttribute('aria-selected', 'true') - // The visible item should be selected - await expect.element(page.getByRole('option', {name: 'item one'})).toHaveAttribute('aria-selected', 'true') + // Clear the filter + await userEvent.clear(page.getByLabelText('Filter items')) - // Clear the filter - await userEvent.clear(page.getByLabelText('Filter items')) + // Now all items should be visible, but only "item one" should be selected + expect(page.getByRole('option').elements()).toHaveLength(3) + await expect.element(page.getByRole('option', {name: 'item one'})).toHaveAttribute('aria-selected', 'true') + await expect.element(page.getByRole('option', {name: 'item two'})).toHaveAttribute('aria-selected', 'false') + await expect.element(page.getByRole('option', {name: 'item three'})).toHaveAttribute('aria-selected', 'false') - // Now all items should be visible, but only "item one" should be selected - expect(page.getByRole('option').elements()).toHaveLength(3) - await expect.element(page.getByRole('option', {name: 'item one'})).toHaveAttribute('aria-selected', 'true') - await expect.element(page.getByRole('option', {name: 'item two'})).toHaveAttribute('aria-selected', 'false') - await expect.element(page.getByRole('option', {name: 'item three'})).toHaveAttribute('aria-selected', 'false') - - // Select All checkbox should be in indeterminate state - const selectAllCheckbox = page.getByRole('checkbox', {name: 'Select all'}) - await expect.element(selectAllCheckbox).not.toBeChecked() - expect(selectAllCheckbox.element()).toHaveProperty('indeterminate', true) + // Select All checkbox should be in indeterminate state + const selectAllCheckbox = page.getByRole('checkbox', {name: 'Select all'}) + await expect.element(selectAllCheckbox).not.toBeChecked() + expect(selectAllCheckbox.element()).toHaveProperty('indeterminate', true) + }) }) - }) - describe('disableSelectOnHover', () => { - it('should not update aria-activedescendant when hovering over items when disableSelectOnHover is true', async () => { - render() + describe('disableSelectOnHover', () => { + it('should not update aria-activedescendant when hovering over items when disableSelectOnHover is true', async () => { + render() - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - const input = page.getByPlaceholder('Filter items') - const options = page.getByRole('option').elements() + const input = page.getByPlaceholder('Filter items') + const options = page.getByRole('option').elements() - // Initially, aria-activedescendant should not be set if setInitialFocus is false (default) - const initialActiveDescendant = input.element().getAttribute('aria-activedescendant') + // Initially, aria-activedescendant should not be set if setInitialFocus is false (default) + const initialActiveDescendant = input.element().getAttribute('aria-activedescendant') - // Hover over the first item - await userEvent.hover(options[0]) + // Hover over the first item + await userEvent.hover(options[0]) - // aria-activedescendant should not change when disableSelectOnHover is true - expect(input.element().getAttribute('aria-activedescendant')).toBe(initialActiveDescendant) + // aria-activedescendant should not change when disableSelectOnHover is true + expect(input.element().getAttribute('aria-activedescendant')).toBe(initialActiveDescendant) - // Hover over the second item - await userEvent.hover(options[1]) + // Hover over the second item + await userEvent.hover(options[1]) - // aria-activedescendant should still not change - expect(input.element().getAttribute('aria-activedescendant')).toBe(initialActiveDescendant) - }) + // aria-activedescendant should still not change + expect(input.element().getAttribute('aria-activedescendant')).toBe(initialActiveDescendant) + }) - it('should update aria-activedescendant when hovering over items when disableSelectOnHover is false (default)', async () => { - render() + it('should update aria-activedescendant when hovering over items when disableSelectOnHover is false (default)', async () => { + render() - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - const input = page.getByPlaceholder('Filter items') - const options = page.getByRole('option').elements() + const input = page.getByPlaceholder('Filter items') + const options = page.getByRole('option').elements() - // Hover over the first item - await userEvent.hover(options[0]) + // Hover over the first item + await userEvent.hover(options[0]) - // aria-activedescendant should be set to the first item - expect(input.element().getAttribute('aria-activedescendant')).toBe(options[0].id) + // aria-activedescendant should be set to the first item + expect(input.element().getAttribute('aria-activedescendant')).toBe(options[0].id) - // Hover over the second item - await userEvent.hover(options[1]) + // Hover over the second item + await userEvent.hover(options[1]) - // aria-activedescendant should be updated to the second item - expect(input.element().getAttribute('aria-activedescendant')).toBe(options[1].id) + // aria-activedescendant should be updated to the second item + expect(input.element().getAttribute('aria-activedescendant')).toBe(options[1].id) + }) }) - }) - describe('setInitialFocus', () => { - it('should not set aria-activedescendant until user interaction when setInitialFocus is true', async () => { - render() + describe('setInitialFocus', () => { + it('should not set aria-activedescendant until user interaction when setInitialFocus is true', async () => { + render() - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - const input = page.getByPlaceholder('Filter items') - const options = page.getByRole('option').elements() + const input = page.getByPlaceholder('Filter items') + const options = page.getByRole('option').elements() - // Initially, aria-activedescendant should not be set - expect(input.element().getAttribute('aria-activedescendant')).toBeFalsy() + // Initially, aria-activedescendant should not be set + expect(input.element().getAttribute('aria-activedescendant')).toBeFalsy() - // User interacts with keyboard - await userEvent.keyboard('{ArrowDown}') + // User interacts with keyboard + await userEvent.keyboard('{ArrowDown}') - // Now aria-activedescendant should be set to the first item - expect(input.element().getAttribute('aria-activedescendant')).toBe(options[0].id) - }) + // Now aria-activedescendant should be set to the first item + expect(input.element().getAttribute('aria-activedescendant')).toBe(options[0].id) + }) - it('should set aria-activedescendant to the first item on mount when setInitialFocus is false (default)', async () => { - render() + it('should set aria-activedescendant to the first item on mount when setInitialFocus is false (default)', async () => { + render() - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - const input = page.getByPlaceholder('Filter items') - const options = page.getByRole('option').elements() + const input = page.getByPlaceholder('Filter items') + const options = page.getByRole('option').elements() - await waitFor(() => { - expect(input.element().getAttribute('aria-activedescendant')).toBe(options[0].id) + await waitFor(() => { + expect(input.element().getAttribute('aria-activedescendant')).toBe(options[0].id) + }) }) - }) - it('should not set aria-activedescendant on mouse hover until after first interaction when setInitialFocus is true', async () => { - render() + it('should not set aria-activedescendant on mouse hover until after first interaction when setInitialFocus is true', async () => { + render() - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - const input = page.getByPlaceholder('Filter items') - const options = page.getByRole('option').elements() + const input = page.getByPlaceholder('Filter items') + const options = page.getByRole('option').elements() - // Initially, aria-activedescendant should not be set - expect(input.element().getAttribute('aria-activedescendant')).toBeFalsy() + // Initially, aria-activedescendant should not be set + expect(input.element().getAttribute('aria-activedescendant')).toBeFalsy() - // Hover over the first item (this is the first interaction) - await userEvent.hover(options[0]) + // Hover over the first item (this is the first interaction) + await userEvent.hover(options[0]) - // Now aria-activedescendant should be set to the first item - expect(input.element().getAttribute('aria-activedescendant')).toBe(options[0].id) + // Now aria-activedescendant should be set to the first item + expect(input.element().getAttribute('aria-activedescendant')).toBe(options[0].id) - // Hover over the second item - await userEvent.hover(options[1]) + // Hover over the second item + await userEvent.hover(options[1]) - // aria-activedescendant should update to the second item - expect(input.element().getAttribute('aria-activedescendant')).toBe(options[1].id) + // aria-activedescendant should update to the second item + expect(input.element().getAttribute('aria-activedescendant')).toBe(options[1].id) + }) }) - }) - describe('data-component attributes', () => { - it('renders SelectPanel with data-component attribute', async () => { - renderWithProp(, usingRemoveActiveDescendant) + describe('data-component attributes', () => { + it('renders SelectPanel with data-component attribute', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - await expect - .element(page.getByRole('dialog').element().querySelector('[data-component="SelectPanel"]')) - .toBeInTheDocument() - }) + await expect + .element(page.getByRole('dialog').element().querySelector('[data-component="SelectPanel"]')) + .toBeInTheDocument() + }) - it('renders SelectPanel.Header with data-component attribute', async () => { - renderWithProp(, usingRemoveActiveDescendant) + it('renders SelectPanel.Header with data-component attribute', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - await expect - .element( - page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.Header"]'), - ) - .toBeInTheDocument() - }) + await expect + .element( + page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.Header"]'), + ) + .toBeInTheDocument() + }) - it('renders SelectPanel.Title with data-component attribute', async () => { - renderWithProp(, usingRemoveActiveDescendant) + it('renders SelectPanel.Title with data-component attribute', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - await expect - .element( - page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.Title"]'), - ) - .toBeInTheDocument() - }) + await expect + .element( + page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.Title"]'), + ) + .toBeInTheDocument() + }) - it('renders SelectPanel.Subtitle with data-component attribute', async () => { - renderWithProp(, usingRemoveActiveDescendant) + it('renders SelectPanel.Subtitle with data-component attribute', async () => { + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - await expect - .element( - page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.Subtitle"]'), - ) - .toBeInTheDocument() - }) - - it('renders SelectPanel.Footer with data-component attribute when using deprecated footer prop', async () => { - function SelectPanelWithFooter() { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) - - return ( - test footer} - items={items} - placeholder="Select items" - placeholderText="Filter items" - selected={selected} - onSelectedChange={setSelected} - filterValue={filter} - onFilterChange={setFilter} - open={open} - onOpenChange={setOpen} - /> - ) - } - - renderWithProp(, usingRemoveActiveDescendant) - - await userEvent.click(page.getByText('Select items', {exact: true})) - - await expect - .element( - page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.Footer"]'), - ) - .toBeInTheDocument() - }) - - it('renders SelectPanel.Footer with data-component attribute when using modal variant', async () => { - renderWithProp( {}} />, usingRemoveActiveDescendant) - - await userEvent.click(page.getByText('Select items', {exact: true})) - - await expect - .element( - page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.Footer"]'), - ) - .toBeInTheDocument() - }) - - it('renders SelectPanel.CancelButton with data-component attribute', async () => { - renderWithProp( {}} />, usingRemoveActiveDescendant) - - await userEvent.click(page.getByText('Select items', {exact: true})) - - await expect - .element( - page - .getByRole('dialog') - .element() - .querySelector('[data-component="SelectPanel.CancelButton"]'), - ) - .toBeInTheDocument() - }) + await expect + .element( + page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.Subtitle"]'), + ) + .toBeInTheDocument() + }) - it('renders SelectPanel.SaveButton with data-component attribute', async () => { - renderWithProp( {}} />, usingRemoveActiveDescendant) + it('renders SelectPanel.Footer with data-component attribute when using deprecated footer prop', async () => { + function SelectPanelWithFooter() { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - await userEvent.click(page.getByText('Select items', {exact: true})) + return ( + test footer} + items={items} + placeholder="Select items" + placeholderText="Filter items" + selected={selected} + onSelectedChange={setSelected} + filterValue={filter} + onFilterChange={setFilter} + open={open} + onOpenChange={setOpen} + /> + ) + } - await expect - .element( - page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.SaveButton"]'), - ) - .toBeInTheDocument() - }) + renderWithProp(, usingRemoveActiveDescendant) - // Note: SelectPanel.CloseButton is only rendered on non-narrow screens in modal variant. - // On narrow screens, AnchoredOverlay handles the close button display. + await userEvent.click(page.getByText('Select items', {exact: true})) - it('renders SelectPanel.Backdrop with data-component attribute in modal variant', async () => { - renderWithProp( {}} />, usingRemoveActiveDescendant) + await expect + .element( + page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.Footer"]'), + ) + .toBeInTheDocument() + }) - await userEvent.click(page.getByText('Select items', {exact: true})) + it('renders SelectPanel.Footer with data-component attribute when using modal variant', async () => { + renderWithProp( {}} />, usingRemoveActiveDescendant) - await expect - .element(document.querySelector('[data-component="SelectPanel.Backdrop"]')) - .toBeInTheDocument() - }) + await userEvent.click(page.getByText('Select items', {exact: true})) - it('renders SelectPanel.SecondaryAction with data-component attribute', async () => { - function SelectPanelWithSecondaryAction() { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) + await expect + .element( + page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.Footer"]'), + ) + .toBeInTheDocument() + }) - return ( - Action} - items={items} - placeholder="Select items" - placeholderText="Filter items" - selected={selected} - onSelectedChange={setSelected} - filterValue={filter} - onFilterChange={setFilter} - open={open} - onOpenChange={setOpen} - variant="modal" - onCancel={() => {}} - /> - ) - } + it('renders SelectPanel.CancelButton with data-component attribute', async () => { + renderWithProp( {}} />, usingRemoveActiveDescendant) - renderWithProp(, usingRemoveActiveDescendant) + await userEvent.click(page.getByText('Select items', {exact: true})) - await userEvent.click(page.getByText('Select items', {exact: true})) + await expect + .element( + page + .getByRole('dialog') + .element() + .querySelector('[data-component="SelectPanel.CancelButton"]'), + ) + .toBeInTheDocument() + }) - await expect - .element( - page - .getByRole('dialog') - .element() - .querySelector('[data-component="SelectPanel.SecondaryAction"]'), - ) - .toBeInTheDocument() - }) + it('renders SelectPanel.SaveButton with data-component attribute', async () => { + renderWithProp( {}} />, usingRemoveActiveDescendant) - it('renders SelectPanel.SecondaryActionButton with data-component attribute', async () => { - function SelectPanelWithSecondaryActionButton() { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) + await userEvent.click(page.getByText('Select items', {exact: true})) - return ( - Action} - items={items} - placeholder="Select items" - placeholderText="Filter items" - selected={selected} - onSelectedChange={setSelected} - filterValue={filter} - onFilterChange={setFilter} - open={open} - onOpenChange={setOpen} - variant="modal" - onCancel={() => {}} - /> - ) - } + await expect + .element( + page + .getByRole('dialog') + .element() + .querySelector('[data-component="SelectPanel.SaveButton"]'), + ) + .toBeInTheDocument() + }) - renderWithProp(, usingRemoveActiveDescendant) + // Note: SelectPanel.CloseButton is only rendered on non-narrow screens in modal variant. + // On narrow screens, AnchoredOverlay handles the close button display. - await userEvent.click(page.getByText('Select items', {exact: true})) + it('renders SelectPanel.Backdrop with data-component attribute in modal variant', async () => { + renderWithProp( {}} />, usingRemoveActiveDescendant) - await expect - .element( - page - .getByRole('dialog') - .element() - .querySelector('[data-component="SelectPanel.SecondaryActionButton"]'), - ) - .toBeInTheDocument() - }) - - it('renders SelectPanel.SecondaryActionLink with data-component attribute', async () => { - function SelectPanelWithSecondaryActionLink() { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) - - return ( - Link} - items={items} - placeholder="Select items" - placeholderText="Filter items" - selected={selected} - onSelectedChange={setSelected} - filterValue={filter} - onFilterChange={setFilter} - open={open} - onOpenChange={setOpen} - variant="modal" - onCancel={() => {}} - /> - ) - } + await userEvent.click(page.getByText('Select items', {exact: true})) - renderWithProp(, usingRemoveActiveDescendant) + await expect + .element(document.querySelector('[data-component="SelectPanel.Backdrop"]')) + .toBeInTheDocument() + }) - await userEvent.click(page.getByText('Select items', {exact: true})) + it('renders SelectPanel.SecondaryAction with data-component attribute', async () => { + function SelectPanelWithSecondaryAction() { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - await expect - .element( - page - .getByRole('dialog') - .element() - .querySelector('[data-component="SelectPanel.SecondaryActionLink"]'), - ) - .toBeInTheDocument() - }) + return ( + Action} + items={items} + placeholder="Select items" + placeholderText="Filter items" + selected={selected} + onSelectedChange={setSelected} + filterValue={filter} + onFilterChange={setFilter} + open={open} + onOpenChange={setOpen} + variant="modal" + onCancel={() => {}} + /> + ) + } - it('renders SelectPanel.Notice with data-component attribute', async () => { - function SelectPanelWithNotice() { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) + renderWithProp(, usingRemoveActiveDescendant) - return ( - - ) - } + await userEvent.click(page.getByText('Select items', {exact: true})) - renderWithProp(, usingRemoveActiveDescendant) + await expect + .element( + page + .getByRole('dialog') + .element() + .querySelector('[data-component="SelectPanel.SecondaryAction"]'), + ) + .toBeInTheDocument() + }) - await userEvent.click(page.getByText('Select items', {exact: true})) + it('renders SelectPanel.SecondaryActionButton with data-component attribute', async () => { + function SelectPanelWithSecondaryActionButton() { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - await expect - .element( - page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.Notice"]'), - ) - .toBeInTheDocument() - }) + return ( + Action} + items={items} + placeholder="Select items" + placeholderText="Filter items" + selected={selected} + onSelectedChange={setSelected} + filterValue={filter} + onFilterChange={setFilter} + open={open} + onOpenChange={setOpen} + variant="modal" + onCancel={() => {}} + /> + ) + } - it('renders SelectPanel.Message with data-component attribute when message is shown', async () => { - function SelectPanelWithMessage() { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) + renderWithProp(, usingRemoveActiveDescendant) - return ( - - ) - } + await userEvent.click(page.getByText('Select items', {exact: true})) - renderWithProp(, usingRemoveActiveDescendant) + await expect + .element( + page + .getByRole('dialog') + .element() + .querySelector('[data-component="SelectPanel.SecondaryActionButton"]'), + ) + .toBeInTheDocument() + }) - await userEvent.click(page.getByText('Select items', {exact: true})) + it('renders SelectPanel.SecondaryActionLink with data-component attribute', async () => { + function SelectPanelWithSecondaryActionLink() { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - await expect - .element( - page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.Message"]'), - ) - .toBeInTheDocument() - await expect - .element( - page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.MessageIcon"]'), - ) - .toBeInTheDocument() - await expect - .element( - page - .getByRole('dialog') - .element() - .querySelector('[data-component="SelectPanel.MessageTitle"]'), - ) - .toBeInTheDocument() - await expect - .element( - page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.MessageBody"]'), - ) - .toBeInTheDocument() - }) + return ( + Link} + items={items} + placeholder="Select items" + placeholderText="Filter items" + selected={selected} + onSelectedChange={setSelected} + filterValue={filter} + onFilterChange={setFilter} + open={open} + onOpenChange={setOpen} + variant="modal" + onCancel={() => {}} + /> + ) + } - it('renders SelectPanel.MessageAction with data-component attribute when action is provided', async () => { - function SelectPanelWithMessageAction() { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) + renderWithProp(, usingRemoveActiveDescendant) - return ( - Retry, - }} - items={[]} - placeholder="Select items" - placeholderText="Filter items" - selected={selected} - onSelectedChange={setSelected} - filterValue={filter} - onFilterChange={setFilter} - open={open} - onOpenChange={setOpen} - /> - ) - } + await userEvent.click(page.getByText('Select items', {exact: true})) - renderWithProp(, usingRemoveActiveDescendant) + await expect + .element( + page + .getByRole('dialog') + .element() + .querySelector('[data-component="SelectPanel.SecondaryActionLink"]'), + ) + .toBeInTheDocument() + }) - await userEvent.click(page.getByText('Select items', {exact: true})) + it('renders SelectPanel.Notice with data-component attribute', async () => { + function SelectPanelWithNotice() { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - await expect - .element( - page - .getByRole('dialog') - .element() - .querySelector('[data-component="SelectPanel.MessageAction"]'), - ) - .toBeInTheDocument() - }) + return ( + + ) + } - it('allows accessing nested ActionList data-component attributes from SelectPanel', async () => { - const itemsWithLeadingVisual = [ - {text: 'item one', leadingVisual: () => Icon}, - {text: 'item two', leadingVisual: () => Icon}, - ] + renderWithProp(, usingRemoveActiveDescendant) - function SelectPanelWithLeadingVisuals() { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) + await userEvent.click(page.getByText('Select items', {exact: true})) - return ( - - ) - } + await expect + .element( + page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.Notice"]'), + ) + .toBeInTheDocument() + }) - renderWithProp(, usingRemoveActiveDescendant) + it('renders SelectPanel.Message with data-component attribute when message is shown', async () => { + function SelectPanelWithMessage() { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - await userEvent.click(page.getByText('Select items', {exact: true})) + return ( + + ) + } - // Test that you can query for ActionList primitives nested within SelectPanel - await expect - .element( - page - .getByRole('dialog') - .element() - .querySelector('[data-component="SelectPanel"] [data-component="ActionList.Item"]'), - ) - .toBeInTheDocument() + renderWithProp(, usingRemoveActiveDescendant) - await expect - .element( - page - .getByRole('dialog') - .element() - .querySelector('[data-component="SelectPanel"] [data-component="ActionList.LeadingVisual"]'), - ) - .toBeInTheDocument() + await userEvent.click(page.getByText('Select items', {exact: true})) - await expect - .element( - page - .getByRole('dialog') - .element() - .querySelector('[data-component="SelectPanel"] [data-component="ActionList.Item.Label"]'), - ) - .toBeInTheDocument() + await expect + .element( + page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.Message"]'), + ) + .toBeInTheDocument() + await expect + .element( + page + .getByRole('dialog') + .element() + .querySelector('[data-component="SelectPanel.MessageIcon"]'), + ) + .toBeInTheDocument() + await expect + .element( + page + .getByRole('dialog') + .element() + .querySelector('[data-component="SelectPanel.MessageTitle"]'), + ) + .toBeInTheDocument() + await expect + .element( + page + .getByRole('dialog') + .element() + .querySelector('[data-component="SelectPanel.MessageBody"]'), + ) + .toBeInTheDocument() + }) - // Test that you can query for the TextInput nested within SelectPanel - await expect - .element( - page - .getByRole('dialog') - .element() - .querySelector( - '[data-component="SelectPanel"] [data-component="TextInput"] [data-component="input"]', - ), - ) - .toBeInTheDocument() - }) + it('renders SelectPanel.MessageAction with data-component attribute when action is provided', async () => { + function SelectPanelWithMessageAction() { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - it('renders SelectPanel.CloseButton with data-component attribute on wide viewports in modal variant', async () => { - await page.viewport(1400, 728) + return ( + Retry, + }} + items={[]} + placeholder="Select items" + placeholderText="Filter items" + selected={selected} + onSelectedChange={setSelected} + filterValue={filter} + onFilterChange={setFilter} + open={open} + onOpenChange={setOpen} + /> + ) + } - renderWithProp( {}} />, usingRemoveActiveDescendant) + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - await expect - .element( - page.getByRole('dialog').element().querySelector('[data-component="SelectPanel.CloseButton"]'), - ) - .toBeInTheDocument() - }) + await expect + .element( + page + .getByRole('dialog') + .element() + .querySelector('[data-component="SelectPanel.MessageAction"]'), + ) + .toBeInTheDocument() + }) - it('renders SelectPanel.SaveAndCloseButton with data-component attribute on narrow viewports', async () => { - await page.viewport(320, 568) + it('allows accessing nested ActionList data-component attributes from SelectPanel', async () => { + const itemsWithLeadingVisual = [ + {text: 'item one', leadingVisual: () => Icon}, + {text: 'item two', leadingVisual: () => Icon}, + ] - function MultiSelectPanelWithoutCancel() { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) + function SelectPanelWithLeadingVisuals() { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - return ( - + return ( - - ) - } + ) + } - render() + renderWithProp(, usingRemoveActiveDescendant) - await userEvent.click(page.getByText('Select items', {exact: true})) + await userEvent.click(page.getByText('Select items', {exact: true})) - await expect - .element( - page - .getByRole('dialog') - .element() - .querySelector('[data-component="SelectPanel.SaveAndCloseButton"]'), - ) - .toBeInTheDocument() + // Test that you can query for ActionList primitives nested within SelectPanel + await expect + .element( + page + .getByRole('dialog') + .element() + .querySelector('[data-component="SelectPanel"] [data-component="ActionList.Item"]'), + ) + .toBeInTheDocument() + + await expect + .element( + page + .getByRole('dialog') + .element() + .querySelector( + '[data-component="SelectPanel"] [data-component="ActionList.LeadingVisual"]', + ), + ) + .toBeInTheDocument() + + await expect + .element( + page + .getByRole('dialog') + .element() + .querySelector('[data-component="SelectPanel"] [data-component="ActionList.Item.Label"]'), + ) + .toBeInTheDocument() + + // Test that you can query for the TextInput nested within SelectPanel + await expect + .element( + page + .getByRole('dialog') + .element() + .querySelector( + '[data-component="SelectPanel"] [data-component="TextInput"] [data-component="input"]', + ), + ) + .toBeInTheDocument() + }) + + it('renders SelectPanel.CloseButton with data-component attribute on wide viewports in modal variant', async () => { + await page.viewport(1400, 728) + + renderWithProp( {}} />, usingRemoveActiveDescendant) + + await userEvent.click(page.getByText('Select items', {exact: true})) + + await expect + .element( + page + .getByRole('dialog') + .element() + .querySelector('[data-component="SelectPanel.CloseButton"]'), + ) + .toBeInTheDocument() + }) + + it('renders SelectPanel.SaveAndCloseButton with data-component attribute on narrow viewports', async () => { + await page.viewport(320, 568) + + function MultiSelectPanelWithoutCancel() { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) + + return ( + + + + ) + } + + render() + + await userEvent.click(page.getByText('Select items', {exact: true})) + + await expect + .element( + page + .getByRole('dialog') + .element() + .querySelector('[data-component="SelectPanel.SaveAndCloseButton"]'), + ) + .toBeInTheDocument() + }) }) }) - }) - describe('Event propagation', () => { - function EventSelectPanel() { - const [selected, setSelected] = React.useState([]) - const [filter, setFilter] = React.useState('') - const [open, setOpen] = React.useState(false) + describe('Event propagation', () => { + function EventSelectPanel() { + const [selected, setSelected] = React.useState([]) + const [filter, setFilter] = React.useState('') + const [open, setOpen] = React.useState(false) - const onSelectedChange = (selected: SelectPanelProps['items']) => { - setSelected(selected) - } + const onSelectedChange = (selected: SelectPanelProps['items']) => { + setSelected(selected) + } - return ( - // eslint-disable-next-line jsx-a11y/no-static-element-interactions -
) => { - const isAlphabetKey = e.key.length === 1 && /[a-z\d]/i.test(e.key) - const container = e.currentTarget - - if (!isAlphabetKey) return - container.setAttribute('data-keydown-called', 'true') - }} - data-keydown-called="false" - > - - { - setFilter(value) - }} - open={open} - onOpenChange={isOpen => { - setOpen(isOpen) + return ( +
) => { + const isAlphabetKey = e.key.length === 1 && /[a-z\d]/i.test(e.key) + const container = e.currentTarget + + if (!isAlphabetKey) return + container.setAttribute('data-keydown-called', 'true') }} - _PrivateFocusManagement="roving-tabindex" - /> -
- ) - } + data-keydown-called="false" + > + + { + setFilter(value) + }} + open={open} + onOpenChange={isOpen => { + setOpen(isOpen) + }} + _PrivateFocusManagement="roving-tabindex" + /> +
+ ) + } - it('should prevent event propagation when using keyboard while focusing on an item', async () => { - render() + it('should prevent event propagation when using keyboard while focusing on an item', async () => { + render() - const toggleButton = page.getByRole('button', {name: 'Toggle SelectPanel'}) - const container = toggleButton.element().parentElement + const toggleButton = page.getByRole('button', {name: 'Toggle SelectPanel'}) + const container = toggleButton.element().parentElement - await userEvent.click(toggleButton) + await userEvent.click(toggleButton) - await expect.element(page.getByText('Select items', {exact: true})).toBeInTheDocument() + await expect.element(page.getByText('Select items', {exact: true})).toBeInTheDocument() - const listbox = page.getByRole('listbox') - await expect.element(listbox).toBeInTheDocument() - await expect.element(listbox).toHaveAttribute('aria-multiselectable', 'true') + const listbox = page.getByRole('listbox') + await expect.element(listbox).toBeInTheDocument() + await expect.element(listbox).toHaveAttribute('aria-multiselectable', 'true') - const options = page.getByRole('option').elements() - expect(options).toHaveLength(3) + const options = page.getByRole('option').elements() + expect(options).toHaveLength(3) - const firstOption = options[0] - await expect.element(firstOption).toHaveTextContent('item one') + const firstOption = options[0] + await expect.element(firstOption).toHaveTextContent('item one') - await userEvent.keyboard('{ArrowDown}') + await userEvent.keyboard('{ArrowDown}') - await expect.element(firstOption).toHaveFocus() + await expect.element(firstOption).toHaveFocus() - await userEvent.keyboard('{ArrowDown}') + await userEvent.keyboard('{ArrowDown}') - // Trigger alphabet key that should not propagate - await userEvent.keyboard('A') + // Trigger alphabet key that should not propagate + await userEvent.keyboard('A') - await expect.element(options[1]).toHaveFocus() - expect(container?.getAttribute('data-keydown-called')).toBe('false') + await expect.element(options[1]).toHaveFocus() + expect(container?.getAttribute('data-keydown-called')).toBe('false') + }) }) - }) -} + } -describe('SelectPanel displayInViewport prop', () => { - const mockGetAnchoredPosition = vi.mocked(getAnchoredPosition) + describe('SelectPanel displayInViewport prop', () => { + const mockGetAnchoredPosition = vi.mocked(getAnchoredPosition) - beforeEach(() => { - mockGetAnchoredPosition.mockClear() - }) + beforeEach(() => { + mockGetAnchoredPosition.mockClear() + }) - it('should forward displayInViewport={true} to getAnchoredPosition', async () => { - render() + it('should forward displayInViewport={true} to getAnchoredPosition', async () => { + render() - await userEvent.click(page.getByRole('button', {name: 'Select items'})) + await userEvent.click(page.getByRole('button', {name: 'Select items'})) - await waitFor(async () => { - await expect.element(page.getByRole('listbox')).toBeInTheDocument() - }) + await waitFor(async () => { + await expect.element(page.getByRole('listbox')).toBeInTheDocument() + }) + + await waitFor(() => { + expect(mockGetAnchoredPosition).toHaveBeenCalled() + }) - await waitFor(() => { - expect(mockGetAnchoredPosition).toHaveBeenCalled() + const calls = mockGetAnchoredPosition.mock.calls + const lastCall = calls[calls.length - 1] + expect(lastCall[2]?.displayInViewport).toBe(true) }) - const calls = mockGetAnchoredPosition.mock.calls - const lastCall = calls[calls.length - 1] - expect(lastCall[2]?.displayInViewport).toBe(true) - }) + it('should not set displayInViewport when prop is not provided', async () => { + render() - it('should not set displayInViewport when prop is not provided', async () => { - render() + await userEvent.click(page.getByRole('button', {name: 'Select items'})) - await userEvent.click(page.getByRole('button', {name: 'Select items'})) + await waitFor(async () => { + await expect.element(page.getByRole('listbox')).toBeInTheDocument() + }) - await waitFor(async () => { - await expect.element(page.getByRole('listbox')).toBeInTheDocument() - }) + await waitFor(() => { + expect(mockGetAnchoredPosition).toHaveBeenCalled() + }) - await waitFor(() => { - expect(mockGetAnchoredPosition).toHaveBeenCalled() + const calls = mockGetAnchoredPosition.mock.calls + const lastCall = calls[calls.length - 1] + expect(lastCall[2]?.displayInViewport).not.toBe(true) }) - - const calls = mockGetAnchoredPosition.mock.calls - const lastCall = calls[calls.length - 1] - expect(lastCall[2]?.displayInViewport).not.toBe(true) }) }) diff --git a/packages/react/src/SelectPanel/SelectPanel.tsx b/packages/react/src/SelectPanel/SelectPanel.tsx index f3b655065d1..4443a37593a 100644 --- a/packages/react/src/SelectPanel/SelectPanel.tsx +++ b/packages/react/src/SelectPanel/SelectPanel.tsx @@ -1,37 +1,73 @@ import {SearchIcon, TriangleDownIcon, XIcon, type IconProps} from '@primer/octicons-react' import React, {useCallback, useEffect, useMemo, useRef, useState, type JSX} from 'react' import type {AnchoredOverlayProps} from '../AnchoredOverlay' -import {AnchoredOverlay} from '../AnchoredOverlay' import type {AnchoredOverlayWrapperAnchorProps} from '../AnchoredOverlay/AnchoredOverlay' import type {FilteredActionListProps} from '../FilteredActionList' import {FilteredActionList} from '../FilteredActionList' -import Heading from '../Heading' import type {OverlayProps} from '../Overlay' import type {TextInputProps} from '../TextInput' import type {ItemProps, ItemInput} from './' -import {SelectPanelMessage} from './SelectPanelMessage' +import {ComposableSelectPanelMessage, SelectPanelLoading, SelectPanelMessage} from './SelectPanelMessage' +import Heading from '../Heading' import {Button, IconButton, LinkButton} from '../Button' import {useProvidedRefOrCreate} from '../hooks' -import type {FocusZoneHookSettings} from '../hooks/useFocusZone' import {useId} from '../hooks/useId' import {useProvidedStateOrCreate} from '../hooks/useProvidedStateOrCreate' import useSafeTimeout from '../hooks/useSafeTimeout' import type {FilteredActionListLoadingType} from '../FilteredActionList/FilteredActionListLoaders' import {FilteredActionListLoadingTypes} from '../FilteredActionList/FilteredActionListLoaders' import {useFeatureFlag} from '../FeatureFlags' -import {announce, announceFromElement} from '@primer/live-region-element' +import {announceFromElement} from '@primer/live-region-element' import classes from './SelectPanel.module.css' import {clsx} from 'clsx' import {debounce} from '@github/mini-throttle' import {useResponsiveValue} from '../hooks/useResponsiveValue' import type {ButtonProps, LinkButtonProps} from '../Button/types' import {Banner} from '../Banner' -import {isAlphabetKey} from '../hooks/useMnemonics' import {useFormControlContext} from '../FormControl/_FormControlContext' +import {announceLoading, preventBubbling} from './utils/utils' +import type {InitialLoadingType, SelectPanelMultiSelection, SelectPanelSingleSelection} from './types' +import {SelectPanelContext} from './SelectPanelContext' +import {useSelectPanel} from './useSelectPanel' +import {ConfiguredSelectPanelOverlay} from './SelectPanelOverlay' +import {ConfiguredSelectPanelCollection} from './ConfiguredSelectPanelAdapter' +import {supportsConfiguredNativeOverlay} from './platform/configuredNativeCompatibility' +import {NativeSelectPanelProvider} from './platform/NativeSelectPanelProvider' +import {useNativeSelectPanel} from './platform/NativeSelectPanelContext' +import nativeClasses from './platform/PlatformSelectPanel.module.css' +import { + SelectPanelRoot, + SelectPanelTrigger, + SelectPanelOverlay, + SelectPanelContent, + SelectPanelHeader, + SelectPanelTitle, + SelectPanelDescription, + SelectPanelSearchInput, + SelectPanelList, + SelectPanelItem, + SelectPanelGroup, + SelectPanelFooter, +} from './SelectPanelParts' +import { + SelectPanelBackButton, + SelectPanelCancelButton, + SelectPanelClearSearchButton, + SelectPanelClearSelectionButton, + SelectPanelCloseButton, + SelectPanelForm, + SelectPanelSubmitButton, +} from './SelectPanelActions' + +export type {InitialLoadingType} from './types' + +// eslint-disable-next-line react-refresh/only-export-components -- Internal export for selection regression tests; not part of the package API. +export function areItemsEqual(first: ItemInput, second: ItemInput) { + return first.id !== undefined ? first.id === second.id : first === second +} // we add a delay so that it does not interrupt default screen reader announcement and queues after it -const SHORT_DELAY_MS = 500 const LONG_DELAY_MS = 1000 const EMPTY_MESSAGE = { title: 'No items available', @@ -44,32 +80,6 @@ const DefaultEmptyMessage = ( ) -async function announceText(text: string, delayMs = SHORT_DELAY_MS) { - const liveRegion = document.querySelector('live-region') - - liveRegion?.clear() // clear previous announcements - - await announce(text, { - delayMs, - from: liveRegion ? liveRegion : undefined, // announce will create a liveRegion if it doesn't find one - }) -} - -async function announceLoading() { - await announceText('Loading.') -} - -interface SelectPanelSingleSelection { - selected: ItemInput | undefined - onSelectedChange: (selected: ItemInput | undefined) => void -} - -interface SelectPanelMultiSelection { - selected: ItemInput[] - onSelectedChange: (selected: ItemInput[]) => void -} - -export type InitialLoadingType = 'spinner' | 'skeleton' export type SelectPanelSecondaryAction = | React.ReactElement | React.ReactElement @@ -145,23 +155,8 @@ function isMultiSelectVariant( return Array.isArray(selected) } -const focusZoneSettings: Partial = { - // Let FilteredActionList handle focus zone - disabled: true, -} - const closeButtonProps = {'aria-label': 'Cancel and close'} -const areItemsEqual = (itemA: ItemInput, itemB: ItemInput) => { - // prefer checking equivality by item.id - if (typeof itemA.id !== 'undefined') return itemA.id === itemB.id - else return itemA === itemB -} - -const doesItemsIncludeItem = (items: ItemInput[], item: ItemInput) => { - return items.some(i => areItemsEqual(i, item)) -} - const getSelectedItems = ( selected: SelectPanelSingleSelection['selected'] | SelectPanelMultiSelection['selected'], ): ItemInput[] => { @@ -182,6 +177,8 @@ const defaultRenderAnchor: NonNullable = props } function Panel({ + Collection = FilteredActionList, + composable = false, open, onOpenChange, renderAnchor = defaultRenderAnchor, @@ -219,7 +216,8 @@ function Panel({ displayInViewport, cssAnchorPositioningSettings, ...listProps -}: SelectPanelProps): JSX.Element { +}: SelectPanelProps & {Collection?: React.ComponentType; composable?: boolean}): JSX.Element { + const native = useNativeSelectPanel() const titleId = useId() const subtitleId = useId() const [filterValue, setInternalFilterValue] = useProvidedStateOrCreate(externalFilterValue, undefined, '') @@ -259,7 +257,7 @@ function Panel({ } const {dataLoadedOnce, isLoading} = loadingState - const [inputRef, setInputRef] = React.useState | null>(null) + const [inputRef, setInputRef] = React.useState | null>(null) const [listContainerElement, setListContainerElement] = useState(null) const [needsNoItemsAnnouncement, setNeedsNoItemsAnnouncement] = useState(false) const isNarrowScreenSize = useResponsiveValue({narrow: true, regular: false, wide: false}, false) @@ -333,7 +331,7 @@ function Panel({ ) const onInputRefChanged = useCallback( - (ref: React.RefObject) => { + (ref: React.RefObject) => { setInputRef(ref) }, [setInputRef], @@ -446,7 +444,7 @@ function Panel({ // disable body scroll when the panel is open in modal mode or on narrow screens useEffect(() => { // eslint-disable-next-line react-you-might-not-need-an-effect/no-event-handler - if (open && (variant === 'modal' || (isNarrowScreenSize && usingFullScreenOnNarrow))) { + if (!native.dialog && open && (variant === 'modal' || (isNarrowScreenSize && usingFullScreenOnNarrow))) { const bodyOverflowStyle = document.body.style.overflow || '' // If the body is already set to overflow: hidden, it likely means // that there is already a modal open. In that case, we should bail @@ -461,7 +459,7 @@ function Panel({ document.body.style.overflow = bodyOverflowStyle } } - }, [isNarrowScreenSize, open, usingFullScreenOnNarrow, variant]) + }, [isNarrowScreenSize, open, usingFullScreenOnNarrow, variant, native.dialog]) useEffect(() => { // eslint-disable-next-line react-you-might-not-need-an-effect/no-event-handler @@ -685,6 +683,45 @@ function Panel({ [selected, selectedItemsSet, intermediateSelected, isSingleSelectModal], ) + const workingSelection = useMemo(() => { + if (isSingleSelectModal) return intermediateSelected ? [intermediateSelected] : [] + return Array.isArray(selected) ? selected : selected ? [selected] : [] + }, [selected, intermediateSelected, isSingleSelectModal]) + const panelState = useSelectPanel({ + open, + onOpenChange: (nextOpen, reason) => { + onOpenChange( + nextOpen, + reason === 'submit' ? 'selection' : reason === 'close' || reason === 'back' ? 'cancel' : reason, + ) + }, + selected: workingSelection, + isItemEqual: areItemsEqual, + isItemDisabled: item => Boolean(item.disabled), + selectionMode: isMultiSelectVariant(selected) ? 'multiple' : 'single', + closeOnSelect: false, + filterValue, + onFilterChange, + onSelectedChange: nextSelected => { + if (isMultiSelectVariant(selected)) { + const onChange = onSelectedChange as SelectPanelMultiSelection['onSelectedChange'] + onChange(nextSelected) + } else if (isSingleSelectModal) { + setIntermediateSelectionState({ + isSingleSelectModal, + open, + selected, + value: nextSelected[0], + }) + } else { + const onChange = onSelectedChange as SelectPanelSingleSelection['onSelectedChange'] + onChange(nextSelected[0]) + onClose('selection') + } + }, + }) + + const {selectItem} = panelState const itemsToRender = useMemo(() => { // Pre-compute a Set of selected item IDs/references for O(1) lookups during sorting // This avoids O(m * k) work per comparison in the sort function @@ -718,40 +755,26 @@ function Panel({ return } - if (isMultiSelectVariant(selected)) { - const otherSelectedItems = selected.filter(selectedItem => !areItemsEqual(selectedItem, item)) - const newSelectedItems = doesItemsIncludeItem(selected, item) - ? otherSelectedItems - : [...otherSelectedItems, item] - - const multiSelectOnChange = onSelectedChange as SelectPanelMultiSelection['onSelectedChange'] - multiSelectOnChange(newSelectedItems) - return - } - - if (isSingleSelectModal) { - if (intermediateSelected?.id === item.id) { - // if the item is already selected, we need to unselect it - setIntermediateSelectionState({ - isSingleSelectModal, - open, - selected, - value: undefined, - }) - } else { - setIntermediateSelectionState({ - isSingleSelectModal, - open, - selected, - value: item, - }) - } - return + if (composable) { + selectItem(item) + } else if (isMultiSelectVariant(selected)) { + const nextSelected = selected.some(value => areItemsEqual(value, item)) + ? selected.filter(value => !areItemsEqual(value, item)) + : [...selected, item] + const onChange = onSelectedChange as SelectPanelMultiSelection['onSelectedChange'] + onChange(nextSelected) + } else if (isSingleSelectModal) { + setIntermediateSelectionState({ + isSingleSelectModal, + open, + selected, + value: intermediateSelected?.id === item.id ? undefined : item, + }) + } else { + const onChange = onSelectedChange as SelectPanelSingleSelection['onSelectedChange'] + onChange(item === selected ? undefined : item) + onClose('selection') } - // single select anchored, direct save on click - const singleSelectOnChange = onSelectedChange as SelectPanelSingleSelection['onSelectedChange'] - singleSelectOnChange(item === selected ? undefined : item) - onClose('selection') }, } as ItemProps }) @@ -771,16 +794,18 @@ function Panel({ return 0 }) }, [ - onClose, - onSelectedChange, items, - selected, isItemCurrentlySelected, - isSingleSelectModal, - intermediateSelected, - open, + selectItem, shouldOrderSelectedFirst, selectedOnSort, + composable, + selected, + onSelectedChange, + isSingleSelectModal, + open, + intermediateSelected, + onClose, ]) const focusTrapSettings = useMemo(() => ({initialFocusRef: inputRef || undefined}), [inputRef]) @@ -880,28 +905,7 @@ function Panel({ 'anchored', ) - const preventBubbling = useCallback( - (event: React.KeyboardEvent) => { - overlayProps?.onKeyDown?.(event as unknown as React.KeyboardEvent) - - // skip if a TextInput has focus - const activeElement = document.activeElement as HTMLElement - if (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA') return - - // skip if used with modifier to preserve shortcuts like ⌘ + F - const hasModifier = event.ctrlKey || event.altKey || event.metaKey - if (hasModifier) return - - // skip if it's not the forward slash or an alphabet key - if (event.key !== '/' && !isAlphabetKey(event.nativeEvent as KeyboardEvent)) { - return - } - - // if this is a typeahead event, don't propagate outside of menu - event.stopPropagation() - }, - [overlayProps], - ) + const onOverlayKeyDown = useMemo(() => preventBubbling(overlayProps?.onKeyDown), [overlayProps?.onKeyDown]) const mergedOverlayProps = useMemo( () => ({ @@ -909,7 +913,7 @@ function Panel({ 'aria-labelledby': titleId, 'aria-describedby': subtitle ? subtitleId : undefined, ...overlayProps, - ...(variant === 'modal' + ...(variant === 'modal' && !native.dialog ? { top: '50vh' as const, left: '50vw' as const, @@ -917,30 +921,41 @@ function Panel({ } : {}), style: { - transform: variant === 'modal' ? 'translate(-50%, -50%)' : undefined, + transform: variant === 'modal' && !native.dialog ? 'translate(-50%, -50%)' : undefined, + ...(native.dialog ? overlayProps?.style : {}), ...(isKeyboardVisible ? { maxHeight: availablePanelHeight !== undefined ? `${availablePanelHeight}px` : 'auto', } : {}), } as React.CSSProperties, - onKeyDown: preventBubbling, + onKeyDown: onOverlayKeyDown, }), - [titleId, subtitle, subtitleId, overlayProps, variant, isKeyboardVisible, availablePanelHeight, preventBubbling], + [ + titleId, + subtitle, + subtitleId, + overlayProps, + variant, + native.dialog, + isKeyboardVisible, + availablePanelHeight, + onOverlayKeyDown, + ], ) - return ( + const content = ( <> - -
-
+ +
- - {title} - + {composable ? ( + + {title} + + ) : ( + + {title} + + )} {subtitle ? ( -
- {subtitle} -
+ composable ? ( + + {subtitle} + + ) : ( +
+ {subtitle} +
+ ) ) : null}
{/* AnchoredOverlay displays the close button on narrow screens */} @@ -984,7 +1015,7 @@ function Panel({ }} /> ) : null} -
+ {notice && (
)} - {footer ? ( -
- {footer} -
+ {footer} ) : renderFooter ? ( -
) : null} -
+ ) : null} -
-
- {variant === 'modal' && open ?
: null} + + + {variant === 'modal' && open && !native.dialog ? ( +
+ ) : null} ) + return composable ? {content} : content } const SecondaryButton: React.FC = props => { @@ -1124,9 +1155,42 @@ const SecondaryLink: React.FC = props => { ) } -export const SelectPanel = Object.assign(Panel, { +function ConfiguredSelectPanel(props: SelectPanelProps) { + const composable = useFeatureFlag('primer_react_select_panel_composable_adapter') + return ( + + + + ) +} + +export const SelectPanel = Object.assign(ConfiguredSelectPanel, { __SLOT__: Symbol('SelectPanel'), SecondaryActionButton: SecondaryButton, SecondaryActionLink: SecondaryLink, - Message: SelectPanelMessage, + Root: SelectPanelRoot, + Trigger: SelectPanelTrigger, + Overlay: SelectPanelOverlay, + Content: SelectPanelContent, + Header: SelectPanelHeader, + Title: SelectPanelTitle, + Description: SelectPanelDescription, + SearchInput: SelectPanelSearchInput, + List: SelectPanelList, + Item: SelectPanelItem, + Group: SelectPanelGroup, + Footer: SelectPanelFooter, + CloseButton: SelectPanelCloseButton, + CancelButton: SelectPanelCancelButton, + SubmitButton: SelectPanelSubmitButton, + ClearSelectionButton: SelectPanelClearSelectionButton, + ClearSearchButton: SelectPanelClearSearchButton, + BackButton: SelectPanelBackButton, + Form: SelectPanelForm, + Loading: SelectPanelLoading, + Message: ComposableSelectPanelMessage, }) diff --git a/packages/react/src/SelectPanel/SelectPanel.types.test.tsx b/packages/react/src/SelectPanel/SelectPanel.types.test.tsx index a746a08cfca..29a150ee67d 100644 --- a/packages/react/src/SelectPanel/SelectPanel.types.test.tsx +++ b/packages/react/src/SelectPanel/SelectPanel.types.test.tsx @@ -1,4 +1,10 @@ import {SelectPanel} from '../SelectPanel' +import {createRef} from 'react' +import {Button} from '../Button' +import {ActionList} from '../ActionList' +import {InfoIcon} from '@primer/octicons-react' +import type {SelectPanelItemAction} from '.' +import type {SelectPanelValue} from './useSelectPanel' export function shouldAcceptCallWithNoProps() { return ( @@ -28,3 +34,107 @@ export function shouldAcceptDOMPropsOnOverlay() { /> ) } + +export function shouldAcceptComposableParts() { + const item = {id: 'one', text: 'Item one'} + const triggerRef = createRef() + const inputRef = createRef() + const listRef = createRef() + const itemRef = createRef() + return ( + selected.map(value => String(value))} + onSubmit={selected => selected.map(value => String(value))} + > + + + , + ) + const form = screen.getByRole('form', {name: 'Selection'}) + + expect(ref.current).toBe(form) + expect(form).toHaveAttribute('id', 'selection') + expect(fireEvent.submit(form)).toBe(false) + expect(calls).toEqual(['form', 'panel']) + expect(onSubmit).toHaveBeenCalledExactlyOnceWith(['apple']) + expect(onOpenChange).toHaveBeenCalledWith(false, 'submit') + }) + + it('honors a prevented native form submission', () => { + const onSubmit = vi.fn() + const onOpenChange = vi.fn() + render( + + event.preventDefault()} /> + , + ) + + expect(fireEvent.submit(screen.getByRole('form', {name: 'Selection'}))).toBe(false) + expect(onSubmit).not.toHaveBeenCalled() + expect(onOpenChange).not.toHaveBeenCalled() + }) + + it.each([undefined, 'submit'] as const)('submits natively exactly once with SubmitButton type %s', async type => { + const user = userEvent.setup() + const onSubmit = vi.fn() + const onFormSubmit = vi.fn() + render( + + + + + , + ) + + const button = screen.getByRole('button', {name: 'Save'}) + expect(button).toHaveAttribute('type', 'submit') + await user.click(button) + expect(onSubmit).toHaveBeenCalledExactlyOnceWith(['apple']) + expect(onFormSubmit).toHaveBeenCalledOnce() + }) + + it('honors Form onSubmit cancellation when clicking SubmitButton', async () => { + const user = userEvent.setup() + const onSubmit = vi.fn() + const onOpenChange = vi.fn() + const onFormSubmit = vi.fn((event: React.FormEvent) => event.preventDefault()) + render( + + + + + , + ) + + await user.click(screen.getByRole('button', {name: 'Save'})) + + expect(onFormSubmit).toHaveBeenCalledOnce() + expect(onSubmit).not.toHaveBeenCalled() + expect(onOpenChange).not.toHaveBeenCalled() + }) + + it('honors a canceled SubmitButton click inside its Form', async () => { + const user = userEvent.setup() + const onSubmit = vi.fn() + const onFormSubmit = vi.fn() + render( + + + event.preventDefault()} /> + + , + ) + + await user.click(screen.getByRole('button', {name: 'Save'})) + + expect(onSubmit).not.toHaveBeenCalled() + expect(onFormSubmit).not.toHaveBeenCalled() + }) + + it('preserves native validation for SubmitButton inside its Form', async () => { + const user = userEvent.setup() + const onSubmit = vi.fn() + const onFormSubmit = vi.fn() + render( + + + + + + , + ) + + await user.click(screen.getByRole('button', {name: 'Save'})) + expect(onSubmit).not.toHaveBeenCalled() + expect(onFormSubmit).not.toHaveBeenCalled() + + await user.type(screen.getByRole('textbox', {name: 'Required explanation'}), 'A reason') + await user.click(screen.getByRole('button', {name: 'Save'})) + expect(onSubmit).toHaveBeenCalledOnce() + expect(onFormSubmit).toHaveBeenCalledOnce() + }) + + it('does not submit its Form while SubmitButton is loading', async () => { + const user = userEvent.setup() + const onSubmit = vi.fn() + const onFormSubmit = vi.fn() + render( + + + + + , + ) + const button = screen.getByTestId('saving') + expect(button).toHaveAttribute('type', 'button') + + await user.click(button) + + expect(onSubmit).not.toHaveBeenCalled() + expect(onFormSubmit).not.toHaveBeenCalled() + }) + + it('does not inherit a parent Root form when a nested Root has no form adapter', async () => { + const user = userEvent.setup() + const onParentSubmit = vi.fn() + const onChildSubmit = vi.fn() + const onParentFormSubmit = vi.fn() + render( + + + + + + + , + ) + const button = screen.getByRole('button', {name: 'Save'}) + expect(button).toHaveAttribute('type', 'button') + + await user.click(button) + + expect(onChildSubmit).toHaveBeenCalledExactlyOnceWith(['child']) + expect(onParentSubmit).not.toHaveBeenCalled() + expect(onParentFormSubmit).not.toHaveBeenCalled() + }) + + it.each(['portal', 'form attribute'] as const)( + 'does not submit an unrelated form associated by %s', + async association => { + const user = userEvent.setup() + const onExternalSubmit = vi.fn((event: React.FormEvent) => event.preventDefault()) + const onFormSubmit = vi.fn() + const onSubmit = vi.fn() + render(
) + const externalForm = screen.getByRole('form', {name: 'External'}) + const button = + render( + + + {association === 'portal' ? createPortal(button, externalForm) : button} + + , + ) + const submitButton = screen.getByRole('button', {name: 'Save'}) + expect((submitButton as HTMLButtonElement).form).toBe(externalForm) + expect(submitButton).toHaveAttribute('type', 'button') + + await user.click(submitButton) + + expect(onSubmit).toHaveBeenCalledOnce() + expect(onFormSubmit).not.toHaveBeenCalled() + expect(onExternalSubmit).not.toHaveBeenCalled() + }, + ) + + it('keeps an unassociated portaled SubmitButton a direct action', async () => { + const user = userEvent.setup() + const {container: portalContainer} = render(
) + const onSubmit = vi.fn() + const onFormSubmit = vi.fn() + render( + + + {createPortal(, portalContainer)} + + , + ) + const button = screen.getByRole('button', {name: 'Save'}) + expect(button).toHaveAttribute('type', 'button') + expect((button as HTMLButtonElement).form).toBeNull() + + await user.click(button) + + expect(onSubmit).toHaveBeenCalledOnce() + expect(onFormSubmit).not.toHaveBeenCalled() + }) + + it.each([false, true])('isolates a portaled child Root form submission (canceled: %s)', async canceled => { + const user = userEvent.setup() + const {container: portalContainer} = render(
) + const onParentSubmit = vi.fn() + const onParentFormSubmit = vi.fn() + const onChildSubmit = vi.fn() + const onChildFormSubmit = vi.fn((event: React.FormEvent) => { + if (canceled) event.preventDefault() + }) + render( + + + {createPortal( + + + + + , + portalContainer, + )} + + , + ) + expect(screen.getByRole('form', {name: 'Parent'})).not.toContainElement(screen.getByRole('form', {name: 'Child'})) + + await user.click(screen.getByRole('button', {name: 'Save'})) + + expect(onChildFormSubmit).toHaveBeenCalledOnce() + if (canceled) { + expect(onChildSubmit).not.toHaveBeenCalled() + } else { + expect(onChildSubmit).toHaveBeenCalledExactlyOnceWith(['child']) + } + expect(onParentFormSubmit).not.toHaveBeenCalled() + expect(onParentSubmit).not.toHaveBeenCalled() + }) + + it('does not bubble a portaled panel submission into an application form', async () => { + const user = userEvent.setup() + const {container: portalContainer} = render(
) + const onApplicationSubmit = vi.fn((event: React.FormEvent) => event.preventDefault()) + const onSubmit = vi.fn() + render( + + + {createPortal( + + + , + portalContainer, + )} + + , + ) + + await user.click(screen.getByRole('button', {name: 'Save'})) + + expect(onSubmit).toHaveBeenCalledOnce() + expect(onApplicationSubmit).not.toHaveBeenCalled() + }) + + it('ignores a submit event from a portaled native child form', async () => { + const user = userEvent.setup() + const {container: portalContainer} = render(
) + const onSubmit = vi.fn() + const onFormSubmit = vi.fn() + const onChildSubmit = vi.fn((event: React.FormEvent) => event.preventDefault()) + render( + + + {createPortal( +
+ +
, + portalContainer, + )} +
+
, + ) + + await user.click(screen.getByRole('button', {name: 'Submit child'})) + + expect(onChildSubmit).toHaveBeenCalledOnce() + expect(onFormSubmit).not.toHaveBeenCalled() + expect(onSubmit).not.toHaveBeenCalled() + }) + + it('does not submit on Enter in search or when selecting an option', async () => { + const user = userEvent.setup() + const onSubmit = vi.fn() + const onFormSubmit = vi.fn() + render( + + + + + Apple + + + + , + ) + const input = screen.getByRole('combobox', {name: 'Filter fruit'}) + const option = screen.getByRole('option', {name: 'Apple'}) + await user.click(input) + expect(input).toHaveAttribute('aria-activedescendant', option.id) + await user.keyboard('{Enter}') + expect(option).toHaveAttribute('aria-selected', 'true') + expect(onSubmit).not.toHaveBeenCalled() + expect(onFormSubmit).not.toHaveBeenCalled() + + await user.keyboard('{ArrowDown}') + expect(input).toHaveFocus() + await user.keyboard('{Enter}') + expect(option).toHaveAttribute('aria-selected', 'false') + expect(onSubmit).not.toHaveBeenCalled() + expect(onFormSubmit).not.toHaveBeenCalled() + }) +}) diff --git a/packages/react/src/SelectPanel/SelectPanelActions.tsx b/packages/react/src/SelectPanel/SelectPanelActions.tsx new file mode 100644 index 00000000000..860f551cc8e --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanelActions.tsx @@ -0,0 +1,220 @@ +import React from 'react' +import {ChevronLeftIcon, XIcon} from '@primer/octicons-react' +import {Button, IconButton, type ButtonProps, type IconButtonProps} from '../Button' +import {useMergedRefs} from '../hooks/useMergedRefs' +import useLayoutEffect from '../utils/useIsomorphicLayoutEffect' +import {useSelectPanelContext} from './SelectPanelContext' +import {nativeInvokerProps, useNativeSelectPanel} from './platform/NativeSelectPanelContext' + +const SelectPanelFormContext = React.createContext<{ + rootId: string + formRef: React.RefObject +} | null>(null) + +export type SelectPanelCloseButtonProps = Omit< + IconButtonProps, + 'icon' | 'aria-label' | 'aria-labelledby' | 'children' +> & { + 'aria-label'?: string + 'aria-labelledby'?: string +} + +export const SelectPanelCloseButton = React.forwardRef( + function SelectPanelCloseButton( + { + onClick, + 'aria-label': ariaLabel = 'Close', + 'aria-labelledby': ariaLabelledBy, + type = 'button', + variant = 'invisible', + ...props + }, + ref, + ) { + const state = useSelectPanelContext() + const native = useNativeSelectPanel() + const invokers = native.invokers && native.targetId === state.panelId && type === 'button' + return ( + { + onClick?.(event) + if (!event.defaultPrevented && !props.disabled) { + if (invokers) return + event.preventDefault() + state.dismiss('close') + } + }} + /> + ) + }, +) + +export const SelectPanelCancelButton = React.forwardRef( + function SelectPanelCancelButton({onClick, children = 'Cancel', type = 'button', ...props}, ref) { + const state = useSelectPanelContext() + return ( + + ) + }, +) + +export const SelectPanelSubmitButton = React.forwardRef( + function SelectPanelSubmitButton({onClick, children = 'Save', type, ...props}, ref) { + const state = useSelectPanelContext() + const formContext = React.useContext(SelectPanelFormContext) + const buttonRef = React.useRef(null) + const mergedRef = useMergedRefs(ref, buttonRef) + const [associatedForm, setAssociatedForm] = React.useState(null) + const isOwnForm = formContext?.rootId === state.id + const canSubmitForm = isOwnForm && associatedForm !== null && associatedForm === formContext.formRef.current + + // Portals and form attributes can make the DOM association differ from React ancestry. + useLayoutEffect(() => { + setAssociatedForm(buttonRef.current?.form ?? null) + }, [formContext, props.form]) + + return ( + + ) + }, +) + +export const SelectPanelClearSelectionButton = React.forwardRef( + function SelectPanelClearSelectionButton({onClick, children = 'Clear selection', type = 'button', ...props}, ref) { + const state = useSelectPanelContext() + return ( + + ) + }, +) + +export const SelectPanelClearSearchButton = React.forwardRef( + function SelectPanelClearSearchButton({onClick, children = 'Clear search', type = 'button', ...props}, ref) { + const state = useSelectPanelContext() + return ( + + ) + }, +) + +export const SelectPanelBackButton = React.forwardRef(function SelectPanelBackButton( + {onClick, children = 'Back', type = 'button', leadingVisual = ChevronLeftIcon, ...props}, + ref, +) { + const state = useSelectPanelContext() + return ( + + ) +}) + +export type SelectPanelFormProps = React.ComponentPropsWithoutRef<'form'> + +/** + * An opt-in native form adapter. Omit this part when the panel is already inside + * a form; action buttons do not require a form to submit the current selection. + * Associated SubmitButtons use native submission and validation. + */ +export const SelectPanelForm = React.forwardRef(function SelectPanelForm( + {onSubmit, ...props}, + ref, +) { + const state = useSelectPanelContext() + const formRef = React.useRef(null) + const mergedRef = useMergedRefs(ref, formRef) + const context = React.useMemo(() => ({rootId: state.id, formRef}), [state.id]) + return ( + +
{ + if (event.target !== event.currentTarget) return + event.stopPropagation() + onSubmit?.(event) + if (event.defaultPrevented) return + event.preventDefault() + state.submit() + }} + /> + + ) +}) diff --git a/packages/react/src/SelectPanel/SelectPanelContext.ts b/packages/react/src/SelectPanel/SelectPanelContext.ts new file mode 100644 index 00000000000..3a757871a59 --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanelContext.ts @@ -0,0 +1,28 @@ +import React from 'react' +import type {SelectPanelState} from './useSelectPanel' + +type SelectPanelShellState = Omit, 'selected' | 'selectItem' | 'isSelected'> + +export const SelectPanelContext = React.createContext(null) +export const ParentPanelContext = React.createContext(null) +export const SelectPanelDialogContext = React.createContext(false) +export const SelectPanelSelectionContext = React.createContext | null>(null) + +export function useSelectPanelContext() { + const context = React.useContext(SelectPanelContext) + if (context === null) { + throw new Error('SelectPanel parts must be rendered inside SelectPanel.Root.') + } + return context +} + +export function useSelectPanelSelection() { + const context = React.useContext(SelectPanelSelectionContext) + if (context === null) { + throw new Error('SelectPanel items and rows must be rendered inside SelectPanel.Root.') + } + return context +} diff --git a/packages/react/src/SelectPanel/SelectPanelMessage.test.tsx b/packages/react/src/SelectPanel/SelectPanelMessage.test.tsx new file mode 100644 index 00000000000..ed3f5a72a2a --- /dev/null +++ b/packages/react/src/SelectPanel/SelectPanelMessage.test.tsx @@ -0,0 +1,152 @@ +import React from 'react' +import {render, screen, waitFor} from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import {afterEach, beforeEach, describe, expect, it} from 'vitest' +import {SearchIcon} from '@primer/octicons-react' +import {getLiveRegion} from '../live-region/__tests__/test-helpers' +import {SelectPanel} from './SelectPanel' + +const {Loading: SelectPanelLoading, Message: SelectPanelMessage} = SelectPanel + +describe('SelectPanel status parts', () => { + beforeEach(() => { + document.body.appendChild(document.createElement('live-region')) + }) + + afterEach(() => { + getLiveRegion().remove() + }) + + it.each(['empty', 'warning', 'error'] as const)('announces a full %s message politely when shown', variant => { + const ref = React.createRef() + render( + + Try a different query. + , + ) + + expect(ref.current).toBe(screen.getByTestId('message')) + expect(ref.current).toHaveAttribute('data-size', 'full') + expect(getLiveRegion().getMessage('polite')).toContain('Nothing to display') + expect(getLiveRegion().getMessage('polite')).toContain('Try a different query.') + expect(getLiveRegion().getMessage('assertive')).toBe('') + }) + + it('supports a compact inline message without a title', () => { + render( + + Some results could not be loaded. + , + ) + + expect(screen.getByTestId('message')).toHaveAttribute('data-size', 'inline') + expect(screen.getByTestId('message')).toHaveClass('custom-message') + expect(getLiveRegion().getMessage('polite')).toBe('Some results could not be loaded.') + }) + + it('retains the custom icon and action API without including actions in announcements', async () => { + const user = userEvent.setup() + function Message() { + const [attempts, setAttempts] = React.useState(0) + return ( + setAttempts(attempts + 1)}> + Retry request ({attempts}) + + } + data-testid="message" + > + Please try again. + + ) + } + render() + const message = getLiveRegion().getMessage('polite') + + expect(screen.getByTestId('message').querySelector('.octicon-search')).not.toBeNull() + expect(message).toContain('Search failed') + expect(message).toContain('Please try again.') + expect(message).not.toContain('Retry request') + await user.click(screen.getByRole('button', {name: 'Retry request (0)'})) + expect(screen.getByRole('button', {name: 'Retry request (1)'})).toBeInTheDocument() + expect(getLiveRegion().getMessage('polite')).toBe(message) + }) + + it('announces changed message content', async () => { + const {rerender} = render( + + Try another query. + , + ) + rerender( + + Try again later. + , + ) + + await waitFor(() => expect(getLiveRegion().getMessage('polite')).toContain('Search unavailable')) + expect(getLiveRegion().getMessage('polite')).toContain('Try again later.') + }) + + it.each(['full', 'inline'] as const)('announces loading in the %s layout without duplicate spinner text', size => { + const ref = React.createRef() + render() + + expect(ref.current).toBe(screen.getByTestId('loading')) + expect(ref.current).toHaveAttribute('data-size', size) + expect(ref.current).toHaveClass('custom-loading') + expect(ref.current).toHaveTextContent('Loading items...') + expect(getLiveRegion().getMessage('polite')).toBe('Loading items...') + }) + + it('defaults loading to full size and supports a custom loading message', () => { + render(Fetching labels...) + + expect(screen.getByTestId('loading')).toHaveAttribute('data-size', 'full') + expect(getLiveRegion().getMessage('polite')).toBe('Fetching labels...') + }) + + it('does not announce hidden status parts', () => { + render( + <> +