Skip to content

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

TypeScript

fix(calendar): valid APG grid structure + correct arrow nav with disabled days (complex-2, complex-3) (#3416)

Cindy Zhanga361de369a7d
diff --git a/.changeset/calendar-grid-structure.md b/.changeset/calendar-grid-structure.md
new file mode 100644
index 0000000000..c4a514eb66
--- /dev/null
+++ b/.changeset/calendar-grid-structure.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Calendar: the month view now uses a valid ARIA grid structure — the weekday names are `columnheader` cells inside the `grid`, each week is a `row` whose direct children are `gridcell`s, and week-number cells are `rowheader`s. Arrow-key navigation now lands on the correct dates when some days are disabled (via `min`/`max`/`dateConstraints`): moving up/down keeps the true 7-column geometry and skips disabled days to the same weekday, instead of shifting to the wrong weekday. (#3343)
+@cixzhang
diff --git a/packages/core/src/Calendar/Calendar.test.tsx b/packages/core/src/Calendar/Calendar.test.tsx
index 19ae547579..bbbfac927f 100644
--- a/packages/core/src/Calendar/Calendar.test.tsx
+++ b/packages/core/src/Calendar/Calendar.test.tsx
@@ -10,19 +10,21 @@
*/
import {describe, it, expect, vi} from 'vitest';
-import {act, render, screen} from '@testing-library/react';
+import {act, render, screen, within} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {Calendar} from './Calendar';
import type {CalendarHandle} from './Calendar';
/**
* Helper to find a day button by its day number.
- * Day buttons have aria-labels like "Thursday, January 15, 2026".
+ * Day buttons are native <button> elements with aria-labels like
+ * "Thursday, January 15, 2026". Each button is the sole child of a
+ * role="gridcell" wrapper.
*/
function getDayButton(day: number, month = 'January', year = 2026) {
// Match the full date pattern with the day number
const pattern = new RegExp(`${month}\\s+${day},\\s+${year}`);
- return screen.getByRole('gridcell', {name: pattern});
+ return screen.getByRole('button', {name: pattern});
}
describe('Calendar', () => {
@@ -323,6 +325,75 @@ describe('Calendar', () => {
expect(screen.getAllByRole('gridcell').length).toBeGreaterThan(0);
});
+ it('renders a valid APG grid: one grid, header row of columnheaders inside it, week rows of gridcells', () => {
+ render(<Calendar focusDate="2026-01-01" />);
+
+ const grids = screen.getAllByRole('grid');
+ expect(grids.length).toBe(1);
+ const grid = grids[0];
+
+ // The columnheaders live INSIDE the grid.
+ const columnHeaders = screen.getAllByRole('columnheader');
+ expect(columnHeaders.length).toBe(7);
+ for (const header of columnHeaders) {
+ expect(grid.contains(header)).toBe(true);
+ }
+
+ // The grid's rows: first is the header row of columnheaders, the rest are
+ // week rows whose direct children are gridcells.
+ const rows = within(grid).getAllByRole('row');
+ // 1 header row + 6 week rows (fixed 6-row grid).
+ expect(rows.length).toBe(7);
+
+ const [headerRow, ...weekRows] = rows;
+
+ // Header row's direct children are the 7 columnheaders.
+ const headerChildren = Array.from(headerRow.children);
+ const headerColHeaders = headerChildren.filter(
+ child => child.getAttribute('role') === 'columnheader',
+ );
+ expect(headerColHeaders.length).toBe(7);
+
+ // Each week row's direct children are gridcells (7 per row).
+ for (const row of weekRows) {
+ const gridcellChildren = Array.from(row.children).filter(
+ child => child.getAttribute('role') === 'gridcell',
+ );
+ expect(gridcellChildren.length).toBe(7);
+ }
+ });
+
+ it('renders week-number cells as rowheader when hasWeekNumbers is set', () => {
+ render(<Calendar hasWeekNumbers focusDate="2026-01-01" />);
+
+ const grid = screen.getByRole('grid');
+ const rowHeaders = within(grid).getAllByRole('rowheader');
+ // One rowheader (week number) per week row.
+ expect(rowHeaders.length).toBeGreaterThanOrEqual(5);
+ // Week numbers are numeric.
+ for (const header of rowHeaders) {
+ expect(header.textContent).toMatch(/^\d+$/);
+ }
+ });
+
+ it('gridcell wrappers are direct children of week rows, and the button is inside the gridcell', () => {
+ render(<Calendar focusDate="2026-01-01" />);
+
+ const grid = screen.getByRole('grid');
+ const gridcells = within(grid).getAllByRole('gridcell');
+ for (const cell of gridcells) {
+ // The gridcell's parent is a role="row".
+ const parent = cell.parentElement;
+ expect(parent?.getAttribute('role')).toBe('row');
+ // The day button (if present) is a descendant of the gridcell.
+ const button = cell.querySelector('button');
+ if (button) {
+ expect(cell.contains(button)).toBe(true);
+ expect(button).not.toHaveAttribute('role', 'gridcell');
+ }
+ }
+ });
+
it('has navigation buttons with accessible labels', () => {
render(<Calendar />);
@@ -354,7 +425,7 @@ describe('Calendar', () => {
// Focus Jan 28
const day28 = getDayButton(28);
await user.click(day28);
- day28.querySelector('button')?.focus();
+ day28.focus();
// Press ArrowDown — should move to Feb 4 (+7 days), not Feb 28
await user.keyboard('{ArrowDown}');
@@ -364,6 +435,53 @@ describe('Calendar', () => {
expect(focusedElement).toHaveAttribute('data-date', '2026-02-04');
});
+ it('ArrowDown lands on the same weekday +7 days even when earlier days are disabled (complex-2)', async () => {
+ const user = userEvent.setup();
+
+ // min disables Jan 1–4 (HTML-disabled). Jan 8 is a Thursday; ArrowDown must
+ // land on Jan 15 (the same weekday, +7 days), not a shifted date caused by
+ // the removed enabled cells.
+ render(<Calendar focusDate="2026-01-01" min="2026-01-05" />);
+
+ const day1 = getDayButton(1);
+ expect(day1).toBeDisabled();
+
+ const day8 = getDayButton(8);
+ day8.focus();
+
+ await user.keyboard('{ArrowDown}');
+ expect(document.activeElement).toHaveAttribute('data-date', '2026-01-15');
+
+ await user.keyboard('{ArrowDown}');
+ expect(document.activeElement).toHaveAttribute('data-date', '2026-01-22');
+ });
+
+ it('ArrowUp skips a disabled cell in the same column to the next enabled row (complex-2)', async () => {
+ const user = userEvent.setup();
+
+ // max disables Jan 22 onward. Focus Feb 5 handling is out of scope; instead
+ // use dateConstraints to disable a single mid-grid day and verify column
+ // geometry is preserved (ArrowUp from Jan 15 skips disabled Jan 8 → Jan 1).
+ const disableJan8 = (date: Date) =>
+ !(
+ date.getFullYear() === 2026 &&
+ date.getMonth() === 0 &&
+ date.getDate() === 8
+ );
+
+ render(<Calendar focusDate="2026-01-01" dateConstraints={[disableJan8]} />);
+
+ const day8 = getDayButton(8);
+ expect(day8).toBeDisabled();
+
+ const day15 = getDayButton(15);
+ day15.focus();
+
+ // ArrowUp: same column one row up is Jan 8 (disabled) → skip to Jan 1.
+ await user.keyboard('{ArrowUp}');
+ expect(document.activeElement).toHaveAttribute('data-date', '2026-01-01');
+ });
+
it('prev button is disabled when focusDate month contains min', () => {
render(<Calendar focusDate="2026-01-01" min="2026-01-15" />);
diff --git a/packages/core/src/Calendar/Calendar.tsx b/packages/core/src/Calendar/Calendar.tsx
index e27967d857..01992cdc77 100644
--- a/packages/core/src/Calendar/Calendar.tsx
+++ b/packages/core/src/Calendar/Calendar.tsx
@@ -621,11 +621,22 @@ function MonthGrid({
}
}, [getFocusedDate, onNavigateNext]);
- // Grid focus navigation
+ // Grid focus navigation.
+ //
+ // The hook enumerates ALL grid cells (every `role="gridcell"`, including
+ // disabled days and empty placeholder cells) so the true 7-column geometry is
+ // preserved. `isCellFocusable` / `getFocusTarget` tell the hook which cells
+ // can take focus (those containing an enabled day button) and where to send
+ // 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: 'button:not([disabled])',
+ cellSelector: '[role="gridcell"]',
+ isCellFocusable: cell =>
+ cell.querySelector('button:not([disabled])') !== null,
+ getFocusTarget: cell => cell.querySelector<HTMLElement>('button'),
onNavigateBefore: handleNavigatePrevious,
onNavigateAfter: handleNavigateNext,
onPageUp: handlePageUp,
@@ -704,31 +715,7 @@ function MonthGrid({
return (
<div {...stylex.props(monthGridStyles.monthGrid)}>
- {/* Day names header */}
- <div
- {...stylex.props(
- monthGridStyles.weekHeader,
- hasWeekNumbers && monthGridStyles.weekHeaderWithNumbers,
- )}>
- {hasWeekNumbers && (
- <div
- {...stylex.props(
- monthGridStyles.dayName,
- monthGridStyles.weekNumberHeader,
- )}
- />
- )}
- {dayNames.map(name => (
- <div
- key={name}
- role="columnheader"
- {...stylex.props(monthGridStyles.dayName)}>
- {name}
- </div>
- ))}
- </div>
-
- {/* Days grid */}
+ {/* Days grid (APG grid: header row of columnheaders + week rows) */}
<div
ref={gridRef}
role="grid"
@@ -738,6 +725,27 @@ function MonthGrid({
monthGridStyles.daysGrid,
hasWeekNumbers && monthGridStyles.daysGridWithNumbers,
)}>
+ {/* Day names header row (columnheaders live inside the grid). Uses the
+ same display:contents row so its cells align to the grid columns. */}
+ <div role="row" {...stylex.props(monthGridStyles.weekRow)}>
+ {hasWeekNumbers && (
+ <div
+ {...stylex.props(
+ monthGridStyles.dayName,
+ monthGridStyles.weekNumberHeader,
+ )}
+ />
+ )}
+ {dayNames.map(name => (
+ <div
+ key={name}
+ role="columnheader"
+ {...stylex.props(monthGridStyles.dayName)}>
+ {name}
+ </div>
+ ))}
+ </div>
+
{weeks.map(week => {
const weekDate = week.find(d => !d.isOutside)?.date || week[0].date;
const weekNum = plainDateGetWeekNumber(weekDate);
@@ -748,7 +756,9 @@ function MonthGrid({
role="row"
{...stylex.props(monthGridStyles.weekRow)}>
{hasWeekNumbers && (
- <div {...stylex.props(monthGridStyles.weekNumber)}>
+ <div
+ role="rowheader"
+ {...stylex.props(monthGridStyles.weekNumber)}>
{weekNum}
</div>
)}
@@ -819,7 +829,9 @@ function DayCell({
const {date, isOutside, dayNumber} = day;
if (isOutside && !hasOutsideDays) {
- return <div {...stylex.props(dayCellStyles.cell)} />;
+ // Empty placeholder cell — still a gridcell so the grid geometry stays a
+ // clean 7-per-row set for keyboard navigation.
+ return <div role="gridcell" {...stylex.props(dayCellStyles.cell)} />;
}
const state = computeDayCellState({
@@ -841,7 +853,7 @@ function DayCell({
const previewRounding = computePreviewRounding(state);
return (
- <div {...stylex.props(dayCellStyles.cell)}>
+ <div role="gridcell" {...stylex.props(dayCellStyles.cell)}>
{/* Range background */}
{state.isInRange && (
<div
@@ -879,7 +891,6 @@ function DayCell({
{/* Day button */}
<button
type="button"
- role="gridcell"
data-date={day.iso}
aria-label={plainDateFormat(date, DATE_FORMAT_WITH_WEEKDAY)}
aria-selected={state.isSelected || state.isInRange || undefined}
diff --git a/packages/core/src/Calendar/styles.ts b/packages/core/src/Calendar/styles.ts
index 61209f017c..ddd8af3a97 100644
--- a/packages/core/src/Calendar/styles.ts
+++ b/packages/core/src/Calendar/styles.ts
@@ -78,17 +78,12 @@ export const monthGridStyles = stylex.create({
monthGrid: {
flex: '1 1 0',
},
- weekHeader: {
- display: 'grid',
- gridTemplateColumns: 'repeat(7, 1fr)',
- marginBottom: spacingVars['--spacing-1'],
- },
- weekHeaderWithNumbers: {
- gridTemplateColumns: 'auto repeat(7, 1fr)',
- },
dayName: {
width: sizeVars['--size-element-md'],
- height: sizeVars['--size-element-md'],
+ // Restores the small gap the standalone header used to have below it.
+ height: `calc(${sizeVars['--size-element-md']} + ${spacingVars['--spacing-1']})`,
+ paddingBottom: spacingVars['--spacing-1'],
+ boxSizing: 'border-box',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
diff --git a/packages/core/src/hooks/useGridFocus.ts b/packages/core/src/hooks/useGridFocus.ts
index afce11529e..db8dcdf662 100644
--- a/packages/core/src/hooks/useGridFocus.ts
+++ b/packages/core/src/hooks/useGridFocus.ts
@@ -26,11 +26,38 @@ export interface UseGridFocusOptions {
columns: number;
/**
- * Selector for focusable cells within the grid.
+ * Selector for cells within the grid. This should match ALL grid cell
+ * positions in DOM order (including disabled/empty ones) so the hook can
+ * preserve the true grid geometry when computing rows and columns.
+ *
+ * Use {@link UseGridFocusOptions.isCellFocusable} to distinguish cells that
+ * can receive focus from those that cannot (disabled or empty). Navigation
+ * moves to a target row/column and, if that cell is not focusable, continues
+ * in the same direction to the next focusable cell — the geometry is never
+ * collapsed to only-focusable cells.
+ *
* @default 'button:not([disabled]), [tabindex]:not([tabindex="-1"])'
*/
cellSelector?: string;
+ /**
+ * Predicate determining whether a cell matched by {@link cellSelector} can
+ * receive focus. When omitted, every matched cell is considered focusable
+ * (backwards-compatible behavior).
+ *
+ * @param cell A cell element matched by `cellSelector`.
+ */
+ isCellFocusable?: (cell: HTMLElement) => boolean;
+
+ /**
+ * Resolves the element to focus for a given cell. Useful when the cell is a
+ * wrapper element (e.g. a `role="gridcell"` div) whose focusable content is a
+ * descendant (e.g. a `<button>`). When omitted, the cell itself is focused.
+ *
+ * @param cell A cell element matched by `cellSelector`.
+ */
+ getFocusTarget?: (cell: HTMLElement) => HTMLElement | null;
+
/**
* Callback when navigation would go before the first cell.
* Useful for navigating to previous month in calendars.
@@ -99,6 +126,12 @@ export interface UseGridFocusReturn<T extends HTMLElement = HTMLElement> {
* - Ctrl+End: Move to last cell in grid
* - Page Up/Down: Custom callbacks (e.g., month navigation)
*
+ * The hook enumerates ALL cells matched by `cellSelector` in DOM order and
+ * computes row/column over that full set, preserving the true grid geometry
+ * even when some cells are disabled or empty. When a move lands on a
+ * non-focusable cell (per `isCellFocusable`), it continues in the same
+ * direction to the next focusable cell.
+ *
* @example
* ```
* const {gridRef, handleKeyDown} = useGridFocus({
@@ -118,6 +151,8 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(
const {
columns,
cellSelector = 'button:not([disabled]), [tabindex]:not([tabindex="-1"])',
+ isCellFocusable,
+ getFocusTarget,
onNavigateBefore,
onNavigateAfter,
onPageUp,
@@ -127,7 +162,8 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(
const gridRef = useRef<T>(null);
/**
- * Get all focusable cells in the grid.
+ * Get all cells in the grid, in DOM order. This includes disabled and empty
+ * cells so the true grid geometry is preserved.
*/
const getCells = useCallback((): HTMLElement[] => {
if (!gridRef.current) {
@@ -139,7 +175,48 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(
}, [cellSelector]);
/**
- * Get the currently focused cell index.
+ * Whether a cell can receive focus.
+ */
+ const cellFocusable = useCallback(
+ (cell: HTMLElement | undefined): boolean => {
+ if (!cell) {
+ return false;
+ }
+ return isCellFocusable ? isCellFocusable(cell) : true;
+ },
+ [isCellFocusable],
+ );
+
+ /**
+ * Resolve the element that should actually receive focus for a cell.
+ */
+ const resolveFocusTarget = useCallback(
+ (cell: HTMLElement | undefined): HTMLElement | null => {
+ if (!cell) {
+ return null;
+ }
+ return getFocusTarget ? getFocusTarget(cell) : cell;
+ },
+ [getFocusTarget],
+ );
+
+ /**
+ * Focus a cell (resolving to its focus target).
+ */
+ const focusCellElement = useCallback(
+ (cell: HTMLElement | undefined): boolean => {
+ const target = resolveFocusTarget(cell);
+ if (target) {
+ target.focus();
+ return true;
+ }
+ return false;
+ },
+ [resolveFocusTarget],
+ );
+
+ /**
+ * Get the currently focused cell index within the full cell set.
*/
const getCurrentIndex = useCallback((): number => {
const cells = getCells();
@@ -148,32 +225,28 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(
}, [getCells]);
/**
- * Focus a cell by index, clamping to valid range.
- * Returns true if focus was successful, false if navigation callback was triggered.
+ * Find the next focusable cell starting at `startIndex`, moving by `step`.
+ * Returns the index of the focusable cell, or -1 if none exists in range
+ * (i.e. we ran off the start/end of the grid).
*/
- const focusCellInternal = useCallback(
- (index: number, currentColumn: number, offset: number) => {
- const cells = getCells();
- if (cells.length === 0) {
- return;
- }
-
- if (index < 0) {
- onNavigateBefore?.(currentColumn, offset);
- return;
- }
- if (index >= cells.length) {
- onNavigateAfter?.(currentColumn, offset);
- return;
+ const findFocusableInDirection = useCallback(
+ (cells: HTMLElement[], startIndex: number, step: number): number => {
+ let index = startIndex;
+ while (index >= 0 && index < cells.length) {
+ if (cellFocusable(cells[index])) {
+ return index;
+ }
+ index += step;
}
-
- cells[index]?.focus();
+ return -1;
},
- [getCells, onNavigateBefore, onNavigateAfter],
+ [cellFocusable],
);
/**
- * Public focusCell that doesn't trigger navigation callbacks
+ * Focus a cell by index, clamping to valid range. Skips non-focusable cells
+ * toward the nearest edge. Used by public focus helpers (no navigation
+ * callbacks).
*/
const focusCell = useCallback(
(index: number) => {
@@ -182,38 +255,55 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(
return;
}
const clampedIndex = Math.max(0, Math.min(index, cells.length - 1));
- cells[clampedIndex]?.focus();
+ // Prefer the requested cell; otherwise search forward, then backward.
+ let target = findFocusableInDirection(cells, clampedIndex, 1);
+ if (target === -1) {
+ target = findFocusableInDirection(cells, clampedIndex, -1);
+ }
+ if (target !== -1) {
+ focusCellElement(cells[target]);
+ }
},
- [getCells],
+ [getCells, findFocusableInDirection, focusCellElement],
);
/**
- * Focus the first cell.
+ * Focus the first focusable cell.
*/
const focusFirst = useCallback(() => {
const cells = getCells();
- cells[0]?.focus();
- }, [getCells]);
+ const index = findFocusableInDirection(cells, 0, 1);
+ if (index !== -1) {
+ focusCellElement(cells[index]);
+ }
+ }, [getCells, findFocusableInDirection, focusCellElement]);
/**
- * Focus the last cell.
+ * Focus the last focusable cell.
*/
const focusLast = useCallback(() => {
const cells = getCells();
- cells[cells.length - 1]?.focus();
- }, [getCells]);
+ const index = findFocusableInDirection(cells, cells.length - 1, -1);
+ if (index !== -1) {
+ focusCellElement(cells[index]);
+ }
+ }, [getCells, findFocusableInDirection, focusCellElement]);
/**
* Handle keyboard navigation.
*/
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
+ const cells = getCells();
+ if (cells.length === 0) {
+ return;
+ }
+
const currentIndex = getCurrentIndex();
if (currentIndex === -1) {
return;
}
- const cells = getCells();
const currentRow = Math.floor(currentIndex / columns);
const currentCol = currentIndex % columns;
const totalRows = Math.ceil(cells.length / columns);
@@ -221,65 +311,95 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(
let handled = true;
switch (e.key) {
- case 'ArrowRight':
- // Horizontal navigation: offset = 1
- focusCellInternal(currentIndex + 1, (currentCol + 1) % columns, 1);
+ 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]);
+ } else {
+ onNavigateAfter?.((currentCol + 1) % columns, 1);
+ }
break;
+ }
- case 'ArrowLeft':
- // Horizontal navigation: offset = 1
- focusCellInternal(
- currentIndex - 1,
- currentCol === 0 ? columns - 1 : currentCol - 1,
- 1,
- );
+ case 'ArrowLeft': {
+ const target = findFocusableInDirection(cells, currentIndex - 1, -1);
+ if (target !== -1) {
+ focusCellElement(cells[target]);
+ } else {
+ onNavigateBefore?.(
+ currentCol === 0 ? columns - 1 : currentCol - 1,
+ 1,
+ );
+ }
break;
+ }
- case 'ArrowDown':
- // Vertical navigation: offset = columns (7 for calendar)
+ case 'ArrowDown': {
if (currentRow < totalRows - 1) {
- const nextIndex = currentIndex + columns;
- if (nextIndex < cells.length) {
- focusCellInternal(nextIndex, currentCol, columns);
+ // Move to the same column one row down, then continue downward
+ // (by whole rows) to the next focusable cell in that column.
+ const target = findFocusableInDirection(
+ cells,
+ currentIndex + columns,
+ columns,
+ );
+ if (target !== -1) {
+ focusCellElement(cells[target]);
} else {
- // Last row might be partial, focus last cell
- focusCellInternal(cells.length - 1, currentCol, columns);
+ onNavigateAfter?.(currentCol, columns);
}
} else {
onNavigateAfter?.(currentCol, columns);
}
break;
+ }
- case 'ArrowUp':
- // Vertical navigation: offset = columns (7 for calendar)
+ case 'ArrowUp': {
if (currentRow > 0) {
- focusCellInternal(currentIndex - columns, currentCol, columns);
+ const target = findFocusableInDirection(
+ cells,
+ currentIndex - columns,
+ -columns,
+ );
+ if (target !== -1) {
+ focusCellElement(cells[target]);
+ } else {
+ onNavigateBefore?.(currentCol, columns);
+ }
} else {
onNavigateBefore?.(currentCol, columns);
}
break;
+ }
case 'Home':
if (e.ctrlKey || e.metaKey) {
- // Ctrl+Home: first cell in grid
+ // Ctrl+Home: first focusable cell in grid
focusFirst();
} else {
- // Home: first cell in current row
- focusCell(currentRow * columns);
+ // Home: first focusable cell in current row (searching rightward)
+ const rowStart = currentRow * columns;
+ const rowEnd = Math.min(rowStart + columns - 1, cells.length - 1);
+ const target = findFocusableInDirection(cells, rowStart, 1);
+ if (target !== -1 && target <= rowEnd) {
+ focusCellElement(cells[target]);
+ }
}
break;
case 'End':
if (e.ctrlKey || e.metaKey) {
- // Ctrl+End: last cell in grid
+ // Ctrl+End: last focusable cell in grid
focusLast();
} else {
- // End: last cell in current row
- const rowEnd = Math.min(
- (currentRow + 1) * columns - 1,
- cells.length - 1,
- );
- focusCell(rowEnd);
+ // End: last focusable cell in current row (searching leftward)
+ const rowStart = currentRow * columns;
+ const rowEnd = Math.min(rowStart + columns - 1, cells.length - 1);
+ const target = findFocusableInDirection(cells, rowEnd, -1);
+ if (target !== -1 && target >= rowStart) {
+ focusCellElement(cells[target]);
+ }
}
break;
@@ -302,8 +422,8 @@ export function useGridFocus<T extends HTMLElement = HTMLElement>(
},
[
columns,
- focusCell,
- focusCellInternal,
+ findFocusableInDirection,
+ focusCellElement,
focusFirst,
focusLast,
getCells,