An open source design system that's fully customizable and agent ready
TypeScript
fix(Selector): the keyboard-active option draws the focus ring, so it reads at 3:1 against the list (#10024)
Cindy Zhang2947be858fd1
diff --git a/.changeset/selector-active-option-ring.md b/.changeset/selector-active-option-ring.mdnew file mode 100644index 0000000000..0fd4e33dde--- /dev/null+++ b/.changeset/selector-active-option-ring.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Selector: after keyboard input, the active option draws the standard focus ring inside its edge, so people moving through the list with the keyboard can see where they are. The overlay fill alone measured about 1.09:1 against the listbox in light mode and 1.15:1 in dark, under the 3:1 a state indicator needs; with the stock theme the ring measures 5.39:1 (light) and 3.10:1 (dark). The ring takes its width, style and color from the `--focus-outline-*` tokens, like every other focus ring. After pointer input the active option keeps the fill alone, as a focused DropdownMenu row does.++@cixzhangdiff --git a/docs/specs/components/MultiSelector/MultiSelector.spec.md b/docs/specs/components/MultiSelector/MultiSelector.spec.mdindex ca7054a1ee..3443686184 100644--- a/docs/specs/components/MultiSelector/MultiSelector.spec.md+++ b/docs/specs/components/MultiSelector/MultiSelector.spec.md@@ -334,6 +334,10 @@ empty-state content remains one shared tree.## Current-state impact+- **Active option perception.** The active option shows only the+ `--color-overlay-hover` fill, under 3:1 against the listbox in light and+ dark, against `spec:AST-020` FR1 (WCAG 2.2 1.4.11). Selector draws the+ shared focus ring after keyboard input (`component:Selector` AR5).- **Loading read as no options (FR2).** `isLoading` withholds the Empty state,the create row, and search announcements, so a person searching while thefield reports loading sees and hears nothing, against `spec:AST-001` FR4.diff --git a/docs/specs/components/Selector/Selector.spec.md b/docs/specs/components/Selector/Selector.spec.mdindex d8011d8c7c..4271e5c78a 100644--- a/docs/specs/components/Selector/Selector.spec.md+++ b/docs/specs/components/Selector/Selector.spec.md@@ -228,6 +228,11 @@ These requirements describe shipped behavior on current `main`.accessible description also announces that state. Search and non-search modesuse the same read-only combobox semantics because neither exposes a searchcontrol in this state.+- **AR5 — Active option perception.** After keyboard input the active option+ draws the shared focus ring inside its edge; the ring's color meets 3:1+ against the listbox in light and dark (`spec:AST-020` FR1, WCAG 2.2 1.4.11).+ After pointer input the active option keeps the overlay fill alone, as a+ focused DropdownMenu row does (`component:DropdownMenuItem` AR4).## Design relationships@@ -354,6 +359,7 @@ new theming target.| FR5 | loading, empty-state, and live-region tests | empty options, unmatched search, loading | Empty/no-results output appears or is announced while loading | `audit:Selector/behavior` || FR6, AR4 | read-only interaction, form, ARIA, and theme-state tests | search/non-search, clearable, open→read-only, disabled precedence | A value changes, popup or edit affordance remains, form value disappears, or read-only semantics are absent | `audit:Selector/accessibility` || FR7 | `Selector.test.tsx` press model suite | finger release over another option, finger/mouse release outside, listbox marker | The press option is selected, the listbox takes focus, a finger release outside closes the list, or the stray click selects | `audit:Selector/behavior` |+| AR5 | `Selector.activeOption.test.tsx`: the ring after keyboard input, no ring after pointer input, the ring again when keyboard input follows a pointer highlight; the active option's indicator measured against the listbox in light and dark | keyboard-active option, pointer-active option | Removing the ring, or drawing it after pointer input, fails; an indicator under 3:1 against the listbox in either mode fails (the fill alone measures 1.09:1 light and 1.15:1 dark) | `audit:Selector/accessibility` || source-build contract | `Selector.source-build.test.mjs` | package source compiled by consumer Babel | Moving evaluated StyleX values outside the supported source form fails compilation | `audit:Selector/code-health` |## Decision logdiff --git a/docs/specs/components/Typeahead/BaseTypeahead.spec.md b/docs/specs/components/Typeahead/BaseTypeahead.spec.mdindex 6729a5ef3e..35c5f80f32 100644--- a/docs/specs/components/Typeahead/BaseTypeahead.spec.md+++ b/docs/specs/components/Typeahead/BaseTypeahead.spec.md@@ -275,6 +275,10 @@ Consumer migration instructions belong in consumer docs and release notes.## Current-state impact+- **Active option perception.** The active option shows only the+ `--color-overlay-hover` fill, under 3:1 against the listbox in light and+ dark, against `spec:AST-020` FR1 (WCAG 2.2 1.4.11). Selector draws the+ shared focus ring after keyboard input (`component:Selector` AR5).- **Empty-search message (FR4).** A completed empty search renders its messageas a disabled option instead of presentational text, against `spec:AST-058`FR7.diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsxindex 90bb2bc035..bb505ebbd8 100644--- a/packages/core/src/MultiSelector/MultiSelector.tsx+++ b/packages/core/src/MultiSelector/MultiSelector.tsx@@ -79,6 +79,7 @@ import {joinAriaIDs} from '../utils/inputAria';import {withholdCallerHandlers} from '../utils/disabledInteraction';import {devWarn, warnOnce} from '../utils/devWarning';import {useInteractionModalityTracking} from '../utils/interactionModality';+import {useKeyboardHighlight} from '../hooks/useKeyboardHighlight';import {useAnnounce} from '../hooks/useAnnounce';import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector';import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';@@ -1851,23 +1852,12 @@ export function MultiSelector<T extends MultiSelectorOptionType>({),});- const [isKeyboardHighlight, setIsKeyboardHighlight] = useState(- () => readModality() === 'keyboard',- );- const onKeyDown = useCallback(- (event: React.KeyboardEvent<HTMLElement>) => {- onComboboxKeyDown(event);- setIsKeyboardHighlight(readModality() === 'keyboard');- },- [onComboboxKeyDown, readModality],- );- const onItemMouseEnter = useCallback(- (...args: Parameters<typeof onComboboxItemMouseEnter>) => {- onComboboxItemMouseEnter(...args);- setIsKeyboardHighlight(readModality() === 'keyboard');- },- [onComboboxItemMouseEnter, readModality],- );+ const {isKeyboardHighlight, onKeyDown, onItemMouseEnter} =+ useKeyboardHighlight(+ readModality,+ onComboboxKeyDown,+ onComboboxItemMouseEnter,+ );// The trigger button owns its click so a consumer `onClick`, which lands on// the button, composes after the built-in toggle. A press elsewhere in thediff --git a/packages/core/src/Selector/Selector.activeOption.test.tsx b/packages/core/src/Selector/Selector.activeOption.test.tsxnew file mode 100644index 0000000000..b21280df03--- /dev/null+++ b/packages/core/src/Selector/Selector.activeOption.test.tsx@@ -0,0 +1,136 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {render, screen} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {Selector} from './Selector';+import {compositeOver, contrastRatio} from '../theme/contrast';+import {resolveThemeToken} from '../theme/tokens';+import {parseColor} from '../utils/color';++const OPTIONS = [+ {value: 'Apple', label: 'Apple'},+ {value: 'Banana', label: 'Banana'},+ {value: 'Cherry', label: 'Cherry'},+];++function renderSelector() {+ render(+ <Selector+ label="Fruit"+ options={OPTIONS}+ value="Apple"+ onChange={() => {}}+ />,+ );+ return screen.getByRole('combobox', {name: 'Fruit'});+}++function activeOption(field: HTMLElement): HTMLElement {+ const id = field.getAttribute('aria-activedescendant');+ expect(id).toBeTruthy();+ const row = document.getElementById(id ?? '');+ expect(row).not.toBeNull();+ return row as HTMLElement;+}++function option(name: string): HTMLElement {+ const row = screen+ .getAllByRole('option', {hidden: true})+ .find(candidate => candidate.textContent?.includes(name));+ expect(row).toBeDefined();+ return row as HTMLElement;+}++function hasRing(row: HTMLElement): boolean {+ return getComputedStyle(row)+ .getPropertyValue('outline-color')+ .includes('--focus-outline-color');+}++/** The token a `var(--name)` value reads, or null for any other value. */+function tokenOf(value: string): string | null {+ return /var\((--[\w-]+)\)/.exec(value)?.[1] ?? null;+}++/**+ * Contrast of what marks the active option against the listbox it sits on:+ * the ring when the row draws one, else the row's fill over the listbox.+ */+function indicatorContrast(row: HTMLElement, mode: 'light' | 'dark'): number {+ const listbox = resolveThemeToken(null, '--color-background-popover', {+ mode,+ });+ const style = getComputedStyle(row);+ const ringToken = tokenOf(style.getPropertyValue('outline-color'));+ if (ringToken != null) {+ return contrastRatio(resolveThemeToken(null, ringToken, {mode}), listbox);+ }+ const fillToken = tokenOf(style.backgroundColor);+ expect(fillToken).not.toBeNull();+ const fill = parseColor(resolveThemeToken(null, fillToken ?? '', {mode}));+ const backdrop = parseColor(listbox);+ expect(fill).not.toBeNull();+ expect(backdrop).not.toBeNull();+ if (fill == null || backdrop == null) {+ return 0;+ }+ return contrastRatio(compositeOver(fill, backdrop), backdrop);+}++describe('Selector active option indicator', () => {+ it('draws the focus ring inside the active option after keyboard input', async () => {+ const user = userEvent.setup();+ const field = renderSelector();+ field.focus();+ await user.keyboard('{ArrowDown}');+ await user.keyboard('{ArrowDown}');++ const row = activeOption(field);+ expect(row).toHaveTextContent('Banana');+ expect(hasRing(row)).toBe(true);+ expect(getComputedStyle(row).getPropertyValue('outline-offset')).toContain(+ '--focus-outline-width',+ );+ });++ // WCAG 2.2 1.4.11: a state indicator needs 3:1 against the listbox it sits+ // on. The overlay fill alone measures about 1.09:1 (light) and 1.15:1+ // (dark).+ it.each(['light', 'dark'] as const)(+ 'marks the keyboard-active option at 3:1 or more against the listbox in %s mode',+ async mode => {+ const user = userEvent.setup();+ const field = renderSelector();+ field.focus();+ await user.keyboard('{ArrowDown}');++ expect(+ indicatorContrast(activeOption(field), mode),+ ).toBeGreaterThanOrEqual(3);+ },+ );++ it('keeps the fill without a ring after pointer input', async () => {+ const user = userEvent.setup();+ const field = renderSelector();+ await user.click(field);+ await user.hover(option('Cherry'));++ const row = activeOption(field);+ expect(row).toHaveTextContent('Cherry');+ expect(hasRing(row)).toBe(false);+ });++ it('draws the ring again when keyboard input follows a pointer highlight', async () => {+ const user = userEvent.setup();+ const field = renderSelector();+ await user.click(field);+ await user.hover(option('Banana'));+ await user.keyboard('{ArrowDown}');++ const row = activeOption(field);+ expect(row).toHaveTextContent('Cherry');+ expect(hasRing(row)).toBe(true);+ });+});diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsxindex ee50746dad..b1e92a2311 100644--- a/packages/core/src/Selector/Selector.tsx+++ b/packages/core/src/Selector/Selector.tsx@@ -53,6 +53,7 @@ import {useKeepLayerOpenProps, type LayerPlacement} from '../Layer/useLayer';import {InternalInputClearButton} from '../Field/InputClearButton';import {Spinner} from '../Spinner';import {PanelSearchInput} from '../Field/PanelSearchInput';+import {useKeyboardHighlight} from '../hooks/useKeyboardHighlight';import {useAnnounce} from '../hooks/useAnnounce';import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';import {@@ -66,6 +67,7 @@ import {fontWeightVars,typeScaleVars,borderVars,+ focusVars,} from '../theme/tokens.stylex';import type {SelectorOptionType, SelectorOptionData} from './types';import {isOptionData, isDivider, isSection, normalizeOption} from './utils';@@ -456,7 +458,7 @@ const styles = stylex.create({':is(:disabled,[aria-disabled="true"])': 'default',},textAlign: 'start',- outline: 'none',+ outlineStyle: 'none',},itemContent: {display: 'flex',@@ -489,6 +491,15 @@ const styles = stylex.create({itemHighlighted: {backgroundColor: colorVars['--color-overlay-hover'],},+ // The fill alone does not reach 3:1 against the listbox. After keyboard+ // input, the active option also draws the standard focus ring, inside the+ // row by its own width, as a focused menu row does.+ itemKeyboardHighlighted: {+ outlineWidth: focusVars['--focus-outline-width'],+ outlineStyle: focusVars['--focus-outline-style'],+ outlineColor: focusVars['--focus-outline-color'],+ outlineOffset: `calc(-1 * ${focusVars['--focus-outline-width']})`,+ },itemSelected: {fontWeight: fontWeightVars['--font-weight-medium'],},@@ -920,6 +931,8 @@ interface SelectorOptionRowProps {flatIndex: number;id: string;isHighlighted: boolean;+ /** The highlight came from keyboard input, so the row draws the focus ring. */+ isKeyboardHighlighted: boolean;isSelected: boolean;size: SelectorSize;indicatorPosition: IndicatorPosition;@@ -938,6 +951,7 @@ const SelectorOptionRow = memo(function SelectorOptionRow({flatIndex,id,isHighlighted,+ isKeyboardHighlighted,isSelected,size,indicatorPosition,@@ -998,6 +1012,7 @@ const SelectorOptionRow = memo(function SelectorOptionRow({styles.item,itemSizeStyles[size],isHighlighted && styles.itemHighlighted,+ isKeyboardHighlighted && styles.itemKeyboardHighlighted,isSelected && styles.itemSelected,item.disabled && styles.itemDisabled,),@@ -1482,10 +1497,10 @@ export function Selector<T extends SelectorOptionType>(highlightedIndex,setHighlightedIndex,getItemId,- onTriggerClick,- onKeyDown,+ onTriggerClick: comboboxTriggerClick,+ onKeyDown: comboboxKeyDown,onItemSelect,- onItemMouseEnter,+ onItemMouseEnter: comboboxItemMouseEnter,} = useCombobox({selectableItems: filteredItems,// The optimistic value, not the raw prop: with a pending changeAction the@@ -1504,6 +1519,23 @@ export function Selector<T extends SelectorOptionType>(listboxId,});+ // Only after keyboard input does the active option draw the focus ring; a+ // pointer highlight keeps the fill alone, as a focused menu row does.+ const {+ isKeyboardHighlight: isHighlightFromKeyboard,+ noteHighlightMove,+ onKeyDown,+ onItemMouseEnter,+ } = useKeyboardHighlight(+ triggerModality.readModality,+ comboboxKeyDown,+ comboboxItemMouseEnter,+ );+ const onTriggerClick = useCallback(() => {+ comboboxTriggerClick();+ noteHighlightMove();+ }, [comboboxTriggerClick, noteHighlightMove]);+// Type-to-select, shared with the other collections (menus, listboxes).// Open, it walks the highlight — aria-activedescendant announces each match.// Closed, it commits the match like a native select, which changes the value@@ -1580,6 +1612,7 @@ export function Selector<T extends SelectorOptionType>(if (isDisabled || isEffectivelyReadOnly) {return;}+ noteHighlightMove();// With hasSearch the query input owns typing, so type-to-select is off.if (!hasSearch && typeahead.onKeyDown(e)) {e.preventDefault();@@ -1587,7 +1620,14 @@ export function Selector<T extends SelectorOptionType>(}onKeyDown(e);},- [isDisabled, isEffectivelyReadOnly, hasSearch, typeahead, onKeyDown],+ [+ isDisabled,+ isEffectivelyReadOnly,+ hasSearch,+ typeahead,+ onKeyDown,+ noteHighlightMove,+ ],);// Highlight scrolling (and its hover/keyboard split) lives in useCombobox.@@ -1729,6 +1769,9 @@ export function Selector<T extends SelectorOptionType>(flatIndex={flatIndex}id={getItemId(flatIndex)}isHighlighted={flatIndex === highlightedIndex}+ isKeyboardHighlighted={+ flatIndex === highlightedIndex && isHighlightFromKeyboard+ }isSelected={item.value === normalizedValue}size={size}indicatorPosition={indicatorPosition}@@ -1742,6 +1785,7 @@ export function Selector<T extends SelectorOptionType>(renderOption,indicatorPosition,highlightedIndex,+ isHighlightFromKeyboard,size,normalizedValue,getItemId,diff --git a/packages/core/src/hooks/useKeyboardHighlight.ts b/packages/core/src/hooks/useKeyboardHighlight.tsnew file mode 100644index 0000000000..fdc0edfc05--- /dev/null+++ b/packages/core/src/hooks/useKeyboardHighlight.ts@@ -0,0 +1,71 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useKeyboardHighlight.ts+ * @input The owning combobox's shared modality reader and its keydown and+ * option-hover handlers+ * @output Exports useKeyboardHighlight: whether the last highlight move came+ * from keyboard input, the handlers wrapped to record each move, and the+ * recorder for other paths that move the highlight+ * @position Internal hook; used by Selector and MultiSelector to draw+ * keyboard-only highlight paint+ */++import {useCallback, useState} from 'react';+import type {InteractionModality} from '../utils/interactionModality';++interface KeyboardHighlight<+ KeyArgs extends unknown[],+ HoverArgs extends unknown[],+> {+ /** The last highlight move came from keyboard input. */+ isKeyboardHighlight: boolean;+ /** Records the current input for a path that moves the highlight. */+ noteHighlightMove: () => void;+ onKeyDown: (...args: KeyArgs) => void;+ onItemMouseEnter: (...args: HoverArgs) => void;+}++/**+ * A highlight moves from both keys and the pointer, but keyboard-only paint+ * follows the shared interaction modality. The hook reads that modality each+ * time the highlight moves.+ */+export function useKeyboardHighlight<+ KeyArgs extends unknown[],+ HoverArgs extends unknown[],+>(+ readModality: () => InteractionModality,+ onKeyDown: (...args: KeyArgs) => void,+ onItemMouseEnter: (...args: HoverArgs) => void,+): KeyboardHighlight<KeyArgs, HoverArgs> {+ const [isKeyboardHighlight, setIsKeyboardHighlight] = useState(+ () => readModality() === 'keyboard',+ );+ const noteHighlightMove = useCallback(+ () => setIsKeyboardHighlight(readModality() === 'keyboard'),+ [readModality],+ );+ const handleKeyDown = useCallback(+ (...args: KeyArgs) => {+ onKeyDown(...args);+ noteHighlightMove();+ },+ [onKeyDown, noteHighlightMove],+ );+ const handleItemMouseEnter = useCallback(+ (...args: HoverArgs) => {+ onItemMouseEnter(...args);+ noteHighlightMove();+ },+ [onItemMouseEnter, noteHighlightMove],+ );+ return {+ isKeyboardHighlight,+ noteHighlightMove,+ onKeyDown: handleKeyDown,+ onItemMouseEnter: handleItemMouseEnter,+ };+}