Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/select-floating-ui-keyboard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/ui': patch
---

Improve `Select` keyboard and screen reader support by routing navigation through floating-ui's interaction hooks. Pressing `ArrowUp`/`ArrowDown` on a focused, closed `Select` now opens the listbox, and the active option is announced via `aria-activedescendant`. The searchable variant (for example the `PhoneInput` country picker) now exposes a proper combobox: its input is marked `role="combobox"` with `aria-controls`, `aria-autocomplete="list"`, and `aria-activedescendant`, while the plain variant keeps its listbox semantics.
2 changes: 1 addition & 1 deletion packages/ui/bundlewatch.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
{ "path": "./dist/ui.shared.browser.js", "maxSize": "40KB" },
{ "path": "./dist/framework*.js", "maxSize": "44KB" },
{ "path": "./dist/vendors*.js", "maxSize": "73KB" },
{ "path": "./dist/ui-common*.js", "maxSize": "130KB" },
{ "path": "./dist/ui-common*.js", "maxSize": "132KB" },
{ "path": "./dist/signin*.js", "maxSize": "17KB" },
{ "path": "./dist/signup*.js", "maxSize": "13KB" },
{ "path": "./dist/userprofile*.js", "maxSize": "16KB" },
Expand Down
222 changes: 129 additions & 93 deletions packages/ui/src/elements/Select.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { createContextAndHook } from '@clerk/shared/react';
import type { SelectId } from '@clerk/shared/types';
import { FloatingList, useInteractions, useListItem, useListNavigation } from '@floating-ui/react';
import type { PropsWithChildren, ReactElement, ReactNode } from 'react';
import React, { useState } from 'react';
import React from 'react';

import { Button, descriptors, Flex, Icon, Input, Text } from '../customizables';
import { usePopover, useSearchInput } from '../hooks';
Expand All @@ -15,6 +16,7 @@ import { Popover } from './Popover';

type UsePopoverReturn = ReturnType<typeof usePopover>;
type UseSearchInputReturn = ReturnType<typeof useSearchInput>;
type UseInteractionsReturn = ReturnType<typeof useInteractions>;

type Option = { value: string | null; label?: string };

Expand Down Expand Up @@ -44,7 +46,12 @@ type SelectState<O extends Option> = Pick<
buttonRenderOption: RenderOption<O>;
selectedOption: Option | null;
select: (option: O) => void;
focusedItemRef: React.RefObject<HTMLDivElement>;
getReferenceProps: UseInteractionsReturn['getReferenceProps'];
getFloatingProps: UseInteractionsReturn['getFloatingProps'];
getItemProps: UseInteractionsReturn['getItemProps'];
activeIndex: number | null;
setActiveIndex: React.Dispatch<React.SetStateAction<number | null>>;
elementsRef: React.MutableRefObject<Array<HTMLElement | null>>;
onTriggerClick: () => void;
generatedTriggerId: string;
triggerId: string;
Expand Down Expand Up @@ -109,7 +116,25 @@ export const Select = withFloatingTree(<O extends Option>(props: PropsWithChildr
offset: { mainAxis: 6, crossAxis: -1 },
});
const togglePopover = popoverCtx.toggle;
const focusedItemRef = React.useRef<HTMLDivElement>(null);
const { context } = popoverCtx;
const elementsRef = React.useRef<Array<HTMLElement | null>>([]);
const [activeIndex, setActiveIndex] = React.useState<number | null>(null);

// Delegate keyboard interactions to floating-ui so the trigger opens the
// listbox on ArrowUp/ArrowDown and navigation stays a single source of truth.
// `virtual` keeps DOM focus on the listbox (or the search input in combobox
// mode) and exposes the active option via `aria-activedescendant`.
const selectedIndex = options.findIndex(o => o.value === value);
const listNavigation = useListNavigation(context, {
listRef: elementsRef,
activeIndex,
selectedIndex: selectedIndex === -1 ? null : selectedIndex,
onNavigate: setActiveIndex,
loop: true,
virtual: true,
});
const { getReferenceProps, getFloatingProps, getItemProps } = useInteractions([listNavigation]);

const generatedTriggerId = React.useId();
const generatedListboxId = React.useId();
const [triggerId, setTriggerId] = React.useState(generatedTriggerId);
Expand Down Expand Up @@ -142,14 +167,19 @@ export const Select = withFloatingTree(<O extends Option>(props: PropsWithChildr
searchInputCtx,
selectedOption: options.find(o => o.value === value) || null,
noResultsMessage,
focusedItemRef,
value,
renderOption: renderOption || defaultRenderOption,
buttonRenderOption: renderOption || defaultButtonRenderOption,
placeholder,
searchPlaceholder,
comparator,
select,
getReferenceProps,
getFloatingProps,
getItemProps,
activeIndex,
setActiveIndex,
elementsRef,
onTriggerClick: togglePopover,
generatedTriggerId,
triggerId,
Expand All @@ -171,41 +201,43 @@ export const Select = withFloatingTree(<O extends Option>(props: PropsWithChildr
type SelectrenderOptionProps<O extends Option> = {
option: Option;
index: number;
id: string;
renderOption: RenderOption<O>;
handleSelect: (option: Option) => void;
getItemProps: UseInteractionsReturn['getItemProps'];
isFocused?: boolean;
isSelected?: boolean;
elementId?: SelectId;
};

const SelectRenderOption = React.memo(
React.forwardRef((props: SelectrenderOptionProps<any>, ref?: React.ForwardedRef<HTMLDivElement>) => {
const { option, renderOption, isSelected, index, handleSelect, isFocused, elementId } = props;
const SelectRenderOption = React.memo((props: SelectrenderOptionProps<any>) => {
const { option, renderOption, isSelected, index, id, handleSelect, getItemProps, isFocused, elementId } = props;
const item = useListItem();

return (
<Flex
ref={ref}
role='option'
aria-selected={isSelected}
sx={{
userSelect: 'none',
cursor: 'pointer',
}}
onClick={() => {
handleSelect(option);
}}
>
{React.cloneElement(renderOption(option, index, isSelected) as React.ReactElement<unknown>, {
//@ts-expect-error
elementDescriptor: descriptors.selectOption,
elementId: descriptors.selectOption.setId(elementId),
'data-selected': isSelected,
'data-focused': isFocused,
})}
</Flex>
);
}),
);
return (
<Flex
ref={item.ref}
id={id}
role='option'
aria-selected={isSelected}
sx={{
userSelect: 'none',
cursor: 'pointer',
}}
{...getItemProps({
onClick: () => handleSelect(option),
})}
>
{React.cloneElement(renderOption(option, index, isSelected) as React.ReactElement<unknown>, {
//@ts-expect-error
elementDescriptor: descriptors.selectOption,
elementId: descriptors.selectOption.setId(elementId),
'data-selected': isSelected,
'data-focused': isFocused,
})}
</Flex>
);
});

const SelectSearchbar = (props: PropsOfComponent<typeof InputWithIcon>) => {
const { sx, ...rest } = props;
Expand Down Expand Up @@ -277,78 +309,72 @@ export const SelectOptionList = (props: SelectOptionListProps) => {
renderOption,
searchPlaceholder,
comparator,
focusedItemRef,
noResultsMessage,
select,
onTriggerClick,
elementId,
triggerId,
generatedListboxId,
setListboxId,
portal,
getFloatingProps,
getItemProps,
activeIndex,
setActiveIndex,
elementsRef,
} = useSelectState();
const { filteredItems: options, searchInputProps } = searchInputCtx;
const [focusedIndex, setFocusedIndex] = useState(0);
const { isOpen, floating, styles, nodeId, context, getFloatingProps } = popoverCtx;
const { isOpen, floating, styles, nodeId, context } = popoverCtx;
const containerRef = React.useRef<HTMLDivElement>(null);
const effectiveListboxId = id ?? generatedListboxId;
const effectiveAriaLabelledBy = ariaLabelledBy ?? (ariaLabel ? undefined : triggerId);
const optionId = (index: number) => `${effectiveListboxId}-option-${index}`;

React.useEffect(() => {
setListboxId(effectiveListboxId);
}, [effectiveListboxId, setListboxId]);

const scrollToItemOnSelectedIndexChange = () => {
if (!isOpen) {
setFocusedIndex(-1);
return;
}
// Jest could not resolve `focusedItemRef.current` so we need to call scrollIntoView with ?.()
focusedItemRef.current?.scrollIntoView?.({ block: 'nearest' });
};

React.useEffect(scrollToItemOnSelectedIndexChange, [focusedIndex, isOpen]);
React.useEffect(() => setFocusedIndex(0), [options.length]);
// Reset the highlighted option to the top of the list whenever the filtered
// results change while searching. Intentionally keyed only on the result
// count so it does not fight floating-ui's highlight-on-open behavior.
React.useEffect(() => {
if (!comparator) {
containerRef?.current?.focus();
}

if (isOpen) {
setFocusedIndex(options.findIndex(o => o.value === value));
// Jest could not resolve `focusedItemRef.current` so we need to call scrollIntoView with ?.()
focusedItemRef.current?.scrollIntoView?.({ block: 'nearest' });
return;
setActiveIndex(0);
}
}, [isOpen]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [options.length]);

const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.key === 'ArrowUp') {
e.preventDefault();
if (isOpen) {
return setFocusedIndex((i = 0) => (i === 0 ? options.length - 1 : i - 1));
}
return onTriggerClick();
React.useEffect(() => {
if (isOpen && !comparator) {
containerRef.current?.focus();
}
}, [isOpen, comparator]);

if (e.key === 'ArrowDown') {
const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.key === 'Enter' && activeIndex != null && activeIndex >= 0) {
e.preventDefault();
if (isOpen) {
if (onReachEnd && focusedIndex === options.length - 1) {
onReachEnd();
return;
}
return setFocusedIndex((i = 0) => (i === options.length - 1 ? 0 : i + 1));
const option = options[activeIndex];
if (option) {
select(option);
}
return onTriggerClick();
return;
}

if (e.key === 'Enter' && focusedIndex >= 0) {
e.preventDefault();
return select(options[focusedIndex]);
if (e.key === 'ArrowDown' && onReachEnd && activeIndex === options.length - 1) {
onReachEnd();
}
};

// floating-ui exposes the active option through `aria-activedescendant`, but
// it puts it on this (unfocused) wrapper. Lift it onto the element that
// actually holds focus: the listbox in select mode, the search input in
// combobox mode.
const { 'aria-activedescendant': rawActiveDescendant, ...floatingProps } = getFloatingProps(
popoverCtx.getFloatingProps({ onKeyDown }),
);
// SAFETY: floating-ui types its prop getters as Record<string, unknown>. The
// active descendant is the id string of the active option, or undefined.
const activeDescendant = rawActiveDescendant as string | undefined;

return (
<Popover
nodeId={nodeId}
Expand All @@ -361,7 +387,7 @@ export const SelectOptionList = (props: SelectOptionListProps) => {
elementDescriptor={descriptors.selectOptionsContainer}
elementId={descriptors.selectOptionsContainer.setId(elementId)}
ref={floating}
{...getFloatingProps({ onKeyDown })}
{...floatingProps}
direction='col'
justify='start'
sx={[
Expand All @@ -381,6 +407,11 @@ export const SelectOptionList = (props: SelectOptionListProps) => {
{comparator && (
<SelectSearchbar
placeholder={searchPlaceholder}
role='combobox'
aria-expanded={isOpen}
aria-controls={effectiveListboxId}
aria-autocomplete='list'
aria-activedescendant={activeDescendant}
{...searchInputProps}
/>
)}
Expand All @@ -391,6 +422,7 @@ export const SelectOptionList = (props: SelectOptionListProps) => {
role='listbox'
aria-label={ariaLabel}
aria-labelledby={effectiveAriaLabelledBy}
aria-activedescendant={comparator ? undefined : activeDescendant}
tabIndex={comparator ? undefined : 0}
sx={[
theme => ({
Expand All @@ -404,24 +436,27 @@ export const SelectOptionList = (props: SelectOptionListProps) => {
]}
{...rest}
>
{options.map((option, index) => {
const isFocused = index === focusedIndex;
const isSelected = value === option.value;

return (
<SelectRenderOption
key={option.value}
index={index}
ref={isFocused ? focusedItemRef : undefined}
option={option}
renderOption={renderOption}
isSelected={isSelected}
isFocused={isFocused}
handleSelect={select}
elementId={elementId}
/>
);
})}
<FloatingList elementsRef={elementsRef}>
{options.map((option, index) => {
const isFocused = index === activeIndex;
const isSelected = value === option.value;

return (
<SelectRenderOption
key={option.value}
index={index}
id={optionId(index)}
option={option}
renderOption={renderOption}
getItemProps={getItemProps}
isSelected={isSelected}
isFocused={isFocused}
handleSelect={select}
elementId={elementId}
/>
);
})}
</FloatingList>
{noResultsMessage && options.length === 0 && <SelectNoResults>{noResultsMessage}</SelectNoResults>}
{footer}
</Flex>
Expand All @@ -447,6 +482,7 @@ export const SelectButton = (
generatedTriggerId,
listboxId,
setTriggerId,
getReferenceProps,
} = useSelectState();
const { reference, isOpen } = popoverCtx;
const effectiveTriggerId = id ?? generatedTriggerId;
Expand All @@ -468,7 +504,7 @@ export const SelectButton = (
id={effectiveTriggerId}
variant='outline'
textVariant='buttonLarge'
onClick={onTriggerClick}
{...getReferenceProps({ onClick: onTriggerClick })}
aria-expanded={isOpen}
aria-haspopup='listbox'
aria-controls={ariaControls ?? (isOpen ? listboxId : undefined)}
Expand Down
Loading
Loading