Skip to content

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

TypeScript

fix(hooks): useListFocus skips disabled items (menus-4, navigation-5, infra-15) (#3376)

Cindy Zhang7a4596c5eeed
diff --git a/.changeset/uselistfocus-disabled-skip.md b/.changeset/uselistfocus-disabled-skip.md
new file mode 100644
index 0000000000..415b26fd6f
--- /dev/null
+++ b/.changeset/uselistfocus-disabled-skip.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] useListFocus (menu/toolbar keyboard navigation): arrow keys, Home, and End now skip disabled items instead of stalling on one whose `.focus()` silently no-ops. This unfreezes keyboard navigation in NavHeadingMenu and Toolbar/ButtonGroup when a disabled control is present. The default item selector also now matches `menuitemradio`/`menuitemcheckbox` (#3343).
+@cixzhang
diff --git a/packages/core/src/hooks/useListFocus.test.tsx b/packages/core/src/hooks/useListFocus.test.tsx
new file mode 100644
index 0000000000..70b41e6662
--- /dev/null
+++ b/packages/core/src/hooks/useListFocus.test.tsx
@@ -0,0 +1,106 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useListFocus.test.tsx
+ * @input Uses vitest, @testing-library/react, useListFocus hook
+ * @output Unit tests for useListFocus disabled-item skipping + navigation
+ * @position Testing; validates useListFocus.ts keyboard navigation
+ *
+ * SYNC: When useListFocus.ts changes, update tests to match new behavior
+ */
+
+import {describe, it, expect} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
+import {useListFocus} from './useListFocus';
+
+const NO_DISABLED: string[] = [];
+
+function Menu({
+ wrap = true,
+ disabledLabels = NO_DISABLED,
+}: {
+ wrap?: boolean;
+ disabledLabels?: string[];
+}) {
+ const {listRef, handleKeyDown} = useListFocus<HTMLDivElement>({wrap});
+ const items = ['One', 'Two', 'Three', 'Four'];
+ return (
+ <div ref={listRef} role="menu" onKeyDown={handleKeyDown}>
+ {items.map(label => {
+ const disabled = disabledLabels.includes(label);
+ return (
+ <div
+ key={label}
+ role="menuitem"
+ tabIndex={disabled ? undefined : -1}
+ aria-disabled={disabled || undefined}
+ data-testid={label}>
+ {label}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+describe('useListFocus disabled-item skipping', () => {
+ it('ArrowDown skips a disabled item instead of stalling on it', () => {
+ render(<Menu disabledLabels={['Two']} />);
+ const menu = screen.getByRole('menu');
+ screen.getByTestId('One').focus();
+
+ fireEvent.keyDown(menu, {key: 'ArrowDown'});
+ // Should skip disabled "Two" and land on "Three".
+ expect(screen.getByTestId('Three')).toHaveFocus();
+ });
+
+ it('ArrowUp skips a disabled item', () => {
+ render(<Menu disabledLabels={['Three']} />);
+ const menu = screen.getByRole('menu');
+ screen.getByTestId('Four').focus();
+
+ fireEvent.keyDown(menu, {key: 'ArrowUp'});
+ // Should skip disabled "Three" and land on "Two".
+ expect(screen.getByTestId('Two')).toHaveFocus();
+ });
+
+ it('does not freeze at a leading disabled item (regression: menus-4)', () => {
+ render(<Menu disabledLabels={['One']} />);
+ const menu = screen.getByRole('menu');
+ // Focus starts nowhere; ArrowDown should reach the first ENABLED item.
+ fireEvent.keyDown(menu, {key: 'ArrowDown'});
+ expect(screen.getByTestId('Two')).toHaveFocus();
+ });
+
+ it('wraps past a disabled item at the end', () => {
+ render(<Menu disabledLabels={['Four']} wrap />);
+ const menu = screen.getByRole('menu');
+ screen.getByTestId('Three').focus();
+
+ fireEvent.keyDown(menu, {key: 'ArrowDown'});
+ // "Four" is disabled, wrap to "One".
+ expect(screen.getByTestId('One')).toHaveFocus();
+ });
+
+ it('does not wrap when wrap is false', () => {
+ render(<Menu disabledLabels={['Four']} wrap={false} />);
+ const menu = screen.getByRole('menu');
+ screen.getByTestId('Three').focus();
+
+ fireEvent.keyDown(menu, {key: 'ArrowDown'});
+ // "Four" disabled, no wrap -> focus stays on "Three".
+ expect(screen.getByTestId('Three')).toHaveFocus();
+ });
+
+ it('Home focuses the first enabled item, End the last enabled item', () => {
+ render(<Menu disabledLabels={['One', 'Four']} />);
+ const menu = screen.getByRole('menu');
+ screen.getByTestId('Two').focus();
+
+ fireEvent.keyDown(menu, {key: 'End'});
+ expect(screen.getByTestId('Three')).toHaveFocus();
+
+ fireEvent.keyDown(menu, {key: 'Home'});
+ expect(screen.getByTestId('Two')).toHaveFocus();
+ });
+});
diff --git a/packages/core/src/hooks/useListFocus.ts b/packages/core/src/hooks/useListFocus.ts
index 7f79759b6c..2899c88995 100644
--- a/packages/core/src/hooks/useListFocus.ts
+++ b/packages/core/src/hooks/useListFocus.ts
@@ -20,7 +20,7 @@ import {useCallback, useRef} from 'react';
export interface UseListFocusOptions {
/**
* Selector for focusable items within the list.
- * @default '[role="menuitem"]'
+ * @default '[role="menuitem"], [role="menuitemradio"], [role="menuitemcheckbox"]'
*/
itemSelector?: string;
@@ -106,6 +106,19 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
const listRef = useRef<T>(null);
+ /**
+ * Whether an item is disabled and therefore cannot receive DOM focus.
+ * A `.focus()` call on such an element silently no-ops, so navigation must
+ * skip these to avoid freezing on a disabled item (menus-4, navigation-5).
+ */
+ const isItemDisabled = useCallback((el: HTMLElement): boolean => {
+ return (
+ el.getAttribute('aria-disabled') === 'true' ||
+ (el as HTMLButtonElement).disabled === true ||
+ el.hasAttribute('disabled')
+ );
+ }, []);
+
/**
* Get all focusable items in the list.
*/
@@ -118,6 +131,42 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
);
}, [itemSelector]);
+ /**
+ * Find the next enabled item index from `start`, moving by `step`, optionally
+ * wrapping. Returns -1 when no enabled item exists in range. Skipping
+ * disabled items here (rather than relying on the selector) keeps navigation
+ * from stalling on an item whose `.focus()` silently no-ops.
+ */
+ const findEnabledIndex = useCallback(
+ (
+ items: HTMLElement[],
+ start: number,
+ step: 1 | -1,
+ shouldWrap: boolean,
+ ): number => {
+ const count = items.length;
+ if (count === 0) {
+ return -1;
+ }
+ let index = start;
+ for (let i = 0; i < count; i++) {
+ if (index < 0 || index >= count) {
+ if (!shouldWrap) {
+ return -1;
+ }
+ index = (index + count) % count;
+ }
+ const item = items[index];
+ if (item && !isItemDisabled(item)) {
+ return index;
+ }
+ index += step;
+ }
+ return -1;
+ },
+ [isItemDisabled],
+ );
+
/**
* Get the currently focused item index.
*/
@@ -143,20 +192,26 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
);
/**
- * Focus the first item.
+ * Focus the first enabled item.
*/
const focusFirst = useCallback(() => {
const items = getItems();
- items[0]?.focus();
- }, [getItems]);
+ const index = findEnabledIndex(items, 0, 1, false);
+ if (index !== -1) {
+ items[index]?.focus();
+ }
+ }, [getItems, findEnabledIndex]);
/**
- * Focus the last item.
+ * Focus the last enabled item.
*/
const focusLast = useCallback(() => {
const items = getItems();
- items[items.length - 1]?.focus();
- }, [getItems]);
+ const index = findEnabledIndex(items, items.length - 1, -1, false);
+ if (index !== -1) {
+ items[index]?.focus();
+ }
+ }, [getItems, findEnabledIndex]);
/**
* Handle keyboard navigation.
@@ -172,22 +227,19 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
switch (e.key) {
case nextKey: {
- if (currentIndex === -1) {
- items[0]?.focus();
- } else if (currentIndex < items.length - 1) {
- items[currentIndex + 1]?.focus();
- } else if (wrap) {
- items[0]?.focus();
+ const from = currentIndex === -1 ? 0 : currentIndex + 1;
+ const next = findEnabledIndex(items, from, 1, wrap);
+ if (next !== -1) {
+ items[next]?.focus();
}
break;
}
case prevKey: {
- if (currentIndex === -1) {
- items[items.length - 1]?.focus();
- } else if (currentIndex > 0) {
- items[currentIndex - 1]?.focus();
- } else if (wrap) {
- items[items.length - 1]?.focus();
+ const from =
+ currentIndex === -1 ? items.length - 1 : currentIndex - 1;
+ const prev = findEnabledIndex(items, from, -1, wrap);
+ if (prev !== -1) {
+ items[prev]?.focus();
}
break;
}
@@ -213,6 +265,7 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
getItems,
wrap,
orientation,
+ findEnabledIndex,
focusFirst,
focusLast,
onEscape,