Skip to content

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

TypeScript

feat(core): extend useListFocus with roving-tabindex + caret guard; migrate Toolbar (navigation-3/4) (#3384)

Cindy Zhangdb595ae163c1
diff --git a/.changeset/uselistfocus-roving-tabindex.md b/.changeset/uselistfocus-roving-tabindex.md
new file mode 100644
index 0000000000..9d3ce2d9bb
--- /dev/null
+++ b/.changeset/uselistfocus-roving-tabindex.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `useListFocus` gains opt-in roving-tabindex ownership (`hasRovingTabIndex`), caret-aware arrow handling that leaves keys to nested text inputs and contenteditables (`hasCaretGuard`), RTL horizontal navigation (`isRtl`), a `hasHomeEnd` toggle, and `orientation: 'both'` for four-arrow navigation. `Toolbar` now uses it — it is a single tab stop and no longer steals the caret from a toolbar text input or composer (#3343).
+@cixzhang
diff --git a/packages/core/src/Toolbar/Toolbar.test.tsx b/packages/core/src/Toolbar/Toolbar.test.tsx
index 0a6a9e444e..29fff97bd9 100644
--- a/packages/core/src/Toolbar/Toolbar.test.tsx
+++ b/packages/core/src/Toolbar/Toolbar.test.tsx
@@ -256,4 +256,49 @@ describe('Toolbar', () => {
render(<Toolbar label="Actions" data-testid="my-toolbar" />);
expect(screen.getByTestId('my-toolbar')).toBe(screen.getByRole('toolbar'));
});
+
+ it('is a single tab stop — only one item is tabbable (navigation-3)', () => {
+ render(
+ <Toolbar
+ label="Actions"
+ startContent={
+ <>
+ <button type="button">Cut</button>
+ <button type="button">Copy</button>
+ <button type="button">Paste</button>
+ </>
+ }
+ />,
+ );
+ const buttons = screen.getAllByRole('button');
+ const tabbable = buttons.filter(b => b.getAttribute('tabindex') === '0');
+ expect(tabbable).toHaveLength(1);
+ expect(buttons[0]).toHaveAttribute('tabindex', '0');
+ expect(buttons[1]).toHaveAttribute('tabindex', '-1');
+ expect(buttons[2]).toHaveAttribute('tabindex', '-1');
+ });
+
+ it('does not steal caret keys from a text input mid-line (navigation-4)', async () => {
+ const user = userEvent.setup();
+ render(
+ <Toolbar
+ label="Search"
+ startContent={
+ <>
+ <input type="text" aria-label="Query" defaultValue="hello" />
+ <button type="button">Go</button>
+ </>
+ }
+ />,
+ );
+ const inputEl = screen.getByLabelText('Query');
+ if (!(inputEl instanceof HTMLInputElement)) {
+ throw new Error('expected an input');
+ }
+ inputEl.focus();
+ inputEl.setSelectionRange(1, 1); // caret mid-line
+ await user.keyboard('{ArrowRight}');
+ // Caret movement stays in the input; focus is not stolen by the toolbar.
+ expect(document.activeElement).toBe(inputEl);
+ });
});
diff --git a/packages/core/src/Toolbar/Toolbar.tsx b/packages/core/src/Toolbar/Toolbar.tsx
index be4aa4c564..e0da92ee85 100644
--- a/packages/core/src/Toolbar/Toolbar.tsx
+++ b/packages/core/src/Toolbar/Toolbar.tsx
@@ -235,9 +235,11 @@ export function Toolbar({
const gapVar = spacingVars[spacingStepToVar[gap]] as string;
- const {listRef, handleKeyDown} = useListFocus<HTMLDivElement>({
- itemSelector: 'button, input, [tabindex="0"]',
+ const {listRef, handleKeyDown, handleFocus} = useListFocus<HTMLDivElement>({
+ itemSelector: 'button, input, [tabindex]',
orientation,
+ hasRovingTabIndex: true,
+ hasCaretGuard: true,
});
return (
@@ -256,6 +258,7 @@ export function Toolbar({
aria-label={label}
aria-orientation={orientation}
onKeyDown={handleKeyDown}
+ onFocus={handleFocus}
{...mergeProps(
themeProps('toolbar', {size}),
stylex.props(
diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts
index bd2cdc3578..79a98f8f60 100644
--- a/packages/core/src/hooks/index.ts
+++ b/packages/core/src/hooks/index.ts
@@ -21,7 +21,11 @@ export {useGridFocus} from './useGridFocus';
export type {UseGridFocusOptions, UseGridFocusReturn} from './useGridFocus';
export {useListFocus} from './useListFocus';
-export type {UseListFocusOptions, UseListFocusReturn} from './useListFocus';
+export type {
+ UseListFocusOptions,
+ UseListFocusReturn,
+ ListFocusOrientation,
+} from './useListFocus';
export {useTypeahead} from './useTypeahead';
export type {UseTypeaheadOptions, UseTypeaheadReturn} from './useTypeahead';
diff --git a/packages/core/src/hooks/useListFocus.doc.mjs b/packages/core/src/hooks/useListFocus.doc.mjs
index c2b490ce73..f26259912e 100644
--- a/packages/core/src/hooks/useListFocus.doc.mjs
+++ b/packages/core/src/hooks/useListFocus.doc.mjs
@@ -34,11 +34,39 @@ export const docs = {
},
{
name: 'options.orientation',
- type: "'horizontal' | 'vertical'",
- description: "navigation orientation. 'horizontal' uses ArrowLeft/ArrowRight, 'vertical' uses ArrowUp/ArrowDown.",
+ type: "'horizontal' | 'vertical' | 'both'",
+ description: "Navigation orientation. 'horizontal' uses ArrowLeft/ArrowRight, 'vertical' uses ArrowUp/ArrowDown, 'both' accepts all four arrows.",
default: "'vertical'",
required: false,
},
+ {
+ name: 'options.hasHomeEnd',
+ type: 'boolean',
+ description: 'Whether Home/End jump to the first/last enabled item.',
+ default: 'true',
+ required: false,
+ },
+ {
+ name: 'options.isRtl',
+ type: 'boolean',
+ description: 'Whether the list is in a right-to-left context. When true, ArrowLeft/ArrowRight are swapped for horizontal navigation so it follows visual direction.',
+ default: 'false',
+ required: false,
+ },
+ {
+ name: 'options.hasRovingTabIndex',
+ type: 'boolean',
+ description: 'Opt into roving-tabindex ownership: the hook stamps a single tab stop (one item tabindex="0", the rest -1), repairs it as items mount/unmount or toggle disabled, and moves it with arrow navigation. When false, the hook only moves focus and never touches tabindex.',
+ default: 'false',
+ required: false,
+ },
+ {
+ name: 'options.hasCaretGuard',
+ type: 'boolean',
+ description: "When true, arrow keys are not stolen from a nested text input/textarea whose caret is not at the boundary in the direction of travel (or that has a selection), and are never stolen from a nested contenteditable (rich-text editor / chat composer). Preserves inline text editing within the list.",
+ default: 'false',
+ required: false,
+ },
],
returns: [
{
@@ -51,6 +79,11 @@ export const docs = {
type: '(e: React.KeyboardEvent) => void',
description: 'Key down handler to attach to the list container.',
},
+ {
+ name: 'handleFocus',
+ type: '(e: React.FocusEvent) => void',
+ description: 'Focus handler for the container. Keeps the roving tab stop in sync when hasRovingTabIndex is enabled; a no-op otherwise, so it is always safe to attach.',
+ },
{
name: 'focusItem',
type: '(index: number) => void',
@@ -58,21 +91,22 @@ export const docs = {
},
{
name: 'focusFirst',
- type: '() => void',
- description: 'Focus the first focusable item in the list.',
+ type: '() => boolean',
+ description: 'Focus the first enabled item. Returns true when an item was focused.',
},
{
name: 'focusLast',
- type: '() => void',
- description: 'Focus the last focusable item in the list.',
+ type: '() => boolean',
+ description: 'Focus the last enabled item. Returns true when an item was focused.',
},
],
usage: {
description:
- 'Manages keyboard navigation within a linear list following WAI-ARIA menu/listbox/toolbar patterns. Supports arrow key navigation (vertical or horizontal), Home/End for boundaries, optional wrap-around, and Escape to close. Suitable for dropdown menus, toolbars, and any 1D focusable list.',
+ 'Manages keyboard navigation within a linear list following WAI-ARIA menu/listbox/toolbar patterns. Supports arrow key navigation (vertical, horizontal, or both), Home/End for boundaries, optional wrap-around, RTL, and Escape to close. Opt into hasRovingTabIndex for composite widgets (toolbars, segmented controls, tab strips) that own a single tab stop. Suitable for dropdown menus, toolbars, and any 1D focusable list.',
bestPractices: [
{ guidance: true, description: "Set orientation to 'horizontal' for toolbars and tab bars, 'vertical' for dropdown menus." },
{ guidance: true, description: 'Provide an onEscape callback for menus/dropdowns to return focus to the trigger.' },
+ { guidance: true, description: 'Enable hasRovingTabIndex (and hasCaretGuard when the widget can contain text inputs) for toolbar-style composites that should be a single tab stop.' },
{ guidance: false, description: 'Use for 2D grid navigation; prefer useGridFocus for grids and calendars.' },
],
},
@@ -91,14 +125,19 @@ export const docsDense = {
'options.itemSelector': 'selector for focusable items in list.',
'options.wrap': 'whether arrow navigation wraps around at ends.',
'options.onEscape': 'callback when Escape key pressed (e.g. close menu).',
- 'options.orientation': "navigation orientation. 'horizontal' uses ArrowLeft/ArrowRight, 'vertical' uses ArrowUp/ArrowDown.",
+ 'options.orientation': "navigation orientation. 'horizontal' uses ArrowLeft/ArrowRight, 'vertical' uses ArrowUp/ArrowDown, 'both' accepts all four arrows.",
+ 'options.hasHomeEnd': 'whether Home/End jump to first/last enabled item.',
+ 'options.isRtl': 'when true, ArrowLeft/ArrowRight swap for horizontal nav (RTL).',
+ 'options.hasRovingTabIndex': 'opt into roving-tabindex ownership: hook stamps + repairs a single tab stop across items.',
+ 'options.hasCaretGuard': "when true, don't steal arrow keys from a nested text input/textarea mid-line or from a contenteditable.",
},
returnDescriptions: {
listRef: 'ref to attach to list container element.',
handleKeyDown: 'key down handler for list container.',
+ handleFocus: 'focus handler; keeps roving tab stop in sync when hasRovingTabIndex is on (else no-op).',
focusItem: 'focus specific item by index (clamped to valid range).',
- focusFirst: 'focus first focusable item in list.',
- focusLast: 'focus last focusable item in list.',
+ focusFirst: 'focus first enabled item; returns true when focused.',
+ focusLast: 'focus last enabled item; returns true when focused.',
},
usage: {
description:
diff --git a/packages/core/src/hooks/useListFocus.test.tsx b/packages/core/src/hooks/useListFocus.test.tsx
index 70b41e6662..8face9f3f4 100644
--- a/packages/core/src/hooks/useListFocus.test.tsx
+++ b/packages/core/src/hooks/useListFocus.test.tsx
@@ -104,3 +104,272 @@ describe('useListFocus disabled-item skipping', () => {
expect(screen.getByTestId('Two')).toHaveFocus();
});
});
+
+// ---------------------------------------------------------------------------
+// Roving-tabindex mode + composite navigation behaviors.
+// These exercise the opt-in `hasRovingTabIndex`, `isRtl`, `orientation: 'both'`,
+// `hasCaretGuard`, and shortcut-passthrough behaviors.
+// ---------------------------------------------------------------------------
+
+const ROVING_LABELS = ['A', 'B', 'C'];
+
+function RovingToolbar({
+ labels = ROVING_LABELS,
+ disabledLabels = NO_DISABLED,
+ ...opts
+}: {
+ labels?: string[];
+ disabledLabels?: string[];
+} & Parameters<typeof useListFocus>[0]) {
+ const {listRef, handleKeyDown, handleFocus} = useListFocus<HTMLDivElement>({
+ itemSelector: 'button, input, [tabindex]',
+ hasRovingTabIndex: true,
+ orientation: 'horizontal',
+ ...opts,
+ });
+ return (
+ <div
+ ref={listRef}
+ role="toolbar"
+ onKeyDown={handleKeyDown}
+ onFocus={handleFocus}>
+ {labels.map(label => (
+ <button
+ key={label}
+ type="button"
+ disabled={disabledLabels.includes(label)}
+ data-testid={label}>
+ {label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+describe('useListFocus roving tabindex (hasRovingTabIndex)', () => {
+ it('stamps a single tab stop (first enabled item is tabbable)', () => {
+ render(<RovingToolbar />);
+ expect(screen.getByTestId('A')).toHaveAttribute('tabindex', '0');
+ expect(screen.getByTestId('B')).toHaveAttribute('tabindex', '-1');
+ expect(screen.getByTestId('C')).toHaveAttribute('tabindex', '-1');
+ });
+
+ it('promotes the first ENABLED item when the first is disabled (repair)', () => {
+ render(<RovingToolbar disabledLabels={['A']} />);
+ expect(screen.getByTestId('B')).toHaveAttribute('tabindex', '0');
+ expect(screen.getByTestId('A')).toHaveAttribute('tabindex', '-1');
+ });
+
+ it('ArrowRight moves the tab stop to the next enabled item', () => {
+ render(<RovingToolbar />);
+ const toolbar = screen.getByRole('toolbar');
+ screen.getByTestId('A').focus();
+ fireEvent.keyDown(toolbar, {key: 'ArrowRight'});
+ expect(screen.getByTestId('B')).toHaveFocus();
+ expect(screen.getByTestId('B')).toHaveAttribute('tabindex', '0');
+ expect(screen.getByTestId('A')).toHaveAttribute('tabindex', '-1');
+ });
+
+ it('ArrowRight skips a disabled item', () => {
+ render(<RovingToolbar disabledLabels={['B']} />);
+ const toolbar = screen.getByRole('toolbar');
+ screen.getByTestId('A').focus();
+ fireEvent.keyDown(toolbar, {key: 'ArrowRight'});
+ expect(screen.getByTestId('C')).toHaveFocus();
+ });
+
+ it('wraps at the end by default', () => {
+ render(<RovingToolbar />);
+ const toolbar = screen.getByRole('toolbar');
+ screen.getByTestId('C').focus();
+ fireEvent.keyDown(toolbar, {key: 'ArrowRight'});
+ expect(screen.getByTestId('A')).toHaveFocus();
+ });
+
+ it('does not wrap when wrap=false', () => {
+ render(<RovingToolbar wrap={false} />);
+ const toolbar = screen.getByRole('toolbar');
+ screen.getByTestId('C').focus();
+ fireEvent.keyDown(toolbar, {key: 'ArrowRight'});
+ expect(screen.getByTestId('C')).toHaveFocus();
+ });
+
+ it('Home/End jump to first/last enabled items', () => {
+ render(<RovingToolbar />);
+ const toolbar = screen.getByRole('toolbar');
+ screen.getByTestId('B').focus();
+ fireEvent.keyDown(toolbar, {key: 'End'});
+ expect(screen.getByTestId('C')).toHaveFocus();
+ fireEvent.keyDown(toolbar, {key: 'Home'});
+ expect(screen.getByTestId('A')).toHaveFocus();
+ });
+
+ it('flips ArrowLeft/ArrowRight under RTL', () => {
+ render(<RovingToolbar isRtl />);
+ const toolbar = screen.getByRole('toolbar');
+ screen.getByTestId('A').focus();
+ // In RTL, ArrowLeft is "forward".
+ fireEvent.keyDown(toolbar, {key: 'ArrowLeft'});
+ expect(screen.getByTestId('B')).toHaveFocus();
+ });
+
+ it('orientation "both" navigates with all four arrows', () => {
+ render(<RovingToolbar orientation="both" />);
+ const toolbar = screen.getByRole('toolbar');
+ screen.getByTestId('A').focus();
+ fireEvent.keyDown(toolbar, {key: 'ArrowDown'});
+ expect(screen.getByTestId('B')).toHaveFocus();
+ fireEvent.keyDown(toolbar, {key: 'ArrowRight'});
+ expect(screen.getByTestId('C')).toHaveFocus();
+ });
+
+ it('vertical orientation ignores horizontal arrows', () => {
+ render(<RovingToolbar orientation="vertical" />);
+ const toolbar = screen.getByRole('toolbar');
+ screen.getByTestId('A').focus();
+ fireEvent.keyDown(toolbar, {key: 'ArrowDown'});
+ expect(screen.getByTestId('B')).toHaveFocus();
+ fireEvent.keyDown(toolbar, {key: 'ArrowRight'});
+ // ArrowRight is inert in vertical mode.
+ expect(screen.getByTestId('B')).toHaveFocus();
+ });
+
+ it('does not manage tabindex when hasRovingTabIndex is off', () => {
+ render(<RovingToolbar hasRovingTabIndex={false} />);
+ // No tabindex stamped — the buttons keep their intrinsic tab order.
+ expect(screen.getByTestId('A')).not.toHaveAttribute('tabindex');
+ expect(screen.getByTestId('B')).not.toHaveAttribute('tabindex');
+ });
+});
+
+function ToolbarWithInput(opts: Parameters<typeof useListFocus>[0]) {
+ const {listRef, handleKeyDown, handleFocus} = useListFocus<HTMLDivElement>({
+ itemSelector: 'button, input, [tabindex]',
+ hasRovingTabIndex: true,
+ orientation: 'horizontal',
+ hasCaretGuard: true,
+ ...opts,
+ });
+ return (
+ <div
+ ref={listRef}
+ role="toolbar"
+ onKeyDown={handleKeyDown}
+ onFocus={handleFocus}>
+ <button type="button" data-testid="before">
+ Before
+ </button>
+ <input type="text" defaultValue="hello" data-testid="field" />
+ <button type="button" data-testid="after">
+ After
+ </button>
+ </div>
+ );
+}
+
+describe('useListFocus caret-boundary guard (hasCaretGuard, navigation-4)', () => {
+ function getField(): HTMLInputElement {
+ const el = screen.getByTestId('field');
+ if (!(el instanceof HTMLInputElement)) {
+ throw new Error('expected an input');
+ }
+ return el;
+ }
+
+ it('does not steal ArrowRight from a text input mid-line', () => {
+ render(<ToolbarWithInput />);
+ const toolbar = screen.getByRole('toolbar');
+ const field = getField();
+ field.focus();
+ field.setSelectionRange(1, 1); // caret in the middle of "hello"
+ fireEvent.keyDown(toolbar, {key: 'ArrowRight'});
+ // Focus stays in the input; caret movement is left to the browser.
+ expect(field).toHaveFocus();
+ });
+
+ it('steals ArrowRight when the caret is at the end of the input', () => {
+ render(<ToolbarWithInput />);
+ const toolbar = screen.getByRole('toolbar');
+ const field = getField();
+ field.focus();
+ field.setSelectionRange(5, 5); // caret at end of "hello"
+ fireEvent.keyDown(toolbar, {key: 'ArrowRight'});
+ // Now the composite navigates to the next item.
+ expect(screen.getByTestId('after')).toHaveFocus();
+ });
+
+ it('does not steal an arrow key when the input has a selection', () => {
+ render(<ToolbarWithInput />);
+ const toolbar = screen.getByRole('toolbar');
+ const field = getField();
+ field.focus();
+ field.setSelectionRange(0, 5); // whole value selected
+ fireEvent.keyDown(toolbar, {key: 'ArrowRight'});
+ expect(field).toHaveFocus();
+ });
+
+ it('steals the key from a text input when hasCaretGuard is off', () => {
+ render(<ToolbarWithInput hasCaretGuard={false} />);
+ const toolbar = screen.getByRole('toolbar');
+ const field = getField();
+ field.focus();
+ field.setSelectionRange(1, 1); // caret mid-line, but no caret guard
+ fireEvent.keyDown(toolbar, {key: 'ArrowRight'});
+ expect(screen.getByTestId('after')).toHaveFocus();
+ });
+});
+
+function ToolbarWithEditable(opts: Parameters<typeof useListFocus>[0]) {
+ const {listRef, handleKeyDown, handleFocus} = useListFocus<HTMLDivElement>({
+ itemSelector: 'button, input, [contenteditable], [tabindex]',
+ hasRovingTabIndex: true,
+ orientation: 'horizontal',
+ hasCaretGuard: true,
+ ...opts,
+ });
+ return (
+ <div
+ ref={listRef}
+ role="toolbar"
+ onKeyDown={handleKeyDown}
+ onFocus={handleFocus}>
+ <button type="button" data-testid="before">
+ Before
+ </button>
+ <div
+ contentEditable
+ suppressContentEditableWarning
+ data-testid="composer">
+ hello world
+ </div>
+ <button type="button" data-testid="after">
+ After
+ </button>
+ </div>
+ );
+}
+
+describe('useListFocus caret-boundary guard: contenteditable (navigation-4)', () => {
+ it('does not steal arrow keys from a non-empty contenteditable', () => {
+ render(<ToolbarWithEditable />);
+ const toolbar = screen.getByRole('toolbar');
+ const composer = screen.getByTestId('composer');
+ composer.focus();
+ fireEvent.keyDown(toolbar, {key: 'ArrowRight'});
+ // Focus stays in the editor; list navigation must not hijack the arrow.
+ expect(composer).toHaveFocus();
+ fireEvent.keyDown(toolbar, {key: 'ArrowLeft'});
+ expect(composer).toHaveFocus();
+ });
+});
+
+describe('useListFocus shortcut passthrough', () => {
+ it('passes browser shortcut chords (Cmd/Ctrl/Alt) through', () => {
+ render(<RovingToolbar />);
+ const toolbar = screen.getByRole('toolbar');
+ screen.getByTestId('A').focus();
+ fireEvent.keyDown(toolbar, {key: 'ArrowRight', metaKey: true});
+ // Focus should not move on a modified chord.
+ expect(screen.getByTestId('A')).toHaveFocus();
+ });
+});
diff --git a/packages/core/src/hooks/useListFocus.ts b/packages/core/src/hooks/useListFocus.ts
index 2899c88995..ade0ee289c 100644
--- a/packages/core/src/hooks/useListFocus.ts
+++ b/packages/core/src/hooks/useListFocus.ts
@@ -4,15 +4,25 @@
/**
* @file useListFocus.ts
- * @input Uses React useCallback, useRef
+ * @input Uses React useCallback, useRef, useIsomorphicLayoutEffect
* @output Exports useListFocus hook for linear list keyboard navigation
- * @position Core hook; used by TabMenu for dropdown menu navigation, Toolbar for roving tabindex
+ * @position Core hook; used by TabMenu for dropdown menu navigation, Toolbar
+ * for roving tabindex, ButtonGroup, ContextMenu, NavHeadingMenu, and more.
*
* SYNC: When modified, update:
* - /packages/core/src/hooks/index.ts
*/
import {useCallback, useRef} from 'react';
+import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';
+
+/**
+ * Navigation orientation for a linear list.
+ * - `'horizontal'`: ArrowLeft/ArrowRight move between items.
+ * - `'vertical'`: ArrowUp/ArrowDown move between items.
+ * - `'both'`: all four arrows move between items (in linear DOM order).
+ */
+export type ListFocusOrientation = 'horizontal' | 'vertical' | 'both';
/**
* Configuration for list focus behavior
@@ -20,7 +30,7 @@ import {useCallback, useRef} from 'react';
export interface UseListFocusOptions {
/**
* Selector for focusable items within the list.
- * @default '[role="menuitem"], [role="menuitemradio"], [role="menuitemcheckbox"]'
+ * @default '[role="menuitem"]'
*/
itemSelector?: string;
@@ -36,11 +46,51 @@ export interface UseListFocusOptions {
onEscape?: () => void;
/**
- * Navigation orientation. 'horizontal' uses ArrowLeft/ArrowRight,
- * 'vertical' uses ArrowUp/ArrowDown.
+ * Navigation orientation. `'horizontal'` uses ArrowLeft/ArrowRight,
+ * `'vertical'` uses ArrowUp/ArrowDown, `'both'` accepts all four arrows.
* @default 'vertical'
*/
- orientation?: 'horizontal' | 'vertical';
+ orientation?: ListFocusOrientation;
+
+ /**
+ * Whether Home/End jump to the first/last enabled item.
+ * @default true
+ */
+ hasHomeEnd?: boolean;
+
+ /**
+ * Whether the list is in a right-to-left context. When true, ArrowLeft and
+ * ArrowRight are swapped so horizontal navigation follows visual direction.
+ * Only affects horizontal (`'horizontal'`/`'both'`) navigation.
+ * @default false
+ */
+ isRtl?: boolean;
+
+ /**
+ * Roving-tabindex ownership. When true, the hook manages a single tab stop
+ * across the items: exactly one enabled item carries `tabindex="0"` and the
+ * rest `tabindex="-1"`. The tab stop is stamped on mount and repaired
+ * whenever items mount/unmount or toggle disabled, and moves with arrow
+ * navigation. Attach the returned {@link UseListFocusReturn.handleFocus} to
+ * the container's `onFocus` to keep the stop in sync after clicks or
+ * programmatic focus.
+ *
+ * When false (the default), the hook only *moves* focus (`.focus()`) and
+ * never touches `tabindex` — the caller owns tab-stop management.
+ * @default false
+ */
+ hasRovingTabIndex?: boolean;
+
+ /**
+ * When true, arrow keys are not stolen from a nested text input/textarea
+ * whose caret is not at the boundary in the direction of travel (or that has
+ * a non-collapsed selection), and are never stolen from a nested
+ * `contenteditable` (rich-text editor / chat composer). This preserves
+ * normal caret movement while the user is editing inline within the list
+ * (e.g. a toolbar search field or composer).
+ * @default false
+ */
+ hasCaretGuard?: boolean;
}
/**
@@ -57,20 +107,120 @@ export interface UseListFocusReturn<T extends HTMLElement = HTMLElement> {
*/
handleKeyDown: (e: React.KeyboardEvent) => void;
+ /**
+ * Focus handler to attach to the container's `onFocus`. Keeps the roving tab
+ * stop in sync when `hasRovingTabIndex` is enabled; a no-op otherwise, so it is
+ * always safe to attach.
+ */
+ handleFocus: (e: React.FocusEvent) => void;
+
/**
* Focus a specific item by index.
*/
focusItem: (index: number) => void;
/**
- * Focus the first focusable item.
+ * Focus the first enabled item. Returns true when an item was focused.
*/
- focusFirst: () => void;
+ focusFirst: () => boolean;
/**
- * Focus the last focusable item.
+ * Focus the last enabled item. Returns true when an item was focused.
*/
- focusLast: () => void;
+ focusLast: () => boolean;
+}
+
+// Text-editing inputs whose caret must not be hijacked by arrow navigation.
+const TEXT_INPUT_TYPES = new Set([
+ 'text',
+ 'search',
+ 'url',
+ 'tel',
+ 'email',
+ 'password',
+ 'number',
+]);
+
+/**
+ * The nearest `contenteditable` root for `el`, or null when `el` is not inside
+ * an editable region. Prefers the browser's `isContentEditable` property and
+ * falls back to the closest `[contenteditable]` ancestor whose value is not
+ * `"false"` (so environments without `isContentEditable` still work).
+ */
+function getContentEditableRoot(el: HTMLElement): HTMLElement | null {
+ if (el.isContentEditable) {
+ return el;
+ }
+ const candidate = el.closest<HTMLElement>('[contenteditable]');
+ if (candidate && candidate.getAttribute('contenteditable') !== 'false') {
+ return candidate;
+ }
+ return null;
+}
+
+/**
+ * Whether an arrow/Home/End key should be left to the browser because the
+ * event target is a text-editing element whose caret is not yet at the boundary
+ * in the direction of travel (or a selection is present). Returns true when the
+ * list should NOT steal the key.
+ *
+ * Covers three editing surfaces:
+ * - `<textarea>` and text-type `<input>` — use `selectionStart`/`selectionEnd`
+ * to steal only at the boundary in the travel direction.
+ * - `contenteditable` (rich-text editor / chat composer) — precise caret
+ * boundary detection in an arbitrary editable subtree is fragile, so we err
+ * on the side of never hijacking an active editor: defer on every caret key
+ * whenever focus is inside a non-empty contenteditable. (An empty editable
+ * has nothing to caret through, so navigation may proceed.)
+ */
+function shouldDeferToCaret(target: EventTarget | null, key: string): boolean {
+ if (!(target instanceof HTMLElement)) {
+ return false;
+ }
+
+ // contenteditable (covers an element with contenteditable="" / "true" and
+ // descendants that inherit it). `isContentEditable` is the reliable property
+ // in the browser; fall back to the nearest `contenteditable` ancestor for
+ // environments (e.g. jsdom) that don't implement the property.
+ const editableRoot = getContentEditableRoot(target);
+ if (editableRoot) {
+ const selection =
+ typeof window !== 'undefined' ? window.getSelection() : null;
+ // A non-collapsed selection means the user is selecting text — never steal.
+ if (selection && selection.rangeCount > 0 && !selection.isCollapsed) {
+ return true;
+ }
+ // Collapsed caret (or no selection API): defer whenever the editor has
+ // content, so arrow keys stay with the active rich-text editor.
+ return (editableRoot.textContent ?? '').length > 0;
+ }
+
+ const isTextarea = target.tagName === 'TEXTAREA';
+ const isTextInput =
+ target.tagName === 'INPUT' &&
+ TEXT_INPUT_TYPES.has((target as HTMLInputElement).type);
+ if (!isTextarea && !isTextInput) {
+ return false;
+ }
+ const input = target as HTMLInputElement | HTMLTextAreaElement;
+ const {selectionStart, selectionEnd, value} = input;
+ // A non-collapsed selection means the user is selecting text — never steal.
+ if (selectionStart !== selectionEnd) {
+ return true;
+ }
+ // number inputs report null selection; treat as "always defer" for caret keys.
+ if (selectionStart == null) {
+ return true;
+ }
+ if (key === 'ArrowLeft' || key === 'ArrowUp' || key === 'Home') {
+ // Defer unless the caret is at the very start.
+ return selectionStart > 0;
+ }
+ if (key === 'ArrowRight' || key === 'ArrowDown' || key === 'End') {
+ // Defer unless the caret is at the very end.
+ return selectionStart < value.length;
+ }
+ return false;
}
/**
@@ -83,6 +233,12 @@ export interface UseListFocusReturn<T extends HTMLElement = HTMLElement> {
* - End: Move to last item
* - Escape: Custom callback (e.g., close menu)
*
+ * By default the hook only *moves* focus and leaves `tabindex` management to
+ * the caller. Opt into {@link UseListFocusOptions.hasRovingTabIndex} for a hook
+ * that owns a single tab stop (roving tabindex) across the items — stamping and
+ * repairing it as items mount/unmount or toggle disabled — for toolbars,
+ * segmented controls, tab strips, and similar composite widgets.
+ *
* @example
* ```
* const {listRef, handleKeyDown} = useListFocus({
@@ -93,6 +249,22 @@ export interface UseListFocusReturn<T extends HTMLElement = HTMLElement> {
* {items.map(item => <div role="menuitem" tabIndex={0}>{item}</div>)}
* </div>
* ```
+ *
+ * Roving-tabindex composite (e.g. a toolbar):
+ *
+ * @example
+ * ```
+ * const {listRef, handleKeyDown, handleFocus} = useListFocus<HTMLDivElement>({
+ * itemSelector: 'button, input, [tabindex]',
+ * orientation: 'horizontal',
+ * hasRovingTabIndex: true,
+ * hasCaretGuard: true,
+ * });
+ *
+ * <div ref={listRef} role="toolbar" onKeyDown={handleKeyDown} onFocus={handleFocus}>
+ * {children}
+ * </div>
+ * ```
*/
export function useListFocus<T extends HTMLElement = HTMLElement>(
options: UseListFocusOptions = {},
@@ -102,6 +274,10 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
wrap = true,
onEscape,
orientation = 'vertical',
+ hasHomeEnd = true,
+ isRtl = false,
+ hasRovingTabIndex = false,
+ hasCaretGuard = false,
} = options;
const listRef = useRef<T>(null);
@@ -176,6 +352,65 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
return items.findIndex(item => item === active || item.contains(active));
}, [getItems]);
+ // --- Roving tabindex ownership (opt-in via `hasRovingTabIndex`) -------------
+
+ /**
+ * Set `tabindex` on an item, but only when it differs (avoids redundant DOM
+ * writes). Uses setAttribute so the value reflects even for elements (like
+ * `<button>`) whose default tabIndex is already 0.
+ */
+ const setTabIndex = useCallback((el: HTMLElement, value: 0 | -1) => {
+ if (el.getAttribute('tabindex') !== String(value)) {
+ el.setAttribute('tabindex', String(value));
+ }
+ }, []);
+
+ /**
+ * Stamp the roving tab stop: exactly one enabled item is tabbable (0), the
+ * rest are -1. Prefer keeping the currently-tabbable item if it is still
+ * enabled; otherwise promote the first enabled item (tab-stop repair).
+ */
+ const syncTabStops = useCallback(() => {
+ const items = getItems();
+ const enabled = items.filter(el => !isItemDisabled(el));
+ if (enabled.length === 0) {
+ return;
+ }
+ const current = enabled.find(el => el.getAttribute('tabindex') === '0');
+ const tabbable = current ?? enabled[0];
+ for (const el of items) {
+ setTabIndex(el, el === tabbable ? 0 : -1);
+ }
+ }, [getItems, isItemDisabled, setTabIndex]);
+
+ // Keep the tab stop valid across renders (items added/removed, disabled
+ // toggled). Runs after every commit but only when roving tabindex is on.
+ useIsomorphicLayoutEffect(() => {
+ if (hasRovingTabIndex) {
+ syncTabStops();
+ }
+ });
+
+ /**
+ * Move focus to `items[index]`. When roving tabindex is enabled, also move
+ * the tab stop so `index` becomes the sole tabbable item.
+ */
+ const focusIndex = useCallback(
+ (items: HTMLElement[], index: number) => {
+ const target = items[index];
+ if (!target) {
+ return;
+ }
+ if (hasRovingTabIndex) {
+ for (const el of items) {
+ setTabIndex(el, el === target ? 0 : -1);
+ }
+ }
+ target.focus();
+ },
+ [hasRovingTabIndex, setTabIndex],
+ );
+
/**
* Focus an item by index, clamping to valid range.
*/
@@ -186,86 +421,135 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
return;
}
const clampedIndex = Math.max(0, Math.min(index, items.length - 1));
- items[clampedIndex]?.focus();
+ focusIndex(items, clampedIndex);
},
- [getItems],
+ [getItems, focusIndex],
);
/**
- * Focus the first enabled item.
+ * Focus the first enabled item. Returns true when an item was focused.
*/
- const focusFirst = useCallback(() => {
+ const focusFirst = useCallback((): boolean => {
const items = getItems();
const index = findEnabledIndex(items, 0, 1, false);
if (index !== -1) {
- items[index]?.focus();
+ focusIndex(items, index);
+ return true;
}
- }, [getItems, findEnabledIndex]);
+ return false;
+ }, [getItems, findEnabledIndex, focusIndex]);
/**
- * Focus the last enabled item.
+ * Focus the last enabled item. Returns true when an item was focused.
*/
- const focusLast = useCallback(() => {
+ const focusLast = useCallback((): boolean => {
const items = getItems();
const index = findEnabledIndex(items, items.length - 1, -1, false);
if (index !== -1) {
- items[index]?.focus();
+ focusIndex(items, index);
+ return true;
}
- }, [getItems, findEnabledIndex]);
+ return false;
+ }, [getItems, findEnabledIndex, focusIndex]);
+
+ /**
+ * Keep the roving stop pointing at whatever ended up focused (e.g. a click
+ * or programmatic focus) so the next Tab behaves correctly. No-op unless
+ * roving tabindex is enabled.
+ */
+ const handleFocus = useCallback(() => {
+ if (hasRovingTabIndex) {
+ syncTabStops();
+ }
+ }, [hasRovingTabIndex, syncTabStops]);
/**
* Handle keyboard navigation.
*/
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
+ // Let browser/OS shortcut chords (Ctrl/Cmd/Alt + key) through untouched.
+ if (e.ctrlKey || e.metaKey || e.altKey) {
+ return;
+ }
+
+ // Escape is handled regardless of orientation. Preserve the historical
+ // behavior of always consuming Escape here (preventDefault) so consumers
+ // that relied on it are unaffected.
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ onEscape?.();
+ return;
+ }
+
+ const horizontal = orientation === 'horizontal' || orientation === 'both';
+ const vertical = orientation === 'vertical' || orientation === 'both';
+
+ // Resolve which keys advance vs retreat, honoring RTL for horizontal.
+ const nextKeys: string[] = [];
+ const prevKeys: string[] = [];
+ if (horizontal) {
+ nextKeys.push(isRtl ? 'ArrowLeft' : 'ArrowRight');
+ prevKeys.push(isRtl ? 'ArrowRight' : 'ArrowLeft');
+ }
+ if (vertical) {
+ nextKeys.push('ArrowDown');
+ prevKeys.push('ArrowUp');
+ }
+
+ const isNext = nextKeys.includes(e.key);
+ const isPrev = prevKeys.includes(e.key);
+ const isHome = hasHomeEnd && e.key === 'Home';
+ const isEnd = hasHomeEnd && e.key === 'End';
+
+ if (!isNext && !isPrev && !isHome && !isEnd) {
+ return;
+ }
+
+ // Never hijack a caret key from a nested text input mid-line. Check both
+ // the React event target and the actual focused element (events may
+ // bubble up to the container).
+ if (
+ hasCaretGuard &&
+ (shouldDeferToCaret(e.target, e.key) ||
+ shouldDeferToCaret(document.activeElement, e.key))
+ ) {
+ return;
+ }
+
const currentIndex = getCurrentIndex();
const items = getItems();
- let handled = true;
- const nextKey = orientation === 'horizontal' ? 'ArrowRight' : 'ArrowDown';
- const prevKey = orientation === 'horizontal' ? 'ArrowLeft' : 'ArrowUp';
-
- switch (e.key) {
- case nextKey: {
- const from = currentIndex === -1 ? 0 : currentIndex + 1;
- const next = findEnabledIndex(items, from, 1, wrap);
- if (next !== -1) {
- items[next]?.focus();
- }
- break;
+ if (isNext) {
+ const from = currentIndex === -1 ? 0 : currentIndex + 1;
+ const next = findEnabledIndex(items, from, 1, wrap);
+ if (next !== -1) {
+ focusIndex(items, next);
}
- case prevKey: {
- const from =
- currentIndex === -1 ? items.length - 1 : currentIndex - 1;
- const prev = findEnabledIndex(items, from, -1, wrap);
- if (prev !== -1) {
- items[prev]?.focus();
- }
- break;
+ } else if (isPrev) {
+ const from = currentIndex === -1 ? items.length - 1 : currentIndex - 1;
+ const prev = findEnabledIndex(items, from, -1, wrap);
+ if (prev !== -1) {
+ focusIndex(items, prev);
}
- case 'Home':
- focusFirst();
- break;
- case 'End':
- focusLast();
- break;
- case 'Escape':
- onEscape?.();
- break;
- default:
- handled = false;
+ } else if (isHome) {
+ focusFirst();
+ } else if (isEnd) {
+ focusLast();
}
- if (handled) {
- e.preventDefault();
- }
+ e.preventDefault();
},
[
getCurrentIndex,
getItems,
wrap,
orientation,
+ isRtl,
+ hasHomeEnd,
+ hasCaretGuard,
findEnabledIndex,
+ focusIndex,
focusFirst,
focusLast,
onEscape,
@@ -275,6 +559,7 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
return {
listRef,
handleKeyDown,
+ handleFocus,
focusItem,
focusFirst,
focusLast,