Skip to content

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

TypeScript

fix(Calendar): PageUp and PageDown move the focused day by a month (#7467)

Cindy Zhang666ad2f0e3e1
diff --git a/.changeset/calendar-page-keys.md b/.changeset/calendar-page-keys.md
new file mode 100644
index 0000000000..779aed247d
--- /dev/null
+++ b/.changeset/calendar-page-keys.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `Calendar`: PageUp and PageDown move the focused day by a month — into the month the grid shows, on the same day of the month where it exists — instead of by a week; a page from a borrowed adjacent-month day lands on that day of the month now shown rather than on the month's first day. With two months, a page or an arrow crossing a month edge from the first month now lands on the correct day (the second grid no longer overrides the first grid's target). An arrow or page past `min`/`max` changes nothing, and a page into a month with no enabled day keeps focus in the grid.
+
+@cixzhang
diff --git a/packages/core/src/Calendar/Calendar.spec.md b/packages/core/src/Calendar/Calendar.spec.md
index 69c695a038..6e76ce6ba8 100644
--- a/packages/core/src/Calendar/Calendar.spec.md
+++ b/packages/core/src/Calendar/Calendar.spec.md
@@ -90,13 +90,13 @@ Consumer migration instructions belong in consumer docs and release notes.
Draft requirements identify their basis so observed code is not mistaken for an
intentional decision. A `current` contract contains no unresolved rows.
-| ID | Candidate invariant | Basis | Draft review state |
-| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ------------------ |
-| FR1 | Each rendered month is one `role="grid"` named for its month and year, with a `columnheader` per weekday (and, with week numbers, a named `columnheader` above the `rowheader` column) and one `row` per week. | shipped source and focused tests | verify |
-| FR2 | At most one day button in each month's grid holds `tabIndex={0}`; every other day button in that grid is `-1`. | shipped `useGridFocus` behavior; Grid accessibility contract (pending) | verify |
-| FR3 | A disabled day (outside bounds or rejected by a constraint) stays in the grid, is exposed as disabled, and cannot be picked. | shipped source and focused tests | verify |
-| FR4 | In `range` mode the first pick starts the range and the second ends it, a second pick before the start swapping the two so the end never precedes the start; `minRangeSpan`/`maxRangeSpan` bound it. Escape, or picking the start day again when `minRangeSpan` is above 1, clears an in-progress range. | shipped source and focused tests | verify |
-| FR5 | Moving the focused day across a month boundary navigates the visible month so the focused day stays visible, except in a two-month Calendar, where focus can land in the second month's grid on the target or on its first day button that is not natively disabled, which can be an `aria-disabled` borrowed day (AR1); an arrow can also land on a borrowed adjacent-month day, which is exposed `aria-disabled` and cannot be picked. | shipped source and focused tests | verify |
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ------------------ |
+| FR1 | Each rendered month is one `role="grid"` named for its month and year, with a `columnheader` per weekday (and, with week numbers, a named `columnheader` above the `rowheader` column) and one `row` per week. | shipped source and focused tests | verify |
+| FR2 | At most one day button in each month's grid holds `tabIndex={0}`; every other day button in that grid is `-1`. | shipped `useGridFocus` behavior; Grid accessibility contract (pending) | verify |
+| FR3 | A disabled day (outside bounds or rejected by a constraint) stays in the grid, is exposed as disabled, and cannot be picked. | shipped source and focused tests | verify |
+| FR4 | In `range` mode the first pick starts the range and the second ends it, a second pick before the start swapping the two so the end never precedes the start; `minRangeSpan`/`maxRangeSpan` bound it. Escape, or picking the start day again when `minRangeSpan` is above 1, clears an in-progress range. | shipped source and focused tests | verify |
+| FR5 | Moving the focused day across a month boundary navigates the visible month so the focused day stays visible, in one month or two; an arrow can also land on a borrowed adjacent-month day, which is exposed `aria-disabled` and cannot be picked. | shipped source and focused tests | verify |
### Allowed variation
@@ -139,21 +139,17 @@ intentional decision. A `current` contract contains no unresolved rows.
enabled day gives it to the grid's first day button that is not natively
disabled, which can be a borrowed adjacent-month day, or to none.
ArrowLeft and ArrowRight move by a day following the reading direction,
- ArrowUp and ArrowDown by a week, Home and End to the first and last day of the
+ ArrowUp and ArrowDown by a week, Home and End to the first and last enabled day of the
week, PageUp and PageDown by a month, and Enter or Space picks the focused day;
- an arrow skips a day disabled by bounds or a constraint and continues in the
- same direction.
- Implementation gaps: PageUp and PageDown change the visible month but target
- the day a week away and, when that day is not shown, focus the first day
- button in the grid that is not natively disabled, which can be an
- adjacent-month day; the arrow keys, Home and End can focus a borrowed
+ an arrow skips a day disabled by a constraint and continues in the
+ same direction, crossing the month edge when it must; an arrow or Page key whose target
+ lies past `min` or `max` changes nothing and keeps focus where it is, and
+ so does an arrow whose direction has no enabled day within a year; a page
+ onto a day disabled by a constraint focuses that month's first enabled day
+ instead, and changes nothing when that month has no enabled day.
+ Implementation gap: the arrow keys, Home and End can focus a borrowed
adjacent-month day that is `aria-disabled`, because cell focusability checks
- only native `disabled`; and in a two-month Calendar, a key that changes the
- visible months can leave focus in the second month's grid — on its own
- button for the target day or, failing that, on its first day button that is
- not natively disabled, which can be an `aria-disabled` borrowed day that
- cannot be picked — instead of the target day, because each month grid falls
- back on its own.
+ only native `disabled`.
## Design relationships
@@ -196,10 +192,10 @@ button.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |
-| FR1–FR5 | `Calendar.test.tsx` structure ("renders a valid APG grid: one grid, header row of columnheaders inside it, week rows of gridcells", "with week numbers, the header row's corner cell is a named columnheader, so every row child is a grid cell"), selection ("handles reverse range selection (end before start)", "caps the range highlight next to a disabled mid-range day (#2715)", "Escape cancels range selection in progress", "clears the in-progress start when the anchor is clicked again"), bounds ("prev button is disabled when focusDate month contains min", "next button is disabled when focusDate month contains max"), and navigation ("navigates to next month", "calls onFocusDateChange when navigating") suites | single, range, two months, bounded | A missing header row, a reverse pick that does not swap, a range highlight that reaches a disabled day, or a Previous/Next button enabled past `min`/`max` fails. | `audit:Calendar/behavior` |
-| AR1 | `Calendar.test.tsx` ("has accessible grid structure", "sets aria-multiselectable on both grids in a two-month range view", "does not set aria-multiselectable in single mode", "announces the new month politely when clicking next", "displays day names") and `useGridFocus.test.tsx` ("ArrowDown moves the tab stop one row down", "flips ArrowLeft/ArrowRight under RTL"); `Calendar.test.tsx` "ArrowUp skips a disabled cell in the same column to the next enabled row (complex-2)" for the disabled-day skip; the at-most-one-Tab-stop-per-month (FR2), Home/End, Page and activation keys on Calendar itself under the Grid accessibility contract (`internal/a11y-spec`, pending) | LTR and RTL; month boundary; selected, today, disabled days | A day loses its role, name or state, two days in one month hold a Tab stop, or an arrow, Home/End, Page or activation key stops moving or picking. | `audit:Calendar/accessibility` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |
+| FR1–FR5 | `Calendar.test.tsx` structure ("renders a valid APG grid: one grid, header row of columnheaders inside it, week rows of gridcells", "with week numbers, the header row's corner cell is a named columnheader, so every row child is a grid cell"), selection ("handles reverse range selection (end before start)", "caps the range highlight next to a disabled mid-range day (#2715)", "Escape cancels range selection in progress", "clears the in-progress start when the anchor is clicked again"), bounds ("prev button is disabled when focusDate month contains min", "next button is disabled when focusDate month contains max"), and navigation ("navigates to next month", "calls onFocusDateChange when navigating") suites | single, range, two months, bounded | A missing header row, a reverse pick that does not swap, a range highlight that reaches a disabled day, or a Previous/Next button enabled past `min`/`max` fails. | `audit:Calendar/behavior` |
+| AR1 | `Calendar.test.tsx` ("has accessible grid structure", "sets aria-multiselectable on both grids in a two-month range view", "does not set aria-multiselectable in single mode", "announces the new month politely when clicking next", "displays day names") and `useGridFocus.test.tsx` ("ArrowDown moves the tab stop one row down", "flips ArrowLeft/ArrowRight under RTL"); `Calendar.test.tsx` "ArrowUp skips a disabled cell in the same column to the next enabled row (complex-2)" for the disabled-day skip; `Calendar.test.tsx` Page-key cases ("moves the focused day by a month with PageDown and PageUp, into the month now shown", "pages from a borrowed adjacent-month day onto the real day in the month already shown", "an arrow past max changes nothing and leaves no pending target behind", "a page into a month with no enabled day changes nothing and keeps focus", "a page onto a day disabled by a constraint moves the month and focuses its first enabled day", "a page whose target lies past max changes nothing and keeps focus", "in a two-month view a boundary blocks only out-of-range targets, not month movement", "in a two-month view PageDown from the second month moves both months and a later Next click selects no stale day"); the at-most-one-Tab-stop-per-month (FR2), Home/End and activation keys on Calendar itself under the Grid accessibility contract (`internal/a11y-spec`, pending) | LTR and RTL; month boundary; selected, today, disabled days | A day loses its role, name or state, two days in one month hold a Tab stop, or an arrow, Home/End, Page or activation key stops moving or picking. | `audit:Calendar/accessibility` |
## Decision log
diff --git a/packages/core/src/Calendar/Calendar.test.tsx b/packages/core/src/Calendar/Calendar.test.tsx
index 2bb78d31a6..30f0c9ca88 100644
--- a/packages/core/src/Calendar/Calendar.test.tsx
+++ b/packages/core/src/Calendar/Calendar.test.tsx
@@ -9,6 +9,7 @@
* SYNC: When Calendar.tsx changes, update tests accordingly
*/
+import {useState} from 'react';
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {act, render, screen, within, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -971,6 +972,389 @@ describe('Calendar', () => {
});
});
+ it('moves the focused day by a month with PageDown and PageUp, into the month now shown', async () => {
+ const user = userEvent.setup();
+ render(<Calendar focusDate="2026-01-31" />);
+
+ getDayButton(31).focus();
+ await user.keyboard('{PageDown}');
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('February 2026');
+ });
+ // A month, not a week: Jan 31 lands on the last day of February.
+ await waitFor(() => {
+ expect(document.activeElement).toHaveAttribute(
+ 'aria-label',
+ expect.stringMatching(/February 28, 2026/),
+ );
+ });
+
+ await user.keyboard('{PageUp}');
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('January 2026');
+ });
+ await waitFor(() => {
+ expect(document.activeElement).toHaveAttribute(
+ 'aria-label',
+ expect.stringMatching(/January 28, 2026/),
+ );
+ });
+ });
+
+ it("pages from the first of two months onto the right day, not the second grid's fallback", async () => {
+ const user = userEvent.setup();
+ render(<Calendar focusDate="2026-01-01" numberOfMonths={2} />);
+
+ getDayButton(15).focus();
+ await user.keyboard('{PageDown}');
+ await waitFor(() => {
+ expect(document.activeElement).toHaveAttribute(
+ 'aria-label',
+ expect.stringMatching(/February 15, 2026/),
+ );
+ });
+ expect(document.activeElement).not.toHaveAttribute('aria-disabled');
+
+ await user.keyboard('{PageUp}');
+ await waitFor(() => {
+ expect(document.activeElement).toHaveAttribute(
+ 'aria-label',
+ expect.stringMatching(/January 15, 2026/),
+ );
+ });
+ expect(document.activeElement).not.toHaveAttribute('aria-disabled');
+ });
+
+ it('pages from a borrowed adjacent-month day onto the real day in the month already shown', async () => {
+ const user = userEvent.setup();
+ render(<Calendar focusDate="2026-01-01" />);
+
+ // Home from January 1 lands on the borrowed December 28 in the first row.
+ getDayButton(1).focus();
+ await user.keyboard('{Home}');
+ expect(document.activeElement).toHaveAttribute('data-date', '2025-12-28');
+
+ // PageDown targets January 28, which January's grid already shows: no
+ // month change, focus moves there and never to a borrowed copy.
+ await user.keyboard('{PageDown}');
+ await waitFor(() => {
+ expect(document.activeElement).toHaveAttribute(
+ 'data-date',
+ '2026-01-28',
+ );
+ });
+ expect(screen.getByRole('grid')).toHaveAttribute(
+ 'aria-label',
+ 'January 2026',
+ );
+ expect(document.activeElement).not.toHaveAttribute('aria-disabled');
+ });
+
+ it('an arrow past max changes nothing and leaves no pending target behind', async () => {
+ const user = userEvent.setup();
+ const {rerender} = render(
+ <Calendar focusDate="2026-01-01" max="2026-01-31" />,
+ );
+ const last = getDayButton(31);
+ last.focus();
+ await user.keyboard('{ArrowRight}');
+ // January stays, focus stays on the max day.
+ expect(screen.getByRole('button', {name: 'Next month'})).toBeDisabled();
+ expect(document.activeElement).toBe(getDayButton(31));
+
+ // Later the range widens and the user clicks Next: no stale target
+ // pulls focus into the grid.
+ rerender(<Calendar focusDate="2026-01-01" max="2026-02-28" />);
+ const next = screen.getByRole('button', {name: 'Next month'});
+ await user.click(next);
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('February 2026');
+ });
+ expect(document.activeElement).toBe(next);
+ });
+
+ it('a page into a month with no enabled day changes nothing and keeps focus', async () => {
+ const user = userEvent.setup();
+ // Only January 1–15 is enabled: February has no enabled day at all.
+ const earlyJanuaryOnly = (date: Date) =>
+ date.getFullYear() === 2026 &&
+ date.getMonth() === 0 &&
+ date.getDate() <= 15;
+ render(
+ <Calendar
+ focusDate="2026-01-01"
+ dateConstraints={[earlyJanuaryOnly]}
+ />,
+ );
+ getDayButton(10).focus();
+ await user.keyboard('{PageDown}');
+ expect(screen.getByRole('grid')).toHaveAttribute(
+ 'aria-label',
+ 'January 2026',
+ );
+ expect(document.activeElement).toBe(getDayButton(10));
+ });
+
+ it('a page onto a day disabled by a constraint moves the month and focuses its first enabled day', async () => {
+ const user = userEvent.setup();
+ // February 1–14 disabled; February 15 onwards enabled.
+ const noEarlyFebruary = (date: Date) =>
+ !(date.getMonth() === 1 && date.getDate() < 15);
+ render(
+ <Calendar focusDate="2026-01-01" dateConstraints={[noEarlyFebruary]} />,
+ );
+ getDayButton(10).focus();
+ await user.keyboard('{PageDown}');
+ await waitFor(() => {
+ expect(document.activeElement).toHaveAttribute(
+ 'data-date',
+ '2026-02-15',
+ );
+ });
+ expect(screen.getByRole('grid')).toHaveAttribute(
+ 'aria-label',
+ 'February 2026',
+ );
+ });
+
+ it('in a two-month view PageDown from the second month moves both months and a later Next click selects no stale day', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <Calendar
+ focusDate="2026-01-01"
+ numberOfMonths={2}
+ onChange={onChange}
+ />,
+ );
+ getDayButton(10, 'February').focus();
+ await user.keyboard('{PageDown}');
+ // March 10 is in no shown grid, so the months move (Feb + Mar) and
+ // focus lands on March 10.
+ await waitFor(() => {
+ expect(document.activeElement).toHaveAttribute(
+ 'data-date',
+ '2026-03-10',
+ );
+ });
+ expect(
+ screen.getAllByRole('grid').map(g => g.getAttribute('aria-label')),
+ ).toEqual(['February 2026', 'March 2026']);
+ // A later Next click pages again without selecting anything.
+ await user.click(getButton('Next month'));
+ await waitFor(() => {
+ expect(
+ screen.getAllByRole('grid').map(g => g.getAttribute('aria-label')),
+ ).toEqual(['March 2026', 'April 2026']);
+ });
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('a controlled owner that refuses the month change leaves no stale target to steal focus or Enter later', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ function RefusingOwner() {
+ const [focusDate, setFocusDate] = useState<ISODateString>('2026-01-01');
+ const [allow, setAllow] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setAllow(true)}>
+ allow
+ </button>
+ <Calendar
+ focusDate={focusDate}
+ onFocusDateChange={next => {
+ if (allow) {
+ setFocusDate(next);
+ }
+ }}
+ onChange={onChange}
+ />
+ </>
+ );
+ }
+ render(<RefusingOwner />);
+ getDayButton(15).focus();
+ // PageDown asks for February; the owner refuses, so January stays and
+ // focus does not move.
+ await user.keyboard('{PageDown}');
+ expect(screen.getByRole('grid')).toHaveAttribute(
+ 'aria-label',
+ 'January 2026',
+ );
+ expect(document.activeElement).toBe(getDayButton(15));
+ // Later the owner lets February show (through the Next button): the
+ // old February 15 target must not grab focus, and Enter on whatever is
+ // focused must not pick it.
+ await user.click(screen.getByRole('button', {name: 'allow'}));
+ await user.click(getButton('Next month'));
+ await waitFor(() => {
+ expect(screen.getByRole('grid')).toHaveAttribute(
+ 'aria-label',
+ 'February 2026',
+ );
+ });
+ expect(document.activeElement).not.toBe(getDayButton(15, 'February'));
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('a refused target is dropped when focus leaves the day grid, so a later Next click plus Enter picks nothing', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ function Owner({allow}: {allow: boolean}) {
+ const [focusDate, setFocusDate] = useState<ISODateString>('2026-01-01');
+ return (
+ <Calendar
+ focusDate={focusDate}
+ onFocusDateChange={next => {
+ if (allow) {
+ setFocusDate(next);
+ }
+ }}
+ onChange={onChange}
+ />
+ );
+ }
+ const {rerender} = render(<Owner allow={false} />);
+ getDayButton(15).focus();
+ // Refused: January stays, focus stays on January 15.
+ await user.keyboard('{PageDown}');
+ expect(document.activeElement).toBe(getDayButton(15));
+ // Focus moves off the day grid onto the Next button; the owner then
+ // allows month changes without any focus change of its own.
+ act(() => getButton('Next month').focus());
+ rerender(<Owner allow />);
+ await user.click(getButton('Next month'));
+ await waitFor(() => {
+ expect(screen.getByRole('grid')).toHaveAttribute(
+ 'aria-label',
+ 'February 2026',
+ );
+ });
+ // The stale February 15 target must not have taken focus; Enter on
+ // whatever is focused picks nothing.
+ expect(document.activeElement).not.toBe(getDayButton(15, 'February'));
+ await user.keyboard('{Enter}');
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('a refused page target is dropped by an arrow to another day, so showing the months later does not select it', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ function Owner({focusDate}: {focusDate: ISODateString}) {
+ // A controlled owner that ignores every requested change: the shown
+ // months move only when the test re-renders it with a new prop, with
+ // no focus change of its own.
+ return (
+ <Calendar
+ focusDate={focusDate}
+ numberOfMonths={2}
+ onFocusDateChange={() => {}}
+ onChange={onChange}
+ />
+ );
+ }
+ const {rerender} = render(<Owner focusDate="2026-01-01" />);
+ getDayButton(10, 'February').focus();
+ // Declined: Jan–Feb stay; focus stays on February 10.
+ await user.keyboard('{PageDown}');
+ expect(document.activeElement).toBe(getDayButton(10, 'February'));
+ // An arrow to February 11 is a focus move to a day other than the
+ // target, so the stale March 10 target is dropped.
+ await user.keyboard('{ArrowRight}');
+ expect(document.activeElement).toBe(getDayButton(11, 'February'));
+ // The owner now shows February–March without touching focus.
+ rerender(<Owner focusDate="2026-02-01" />);
+ await waitFor(() => {
+ expect(
+ screen.getAllByRole('grid').map(g => g.getAttribute('aria-label')),
+ ).toEqual(['February 2026', 'March 2026']);
+ });
+ expect(document.activeElement).toBe(getDayButton(11, 'February'));
+ await user.keyboard('{Enter}');
+ expect(onChange).not.toHaveBeenCalledWith('2026-03-10');
+ });
+
+ it("the pending target becomes the grid's Tab stop: after a page into the second grid and after a page that moves the months, only it has tabindex 0", async () => {
+ const user = userEvent.setup();
+ render(<Calendar focusDate="2026-01-01" numberOfMonths={2} />);
+ // Per grid: the day buttons with tabindex 0 (each grid keeps at most one;
+ // a borrowed copy in the other grid may share the date).
+ const stops = (gridName: string) =>
+ Array.from(
+ screen
+ .getByRole('grid', {name: gridName})
+ .querySelectorAll<HTMLElement>('button[data-date]'),
+ ).filter(button => button.tabIndex === 0);
+ // PageDown from January 15 lands on February 15 in the second grid —
+ // not February's default stop (its first day), so the stop must move.
+ getDayButton(15).focus();
+ await user.keyboard('{PageDown}');
+ await waitFor(() => {
+ expect(document.activeElement).toHaveAttribute(
+ 'data-date',
+ '2026-02-15',
+ );
+ });
+ expect(
+ stops('February 2026').map(b => b.getAttribute('data-date')),
+ ).toEqual(['2026-02-15']);
+ expect(stops('January 2026')).toHaveLength(1);
+ // PageDown again moves both months; March 15 is March's one stop.
+ await user.keyboard('{PageDown}');
+ await waitFor(() => {
+ expect(document.activeElement).toHaveAttribute(
+ 'data-date',
+ '2026-03-15',
+ );
+ });
+ expect(stops('March 2026').map(b => b.getAttribute('data-date'))).toEqual(
+ ['2026-03-15'],
+ );
+ expect(stops('February 2026')).toHaveLength(1);
+ });
+
+ it('a page whose target lies past max changes nothing and keeps focus', async () => {
+ const user = userEvent.setup();
+ render(<Calendar focusDate="2026-01-01" max="2026-02-10" />);
+ getDayButton(15).focus();
+ // February 15 is past max: no page, no focus drop.
+ await user.keyboard('{PageDown}');
+ // No announcement was made (the live region never mounted) and January
+ // is still the month shown.
+ expect(politeRegion()?.textContent ?? '').not.toContain('February 2026');
+ expect(getDayButton(15)).toHaveAttribute('data-date', '2026-01-15');
+ expect(document.activeElement).toBe(getDayButton(15));
+ });
+
+ it('in a two-month view a boundary blocks only out-of-range targets, not month movement', async () => {
+ const user = userEvent.setup();
+ render(
+ <Calendar focusDate="2026-01-01" min="2026-01-01" numberOfMonths={2} />,
+ );
+ // ArrowUp from February 3 reaches January 27 — in range, in the first
+ // grid — even though Previous is disabled at the January minimum.
+ getDayButton(3, 'February').focus();
+ await user.keyboard('{ArrowUp}');
+ await waitFor(() => {
+ expect(document.activeElement).toHaveAttribute(
+ 'data-date',
+ '2026-01-27',
+ );
+ });
+ // PageDown from January 15 reaches February 15, already visible: no
+ // month change, focus moves to it.
+ getDayButton(15).focus();
+ await user.keyboard('{PageDown}');
+ await waitFor(() => {
+ expect(document.activeElement).toHaveAttribute(
+ 'data-date',
+ '2026-02-15',
+ );
+ });
+ expect(getDayButton(15)).toBeInTheDocument();
+ });
+
it('announces the next month when paging the grid with PageDown', async () => {
const user = userEvent.setup();
render(<Calendar focusDate="2026-01-01" />);
diff --git a/packages/core/src/Calendar/Calendar.tsx b/packages/core/src/Calendar/Calendar.tsx
index 0958a2547b..d9d6ad1f08 100644
--- a/packages/core/src/Calendar/Calendar.tsx
+++ b/packages/core/src/Calendar/Calendar.tsx
@@ -51,6 +51,9 @@ import {
plainDateSetFirstOfMonth,
plainDateAddMonths,
plainDateAddDays,
+ plainDateDiffDays,
+ getDaysInMonth,
+ plainDateIsAfter,
plainDateIsBefore,
plainDateIsEqual,
plainDateGetWeekNumber,
@@ -94,8 +97,10 @@ import {themeProps} from '../utils/themeProps';
import {useLocale, useTranslator} from '../i18n';
import {VisuallyHidden} from '../VisuallyHidden';
-/** Imperative handle for Calendar handleRef */
+/** How a month navigation moves the focused day: by its row offset in days, or by whole months. */
+type NavigationUnit = 'days' | 'months';
+/** Imperative handle for Calendar handleRef */
export interface CalendarHandle {
/** Navigate the calendar to show the month containing the given date */
navigateTo: (date: ISODateString) => void;
@@ -216,6 +221,21 @@ interface CalendarRangeProps extends CalendarBaseProps {
export type CalendarProps = CalendarSingleProps | CalendarRangeProps;
+/** The first day of `month`'s month that `isDisabled` allows, or null. */
+function firstEnabledDayOfMonth(
+ month: PlainDate,
+ isDisabled: (pd: PlainDate) => boolean,
+): PlainDate | null {
+ const days = getDaysInMonth(month.year, month.month);
+ for (let day = 1; day <= days; day += 1) {
+ const pd = {year: month.year, month: month.month, day};
+ if (!isDisabled(pd)) {
+ return pd;
+ }
+ }
+ return null;
+}
+
// =============================================================================
// Main Component
// =============================================================================
@@ -335,6 +355,39 @@ export function Calendar({ref, ...props}: CalendarProps) {
});
}, [baseMonth, numberOfMonths]);
+ // A pending target is claimed by the grid that shows its month, or dropped
+ // by the next focus move that is not onto the target day: when a controlled
+ // owner refuses the month change, no grid shows the target's month, and a
+ // stale target would later steal focus (and Enter) when that month does
+ // appear. Only a grid showing the target's month receives it; any other
+ // focus change (an arrow to another day, the month header's buttons, or out
+ // of the calendar) drops it (see onBlur below).
+ const claimablePendingFocus = useMemo(() => {
+ if (pendingFocus == null) {
+ return null;
+ }
+ const target = plainDateFromISO(pendingFocus);
+ return visibleMonths.some(
+ pd => pd.year === target.year && pd.month === target.month,
+ )
+ ? pendingFocus
+ : null;
+ }, [pendingFocus, visibleMonths]);
+ const handleRootBlur = useCallback(
+ (e: React.FocusEvent<HTMLDivElement>) => {
+ // Only the move onto the target day itself keeps the target: an arrow
+ // to any other day, a move to the header buttons, or focus leaving the
+ // calendar all drop it.
+ const movesToTarget =
+ e.relatedTarget instanceof Element &&
+ e.relatedTarget.getAttribute('data-date') === pendingFocus;
+ if (pendingFocus != null && !movesToTarget) {
+ setPendingFocus(null);
+ }
+ },
+ [pendingFocus],
+ );
+
// Format month header
const monthYearLabel = useMemo(() => {
if (numberOfMonths === 1) {
@@ -365,6 +418,15 @@ export function Calendar({ref, ...props}: CalendarProps) {
}, [monthYearLabel, announce]);
// Determine if prev/next navigation is possible based on min/max
+ const minDateForKeys = useMemo(
+ () => (min ? plainDateFromISO(min) : null),
+ [min],
+ );
+ const maxDateForKeys = useMemo(
+ () => (max ? plainDateFromISO(max) : null),
+ [max],
+ );
+
const canNavigatePrevious = useMemo(() => {
if (!min) {
return true;
@@ -392,26 +454,137 @@ export function Calendar({ref, ...props}: CalendarProps) {
}, [max, baseMonth, numberOfMonths]);
// Navigation handlers
+ // The same constraint view the grids use, so a key can resolve its target
+ // before the month changes.
+ const rootRangeAnchor = useMemo(
+ () =>
+ mode === 'range' && rangeSelectionStart
+ ? plainDateFromISO(rangeSelectionStart)
+ : null,
+ [mode, rangeSelectionStart],
+ );
+ const {isDateDisabled: isRootDateDisabled} = useCalendarConstraints({
+ min,
+ max,
+ dateConstraints,
+ maxRangeSpan,
+ minRangeSpan,
+ rangeAnchor: rootRangeAnchor,
+ });
+
const navigateMonth = useCallback(
- (delta: number, focusedDate?: ISODateString, offset?: number) => {
- const newPd = plainDateAddMonths(baseMonth, delta);
- const newISO = plainDateToISO(newPd);
+ (
+ delta: number,
+ focusedDate?: ISODateString,
+ offset?: number,
+ unit: NavigationUnit = 'days',
+ ) => {
+ const monthIndex = (pd: PlainDate) => pd.year * 12 + pd.month;
+ const firstShown = monthIndex(baseMonth);
+ const lastShown = firstShown + numberOfMonths - 1;
+
+ // The Previous/Next buttons move the month with no focused day.
+ if (!focusedDate) {
+ if (
+ (delta < 0 && !canNavigatePrevious) ||
+ (delta > 0 && !canNavigateNext)
+ ) {
+ return;
+ }
+ const newPd = plainDateAddMonths(baseMonth, delta);
+ if (onFocusDateChange) {
+ onFocusDateChange(plainDateToISO(newPd));
+ } else {
+ setInternalFocusDate(newPd);
+ }
+ return;
+ }
- // Calculate target focus date if a focused date was provided
- if (focusedDate) {
- const currentPd = plainDateFromISO(focusedDate);
- const daysToMove = offset ?? 7;
- const targetPd = plainDateAddDays(currentPd, delta * daysToMove);
- setPendingFocus(plainDateToISO(targetPd));
+ // A key resolves its TARGET day first and decides by that, so a
+ // boundary blocks only out-of-range targets, never the month movement
+ // itself (ArrowUp from February 3 reaches January 27 at a January
+ // minimum), and a direction with no enabled day left changes nothing
+ // rather than dropping focus.
+ const currentPd = plainDateFromISO(focusedDate);
+ const inRange = (pd: PlainDate) =>
+ !(minDateForKeys && plainDateIsBefore(pd, minDateForKeys)) &&
+ !(maxDateForKeys && plainDateIsAfter(pd, maxDateForKeys));
+ let targetPd: PlainDate;
+ if (unit === 'months') {
+ // A page targets the same day of the month a month away (clamped to
+ // that month's length). Past `min`/`max` nothing moves; a month with
+ // no enabled day is no destination either, the same as an arrow with
+ // no enabled day in its direction; a target disabled by a constraint
+ // lands on that month's first enabled day instead.
+ const candidate = plainDateAddMonths(currentPd, delta);
+ if (!inRange(candidate)) {
+ return;
+ }
+ if (isRootDateDisabled(candidate)) {
+ const firstEnabled = firstEnabledDayOfMonth(
+ candidate,
+ isRootDateDisabled,
+ );
+ if (firstEnabled == null) {
+ return;
+ }
+ targetPd = firstEnabled;
+ } else {
+ targetPd = candidate;
+ }
+ } else {
+ // Walk the arrow's direction to the first enabled day, up to a year
+ // away; past `min`/`max` or with every day disabled, nothing moves.
+ const step = delta * (offset ?? 7);
+ let candidate = plainDateAddDays(currentPd, step);
+ let found: PlainDate | null = null;
+ while (Math.abs(plainDateDiffDays(currentPd, candidate)) <= 366) {
+ if (!inRange(candidate)) {
+ return;
+ }
+ if (!isRootDateDisabled(candidate)) {
+ found = candidate;
+ break;
+ }
+ candidate = plainDateAddDays(candidate, step);
+ }
+ if (found == null) {
+ return;
+ }
+ targetPd = found;
}
+ // Focus moves to the target; the months change only when the target's
+ // month is not already shown. The view shifts the least it can in the
+ // key's direction, so the target month becomes the first (backwards)
+ // or last (forwards) month shown.
+ const resolved: PlainDate = targetPd;
+ const targetMonth = monthIndex(resolved);
+ setPendingFocus(plainDateToISO(resolved));
+ if (targetMonth >= firstShown && targetMonth <= lastShown) {
+ return;
+ }
+ const targetFirst = {year: resolved.year, month: resolved.month, day: 1};
+ const newPd =
+ targetMonth < firstShown
+ ? targetFirst
+ : plainDateAddMonths(targetFirst, -(numberOfMonths - 1));
if (onFocusDateChange) {
- onFocusDateChange(newISO);
+ onFocusDateChange(plainDateToISO(newPd));
} else {
setInternalFocusDate(newPd);
}
},
- [baseMonth, onFocusDateChange],
+ [
+ baseMonth,
+ canNavigateNext,
+ canNavigatePrevious,
+ isRootDateDisabled,
+ maxDateForKeys,
+ minDateForKeys,
+ numberOfMonths,
+ onFocusDateChange,
+ ],
);
// Escape key handler to cancel range selection
@@ -515,6 +688,7 @@ export function Calendar({ref, ...props}: CalendarProps) {
<div
ref={ref}
{...rest}
+ onBlur={composeEventHandlers(rest.onBlur, handleRootBlur)}
{...mergeProps(
themeProps('calendar', {mode}),
stylex.props(calendarStyles.calendar, xstyle),
@@ -589,13 +763,13 @@ export function Calendar({ref, ...props}: CalendarProps) {
setHoveredDate(date ? plainDateToISO(date) : null)
}
today={today}
- onNavigatePrevious={(focusedDate, offset) =>
- navigateMonth(-1, focusedDate, offset)
+ onNavigatePrevious={(focusedDate, offset, unit) =>
+ navigateMonth(-1, focusedDate, offset, unit)
}
- onNavigateNext={(focusedDate, offset) =>
- navigateMonth(1, focusedDate, offset)
+ onNavigateNext={(focusedDate, offset, unit) =>
+ navigateMonth(1, focusedDate, offset, unit)
}
- pendingFocus={pendingFocus}
+ pendingFocus={claimablePendingFocus}
onPendingFocusHandled={() => setPendingFocus(null)}
/>
))}
@@ -628,8 +802,16 @@ interface MonthGridProps {
onDayClick: (date: PlainDate) => void;
onDayHover: (date: PlainDate | null) => void;
today: PlainDate;
- onNavigatePrevious?: (focusedDate: ISODateString, offset: number) => void;
- onNavigateNext?: (focusedDate: ISODateString, offset: number) => void;
+ onNavigatePrevious?: (
+ focusedDate: ISODateString,
+ offset: number,
+ unit?: NavigationUnit,
+ ) => void;
+ onNavigateNext?: (
+ focusedDate: ISODateString,
+ offset: number,
+ unit?: NavigationUnit,
+ ) => void;
pendingFocus?: ISODateString | null;
onPendingFocusHandled?: () => void;
}
@@ -775,14 +957,14 @@ function MonthGrid({
const handlePageUp = useCallback(() => {
const focusedDate = getFocusedDate();
if (focusedDate) {
- onNavigatePrevious?.(focusedDate, 7);
+ onNavigatePrevious?.(focusedDate, 1, 'months');
}
}, [getFocusedDate, onNavigatePrevious]);
const handlePageDown = useCallback(() => {
const focusedDate = getFocusedDate();
if (focusedDate) {
- onNavigateNext?.(focusedDate, 7);
+ onNavigateNext?.(focusedDate, 1, 'months');
}
}, [getFocusedDate, onNavigateNext]);
@@ -812,34 +994,53 @@ function MonthGrid({
onPageDown: handlePageDown,
});
- // Handle pending focus after month navigation
+ // Handle pending focus after month navigation. Every mounted month grid
+ // sees the same pending date; only the grid showing that date's month acts,
+ // so a neighbouring grid's fallback never overrides the right target. The
+ // target is the real day in this month, never an outside-day copy; when it
+ // is disabled, the month's first enabled day takes focus instead.
useEffect(() => {
if (!pendingFocus || !gridRef.current) {
return;
}
- const buttons = gridRef.current.querySelectorAll<HTMLElement>(
- 'button:not([disabled])',
- );
-
const targetPd = plainDateFromISO(pendingFocus);
+ if (targetPd.year !== year || targetPd.month !== month.month) {
+ return;
+ }
const targetIso = plainDateToISO(targetPd);
- let targetButton: HTMLElement | null = null;
- for (const button of buttons) {
- if (button.getAttribute('data-date') === targetIso) {
- targetButton = button;
- break;
- }
- }
+ const buttons = Array.from(
+ gridRef.current.querySelectorAll<HTMLElement>(
+ 'button[data-date]:not([disabled]):not([aria-disabled="true"])',
+ ),
+ );
- if (!targetButton && buttons.length > 0) {
- targetButton = buttons[0];
+ // The real target day, else the month's first enabled day, else — in a
+ // month with no enabled day — the first day button that can still take
+ // focus (a borrowed adjacent-month day), so focus stays in the grid
+ // rather than dropping to the page.
+ const targetButton =
+ buttons.find(button => button.getAttribute('data-date') === targetIso) ??
+ buttons[0] ??
+ gridRef.current.querySelector<HTMLElement>(
+ 'button[data-date]:not([disabled])',
+ ) ??
+ null;
+
+ if (targetButton != null) {
+ // The target becomes this grid's one Tab stop before it takes focus,
+ // the way the hook's own arrow moves do (FR2): a programmatic focus
+ // alone would leave the stop on the day the grid mounted with.
+ for (const button of gridRef.current.querySelectorAll<HTMLElement>(
+ 'button[data-date]',
+ )) {
+ button.tabIndex = button === targetButton ? 0 : -1;
+ }
+ targetButton.focus();
}
-
- targetButton?.focus();
onPendingFocusHandled?.();
- }, [pendingFocus, gridRef, onPendingFocusHandled]);
+ }, [pendingFocus, gridRef, month.month, onPendingFocusHandled, year]);
// Parse selection
let selectedDate: PlainDate | null = null;