Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(selector): make the dropdown search part of the panel, not a box inside it (#4928)

Cindy Zhangdad87f591966
diff --git a/.changeset/selector-panel-search-row.md b/.changeset/selector-panel-search-row.md
new file mode 100644
index 0000000000..2806d089f7
--- /dev/null
+++ b/.changeset/selector-panel-search-row.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Selector, MultiSelector: the dropdown panel's search field is now part of the panel instead of a bordered input dropped into it. The panel is already a bordered, elevated surface, so the nested `TextInput` drew a box inside a box; the row now renders a leading magnifier, a borderless input, and the shared clear (✕) button, with a full-bleed divider between it and the options — the same shape the command palette already uses. Focus is shown as an inset ring on the row, rounded to the panel's own corners. Section titles move from labeled dividers to plain secondary headings, matching DropdownMenu and CommandPaletteGroup, and MultiSelector no longer draws a rule under select-all. Behavior, keyboard handling, and accessible names are unchanged; MultiSelector's search row additionally stays put while the options scroll under it. New theme targets: `astryx-selector-search`, `astryx-selector-section-heading`, `astryx-multi-selector-search`, `astryx-multi-selector-section-heading`; anything that styled the dropdown search through `astryx-text-input` needs to move to those.
+
+@cixzhang
diff --git a/packages/core/src/Field/PanelSearchInput.tsx b/packages/core/src/Field/PanelSearchInput.tsx
new file mode 100644
index 0000000000..37d23e056a
--- /dev/null
+++ b/packages/core/src/Field/PanelSearchInput.tsx
@@ -0,0 +1,271 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file PanelSearchInput.tsx
+ * @input Uses React, StyleX, Icon, InputClearButton, theme tokens
+ * @output Exports PanelSearchInput — the search row that sits at the top of a
+ * dropdown panel
+ * @position Shared internal primitive; used by Selector and MultiSelector
+ *
+ * A dropdown panel is already a bordered, elevated surface. Nesting a bordered
+ * TextInput inside it draws a second box within that box, so the field reads as
+ * a control dropped into the menu rather than part of it. This row is the
+ * seamless alternative — magnifier, borderless input, clear button — separated
+ * from the options by a divider the panel owns.
+ *
+ * The field is shaped like the option rows under it rather than like a form
+ * input: same inset from the panel edge, same `--radius-element` corners, same
+ * height. The focus ring is drawn on that rounded box, so focus reads as "this
+ * row of the panel" — the same visual language as an item's highlight — instead
+ * of ringing the whole panel header. It appears for keyboard focus only; see
+ * `fieldKeyboardFocus` for why `:focus-visible` alone does not mean that.
+ *
+ * ┌─ panel ──────────────────┐
+ * │ ┌──────────────────────┐ │ ← field: rounded, inset, item-sized
+ * │ │ ⌕ Search… ✕ │ │
+ * │ └──────────────────────┘ │
+ * ├──────────────────────────┤ ← divider (full-bleed)
+ * │ ┌──────────────────────┐ │
+ * │ │ Apple │ │ ← option row: same box
+ *
+ * The clear button is the shared `InputClearButton`, so the affordance and its
+ * ghost-button behavior match every other input's clear. It renders AFTER the
+ * input in DOM order: the selector components' Tab handling depends on that
+ * order to keep the popup open while focus moves onto it.
+ *
+ * Not exported from the package: it is an implementation detail of the panels
+ * that use it, not public API.
+ */
+
+import {useCallback, useEffect, useState, type Ref} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {Icon} from '../Icon';
+import {InputClearButton} from './InputClearButton';
+import {mergeProps} from '../utils';
+import {
+ getInteractionModality,
+ trackInteractionModality,
+} from '../utils/interactionModality';
+import {
+ colorVars,
+ durationVars,
+ easeVars,
+ radiusVars,
+ spacingVars,
+ typeScaleVars,
+ typographyVars,
+} from '../theme/tokens.stylex';
+import type {BaseProps} from '../BaseProps';
+
+const styles = stylex.create({
+ // Gutter only. Matches the option list's own padding so the field below
+ // lines up with the option rows rather than with the panel edge.
+ wrapper: {
+ paddingBlock: spacingVars['--spacing-1'],
+ paddingInline: spacingVars['--spacing-1'],
+ },
+ // The field proper — the same box an option row draws: `--radius-element`
+ // corners and, at md, a 6/8 padding pair that lands it on the option row's
+ // 32px height. Focus rings THIS, not the full-width row.
+ field: {
+ boxSizing: 'border-box',
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ width: '100%',
+ paddingBlock: spacingVars['--spacing-1-5'],
+ paddingInline: spacingVars['--spacing-2'],
+ borderRadius: radiusVars['--radius-element'],
+ transitionProperty: 'box-shadow',
+ transitionDuration: {
+ default: durationVars['--duration-fast'],
+ '@media (prefers-reduced-motion: reduce)': '0s',
+ },
+ transitionTimingFunction: easeVars['--ease-standard'],
+ },
+ // The focus ring, applied only while focus was taken by keyboard (see
+ // `isKeyboardFocus`). `:has(input:focus-visible)` stays the CSS condition —
+ // the browser's heuristic still decides, this only narrows it — and rings
+ // the field rather than the bare <input> so the magnifier and the clear
+ // button sit inside it, and so tabbing ONTO the clear button does not
+ // re-ring the field.
+ //
+ // Inset, not the shared 3px-offset outline: the field is inset 4-5px from
+ // the panel edge, so an outline at that offset would land on the panel's own
+ // border and the divider. Measured, not guessed.
+ fieldKeyboardFocus: {
+ boxShadow: {
+ default: 'none',
+ ':has(input:focus-visible)': `inset 0 0 0 2px ${colorVars['--color-accent']}`,
+ },
+ },
+ // The icon span needs explicit flex centering to avoid a line-height offset.
+ icon: {
+ display: 'flex',
+ alignItems: 'center',
+ flexShrink: 0,
+ },
+ input: {
+ flexGrow: 1,
+ flexShrink: 1,
+ minWidth: 0,
+ padding: 0,
+ margin: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ color: colorVars['--color-text-primary'],
+ fontFamily: typographyVars['--font-family-body'],
+ // Matches the option rows below it, so the query reads as the first line of
+ // the list. The coarse-pointer floor keeps iOS from zooming on focus.
+ fontSize: {
+ default: typeScaleVars['--text-label-size'],
+ '@media (pointer: coarse)': `max(1rem, ${typeScaleVars['--text-label-size']})`,
+ },
+ lineHeight: typeScaleVars['--text-label-leading'],
+ // The field draws the focus ring (see `field`), so the bare input must not
+ // draw a second one inside it.
+ outline: 'none',
+ '::placeholder': {
+ color: colorVars['--color-text-secondary'],
+ },
+ },
+});
+
+export interface PanelSearchInputProps extends Omit<
+ BaseProps<HTMLInputElement>,
+ 'onChange'
+> {
+ /** Ref forwarded to the input element (for focus management). */
+ ref?: Ref<HTMLInputElement>;
+
+ /**
+ * Accessible name for the input. Rendered as `aria-label`: the panel has no
+ * visible label for the field, and a placeholder is not a reliable name.
+ */
+ label: string;
+
+ /** Accessible name for the clear (✕) button, e.g. `Clear Search options`. */
+ clearLabel: string;
+
+ /** Placeholder text shown while the query is empty. */
+ placeholder?: string;
+
+ /** The current query. */
+ value: string;
+
+ /** Called with the next query on every keystroke and on clear. */
+ onValueChange: (value: string) => void;
+
+ /** Key handler for the input itself. */
+ onKeyDown?: React.KeyboardEventHandler<HTMLInputElement>;
+
+ /** Focus handler for the input; runs after the ring's own bookkeeping. */
+ onFocus?: React.FocusEventHandler<HTMLInputElement>;
+
+ /** Blur handler for the input; runs after the ring's own bookkeeping. */
+ onBlur?: React.FocusEventHandler<HTMLInputElement>;
+
+ /**
+ * Key handler for the row. Events from the input are handled by `onKeyDown`;
+ * this one exists for keys pressed on the clear button, which has no other
+ * handler of its own.
+ */
+ onContainerKeyDown?: React.KeyboardEventHandler<HTMLDivElement>;
+}
+
+/**
+ * Search row for the top of a dropdown panel: magnifier, borderless input, and
+ * a clear button once a query is typed, in a rounded box shaped like the
+ * option rows beneath it.
+ *
+ * `className`/`style`/`xstyle` apply to the outer row (use them to match the
+ * option list's inline padding); every other prop (`role`, `aria-*`, `id`, …)
+ * passes through to the `<input>`, so the caller owns the combobox wiring.
+ */
+export function PanelSearchInput({
+ ref,
+ label,
+ clearLabel,
+ placeholder,
+ value,
+ onValueChange,
+ onKeyDown,
+ onFocus,
+ onBlur,
+ onContainerKeyDown,
+ xstyle,
+ className,
+ style,
+ ...props
+}: PanelSearchInputProps) {
+ // `:focus-visible` matches a text input focused by POINTER as well (CSS
+ // Selectors 4, verified in Chromium), so it cannot express "keyboard focus"
+ // by itself. Gate it on how the user last interacted; the CSS condition
+ // stays `:focus-visible`, this only narrows it.
+ const [isKeyboardFocus, setIsKeyboardFocus] = useState(false);
+
+ useEffect(() => {
+ trackInteractionModality();
+ }, []);
+
+ const handleFocus = useCallback(
+ (e: React.FocusEvent<HTMLInputElement>) => {
+ setIsKeyboardFocus(getInteractionModality() === 'keyboard');
+ onFocus?.(e);
+ },
+ [onFocus],
+ );
+
+ const handleBlur = useCallback(
+ (e: React.FocusEvent<HTMLInputElement>) => {
+ setIsKeyboardFocus(false);
+ onBlur?.(e);
+ },
+ [onBlur],
+ );
+
+ const handleClear = useCallback(() => {
+ onValueChange('');
+ // Clearing puts the caret back where the user was typing, matching
+ // TextInput's built-in clear.
+ if (typeof ref === 'object' && ref?.current) {
+ ref.current.focus();
+ }
+ }, [onValueChange, ref]);
+
+ return (
+ <div
+ onKeyDown={onContainerKeyDown}
+ {...mergeProps(stylex.props(styles.wrapper, xstyle), className, style)}>
+ <div
+ data-keyboard-focus={isKeyboardFocus ? 'true' : undefined}
+ {...stylex.props(
+ styles.field,
+ isKeyboardFocus && styles.fieldKeyboardFocus,
+ )}>
+ <Icon icon="search" size="sm" color="secondary" xstyle={styles.icon} />
+ <input
+ ref={ref}
+ type="text"
+ aria-label={label}
+ placeholder={placeholder}
+ value={value}
+ onChange={e => onValueChange(e.target.value)}
+ onKeyDown={onKeyDown}
+ onFocus={handleFocus}
+ onBlur={handleBlur}
+ {...stylex.props(styles.input)}
+ {...props}
+ />
+ {value !== '' && (
+ <InputClearButton label={clearLabel} onClick={handleClear} />
+ )}
+ </div>
+ </div>
+ );
+}
+
+PanelSearchInput.displayName = 'PanelSearchInput';
diff --git a/packages/core/src/MultiSelector/MultiSelector.doc.mjs b/packages/core/src/MultiSelector/MultiSelector.doc.mjs
index ad76fc74ab..2d9ce3ab3e 100644
--- a/packages/core/src/MultiSelector/MultiSelector.doc.mjs
+++ b/packages/core/src/MultiSelector/MultiSelector.doc.mjs
@@ -27,6 +27,8 @@ export const docs = {
},
{className: 'astryx-multi-selector-clear-icon', deprecatedFor: 'input-clear-icon'},
{className: 'astryx-multi-selector-empty-state'},
+ {className: 'astryx-multi-selector-search'},
+ {className: 'astryx-multi-selector-section-heading'},
{
className: 'astryx-multi-selector-indicator-icon',
states: ['state'],
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index d69faad2f5..73d11bbd26 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -1774,7 +1774,134 @@ describe('MultiSelector indicator (chevron) icon theme target', () => {
});
});
+describe('MultiSelector list structure', () => {
+ it('does not draw a divider under select-all', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={['Apple', 'Banana', 'Orange']}
+ value={[]}
+ onChange={() => {}}
+ hasSelectAll
+ />,
+ );
+ await user.click(screen.getByRole('combobox'));
+ // Select-all is the first row of the list, not a section of its own. No
+ // option here declares a divider and there is no search row, so the panel
+ // should contain no rule at all.
+ expect(document.querySelectorAll('[role="separator"]')).toHaveLength(0);
+ const [first] = screen.getAllByRole('option', h);
+ expect(first).toHaveTextContent('Select all');
+ });
+
+ it('renders a section title as a plain heading inside the group, not a divider', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={[
+ {
+ type: 'section',
+ title: 'Citrus',
+ options: [
+ {value: 'orange', label: 'Orange'},
+ {value: 'lemon', label: 'Lemon'},
+ ],
+ },
+ ]}
+ value={[]}
+ onChange={() => {}}
+ />,
+ );
+ await user.click(screen.getByRole('combobox'));
+
+ // A labeled Divider used to stand in for the heading; it rendered a
+ // role="separator" as a direct child of the listbox and stacked a second
+ // rule under the search row's own.
+ expect(document.querySelectorAll('[role="separator"]')).toHaveLength(0);
+
+ const group = screen.getByRole('group', {name: 'Citrus', ...h});
+ const heading = group.querySelector(
+ '.astryx-multi-selector-section-heading',
+ );
+ expect(heading).toBeTruthy();
+ expect(heading).toHaveTextContent('Citrus');
+ // The group already carries the title as its accessible name, so the
+ // visible heading must not announce it a second time.
+ expect(heading).toHaveAttribute('aria-hidden', 'true');
+ // ...and it precedes the options it heads.
+ const [firstOption] = within(group).getAllByRole('option', h);
+ expect(
+ heading!.compareDocumentPosition(firstOption) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+});
+
describe('MultiSelector search affordances', () => {
+ it('renders the search row seamlessly — no nested input box, a divider under it', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={['Apple', 'Banana', 'Orange']}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+
+ const search = screen.getByRole('combobox', h);
+ // The row is the outer gutter; the input sits inside the rounded field.
+ const row = search.closest('.astryx-multi-selector-search');
+ const field = search.parentElement;
+ if (!row || !field) {
+ throw new Error('search row not found');
+ }
+ // The panel is already a bordered surface: the field inside it must not be
+ // a second bordered box (this used to render a TextInput).
+ expect(row).not.toHaveClass('astryx-text-input');
+ expect(search.closest('.astryx-text-input')).toBeNull();
+ // The field is a rounded box inset from the panel edge, shaped like the
+ // option rows under it — not a full-bleed header strip.
+ expect(field).not.toBe(row);
+ // ...and a divider separates it from the options.
+ const separator = document.querySelector('[role="separator"]');
+ if (!separator) {
+ throw new Error('divider not found');
+ }
+ // Order: row, then divider, then the listbox.
+ expect(
+ row.compareDocumentPosition(separator) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ const listbox = screen.getByRole('listbox', h);
+ expect(
+ separator.compareDocumentPosition(listbox) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
+ it('keeps the search row outside the scrolling option list', async () => {
+ const user = userEvent.setup();
+ render(
+ <MultiSelector
+ label="Fruit"
+ options={['Apple', 'Banana', 'Orange']}
+ value={[]}
+ onChange={() => {}}
+ hasSearch
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ // The options scroll under the header rather than carrying it away, so the
+ // field stays reachable in a long list.
+ const search = screen.getByRole('combobox', h);
+ const listbox = screen.getByRole('listbox', h);
+ expect(listbox.contains(search)).toBe(false);
+ });
+
it('renders a decorative (aria-hidden) magnifier icon whenever hasSearch is on', async () => {
const user = userEvent.setup();
render(
@@ -1788,8 +1915,7 @@ describe('MultiSelector search affordances', () => {
);
await user.click(screen.getByRole('button', {name: 'Fruit'}));
const search = screen.getByRole('combobox', h);
- // The search field is a TextInput; the magnifier is its startIcon, so it
- // sits inside the input container as a sibling of the <input>.
+ // The magnifier leads the search row, as a sibling of the <input>.
const wrapper = search.parentElement;
const magnifier = wrapper?.querySelector('.astryx-icon');
expect(magnifier).toBeTruthy();
diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsx
index 321110bdc5..5b93789db2 100644
--- a/packages/core/src/MultiSelector/MultiSelector.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.tsx
@@ -42,7 +42,7 @@ import {
} from '../Field';
import {Divider} from '../Divider';
import {Spinner} from '../Spinner';
-import {TextInput} from '../TextInput';
+import {PanelSearchInput} from '../Field/PanelSearchInput';
import {CheckboxInput} from '../CheckboxInput';
import type {IndicatorPosition} from '../Indicator';
import {Badge} from '../Badge';
@@ -245,16 +245,6 @@ const styles = stylex.create({
minWidth: 'anchor-size(width)',
},
- // Search field. The inner TextInput owns the border, focus ring, magnifier
- // (startIcon), and clear button (hasClear); this wrapper only supplies the
- // dropdown's inline/block padding around it.
- searchWrapper: {
- display: 'flex',
- alignItems: 'center',
- paddingInline: spacingVars['--spacing-2'],
- paddingBlock: spacingVars['--spacing-1'],
- },
-
// Select-all wrapper
selectAllWrapper: {
display: 'flex',
@@ -263,9 +253,19 @@ const styles = stylex.create({
cursor: 'pointer',
},
- // Section divider with label
- sectionDivider: {
- marginBlock: spacingVars['--spacing-1'],
+ // Section heading. Plain secondary text, no rules — the same treatment
+ // DropdownMenu and CommandPaletteGroup already use for a group heading in a
+ // panel list. A labeled Divider (line–text–line) reads as a separator, and
+ // next to the search row's own divider it stacked two rules a few pixels
+ // apart.
+ sectionHeading: {
+ paddingBlock: spacingVars['--spacing-1'],
+ paddingInline: spacingVars['--spacing-2'],
+ fontFamily: typographyVars['--font-family-body'],
+ fontSize: typeScaleVars['--text-supporting-size'],
+ lineHeight: typeScaleVars['--text-supporting-leading'],
+ color: colorVars['--color-text-secondary'],
+ userSelect: 'none',
},
// Divider
@@ -729,7 +729,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
const inputGroup = useInputGroup();
const [searchQuery, setSearchQuery] = useState('');
- // A typed query shows TextInput's built-in clear (✕) button, which becomes
+ // A typed query shows the search row's clear (✕) button, which becomes
// the next tab stop after the search input.
const hasQuery = searchQuery.length > 0;
@@ -1139,11 +1139,38 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
return null;
}
return (
- <div
- {...stylex.props(styles.searchWrapper)}
- onKeyDown={e => {
- // The clear (✕) button lives inside the TextInput, after the input in
- // DOM order. When it is focused and the user tabs forward there is
+ <PanelSearchInput
+ ref={searchRef}
+ id={searchId}
+ // The search row is the panel's header: a magnifier, a borderless
+ // input, and the shared clear (✕) button. It deliberately does NOT
+ // render a bordered TextInput — the popup is already a bordered
+ // surface, and a field inside it drew a second box within that box.
+ label={t('@astryx.multiSelector.searchOptions')}
+ // Same accessible name the TextInput's built-in clear produced
+ // ("Clear Search options"), so the affordance keeps its name while its
+ // chrome changes.
+ clearLabel={t('@astryx.textInput.clearLabel', {
+ label: t('@astryx.multiSelector.searchOptions'),
+ })}
+ {...themeProps('multi-selector-search')}
+ // When hasSearch is set, focus moves into this input on open, so it —
+ // not the trigger — must be the combobox reporting the highlighted
+ // option via aria-activedescendant (comboboxes-4).
+ role="combobox"
+ aria-expanded={popover.isOpen}
+ aria-controls={listboxId}
+ aria-autocomplete="list"
+ aria-activedescendant={
+ popover.isOpen && highlightedIndex >= 0
+ ? getItemId(highlightedIndex)
+ : undefined
+ }
+ value={searchQuery}
+ onValueChange={handleSearchChange}
+ onContainerKeyDown={e => {
+ // The clear (✕) button lives inside the row, after the input in DOM
+ // order. When it is focused and the user tabs forward there is
// nothing else in the popup, so dismiss it (Shift+Tab returns to the
// input natively). Key events originating on the input are handled on
// the input below; ignore them here so we don't double-dismiss.
@@ -1153,64 +1180,32 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
if (e.key === 'Tab' && !e.shiftKey) {
onKeyDown(e);
}
- }}>
- <TextInput
- ref={searchRef}
- id={searchId}
- // The search field IS a TextInput: the leading magnifier is its
- // `startIcon` and the trailing clear (✕) is its built-in `hasClear`
- // (which resets the value and refocuses the input). We add no bespoke
- // affordance chrome — the field just looks and behaves like every
- // other Astryx input.
- label={t('@astryx.multiSelector.searchOptions')}
- isLabelHidden
- startIcon="search"
- hasClear
- size="sm"
- // Fill the dropdown's width (minus the wrapper's inline padding) so
- // the field is flush end-to-end rather than sized to its content.
- width="100%"
- // When hasSearch is set, focus moves into this input on open, so it —
- // not the trigger — must be the combobox reporting the highlighted
- // option via aria-activedescendant (comboboxes-4). role + aria-* pass
- // through to the underlying <input> via BaseProps.
- role="combobox"
- aria-expanded={popover.isOpen}
- aria-controls={listboxId}
- aria-autocomplete="list"
- aria-activedescendant={
- popover.isOpen && highlightedIndex >= 0
- ? getItemId(highlightedIndex)
- : undefined
+ }}
+ onKeyDown={e => {
+ // Arrow keys navigate options; Enter toggles; Escape closes.
+ // Space and Home/End are left to the input (type a space / move
+ // the caret) per the APG editable combobox; PageUp/PageDown are
+ // the sanctioned substitute for jumping to the first/last option.
+ if (
+ e.key === 'ArrowDown' ||
+ e.key === 'ArrowUp' ||
+ e.key === 'PageUp' ||
+ e.key === 'PageDown' ||
+ e.key === 'Enter' ||
+ e.key === 'Escape'
+ ) {
+ onKeyDown(e);
+ return;
}
- value={searchQuery}
- onChange={handleSearchChange}
- onKeyDown={e => {
- // Arrow keys navigate options; Enter toggles; Escape closes.
- // Space and Home/End are left to the input (type a space / move
- // the caret) per the APG editable combobox; PageUp/PageDown are
- // the sanctioned substitute for jumping to the first/last option.
- if (
- e.key === 'ArrowDown' ||
- e.key === 'ArrowUp' ||
- e.key === 'PageUp' ||
- e.key === 'PageDown' ||
- e.key === 'Enter' ||
- e.key === 'Escape'
- ) {
- onKeyDown(e);
- return;
- }
- // Tab: when a query is showing the clear (✕) button, forward-tab
- // moves focus to it (keeping the popup open) so the affordance is
- // keyboard-reachable. Every other Tab dismisses the popup as usual.
- if (e.key === 'Tab' && (e.shiftKey || !hasQuery)) {
- onKeyDown(e);
- }
- }}
- placeholder={searchPlaceholder}
- />
- </div>
+ // Tab: when a query is showing the clear (✕) button, forward-tab
+ // moves focus to it (keeping the popup open) so the affordance is
+ // keyboard-reachable. Every other Tab dismisses the popup as usual.
+ if (e.key === 'Tab' && (e.shiftKey || !hasQuery)) {
+ onKeyDown(e);
+ }
+ }}
+ placeholder={searchPlaceholder}
+ />
);
}, [
hasSearch,
@@ -1339,12 +1334,11 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
? sortedItems.length - 1
: sortedItems.length;
- // Show select-all only when there are real items to select
+ // Show select-all only when there are real items to select. It reads as
+ // the first row of the list, not a section of its own — no divider under
+ // it (the checkbox column already lines it up with the options below).
if (hasSelectAll && realItemCount > 0) {
elements.push(renderItem(sortedItems[0], 0));
- elements.push(
- <Divider key="select-all-divider" xstyle={styles.divider} />,
- );
cursor = 1;
} else if (hasSelectAll) {
// Skip the select-all sentinel when there are no real items
@@ -1413,17 +1407,23 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
sectionItems.push(renderItem(sortedItems[cursor], cursor));
cursor++;
}
- if (option.title) {
- elements.push(
- <Divider
- key={`section-divider-${i}`}
- label={option.title}
- xstyle={styles.sectionDivider}
- />,
- );
- }
+ // The heading lives INSIDE the group and is aria-hidden: the group
+ // already carries the title as its accessible name, so exposing the
+ // text again would announce it twice. This also keeps role="listbox"'s
+ // children to option/group only — the old labeled Divider sat in the
+ // listbox as a stray role="separator".
elements.push(
<div key={`section-${i}`} role="group" aria-label={option.title}>
+ {option.title && (
+ <div
+ aria-hidden="true"
+ {...mergeProps(
+ themeProps('multi-selector-section-heading'),
+ stylex.props(styles.sectionHeading),
+ )}>
+ {option.title}
+ </div>
+ )}
{sectionItems}
</div>,
);
@@ -1606,16 +1606,40 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
</div>
{popover.render(
- <div {...stylex.props(styles.dropdown)}>
- {renderSearch()}
- <div
- id={listboxId}
- role="listbox"
- aria-multiselectable="true"
- aria-labelledby={triggerId}>
- {renderOptions()}
+ hasSearch ? (
+ // With a search row the panel splits: the header stays put while the
+ // options scroll under it, so the field does not slide out of reach
+ // in a long list. Without one the panel is a single scroll container,
+ // exactly as before.
+ <div>
+ {renderSearch()}
+ {/*
+ Separates the header from the options and spans the panel: the
+ search row and the option list each hold their own inline
+ padding, the line does not, so it reads as the panel's own edge.
+ */}
+ <Divider />
+ <div {...stylex.props(styles.dropdown)}>
+ <div
+ id={listboxId}
+ role="listbox"
+ aria-multiselectable="true"
+ aria-labelledby={triggerId}>
+ {renderOptions()}
+ </div>
+ </div>
</div>
- </div>,
+ ) : (
+ <div {...stylex.props(styles.dropdown)}>
+ <div
+ id={listboxId}
+ role="listbox"
+ aria-multiselectable="true"
+ aria-labelledby={triggerId}>
+ {renderOptions()}
+ </div>
+ </div>
+ ),
{
placement: 'below',
alignment: 'start',
diff --git a/packages/core/src/Selector/Selector.doc.mjs b/packages/core/src/Selector/Selector.doc.mjs
index a7aefb4bd6..0b4c68fbde 100644
--- a/packages/core/src/Selector/Selector.doc.mjs
+++ b/packages/core/src/Selector/Selector.doc.mjs
@@ -27,6 +27,8 @@ export const docs = {
states: ['disabled'],
},
{className: 'astryx-selector-option'},
+ {className: 'astryx-selector-search'},
+ {className: 'astryx-selector-section-heading'},
{className: 'astryx-selector-empty-state'},
{className: 'astryx-selector-clear-icon', deprecatedFor: 'input-clear-icon'},
{className: 'astryx-selector-indicator-icon', states: ['state']},
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index 225aa2326b..59ce85b5eb 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -25,6 +25,7 @@ import {Icon} from '../Icon';
import {RadioIndicator} from '../Indicator';
import {InputGroup, InputGroupText} from '../InputGroup';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+import {__resetInteractionModalityForTest} from '../utils/interactionModality';
import {defineTheme} from '../theme/defineTheme';
import {Theme} from '../theme/Theme';
import {generateThemeCSS} from '../theme/generateThemeRules';
@@ -2386,7 +2387,165 @@ describe('Selector indicator (chevron) icon theme target', () => {
});
});
+describe('Selector section headings', () => {
+ it('renders a section title as a plain heading inside the group, not a divider', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={[
+ {
+ type: 'section',
+ title: 'Citrus',
+ options: [
+ {value: 'orange', label: 'Orange'},
+ {value: 'lemon', label: 'Lemon'},
+ ],
+ },
+ ]}
+ value={undefined}
+ onChange={() => {}}
+ />,
+ );
+ await user.click(screen.getByRole('combobox'));
+
+ // A labeled Divider used to stand in for the heading; it rendered a
+ // role="separator" as a direct child of the listbox and stacked a second
+ // rule under the search row's own.
+ expect(document.querySelectorAll('[role="separator"]')).toHaveLength(0);
+
+ const group = screen.getByRole('group', {name: 'Citrus', hidden: true});
+ const heading = group.querySelector('.astryx-selector-section-heading');
+ expect(heading).toBeTruthy();
+ expect(heading).toHaveTextContent('Citrus');
+ // The group already carries the title as its accessible name, so the
+ // visible heading must not announce it a second time.
+ expect(heading).toHaveAttribute('aria-hidden', 'true');
+ });
+});
+
+describe('Selector search focus ring', () => {
+ // The ring is for keyboard focus only. `:focus-visible` cannot express that
+ // on its own: per CSS Selectors 4 a pointer-focused text input matches it
+ // too (verified in Chromium), which is why a modality gate sits alongside
+ // it. jsdom does not implement `:focus-visible`, so these assert the gate;
+ // the painted ring is verified in real Chromium.
+ //
+ // Focus moves into the search input on the frame after the panel opens, and
+ // the gate is read at that moment: every case must wait for the focus to
+ // land before asserting or typing, or a slow frame reads the modality of
+ // whatever the test did next.
+ beforeEach(() => {
+ __resetInteractionModalityForTest();
+ });
+
+ const field = () =>
+ screen.getByRole('combobox', {hidden: true}).parentElement;
+
+ const waitForSearchFocus = async () =>
+ waitFor(() =>
+ expect(screen.getByRole('combobox', {hidden: true})).toHaveFocus(),
+ );
+
+ it('does not ring when the panel is opened by mouse', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value={undefined}
+ onChange={() => {}}
+ hasSearch
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ await waitForSearchFocus();
+ expect(field()).not.toHaveAttribute('data-keyboard-focus');
+ });
+
+ it('does not ring when the query is typed after a mouse open', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value={undefined}
+ onChange={() => {}}
+ hasSearch
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ await waitForSearchFocus();
+ await user.keyboard('an');
+ // Typing does not retroactively make a pointer focus a keyboard one; the
+ // caret already shows where the text is going.
+ expect(field()).not.toHaveAttribute('data-keyboard-focus');
+ });
+
+ it('rings when the panel is opened from the keyboard', async () => {
+ const user = userEvent.setup();
+ render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value={undefined}
+ onChange={() => {}}
+ hasSearch
+ />,
+ );
+ await user.tab();
+ await user.keyboard('{Enter}');
+ await waitForSearchFocus();
+ expect(field()).toHaveAttribute('data-keyboard-focus', 'true');
+ });
+});
+
describe('Selector search affordances', () => {
+ it('renders the search row seamlessly — no nested input box, a divider under it', async () => {
+ const user = userEvent.setup();
+ const {container} = render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ onChange={() => {}}
+ hasSearch
+ />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+
+ const search = screen.getByRole('combobox', {hidden: true});
+ // The row is the outer gutter; the input sits inside the rounded field.
+ const row = search.closest('.astryx-selector-search');
+ const field = search.parentElement;
+ if (!row || !field) {
+ throw new Error('search row not found');
+ }
+ // The panel is already a bordered surface: the field inside it must not be
+ // a second bordered box (this used to render a TextInput).
+ expect(row).not.toHaveClass('astryx-text-input');
+ expect(search.closest('.astryx-text-input')).toBeNull();
+ // The field is a rounded box inset from the panel edge, shaped like the
+ // option rows under it — not a full-bleed header strip.
+ expect(field).not.toBe(row);
+ expect(getComputedStyle(field).borderRadius).not.toBe('');
+ // ...and a divider separates it from the options.
+ const separator =
+ container.ownerDocument.querySelector('[role="separator"]');
+ if (!separator) {
+ throw new Error('divider not found');
+ }
+ // Order: row, then divider, then the listbox.
+ expect(
+ row.compareDocumentPosition(separator) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ const listbox = screen.getByRole('listbox', {hidden: true});
+ expect(
+ separator.compareDocumentPosition(listbox) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
it('renders a decorative (aria-hidden) magnifier icon whenever hasSearch is on', async () => {
const user = userEvent.setup();
render(
@@ -2400,8 +2559,7 @@ describe('Selector search affordances', () => {
);
await user.click(screen.getByRole('button', {name: 'Fruit'}));
const search = screen.getByRole('combobox', {hidden: true});
- // The search field is a TextInput; the magnifier is its startIcon, so it
- // sits inside the input container as a sibling of the <input>.
+ // The magnifier leads the search row, as a sibling of the <input>.
const container = search.parentElement;
const magnifier = container?.querySelector('.astryx-icon');
expect(magnifier).toBeTruthy();
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index 3ad734a630..564de668f9 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -47,7 +47,7 @@ import {Divider} from '../Divider';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import type {LayerPlacement} from '../Layer/useLayer';
import {Spinner} from '../Spinner';
-import {TextInput} from '../TextInput';
+import {PanelSearchInput} from '../Field/PanelSearchInput';
import {useAnnounce} from '../hooks/useAnnounce';
import {
colorVars,
@@ -226,6 +226,11 @@ const styles = stylex.create({
// pixel in the menu; the borderless ghost variant needs no correction.
paddingInline: `calc(${spacingVars['--spacing-1']} + ${borderVars['--border-width']})`,
},
+ // Same correction for the search row's gutter, so the search field and the
+ // option rows share one left edge.
+ searchRowInput: {
+ paddingInline: `calc(${spacingVars['--spacing-1']} + ${borderVars['--border-width']})`,
+ },
dropdownHidden: {
opacity: 0,
transition: 'none',
@@ -235,15 +240,6 @@ const styles = stylex.create({
popover: {
minWidth: 'anchor-size(width)',
},
- // Search field. The inner TextInput owns the border, focus ring, magnifier
- // (startIcon), and clear button (hasClear); this wrapper only supplies the
- // dropdown's inline/block padding around it.
- searchWrapper: {
- display: 'flex',
- alignItems: 'center',
- paddingInline: spacingVars['--spacing-2'],
- paddingBlock: spacingVars['--spacing-1'],
- },
// Empty state
emptyState: {
@@ -254,9 +250,19 @@ const styles = stylex.create({
fontSize: typeScaleVars['--text-label-size'],
},
- // Section divider with label
- sectionDivider: {
- marginBlock: spacingVars['--spacing-1'],
+ // Section heading. Plain secondary text, no rules — the same treatment
+ // DropdownMenu and CommandPaletteGroup already use for a group heading in a
+ // panel list. A labeled Divider (line–text–line) reads as a separator, and
+ // next to the search row's own divider it stacked two rules a few pixels
+ // apart.
+ sectionHeading: {
+ paddingBlock: spacingVars['--spacing-1'],
+ paddingInline: spacingVars['--spacing-2'],
+ fontFamily: typographyVars['--font-family-body'],
+ fontSize: typeScaleVars['--text-supporting-size'],
+ lineHeight: typeScaleVars['--text-supporting-leading'],
+ color: colorVars['--color-text-secondary'],
+ userSelect: 'none',
},
// Divider
@@ -719,7 +725,7 @@ export function Selector<T extends SelectorOptionType>(
const inputGroup = useInputGroup();
const [searchQuery, setSearchQuery] = useState('');
- // A typed query shows TextInput's built-in clear (✕) button, which becomes
+ // A typed query shows the search row's clear (✕) button, which becomes
// the next tab stop after the search input.
const hasQuery = searchQuery.length > 0;
@@ -1004,11 +1010,40 @@ export function Selector<T extends SelectorOptionType>(
return null;
}
return (
- <div
- {...stylex.props(styles.searchWrapper)}
- onKeyDown={e => {
- // The clear (✕) button lives inside the TextInput, after the input in
- // DOM order. When it is focused and the user tabs forward there is
+ <PanelSearchInput
+ ref={searchRef}
+ id={searchId}
+ // The search row is the panel's header: a magnifier, a borderless
+ // input, and the shared clear (✕) button. It deliberately does NOT
+ // render a bordered TextInput — the popup is already a bordered
+ // surface, and a field inside it drew a second box within that box.
+ label={t('@astryx.selector.searchOptions')}
+ // Same accessible name the TextInput's built-in clear produced
+ // ("Clear Search options"), so the affordance keeps its name while its
+ // chrome changes.
+ clearLabel={t('@astryx.textInput.clearLabel', {
+ label: t('@astryx.selector.searchOptions'),
+ })}
+ {...themeProps('selector-search')}
+ xstyle={variant !== 'ghost' && styles.searchRowInput}
+ // When hasSearch is set, focus moves into this input on open, so it —
+ // not the trigger — must be the combobox that reports the highlighted
+ // option via aria-activedescendant (comboboxes-4). A bare searchbox
+ // left the highlight silent to screen readers.
+ role="combobox"
+ aria-expanded={popover.isOpen}
+ aria-controls={listboxId}
+ aria-autocomplete="list"
+ aria-activedescendant={
+ popover.isOpen && highlightedIndex >= 0
+ ? getItemId(highlightedIndex)
+ : undefined
+ }
+ value={searchQuery}
+ onValueChange={handleSearchChange}
+ onContainerKeyDown={e => {
+ // The clear (✕) button lives inside the row, after the input in DOM
+ // order. When it is focused and the user tabs forward there is
// nothing else in the popup, so dismiss it (Shift+Tab returns to the
// input natively). Key events originating on the input are handled on
// the input below; ignore them here so we don't double-dismiss.
@@ -1018,65 +1053,32 @@ export function Selector<T extends SelectorOptionType>(
if (e.key === 'Tab' && !e.shiftKey) {
onKeyDown(e);
}
- }}>
- <TextInput
- ref={searchRef}
- id={searchId}
- // The search field IS a TextInput: the leading magnifier is its
- // `startIcon` and the trailing clear (✕) is its built-in `hasClear`
- // (which resets the value and refocuses the input). We add no bespoke
- // affordance chrome — the field just looks and behaves like every
- // other Astryx input.
- label={t('@astryx.selector.searchOptions')}
- isLabelHidden
- startIcon="search"
- hasClear
- size="sm"
- // Fill the dropdown's width (minus the wrapper's inline padding) so
- // the field is flush end-to-end rather than sized to its content.
- width="100%"
- // When hasSearch is set, focus moves into this input on open, so it —
- // not the trigger — must be the combobox that reports the highlighted
- // option via aria-activedescendant (comboboxes-4). A bare searchbox
- // left the highlight silent to screen readers. role + aria-* pass
- // through to the underlying <input> via BaseProps.
- role="combobox"
- aria-expanded={popover.isOpen}
- aria-controls={listboxId}
- aria-autocomplete="list"
- aria-activedescendant={
- popover.isOpen && highlightedIndex >= 0
- ? getItemId(highlightedIndex)
- : undefined
+ }}
+ onKeyDown={e => {
+ // Arrow keys navigate options; Enter selects; Escape closes.
+ // Home/End are left to the input for caret movement (APG editable
+ // combobox); PageUp/PageDown are the sanctioned substitute for
+ // jumping to the first/last option.
+ if (
+ e.key === 'ArrowDown' ||
+ e.key === 'ArrowUp' ||
+ e.key === 'PageUp' ||
+ e.key === 'PageDown' ||
+ e.key === 'Enter' ||
+ e.key === 'Escape'
+ ) {
+ onKeyDown(e);
+ return;
}
- value={searchQuery}
- onChange={handleSearchChange}
- onKeyDown={e => {
- // Arrow keys navigate options; Enter selects; Escape closes.
- // Home/End are left to the input for caret movement (APG editable
- // combobox); PageUp/PageDown are the sanctioned substitute for
- // jumping to the first/last option.
- if (
- e.key === 'ArrowDown' ||
- e.key === 'ArrowUp' ||
- e.key === 'PageUp' ||
- e.key === 'PageDown' ||
- e.key === 'Enter' ||
- e.key === 'Escape'
- ) {
- onKeyDown(e);
- return;
- }
- // Tab: when a query is showing the clear (✕) button, forward-tab
- // moves focus to it (keeping the popup open) so the affordance is
- // keyboard-reachable. Every other Tab dismisses the popup as usual.
- if (e.key === 'Tab' && (e.shiftKey || !hasQuery)) {
- onKeyDown(e);
- }
- }}
- placeholder={searchPlaceholder}
- />
- </div>
+ // Tab: when a query is showing the clear (✕) button, forward-tab
+ // moves focus to it (keeping the popup open) so the affordance is
+ // keyboard-reachable. Every other Tab dismisses the popup as usual.
+ if (e.key === 'Tab' && (e.shiftKey || !hasQuery)) {
+ onKeyDown(e);
+ }
+ }}
+ placeholder={searchPlaceholder}
+ />
);
}, [
hasSearch,
@@ -1090,6 +1092,7 @@ export function Selector<T extends SelectorOptionType>(
popover.isOpen,
highlightedIndex,
getItemId,
+ variant,
t,
]);
@@ -1227,17 +1230,23 @@ export function Selector<T extends SelectorOptionType>(
if (sectionItems.length === 0) {
continue;
}
- if (option.title) {
- elements.push(
- <Divider
- key={`section-divider-${i}`}
- label={option.title}
- xstyle={styles.sectionDivider}
- />,
- );
- }
+ // The heading lives INSIDE the group and is aria-hidden: the group
+ // already carries the title as its accessible name, so exposing the
+ // text again would announce it twice. This also keeps role="listbox"'s
+ // children to option/group only — the old labeled Divider sat in the
+ // listbox as a stray role="separator".
elements.push(
<div key={`section-${i}`} role="group" aria-label={option.title}>
+ {option.title && (
+ <div
+ aria-hidden="true"
+ {...mergeProps(
+ themeProps('selector-section-heading'),
+ stylex.props(styles.sectionHeading),
+ )}>
+ {option.title}
+ </div>
+ )}
{sectionItems}
</div>,
);
@@ -1422,6 +1431,12 @@ export function Selector<T extends SelectorOptionType>(
hasSearch ? (
<div>
{renderSearch()}
+ {/*
+ Separates the header from the options and spans the panel: the
+ search row and the listbox each hold their own inline padding,
+ the line does not, so it reads as the panel's own edge.
+ */}
+ <Divider />
<div
ref={listboxRef}
id={listboxId}
diff --git a/packages/core/src/utils/interactionModality.ts b/packages/core/src/utils/interactionModality.ts
new file mode 100644
index 0000000000..e2cc3a67e8
--- /dev/null
+++ b/packages/core/src/utils/interactionModality.ts
@@ -0,0 +1,74 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file interactionModality.ts
+ * @input Global pointerdown/keydown events
+ * @output `getInteractionModality()` — how the user last interacted
+ * @position Internal utility; used where `:focus-visible` alone is too broad
+ *
+ * `:focus-visible` is the right selector for a focus ring and should stay the
+ * condition that draws one. It is not, on its own, "focused by keyboard":
+ * per CSS Selectors 4 a pointer-focused element that supports text entry
+ * matches it too, deliberately, so that a clicked text field still shows where
+ * typing will go. Measured in Chromium — a bare `<input>` clicked with a mouse
+ * matches `:focus-visible`.
+ *
+ * A component that wants a ring for keyboard focus ONLY therefore needs one bit
+ * `:focus-visible` cannot give it: which device moved focus. This records that,
+ * to be used as a gate ALONGSIDE `:focus-visible`, never as a replacement for
+ * it — the browser's heuristic still decides everything else, including
+ * `focus({focusVisible: true})`.
+ *
+ * Listeners are registered once for the document, in the capture phase so they
+ * run before the focus they explain, and are never removed: two passive
+ * listeners for the whole app, versus a pair per mounted input.
+ */
+
+export type InteractionModality = 'keyboard' | 'pointer';
+
+// Default to keyboard: with no interaction yet, focus arrived programmatically
+// or from the browser restoring it, and showing a ring is the safe error.
+let modality: InteractionModality = 'keyboard';
+let isListening = false;
+
+function onPointerDown(): void {
+ modality = 'pointer';
+}
+
+function onKeyDown(event: KeyboardEvent): void {
+ // Modifier-only presses are not navigation — holding Shift before a click
+ // must not turn that click into "keyboard".
+ if (event.metaKey || event.altKey || event.ctrlKey) {
+ return;
+ }
+ modality = 'keyboard';
+}
+
+/**
+ * Start tracking, once per document. Safe to call repeatedly and on the server
+ * (where it does nothing).
+ */
+export function trackInteractionModality(): void {
+ if (isListening || typeof document === 'undefined') {
+ return;
+ }
+ isListening = true;
+ document.addEventListener('pointerdown', onPointerDown, {
+ capture: true,
+ passive: true,
+ });
+ document.addEventListener('keydown', onKeyDown, {
+ capture: true,
+ passive: true,
+ });
+}
+
+/** How the user last interacted with the page. */
+export function getInteractionModality(): InteractionModality {
+ return modality;
+}
+
+/** Test-only: restore the initial state between cases. */
+export function __resetInteractionModalityForTest(): void {
+ modality = 'keyboard';
+}