An open source design system that's fully customizable and agent ready
TypeScript
refactor(useGridFocus): roving tabindex + handleFocus + isRtl; Calendar uses it (#3489)
Cindy Zhang4eb98496a106
diff --git a/.changeset/gridfocus-roving-tabindex.md b/.changeset/gridfocus-roving-tabindex.mdnew file mode 100644index 0000000000..ca1958d686--- /dev/null+++ b/.changeset/gridfocus-roving-tabindex.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[refactor] `useGridFocus` gains `hasRovingTabIndex`, `handleFocus`, and `isRtl`, matching the `useListFocus` API. Calendar now uses `useGridFocus` to own its roving tab stop, removing the unpublished `useCalendarRovingTabindex` hook.+@cixzhangdiff --git a/packages/core/src/Calendar/Calendar.tsx b/packages/core/src/Calendar/Calendar.tsxindex b85bf50067..dd5ce5914d 100644--- a/packages/core/src/Calendar/Calendar.tsx+++ b/packages/core/src/Calendar/Calendar.tsx@@ -32,7 +32,6 @@ import {useGridFocus} from '../hooks';import {useCalendarDays,useCalendarConstraints,- useCalendarRovingTabindex,type CalendarDay,} from './hooks';import {@@ -554,14 +553,34 @@ function MonthGrid({return null;}, [mode, value]);- const {isTabbable} = useCalendarRovingTabindex({- days,- today,- year,- month: month.month,- isDateDisabled,- selectedDate: selectedDateForTabindex,- });+ // Seed the initial roving tab stop for this month. useGridFocus owns the+ // live tab stop (see `hasRovingTabIndex` below) — it honors an existing+ // `tabindex="0"` and repairs/moves it thereafter — so this only decides+ // which day button starts tabbable. Priority: selected date (if visible and+ // enabled) > today (if visible and enabled) > first enabled in-month day.+ const seedTabbableIso = useMemo((): ISODateString | null => {+ if (selectedDateForTabindex) {+ const isSelectedInMonth =+ selectedDateForTabindex.year === year &&+ selectedDateForTabindex.month === month.month;+ if (isSelectedInMonth && !isDateDisabled(selectedDateForTabindex)) {+ return plainDateToISO(selectedDateForTabindex);+ }+ }++ const isTodayInMonth = today.year === year && today.month === month.month;+ if (isTodayInMonth && !isDateDisabled(today)) {+ return plainDateToISO(today);+ }++ for (const day of days) {+ if (!day.isOutside && !isDateDisabled(day.date)) {+ return day.iso;+ }+ }++ return null;+ }, [days, today, year, month.month, isDateDisabled, selectedDateForTabindex]);// Helper to get the focused date from the currently focused element.// Reads the machine-readable `data-date` (ISO) attribute rather than parsing@@ -628,18 +647,22 @@ function MonthGrid({// focus (the day button inside the cell). Arrow keys move to the target// row/column and, if that cell is disabled, continue in the same direction to// the next enabled cell.- const {gridRef, handleKeyDown: handleGridKeyDown} =- useGridFocus<HTMLDivElement>({- columns: 7,- cellSelector: '[role="gridcell"]',- isCellFocusable: cell =>- cell.querySelector('button:not([disabled])') !== null,- getFocusTarget: cell => cell.querySelector<HTMLElement>('button'),- onNavigateBefore: handleNavigatePrevious,- onNavigateAfter: handleNavigateNext,- onPageUp: handlePageUp,- onPageDown: handlePageDown,- });+ const {+ gridRef,+ handleKeyDown: handleGridKeyDown,+ handleFocus: handleGridFocus,+ } = useGridFocus<HTMLDivElement>({+ columns: 7,+ cellSelector: '[role="gridcell"]',+ isCellFocusable: cell =>+ cell.querySelector('button:not([disabled])') !== null,+ getFocusTarget: cell => cell.querySelector<HTMLElement>('button'),+ hasRovingTabIndex: true,+ onNavigateBefore: handleNavigatePrevious,+ onNavigateAfter: handleNavigateNext,+ onPageUp: handlePageUp,+ onPageDown: handlePageDown,+ });// Handle pending focus after month navigationuseEffect(() => {@@ -719,6 +742,7 @@ function MonthGrid({role="grid"aria-label={monthLabel}onKeyDown={handleGridKeyDown}+ onFocus={handleGridFocus}{...stylex.props(monthGridStyles.daysGrid,hasWeekNumbers && monthGridStyles.daysGridWithNumbers,@@ -774,7 +798,7 @@ function MonthGrid({today={today}hasOutsideDays={hasOutsideDays}isDisabled={isDateDisabled(day.date)}- isTabbable={isTabbable(day.iso)}+ isTabbable={day.iso === seedTabbableIso}onDayClick={onDayClick}onDayHover={onDayHover}/>@@ -803,6 +827,11 @@ interface DayCellProps {today: PlainDate;hasOutsideDays: boolean;isDisabled: boolean;+ /**+ * Whether this day seeds the initial roving tab stop. useGridFocus+ * (`hasRovingTabIndex`) owns the live tab stop thereafter — it honors an+ * existing `tabindex="0"` and repairs/moves it on navigation and focus.+ */isTabbable: boolean;onDayClick: (date: PlainDate) => void;onDayHover: (date: PlainDate | null) => void;@@ -894,6 +923,7 @@ function DayCell({aria-selected={state.isSelected || state.isInRange || undefined}aria-disabled={state.effectivelyDisabled || undefined}disabled={isDisabled}+ // Initial roving tab-stop seed; useGridFocus owns it after mount.tabIndex={isTabbableDay ? 0 : -1}onClick={() => !state.effectivelyDisabled && onDayClick(date)}onMouseEnter={() => !state.effectivelyDisabled && onDayHover(date)}diff --git a/packages/core/src/Calendar/hooks/index.ts b/packages/core/src/Calendar/hooks/index.tsindex b96c337b65..13b148d21a 100644--- a/packages/core/src/Calendar/hooks/index.ts+++ b/packages/core/src/Calendar/hooks/index.ts@@ -27,9 +27,3 @@ export type {UseCalendarNavigationOptions,UseCalendarNavigationReturn,} from './useCalendarNavigation';--export {useCalendarRovingTabindex} from './useCalendarRovingTabindex';-export type {- UseCalendarRovingTabindexOptions,- UseCalendarRovingTabindexReturn,-} from './useCalendarRovingTabindex';diff --git a/packages/core/src/Calendar/hooks/useCalendarRovingTabindex.ts b/packages/core/src/Calendar/hooks/useCalendarRovingTabindex.tsdeleted file mode 100644index 6071840165..0000000000--- a/packages/core/src/Calendar/hooks/useCalendarRovingTabindex.ts+++ /dev/null@@ -1,118 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--'use client';--/**- * @file useCalendarRovingTabindex.ts- * @input Uses React useMemo, PlainDate utilities- * @output Exports useCalendarRovingTabindex hook for accessible grid navigation- * @position Calendar-specific hook; used by Calendar- *- * SYNC: When modified, update:- * - /packages/core/src/Calendar/hooks/index.ts- */--import {useMemo} from 'react';-import type {ISODateString} from '../../utils/dateTypes';-import {type PlainDate, plainDateToISO} from '../../utils/plainDate';-import type {CalendarDay} from './useCalendarDays';--/**- * Configuration for calendar roving tabindex- */-export interface UseCalendarRovingTabindexOptions {- /** All days in the grid */- days: CalendarDay[];- /** Today's date as a PlainDate */- today: PlainDate;- /** The year being displayed */- year: number;- /** The month being displayed (1-based: 1 = January, 12 = December) */- month: number;- /** Function to check if a date is disabled */- isDateDisabled: (date: PlainDate) => boolean;- /** Currently selected date (if any) */- selectedDate?: PlainDate | null;-}--/**- * Return type for useCalendarRovingTabindex hook- */-export interface UseCalendarRovingTabindexReturn {- /** The ISO date string of the tabbable element, or null */- tabbableDate: ISODateString | null;- /** Check if a specific date is the tabbable one */- isTabbable: (iso: ISODateString) => boolean;-}--/**- * Hook for managing roving tabindex in calendar grids.- *- * Implements the WAI-ARIA roving tabindex pattern where only one element- * in a group has tabindex="0" while others have tabindex="-1".- *- * Priority for tabbable element:- * 1. Today if visible in the current month and enabled- * 2. First enabled day in the month- *- * @example- * ```- * const {tabbableDate, isTabbable} = useCalendarRovingTabindex({- * days,- * today: {year: 2026, month: 1, day: 20},- * year: 2026,- * month: 1, // January (1-based)- * isDateDisabled,- * });- *- * // In day rendering:- * <button tabIndex={isTabbable(day.iso) ? 0 : -1}>- * {day.dayNumber}- * </button>- * ```- */-export function useCalendarRovingTabindex(- options: UseCalendarRovingTabindexOptions,-): UseCalendarRovingTabindexReturn {- const {days, today, year, month, isDateDisabled, selectedDate} = options;-- // Determine which day should be tabbable- const tabbableDate = useMemo(() => {- // Priority 1: Selected date if visible in this month and enabled- if (selectedDate) {- const isSelectedInMonth =- selectedDate.year === year && selectedDate.month === month;- if (isSelectedInMonth && !isDateDisabled(selectedDate)) {- return plainDateToISO(selectedDate);- }- }-- // Priority 2: Today if visible in this month and enabled- const isTodayInMonth = today.year === year && today.month === month;-- if (isTodayInMonth && !isDateDisabled(today)) {- return plainDateToISO(today);- }-- // Priority 3: First enabled day in this month- for (const day of days) {- if (!day.isOutside && !isDateDisabled(day.date)) {- return day.iso;- }- }-- return null;- }, [days, today, year, month, isDateDisabled, selectedDate]);-- // Check if a specific date is tabbable- const isTabbable = useMemo(() => {- return (iso: ISODateString): boolean => {- return tabbableDate !== null && iso === tabbableDate;- };- }, [tabbableDate]);-- return {- tabbableDate,- isTabbable,- };-}diff --git a/packages/core/src/Calendar/index.ts b/packages/core/src/Calendar/index.tsindex 92f76874da..41c95d653a 100644--- a/packages/core/src/Calendar/index.ts+++ b/packages/core/src/Calendar/index.ts@@ -26,7 +26,6 @@ export {useCalendarDays,useCalendarConstraints,useCalendarNavigation,- useCalendarRovingTabindex,} from './hooks';export type {CalendarDay,@@ -36,8 +35,6 @@ export type {UseCalendarConstraintsReturn,UseCalendarNavigationOptions,UseCalendarNavigationReturn,- UseCalendarRovingTabindexOptions,- UseCalendarRovingTabindexReturn,} from './hooks';// Re-export calendar-specific utilities for advanced usagediff --git a/packages/core/src/hooks/useGridFocus.doc.mjs b/packages/core/src/hooks/useGridFocus.doc.mjsindex 4682a45ed0..23199aa686 100644--- a/packages/core/src/hooks/useGridFocus.doc.mjs+++ b/packages/core/src/hooks/useGridFocus.doc.mjs@@ -21,10 +21,22 @@ export const docs = {{name: 'options.cellSelector',type: 'string',- description: 'Selector for focusable cells within the grid.',+ description: 'Selector for cells within the grid. Should match ALL cell positions in DOM order (including disabled/empty) so grid geometry is preserved.',default: "'button:not([disabled]), [tabindex]:not([tabindex=\"-1\"])'",required: false,},+ {+ name: 'options.isCellFocusable',+ type: '(cell: HTMLElement) => boolean',+ description: 'Predicate for whether a matched cell can receive focus. Omit to treat every matched cell as focusable.',+ required: false,+ },+ {+ name: 'options.getFocusTarget',+ type: '(cell: HTMLElement) => HTMLElement | null',+ description: 'Resolves the element to focus for a cell, e.g. a button inside a role="gridcell" wrapper. Omit to focus the cell itself.',+ required: false,+ },{name: 'options.onNavigateBefore',type: '(column: number, offset: number) => void',@@ -49,6 +61,20 @@ export const docs = {description: 'Callback for Page Down key (e.g., navigate to next month in calendars).',required: false,},+ {+ name: 'options.isRtl',+ type: 'boolean',+ description: 'Swap ArrowLeft/ArrowRight so horizontal navigation follows visual direction in right-to-left contexts.',+ default: 'false',+ required: false,+ },+ {+ name: 'options.hasRovingTabIndex',+ type: 'boolean',+ description: 'Own a single roving tab stop across the grid: one focusable cell (its resolved focus target) carries tabindex="0", the rest -1. Stamped/repaired on render and moved with arrow navigation. Attach the returned handleFocus to the container onFocus.',+ default: 'false',+ required: false,+ },],returns: [{@@ -61,6 +87,11 @@ export const docs = {type: '(e: React.KeyboardEvent) => void',description: 'Key down handler to attach to the grid container.',},+ {+ name: 'handleFocus',+ type: '(e: React.FocusEvent) => void',+ description: 'Focus handler for the grid container. Keeps the roving tab stop in sync when hasRovingTabIndex is enabled; a no-op otherwise, so always safe to attach.',+ },{name: 'focusCell',type: '(index: number) => void',@@ -83,6 +114,7 @@ export const docs = {bestPractices: [{ guidance: true, description: 'Use for calendar date grids: wire onPageUp/onPageDown to month navigation and onNavigateBefore/onNavigateAfter for cross-month arrow key navigation.' },{ guidance: true, description: 'Attach both gridRef and handleKeyDown to the grid container element.' },+ { guidance: true, description: 'For roving-tabindex grids (e.g. Calendar), set hasRovingTabIndex: true and attach handleFocus to the container onFocus; seed one focus target with tabindex=0 and the hook repairs and moves it.' },{ guidance: false, description: 'Use for simple linear lists; prefer useListFocus for 1D navigation.' },],},@@ -99,15 +131,20 @@ export const docsDense = {paramDescriptions: {options: 'config for grid focus behavior.','options.columns': '# columns in grid. Used for up/down navigation (moves by this many cells).',- 'options.cellSelector': 'selector for focusable cells in grid.',+ 'options.cellSelector': 'selector for grid cells in DOM order (incl. disabled/empty) so geometry is preserved.',+ 'options.isCellFocusable': 'predicate for whether a matched cell can take focus. Omit = all focusable.',+ 'options.getFocusTarget': 'resolve element to focus for a cell (e.g. button inside gridcell wrapper). Omit = focus the cell.','options.onNavigateBefore': 'callback when navigation would go before first cell. Receives column index + offset (1 for horizontal, columns for vertical).','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.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: {gridRef: 'ref to attach to grid container element.',handleKeyDown: 'key down handler for grid container.',+ handleFocus: 'focus handler for grid container; syncs roving tab stop when hasRovingTabIndex on, else no-op.',focusCell: 'focus specific cell by index (clamped to valid range).',focusFirst: 'focus first focusable cell in grid.',focusLast: 'focus last focusable cell in grid.',@@ -118,6 +155,7 @@ export const docsDense = {bestPractices: [{ guidance: true, description: 'Use for calendar date grids: wire onPageUp/onPageDown to month navigation + onNavigateBefore/onNavigateAfter for cross-month arrow key navigation.' },{ guidance: true, description: 'Attach both gridRef + handleKeyDown to grid container element.' },+ { guidance: true, description: 'For roving-tabindex grids (e.g. Calendar): hasRovingTabIndex: true + attach handleFocus to onFocus; seed one focus target tabindex=0, hook repairs + moves it.' },{ guidance: false, description: 'Use for simple linear lists; prefer useListFocus for 1D navigation.' },],},diff --git a/packages/core/src/hooks/useGridFocus.test.tsx b/packages/core/src/hooks/useGridFocus.test.tsxnew file mode 100644index 0000000000..67e6262c51--- /dev/null+++ b/packages/core/src/hooks/useGridFocus.test.tsx@@ -0,0 +1,132 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useGridFocus.test.tsx+ * @input Uses vitest, @testing-library/react, useGridFocus hook+ * @output Unit tests for useGridFocus roving tabindex + RTL navigation+ * @position Testing; validates useGridFocus.ts roving-tabindex ownership+ *+ * SYNC: When useGridFocus.ts changes, update tests to match new behavior+ */++import {describe, it, expect} from 'vitest';+import {render, screen, fireEvent} from '@testing-library/react';+import {useGridFocus} from './useGridFocus';++const NO_DISABLED: number[] = [];++/**+ * A 3x3 grid of cells shaped like Calendar: each `role="gridcell"` div wraps a+ * focusable `<button>` (the focus target). `seed` marks which button starts+ * tabbable (mirrors Calendar seeding the selected/today/first-enabled day).+ */+function Grid({+ disabled = NO_DISABLED,+ seed = 0,+ ...opts+}: {+ disabled?: number[];+ seed?: number;+} & Partial<Parameters<typeof useGridFocus>[0]>) {+ const {gridRef, handleKeyDown, handleFocus} = useGridFocus<HTMLDivElement>({+ columns: 3,+ cellSelector: '[role="gridcell"]',+ isCellFocusable: cell =>+ cell.querySelector('button:not([disabled])') !== null,+ getFocusTarget: cell => cell.querySelector<HTMLElement>('button'),+ hasRovingTabIndex: true,+ ...opts,+ });+ return (+ <div+ ref={gridRef}+ role="grid"+ onKeyDown={handleKeyDown}+ onFocus={handleFocus}>+ {Array.from({length: 9}, (_, i) => (+ <div role="gridcell" key={i}>+ <button+ type="button"+ disabled={disabled.includes(i)}+ tabIndex={i === seed ? 0 : -1}+ data-testid={`cell-${i}`}>+ {i}+ </button>+ </div>+ ))}+ </div>+ );+}++describe('useGridFocus roving tabindex (hasRovingTabIndex)', () => {+ it('honors the seeded tab stop and stamps -1 on the rest', () => {+ render(<Grid seed={4} />);+ expect(screen.getByTestId('cell-4')).toHaveAttribute('tabindex', '0');+ expect(screen.getByTestId('cell-0')).toHaveAttribute('tabindex', '-1');+ expect(screen.getByTestId('cell-8')).toHaveAttribute('tabindex', '-1');+ });++ it('repairs to the first focusable cell when no cell is seeded', () => {+ render(<Grid seed={-1} />);+ expect(screen.getByTestId('cell-0')).toHaveAttribute('tabindex', '0');+ expect(screen.getByTestId('cell-1')).toHaveAttribute('tabindex', '-1');+ });++ it('promotes the first ENABLED cell when the seed is disabled', () => {+ render(<Grid seed={-1} disabled={[0, 1]} />);+ expect(screen.getByTestId('cell-2')).toHaveAttribute('tabindex', '0');+ expect(screen.getByTestId('cell-0')).toHaveAttribute('tabindex', '-1');+ });++ it('ArrowRight moves the tab stop to the next cell', () => {+ render(<Grid seed={0} />);+ const grid = screen.getByRole('grid');+ screen.getByTestId('cell-0').focus();+ fireEvent.keyDown(grid, {key: 'ArrowRight'});+ expect(screen.getByTestId('cell-1')).toHaveFocus();+ expect(screen.getByTestId('cell-1')).toHaveAttribute('tabindex', '0');+ expect(screen.getByTestId('cell-0')).toHaveAttribute('tabindex', '-1');+ });++ it('ArrowDown moves the tab stop one row down', () => {+ render(<Grid seed={0} />);+ const grid = screen.getByRole('grid');+ screen.getByTestId('cell-0').focus();+ fireEvent.keyDown(grid, {key: 'ArrowDown'});+ expect(screen.getByTestId('cell-3')).toHaveFocus();+ expect(screen.getByTestId('cell-3')).toHaveAttribute('tabindex', '0');+ });++ it('handleFocus repairs the stop when the tabbable cell became disabled', () => {+ // Seed cell 0 as tabbable, then disable it and fire the container onFocus.+ // syncTabStops should promote the first still-focusable cell (cell 1).+ const {rerender} = render(<Grid seed={0} />);+ const grid = screen.getByRole('grid');+ expect(screen.getByTestId('cell-0')).toHaveAttribute('tabindex', '0');+ rerender(<Grid seed={-1} disabled={[0]} />);+ fireEvent.focus(grid);+ expect(screen.getByTestId('cell-1')).toHaveAttribute('tabindex', '0');+ expect(screen.getByTestId('cell-0')).toHaveAttribute('tabindex', '-1');+ });++ it('flips ArrowLeft/ArrowRight under RTL', () => {+ render(<Grid seed={1} isRtl />);+ const grid = screen.getByRole('grid');+ screen.getByTestId('cell-1').focus();+ // In RTL, ArrowLeft is "forward" (moves to the next cell in DOM order).+ fireEvent.keyDown(grid, {key: 'ArrowLeft'});+ expect(screen.getByTestId('cell-2')).toHaveFocus();+ });++ it('does not manage tabindex when hasRovingTabIndex is off', () => {+ render(<Grid seed={0} hasRovingTabIndex={false} />);+ // The seeded -1/0 values are left untouched (caller owns them), and+ // navigation still works without stamping.+ const grid = screen.getByRole('grid');+ screen.getByTestId('cell-0').focus();+ fireEvent.keyDown(grid, {key: 'ArrowRight'});+ expect(screen.getByTestId('cell-1')).toHaveFocus();+ // cell-1 kept its seeded -1; the hook did not promote it.+ expect(screen.getByTestId('cell-1')).toHaveAttribute('tabindex', '-1');+ });+});diff --git a/packages/core/src/hooks/useGridFocus.ts b/packages/core/src/hooks/useGridFocus.tsindex db8dcdf662..1498d5a4fd 100644--- a/packages/core/src/hooks/useGridFocus.ts+++ b/packages/core/src/hooks/useGridFocus.ts@@ -4,16 +4,17 @@/*** @file useGridFocus.ts- * @input Uses React useCallback, useRef+ * @input Uses React useCallback, useRef, useIsomorphicLayoutEffect* @output Exports useGridFocus hook for grid keyboard navigation* @position Core hook; used by Calendar for date grid navigation** SYNC: When modified, update:* - /packages/core/src/hooks/index.ts- * - /packages/core/src/hooks/useGridFocus.test.ts+ * - /packages/core/src/hooks/useGridFocus.test.tsx*/import {useCallback, useRef} from 'react';+import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';/*** Configuration for grid focus behavior@@ -83,6 +84,34 @@ export interface UseGridFocusOptions {* Callback for Page Down key (e.g., next month).*/onPageDown?: () => void;++ /**+ * 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+ */+ isRtl?: boolean;++ /**+ * Roving-tabindex ownership. When true, the hook manages a single tab stop+ * across the grid: exactly one focusable cell carries `tabindex="0"` and the+ * rest `tabindex="-1"`. The tab stop is stamped on mount and repaired+ * whenever cells mount/unmount or toggle focusable, and moves with arrow+ * navigation. Attach the returned {@link UseGridFocusReturn.handleFocus} to+ * the container's `onFocus` to keep the stop in sync after clicks or+ * programmatic focus.+ *+ * The tab stop is stamped on the resolved focus target (see+ * {@link UseGridFocusOptions.getFocusTarget}), not the cell wrapper, so it+ * works when the focusable element is a descendant of the cell. An existing+ * `tabindex="0"` on a focus target is honored, letting the caller seed which+ * cell is initially tabbable.+ *+ * When false (the default), the hook only *moves* focus (`.focus()`) and+ * never touches `tabindex` — the caller owns tab-stop management.+ * @default false+ */+ hasRovingTabIndex?: boolean;}/**@@ -99,6 +128,13 @@ export interface UseGridFocusReturn<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 cell by index.*/@@ -132,6 +168,12 @@ export interface UseGridFocusReturn<T extends HTMLElement = HTMLElement> {* non-focusable cell (per `isCellFocusable`), it continues in the same* direction to the next focusable cell.*+ * By default the hook only *moves* focus and leaves `tabindex` management to+ * the caller. Opt into {@link UseGridFocusOptions.hasRovingTabIndex} for a hook+ * that owns a single tab stop (roving tabindex) across the grid — stamping and+ * repairing it as cells mount/unmount or toggle focusable, and moving it with+ * arrow navigation.+ ** @example* ```* const {gridRef, handleKeyDown} = useGridFocus({@@ -144,6 +186,24 @@ export interface UseGridFocusReturn<T extends HTMLElement = HTMLElement> {* {cells.map(cell => <button role="gridcell">{cell}</button>)}* </div>* ```+ *+ * Roving-tabindex grid (e.g. a date picker where the cell is a wrapper around+ * a focusable button):+ *+ * @example+ * ```+ * const {gridRef, handleKeyDown, handleFocus} = useGridFocus({+ * columns: 7,+ * cellSelector: '[role="gridcell"]',+ * isCellFocusable: cell => cell.querySelector('button:not([disabled])') != null,+ * getFocusTarget: cell => cell.querySelector('button'),+ * hasRovingTabIndex: true,+ * });+ *+ * <div ref={gridRef} role="grid" onKeyDown={handleKeyDown} onFocus={handleFocus}>+ * {cells}+ * </div>+ * ```*/export function useGridFocus<T extends HTMLElement = HTMLElement>(options: UseGridFocusOptions,@@ -157,6 +217,8 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(onNavigateAfter,onPageUp,onPageDown,+ isRtl = false,+ hasRovingTabIndex = false,} = options;const gridRef = useRef<T>(null);@@ -200,21 +262,102 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>([getFocusTarget],);+ // --- Roving tabindex ownership (opt-in via `hasRovingTabIndex`) -------------++ /**+ * Set `tabindex` on an element, 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));+ }+ }, []);+/**- * Focus a cell (resolving to its focus target).+ * The resolved focus targets of all focusable cells, in DOM order. These are+ * the elements that carry the roving tab stop (a descendant of each cell when+ * `getFocusTarget` is provided, otherwise the cell itself).*/- const focusCellElement = useCallback(+ const getFocusTargets = useCallback((): HTMLElement[] => {+ return getCells()+ .filter(cell => cellFocusable(cell))+ .map(cell => resolveFocusTarget(cell))+ .filter((el): el is HTMLElement => el !== null);+ }, [getCells, cellFocusable, resolveFocusTarget]);++ /**+ * Stamp the roving tab stop: exactly one focus target is tabbable (0), the+ * rest are -1. Prefer keeping the currently-tabbable target if it is still+ * focusable; otherwise promote the first focusable one (tab-stop repair).+ */+ const syncTabStops = useCallback(() => {+ const targets = getFocusTargets();+ if (targets.length === 0) {+ return;+ }+ const current = targets.find(el => el.getAttribute('tabindex') === '0');+ const tabbable = current ?? targets[0];+ for (const el of targets) {+ setTabIndex(el, el === tabbable ? 0 : -1);+ }+ }, [getFocusTargets, setTabIndex]);++ // Keep the tab stop valid across renders (cells added/removed, focusability+ // toggled). Runs after every commit but only when roving tabindex is on.+ useIsomorphicLayoutEffect(() => {+ if (hasRovingTabIndex) {+ syncTabStops();+ }+ });++ /**+ * Move the roving tab stop so `target` becomes the sole tabbable focus+ * target, then focus it. No-op on tab stops unless roving tabindex is on.+ */+ const focusTarget = useCallback(+ (target: HTMLElement | null) => {+ if (!target) {+ return;+ }+ if (hasRovingTabIndex) {+ for (const el of getFocusTargets()) {+ setTabIndex(el, el === target ? 0 : -1);+ }+ }+ target.focus();+ },+ [hasRovingTabIndex, getFocusTargets, setTabIndex],+ );++ /**+ * Focus a cell by resolving and focusing its target, moving the roving tab+ * stop when enabled.+ */+ const focusCellWithStop = useCallback((cell: HTMLElement | undefined): boolean => {const target = resolveFocusTarget(cell);- if (target) {- target.focus();- return true;+ if (!target) {+ return false;}- return false;+ focusTarget(target);+ return true;},- [resolveFocusTarget],+ [resolveFocusTarget, focusTarget],);+ /**+ * 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]);+/*** Get the currently focused cell index within the full cell set.*/@@ -261,10 +404,10 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(target = findFocusableInDirection(cells, clampedIndex, -1);}if (target !== -1) {- focusCellElement(cells[target]);+ focusCellWithStop(cells[target]);}},- [getCells, findFocusableInDirection, focusCellElement],+ [getCells, findFocusableInDirection, focusCellWithStop],);/**@@ -274,9 +417,9 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(const cells = getCells();const index = findFocusableInDirection(cells, 0, 1);if (index !== -1) {- focusCellElement(cells[index]);+ focusCellWithStop(cells[index]);}- }, [getCells, findFocusableInDirection, focusCellElement]);+ }, [getCells, findFocusableInDirection, focusCellWithStop]);/*** Focus the last focusable cell.@@ -285,9 +428,9 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(const cells = getCells();const index = findFocusableInDirection(cells, cells.length - 1, -1);if (index !== -1) {- focusCellElement(cells[index]);+ focusCellWithStop(cells[index]);}- }, [getCells, findFocusableInDirection, focusCellElement]);+ }, [getCells, findFocusableInDirection, focusCellWithStop]);/*** Handle keyboard navigation.@@ -310,12 +453,23 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(let handled = true;- switch (e.key) {+ // In RTL, ArrowLeft/ArrowRight are swapped so horizontal navigation+ // follows visual direction. Vertical keys (Up/Down) are unaffected.+ let key = e.key;+ if (isRtl) {+ if (key === 'ArrowLeft') {+ key = 'ArrowRight';+ } else if (key === 'ArrowRight') {+ key = 'ArrowLeft';+ }+ }++ switch (key) {case 'ArrowRight': {// Move right, skipping non-focusable cells in the same direction.const target = findFocusableInDirection(cells, currentIndex + 1, 1);if (target !== -1) {- focusCellElement(cells[target]);+ focusCellWithStop(cells[target]);} else {onNavigateAfter?.((currentCol + 1) % columns, 1);}@@ -325,7 +479,7 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(case 'ArrowLeft': {const target = findFocusableInDirection(cells, currentIndex - 1, -1);if (target !== -1) {- focusCellElement(cells[target]);+ focusCellWithStop(cells[target]);} else {onNavigateBefore?.(currentCol === 0 ? columns - 1 : currentCol - 1,@@ -345,7 +499,7 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(columns,);if (target !== -1) {- focusCellElement(cells[target]);+ focusCellWithStop(cells[target]);} else {onNavigateAfter?.(currentCol, columns);}@@ -363,7 +517,7 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(-columns,);if (target !== -1) {- focusCellElement(cells[target]);+ focusCellWithStop(cells[target]);} else {onNavigateBefore?.(currentCol, columns);}@@ -383,7 +537,7 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(const rowEnd = Math.min(rowStart + columns - 1, cells.length - 1);const target = findFocusableInDirection(cells, rowStart, 1);if (target !== -1 && target <= rowEnd) {- focusCellElement(cells[target]);+ focusCellWithStop(cells[target]);}}break;@@ -398,7 +552,7 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(const rowEnd = Math.min(rowStart + columns - 1, cells.length - 1);const target = findFocusableInDirection(cells, rowEnd, -1);if (target !== -1 && target >= rowStart) {- focusCellElement(cells[target]);+ focusCellWithStop(cells[target]);}}break;@@ -423,11 +577,12 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>([columns,findFocusableInDirection,- focusCellElement,+ focusCellWithStop,focusFirst,focusLast,getCells,getCurrentIndex,+ isRtl,onNavigateAfter,onNavigateBefore,onPageDown,@@ -438,6 +593,7 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(return {gridRef,handleKeyDown,+ handleFocus,focusCell,focusFirst,focusLast,