Skip to content

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

TypeScript

fix(core): auto-detect RTL for arrow-key navigation in focus hooks (#4350)

Baraa Hamodi619ff702755c
diff --git a/.changeset/a11y-rtl-arrow-keys.md b/.changeset/a11y-rtl-arrow-keys.md
new file mode 100644
index 0000000000..3a379b4a7f
--- /dev/null
+++ b/.changeset/a11y-rtl-arrow-keys.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] hooks: auto-detect RTL direction for arrow-key navigation in useListFocus and useGridFocus (WCAG 1.3.2)
+@bhamodi
diff --git a/packages/core/src/hooks/isRtlElement.ts b/packages/core/src/hooks/isRtlElement.ts
new file mode 100644
index 0000000000..83a98b8dcf
--- /dev/null
+++ b/packages/core/src/hooks/isRtlElement.ts
@@ -0,0 +1,27 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file isRtlElement.ts
+ * @input DOM element (nullable)
+ * @output Exports isRtlElement helper resolving an element's computed text
+ * direction
+ * @position Internal hook utility; used by useListFocus and useGridFocus to
+ * auto-detect RTL for arrow-key navigation (same getComputedStyle precedent
+ * as Resizable's ResizeHandle drag deltas).
+ */
+
+/**
+ * Whether `el` renders right-to-left, per its computed `direction`.
+ *
+ * SSR-safe: returns false when `el` is null or no DOM is available. Callers
+ * should invoke this lazily (on keydown, not on render) so getComputedStyle
+ * runs only when a horizontal arrow key is actually handled.
+ */
+export function isRtlElement(el: HTMLElement | null): boolean {
+ if (!el || typeof window === 'undefined') {
+ return false;
+ }
+ return window.getComputedStyle(el).direction === 'rtl';
+}
diff --git a/packages/core/src/hooks/useGridFocus.doc.mjs b/packages/core/src/hooks/useGridFocus.doc.mjs
index 23199aa686..58ba50035c 100644
--- a/packages/core/src/hooks/useGridFocus.doc.mjs
+++ b/packages/core/src/hooks/useGridFocus.doc.mjs
@@ -64,8 +64,8 @@ export const docs = {
{
name: 'options.isRtl',
type: 'boolean',
- description: 'Swap ArrowLeft/ArrowRight so horizontal navigation follows visual direction in right-to-left contexts.',
- default: 'false',
+ description: 'Swap ArrowLeft/ArrowRight so horizontal navigation follows visual direction in right-to-left contexts. When omitted, auto-detected from the container computed direction on keydown.',
+ default: "undefined (auto-detect from the container's computed direction)",
required: false,
},
{
@@ -138,7 +138,7 @@ export const docsDense = {
'options.onNavigateAfter': 'callback when navigation would go after last cell. Receives column index + offset.',
'options.onPageUp': 'callback for Page Up key (e.g. navigate to previous month in calendars).',
'options.onPageDown': 'callback for Page Down key (e.g. navigate to next month in calendars).',
- 'options.isRtl': 'swap ArrowLeft/ArrowRight for RTL horizontal navigation. default false.',
+ 'options.isRtl': 'swap ArrowLeft/ArrowRight for RTL horizontal navigation. default: auto-detect from container computed direction; explicit boolean wins.',
'options.hasRovingTabIndex': 'own a single roving tab stop across the grid (one focus target tabindex=0, rest -1); repaired on render + moved with arrows. Attach handleFocus to onFocus. default false.',
},
returnDescriptions: {
diff --git a/packages/core/src/hooks/useGridFocus.test.tsx b/packages/core/src/hooks/useGridFocus.test.tsx
index 67e6262c51..8c58add7f6 100644
--- a/packages/core/src/hooks/useGridFocus.test.tsx
+++ b/packages/core/src/hooks/useGridFocus.test.tsx
@@ -23,10 +23,12 @@ const NO_DISABLED: number[] = [];
function Grid({
disabled = NO_DISABLED,
seed = 0,
+ dir,
...opts
}: {
disabled?: number[];
seed?: number;
+ dir?: 'ltr' | 'rtl';
} & Partial<Parameters<typeof useGridFocus>[0]>) {
const {gridRef, handleKeyDown, handleFocus} = useGridFocus<HTMLDivElement>({
columns: 3,
@@ -41,6 +43,7 @@ function Grid({
<div
ref={gridRef}
role="grid"
+ dir={dir}
onKeyDown={handleKeyDown}
onFocus={handleFocus}>
{Array.from({length: 9}, (_, i) => (
@@ -130,3 +133,41 @@ describe('useGridFocus roving tabindex (hasRovingTabIndex)', () => {
expect(screen.getByTestId('cell-1')).toHaveAttribute('tabindex', '-1');
});
});
+
+describe('useGridFocus RTL auto-detection (WCAG 1.3.2)', () => {
+ // jsdom reflects the `dir` attribute into computed style only on the element
+ // that carries it, so tests set dir="rtl" on the grid container itself — the
+ // element the hook reads via gridRef.
+
+ it('auto-detects dir="rtl": ArrowLeft moves forward (next cell)', () => {
+ render(<Grid seed={1} dir="rtl" />);
+ const grid = screen.getByRole('grid');
+ screen.getByTestId('cell-1').focus();
+ fireEvent.keyDown(grid, {key: 'ArrowLeft'});
+ expect(screen.getByTestId('cell-2')).toHaveFocus();
+ });
+
+ it('auto-detects dir="rtl": ArrowRight moves backward (previous cell)', () => {
+ render(<Grid seed={1} dir="rtl" />);
+ const grid = screen.getByRole('grid');
+ screen.getByTestId('cell-1').focus();
+ fireEvent.keyDown(grid, {key: 'ArrowRight'});
+ expect(screen.getByTestId('cell-0')).toHaveFocus();
+ });
+
+ it('leaves vertical navigation unaffected under dir="rtl"', () => {
+ render(<Grid seed={0} dir="rtl" />);
+ const grid = screen.getByRole('grid');
+ screen.getByTestId('cell-0').focus();
+ fireEvent.keyDown(grid, {key: 'ArrowDown'});
+ expect(screen.getByTestId('cell-3')).toHaveFocus();
+ });
+
+ it('explicit isRtl={false} overrides a dir="rtl" container', () => {
+ render(<Grid seed={1} dir="rtl" isRtl={false} />);
+ const grid = screen.getByRole('grid');
+ screen.getByTestId('cell-1').focus();
+ fireEvent.keyDown(grid, {key: 'ArrowRight'});
+ expect(screen.getByTestId('cell-2')).toHaveFocus();
+ });
+});
diff --git a/packages/core/src/hooks/useGridFocus.ts b/packages/core/src/hooks/useGridFocus.ts
index 1498d5a4fd..0182c5d54a 100644
--- a/packages/core/src/hooks/useGridFocus.ts
+++ b/packages/core/src/hooks/useGridFocus.ts
@@ -4,9 +4,12 @@
/**
* @file useGridFocus.ts
- * @input Uses React useCallback, useRef, useIsomorphicLayoutEffect
+ * @input Uses React useCallback, useRef, useIsomorphicLayoutEffect,
+ * isRtlElement
* @output Exports useGridFocus hook for grid keyboard navigation
- * @position Core hook; used by Calendar for date grid navigation
+ * @position Core hook; used by Calendar for date grid navigation. Auto-detects
+ * RTL from the container's computed direction so horizontal arrow keys
+ * follow visual direction (WCAG 1.3.2).
*
* SYNC: When modified, update:
* - /packages/core/src/hooks/index.ts
@@ -14,6 +17,7 @@
*/
import {useCallback, useRef} from 'react';
+import {isRtlElement} from './isRtlElement';
import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';
/**
@@ -88,7 +92,12 @@ export interface UseGridFocusOptions {
/**
* Whether the grid is in a right-to-left context. When true, ArrowLeft and
* ArrowRight are swapped so horizontal navigation follows visual direction.
- * @default false
+ *
+ * When omitted, the direction is auto-detected from the container's computed
+ * `direction` (read lazily on keydown, only for horizontal arrow keys), so
+ * grids inside `dir="rtl"` subtrees flip automatically. Pass an explicit
+ * boolean to override detection.
+ * @default undefined (auto-detect from the container)
*/
isRtl?: boolean;
@@ -217,7 +226,7 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(
onNavigateAfter,
onPageUp,
onPageDown,
- isRtl = false,
+ isRtl,
hasRovingTabIndex = false,
} = options;
@@ -455,13 +464,15 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(
// In RTL, ArrowLeft/ArrowRight are swapped so horizontal navigation
// follows visual direction. Vertical keys (Up/Down) are unaffected.
+ // Direction is resolved lazily — getComputedStyle runs only when a
+ // horizontal arrow key is actually pressed (SSR-safe, no layout thrash
+ // on unrelated keys) — and an explicit `isRtl` always wins.
let key = e.key;
- if (isRtl) {
- if (key === 'ArrowLeft') {
- key = 'ArrowRight';
- } else if (key === 'ArrowRight') {
- key = 'ArrowLeft';
- }
+ if (
+ (key === 'ArrowLeft' || key === 'ArrowRight') &&
+ (isRtl ?? isRtlElement(gridRef.current))
+ ) {
+ key = key === 'ArrowLeft' ? 'ArrowRight' : 'ArrowLeft';
}
switch (key) {
diff --git a/packages/core/src/hooks/useListFocus.doc.mjs b/packages/core/src/hooks/useListFocus.doc.mjs
index 7385a2043b..c8732554a3 100644
--- a/packages/core/src/hooks/useListFocus.doc.mjs
+++ b/packages/core/src/hooks/useListFocus.doc.mjs
@@ -49,8 +49,8 @@ export const docs = {
{
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',
+ 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. When omitted, auto-detected from the container computed direction on keydown.',
+ default: "undefined (auto-detect from the container's computed direction)",
required: false,
},
{
@@ -127,7 +127,7 @@ export const docsDense = {
'options.onEscape': 'callback when Escape key pressed (e.g. close menu).',
'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.isRtl': 'ArrowLeft/ArrowRight swap for horizontal nav (RTL). default: auto-detect from container computed direction; explicit boolean wins.',
'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.",
},
diff --git a/packages/core/src/hooks/useListFocus.test.tsx b/packages/core/src/hooks/useListFocus.test.tsx
index 8face9f3f4..b86a65b107 100644
--- a/packages/core/src/hooks/useListFocus.test.tsx
+++ b/packages/core/src/hooks/useListFocus.test.tsx
@@ -3,7 +3,8 @@
/**
* @file useListFocus.test.tsx
* @input Uses vitest, @testing-library/react, useListFocus hook
- * @output Unit tests for useListFocus disabled-item skipping + navigation
+ * @output Unit tests for useListFocus disabled-item skipping, navigation, and
+ * RTL auto-detection
* @position Testing; validates useListFocus.ts keyboard navigation
*
* SYNC: When useListFocus.ts changes, update tests to match new behavior
@@ -373,3 +374,68 @@ describe('useListFocus shortcut passthrough', () => {
expect(screen.getByTestId('A')).toHaveFocus();
});
});
+
+/**
+ * A horizontal list (menubar-like) for RTL direction tests. jsdom reflects the
+ * `dir` attribute into computed style only on the element that carries it, so
+ * `dir` is set on the list container itself — the element the hook reads via
+ * listRef.
+ */
+function HorizontalMenu({dir, isRtl}: {dir?: 'ltr' | 'rtl'; isRtl?: boolean}) {
+ const {listRef, handleKeyDown} = useListFocus<HTMLDivElement>({
+ orientation: 'horizontal',
+ isRtl,
+ });
+ const items = ['One', 'Two', 'Three'];
+ return (
+ <div ref={listRef} role="menu" dir={dir} onKeyDown={handleKeyDown}>
+ {items.map(label => (
+ <div key={label} role="menuitem" tabIndex={-1} data-testid={label}>
+ {label}
+ </div>
+ ))}
+ </div>
+ );
+}
+
+describe('useListFocus RTL auto-detection (WCAG 1.3.2)', () => {
+ it('auto-detects dir="rtl": ArrowLeft moves to the next item', () => {
+ render(<HorizontalMenu dir="rtl" />);
+ const menu = screen.getByRole('menu');
+ screen.getByTestId('One').focus();
+ fireEvent.keyDown(menu, {key: 'ArrowLeft'});
+ expect(screen.getByTestId('Two')).toHaveFocus();
+ });
+
+ it('auto-detects dir="rtl": ArrowRight moves to the previous item', () => {
+ render(<HorizontalMenu dir="rtl" />);
+ const menu = screen.getByRole('menu');
+ screen.getByTestId('Two').focus();
+ fireEvent.keyDown(menu, {key: 'ArrowRight'});
+ expect(screen.getByTestId('One')).toHaveFocus();
+ });
+
+ it('stays LTR without a direction: ArrowRight moves to the next item', () => {
+ render(<HorizontalMenu />);
+ const menu = screen.getByRole('menu');
+ screen.getByTestId('One').focus();
+ fireEvent.keyDown(menu, {key: 'ArrowRight'});
+ expect(screen.getByTestId('Two')).toHaveFocus();
+ });
+
+ it('explicit isRtl={false} overrides a dir="rtl" container', () => {
+ render(<HorizontalMenu dir="rtl" isRtl={false} />);
+ const menu = screen.getByRole('menu');
+ screen.getByTestId('One').focus();
+ fireEvent.keyDown(menu, {key: 'ArrowRight'});
+ expect(screen.getByTestId('Two')).toHaveFocus();
+ });
+
+ it('explicit isRtl={true} flips arrows without a dir attribute', () => {
+ render(<HorizontalMenu isRtl />);
+ const menu = screen.getByRole('menu');
+ screen.getByTestId('One').focus();
+ fireEvent.keyDown(menu, {key: 'ArrowLeft'});
+ expect(screen.getByTestId('Two')).toHaveFocus();
+ });
+});
diff --git a/packages/core/src/hooks/useListFocus.ts b/packages/core/src/hooks/useListFocus.ts
index ade0ee289c..4a091c5817 100644
--- a/packages/core/src/hooks/useListFocus.ts
+++ b/packages/core/src/hooks/useListFocus.ts
@@ -4,16 +4,20 @@
/**
* @file useListFocus.ts
- * @input Uses React useCallback, useRef, useIsomorphicLayoutEffect
+ * @input Uses React useCallback, useRef, useIsomorphicLayoutEffect,
+ * isRtlElement
* @output Exports useListFocus hook for linear list keyboard navigation
* @position Core hook; used by TabMenu for dropdown menu navigation, Toolbar
* for roving tabindex, ButtonGroup, ContextMenu, NavHeadingMenu, and more.
+ * Auto-detects RTL from the container's computed direction so horizontal
+ * arrow keys follow visual direction (WCAG 1.3.2).
*
* SYNC: When modified, update:
* - /packages/core/src/hooks/index.ts
*/
import {useCallback, useRef} from 'react';
+import {isRtlElement} from './isRtlElement';
import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';
/**
@@ -62,7 +66,12 @@ export interface UseListFocusOptions {
* 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
+ *
+ * When omitted, the direction is auto-detected from the container's computed
+ * `direction` (read lazily on keydown, only for horizontal arrow keys), so
+ * lists inside `dir="rtl"` subtrees flip automatically. Pass an explicit
+ * boolean to override detection.
+ * @default undefined (auto-detect from the container)
*/
isRtl?: boolean;
@@ -275,7 +284,7 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
onEscape,
orientation = 'vertical',
hasHomeEnd = true,
- isRtl = false,
+ isRtl,
hasRovingTabIndex = false,
hasCaretGuard = false,
} = options;
@@ -486,11 +495,18 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(
const vertical = orientation === 'vertical' || orientation === 'both';
// Resolve which keys advance vs retreat, honoring RTL for horizontal.
+ // Direction is resolved lazily — getComputedStyle runs only when a
+ // horizontal arrow key is actually pressed (SSR-safe, no layout thrash
+ // on unrelated keys) — and an explicit `isRtl` always wins.
const nextKeys: string[] = [];
const prevKeys: string[] = [];
if (horizontal) {
- nextKeys.push(isRtl ? 'ArrowLeft' : 'ArrowRight');
- prevKeys.push(isRtl ? 'ArrowRight' : 'ArrowLeft');
+ const rtl =
+ e.key === 'ArrowLeft' || e.key === 'ArrowRight'
+ ? (isRtl ?? isRtlElement(listRef.current))
+ : false;
+ nextKeys.push(rtl ? 'ArrowLeft' : 'ArrowRight');
+ prevKeys.push(rtl ? 'ArrowRight' : 'ArrowLeft');
}
if (vertical) {
nextKeys.push('ArrowDown');