Skip to content

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

TypeScript

fix(Calendar): open on a month inside the min/max window (#5306)

Xinzi Zhou27646f728b77
diff --git a/.changeset/calendar-initial-month-clamp.md b/.changeset/calendar-initial-month-clamp.md
new file mode 100644
index 0000000000..8d17384885
--- /dev/null
+++ b/.changeset/calendar-initial-month-clamp.md
@@ -0,0 +1,18 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Calendar (and DateInput, DateRangeInput, DateTimeInput) now opens on a month inside the min/max window instead of on today
+
+@imdreamrunner
+
+With no `focusDate` and no selected value, the calendar opened on today's month
+even when `min`/`max` excluded it — a 2019 audit window or a booking window that
+opens next spring rendered a grid where every day was disabled, and the only way
+in was clicking the prev/next arrows once per month.
+
+The initial month is now today clamped into the window: today when it is inside,
+otherwise whichever bound is nearest. An explicit `focusDate` or a selected value
+still wins, so nothing changes for callers that already say where to look. With
+`numberOfMonths={2}` a past window lands `max` in the right-hand pane, so neither
+pane is entirely out of bounds.
diff --git a/apps/storybook/stories/Calendar.stories.tsx b/apps/storybook/stories/Calendar.stories.tsx
index 9dddb990f9..3d4512d6a9 100644
--- a/apps/storybook/stories/Calendar.stories.tsx
+++ b/apps/storybook/stories/Calendar.stories.tsx
@@ -149,6 +149,34 @@ export const MinMaxBoundary: Story = {
},
};
+export const WindowAwayFromToday: Story = {
+ name: 'Min/max window away from today',
+ render: () => {
+ const [past, setPast] = useState<ISODateString | undefined>(undefined);
+ const [future, setFuture] = useState<ISODateString | undefined>(undefined);
+ // Windows three years either side of today, so neither contains today.
+ const year = new Date().getFullYear();
+ return (
+ <div style={{display: 'flex', gap: 24, flexWrap: 'wrap'}}>
+ <Calendar
+ mode="single"
+ min={`${year - 3}-02-03` as ISODateString}
+ max={`${year - 3}-05-19` as ISODateString}
+ value={past}
+ onChange={val => setPast(val)}
+ />
+ <Calendar
+ mode="single"
+ min={`${year + 3}-08-11` as ISODateString}
+ max={`${year + 3}-11-24` as ISODateString}
+ value={future}
+ onChange={val => setFuture(val)}
+ />
+ </div>
+ );
+ },
+};
+
export const WithDateConstraints: Story = {
render: () => {
const [value, setValue] = useState<ISODateString | undefined>(undefined);
diff --git a/packages/core/src/Calendar/Calendar.doc.mjs b/packages/core/src/Calendar/Calendar.doc.mjs
index 577717a794..f3351fa29b 100644
--- a/packages/core/src/Calendar/Calendar.doc.mjs
+++ b/packages/core/src/Calendar/Calendar.doc.mjs
@@ -83,7 +83,8 @@ export const docs = {
{
name: 'focusDate',
type: 'ISODateString',
- description: 'Controlled visible month.',
+ description:
+ 'Controlled visible month. Unset, the calendar opens on the selected date, else on today clamped into the min/max window.',
},
{
name: 'onFocusDateChange',
@@ -156,7 +157,7 @@ export const docsZh = {
{name: 'dateConstraints', type: 'Array<(date: Date) => boolean>', description: '自定义约束函数。'},
{name: 'maxRangeSpan', type: 'number', description: '范围模式:范围最多可跨越的天数,含首尾两端(7 = 7 天窗口)。选定起始日后限制窗口大小。'},
{name: 'minRangeSpan', type: 'number', description: '范围模式:范围最少需跨越的天数,含首尾两端(2 表示禁止单日范围)。默认为 1。'},
- {name: 'focusDate', type: 'ISODateString', description: '受控可见月份。'},
+ {name: 'focusDate', type: 'ISODateString', description: '受控可见月份。未设置时,日历打开时显示已选日期所在月份;若无选中值,则显示今天,并将其限制在 min/max 范围内。'},
{name: 'onFocusDateChange', type: '(focusDate: ISODateString) => void', description: '导航回调函数。'},
{name: 'handleRef', type: 'React.Ref<CalendarHandle>', description: '日历导航的命令式句柄,包括 navigateTo()。'},
{name: 'hasOutsideDays', type: 'boolean', description: '显示相邻月份的日期。', default: 'true'},
@@ -221,7 +222,7 @@ export const docsDense = {
dateConstraints: 'custom constraint fns',
maxRangeSpan: 'range mode: max days a range may span, both ends counted (7 = 7-day window)',
minRangeSpan: 'range mode: min days a range must span, both ends counted (default 1)',
- focusDate: 'controlled visible month',
+ focusDate: 'controlled visible month (default: selected date, else today clamped into min/max)',
onFocusDateChange: 'navigation callback',
handleRef: 'imperative navigation handle',
hasOutsideDays: 'show days from adjacent months',
diff --git a/packages/core/src/Calendar/Calendar.test.tsx b/packages/core/src/Calendar/Calendar.test.tsx
index cbaf1a177b..3fb167e264 100644
--- a/packages/core/src/Calendar/Calendar.test.tsx
+++ b/packages/core/src/Calendar/Calendar.test.tsx
@@ -263,6 +263,58 @@ describe('Calendar', () => {
expect(day15).not.toBeDisabled();
});
+ // ─── Initial Visible Month ───────────────────────────────────
+
+ describe('opens on a month inside the min/max window', () => {
+ beforeEach(() => {
+ vi.useFakeTimers({toFake: ['Date']});
+ vi.setSystemTime(new Date(2026, 7, 21, 12, 0, 0));
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('opens on today when today is inside the window', () => {
+ render(<Calendar min="2026-01-01" max="2026-12-31" />);
+
+ expect(screen.getByText('August 2026')).toBeInTheDocument();
+ });
+
+ it('opens on min when the window is entirely in the future', () => {
+ render(<Calendar min="2027-03-04" max="2027-06-30" />);
+
+ expect(screen.getByText('March 2027')).toBeInTheDocument();
+ expect(getDayButton(4, 'March', 2027)).not.toBeDisabled();
+ });
+
+ it('opens on max when the window is entirely in the past', () => {
+ render(<Calendar min="2019-01-01" max="2019-04-30" />);
+
+ expect(screen.getByText('April 2019')).toBeInTheDocument();
+ expect(getDayButton(30, 'April', 2019)).not.toBeDisabled();
+ });
+
+ it('keeps max in the last pane in the two-month layout', () => {
+ render(<Calendar numberOfMonths={2} min="2019-01-01" max="2019-04-30" />);
+
+ expect(screen.getByText('March 2019 – April 2019')).toBeInTheDocument();
+ });
+
+ it('still honors an explicit focusDate outside the window', () => {
+ render(
+ <Calendar focusDate="2026-01-01" min="2027-03-04" max="2027-06-30" />,
+ );
+
+ expect(screen.getByText('January 2026')).toBeInTheDocument();
+ });
+
+ it('still opens on the selected value outside the window', () => {
+ render(<Calendar defaultValue="2031-07-04" min="2019-01-01" />);
+
+ expect(screen.getByText('July 2031')).toBeInTheDocument();
+ });
+ });
+
it('respects custom dateConstraints', () => {
// Only allow weekdays
const isWeekday = (date: Date) => {
diff --git a/packages/core/src/Calendar/Calendar.tsx b/packages/core/src/Calendar/Calendar.tsx
index 971f9becb7..604f8ab51f 100644
--- a/packages/core/src/Calendar/Calendar.tsx
+++ b/packages/core/src/Calendar/Calendar.tsx
@@ -11,6 +11,7 @@
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/Calendar/Calendar.doc.mjs (props table, features, implementation notes)
+ * - /packages/core/src/Calendar/getInitialFocusDate.ts (which month the calendar opens on)
* - /packages/core/src/Calendar/Calendar.test.tsx (tests for new/changed behavior)
* - /packages/core/src/Calendar/index.ts (exports if types change)
* - /apps/storybook/stories/Calendar.stories.tsx (storybook stories)
@@ -60,6 +61,7 @@ import {
} from '../utils/plainDate';
import {mergeProps, composeEventHandlers, rtlStyles} from '../utils';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
+import {getInitialFocusDate} from './getInitialFocusDate';
import {
computeDayCellState,
computeRangeRounding,
@@ -142,7 +144,9 @@ interface CalendarBaseProps extends Omit<
/**
* Controlled focus date (which month is visible).
- * If not provided, defaults to selected date or today.
+ * If not provided, defaults to the selected date, else today clamped into
+ * the `min`/`max` window (so a window that excludes today opens on the
+ * bound nearest to it, not on an all-disabled month).
*/
focusDate?: ISODateString;
@@ -277,20 +281,19 @@ export function Calendar({ref, ...props}: CalendarProps) {
// Determine effective value
const effectiveValue = value !== undefined ? value : internalValue;
- // Focus date state (which month is visible)
- const [internalFocusDate, setInternalFocusDate] = useState<PlainDate>(() => {
- if (focusDateProp) {
- return plainDateFromISO(focusDateProp);
- }
- if (effectiveValue) {
- if (typeof effectiveValue === 'string') {
- return plainDateFromISO(effectiveValue);
- } else {
- return plainDateFromISO(effectiveValue.start);
- }
- }
- return plainDateToday();
- });
+ // Focus date state (which month is visible). Falls back to today, clamped
+ // into the min/max window so a window that doesn't contain today doesn't
+ // open on an all-disabled month.
+ const [internalFocusDate, setInternalFocusDate] = useState<PlainDate>(() =>
+ getInitialFocusDate({
+ focusDate: focusDateProp,
+ value: effectiveValue,
+ min,
+ max,
+ numberOfMonths,
+ today,
+ }),
+ );
// Use controlled focusDate if callback is provided, otherwise use internal state
const isControlledFocus =
diff --git a/packages/core/src/Calendar/getInitialFocusDate.test.ts b/packages/core/src/Calendar/getInitialFocusDate.test.ts
new file mode 100644
index 0000000000..4b242a697e
--- /dev/null
+++ b/packages/core/src/Calendar/getInitialFocusDate.test.ts
@@ -0,0 +1,94 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file getInitialFocusDate.test.ts
+ * @input Uses vitest
+ * @output Test suite for getInitialFocusDate
+ * @position Tests for getInitialFocusDate.ts
+ *
+ * SYNC: When getInitialFocusDate.ts changes, update tests accordingly
+ */
+
+import {describe, it, expect} from 'vitest';
+import {getInitialFocusDate} from './getInitialFocusDate';
+import {plainDateFromISO, plainDateToISO} from '../utils/plainDate';
+
+const TODAY = plainDateFromISO('2026-08-21');
+
+function focusISO(options: Partial<Parameters<typeof getInitialFocusDate>[0]>) {
+ return plainDateToISO(
+ getInitialFocusDate({numberOfMonths: 1, today: TODAY, ...options}),
+ );
+}
+
+describe('getInitialFocusDate', () => {
+ it('opens on today when there are no bounds', () => {
+ expect(focusISO({})).toBe('2026-08-21');
+ });
+
+ it('opens on today when today is inside the min/max window', () => {
+ expect(focusISO({min: '2026-01-01', max: '2026-12-31'})).toBe('2026-08-21');
+ });
+
+ it('treats the bounds as inclusive', () => {
+ expect(focusISO({min: '2026-08-21'})).toBe('2026-08-21');
+ expect(focusISO({max: '2026-08-21'})).toBe('2026-08-21');
+ });
+
+ it('opens on min when the whole window is in the future', () => {
+ expect(focusISO({min: '2027-03-04', max: '2027-06-30'})).toBe('2027-03-04');
+ });
+
+ it('opens on max when the whole window is in the past', () => {
+ expect(focusISO({min: '2019-01-01', max: '2019-04-30'})).toBe('2019-04-01');
+ });
+
+ it('clamps against a one-sided min', () => {
+ expect(focusISO({min: '2030-05-17'})).toBe('2030-05-17');
+ });
+
+ it('clamps against a one-sided max', () => {
+ expect(focusISO({max: '2020-02-09'})).toBe('2020-02-01');
+ });
+
+ it('lands max in the last pane in the two-month layout', () => {
+ // Opening on max's month would spend the second pane entirely
+ // out of bounds, so the window's end sits on the right instead.
+ expect(focusISO({max: '2020-02-09', numberOfMonths: 2})).toBe('2020-01-01');
+ });
+
+ it('does not shift the two-month layout back past min', () => {
+ expect(
+ focusISO({min: '2020-02-03', max: '2020-02-09', numberOfMonths: 2}),
+ ).toBe('2020-02-03');
+ });
+
+ it('prefers the selected value over the bounds', () => {
+ expect(focusISO({value: '2031-07-04', min: '2019-01-01'})).toBe(
+ '2031-07-04',
+ );
+ });
+
+ it('uses a range value start as the visible month', () => {
+ expect(focusISO({value: {start: '2019-03-08', end: '2019-03-19'}})).toBe(
+ '2019-03-08',
+ );
+ });
+
+ it('prefers an explicit focusDate over everything else', () => {
+ expect(
+ focusISO({
+ focusDate: '2015-11-02',
+ value: '2031-07-04',
+ min: '2026-01-01',
+ max: '2026-12-31',
+ }),
+ ).toBe('2015-11-02');
+ });
+
+ it('prefers min when the bounds are inverted', () => {
+ // Degenerate input (min after max) — resolve it deterministically
+ // rather than reading the second bound off a contradiction.
+ expect(focusISO({min: '2027-01-01', max: '2020-01-01'})).toBe('2027-01-01');
+ });
+});
diff --git a/packages/core/src/Calendar/getInitialFocusDate.ts b/packages/core/src/Calendar/getInitialFocusDate.ts
new file mode 100644
index 0000000000..63ecbb45d2
--- /dev/null
+++ b/packages/core/src/Calendar/getInitialFocusDate.ts
@@ -0,0 +1,93 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file getInitialFocusDate.ts
+ * @input PlainDate utilities, min/max bounds, today
+ * @output Exports getInitialFocusDate — the month Calendar opens on
+ * @position Calendar-specific helper; used by Calendar.tsx
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Calendar/getInitialFocusDate.test.ts
+ * - /packages/core/src/Calendar/Calendar.tsx (the only caller)
+ */
+
+import type {ISODateString, DateRange} from '../utils/dateTypes';
+import {
+ type PlainDate,
+ plainDateFromISO,
+ plainDateSetFirstOfMonth,
+ plainDateAddMonths,
+ plainDateIsBefore,
+ plainDateIsAfter,
+} from '../utils/plainDate';
+
+export interface InitialFocusDateOptions {
+ /** Controlled visible month, if the consumer supplied one. */
+ focusDate?: ISODateString;
+ /** Selected value (single date or range), controlled or uncontrolled. */
+ value?: ISODateString | DateRange;
+ /** Earliest selectable date. */
+ min?: ISODateString;
+ /** Latest selectable date. */
+ max?: ISODateString;
+ /** How many month panes the calendar renders (1 or 2). */
+ numberOfMonths: number;
+ /** Today, injected so the caller keeps a single memoized source of "now". */
+ today: PlainDate;
+}
+
+/**
+ * Picks the date whose month the calendar opens on.
+ *
+ * An explicit `focusDate` wins, then the selected value — both are the
+ * consumer's own instruction about where to look, so neither is second-guessed
+ * against `min`/`max`.
+ *
+ * Otherwise the calendar opens on today, clamped into the `min`/`max` window.
+ * Without the clamp a window that doesn't contain today (a 2019 audit range, a
+ * booking window opening next spring) opened on today's month with every day
+ * disabled, leaving prev/next clicking as the only way in.
+ *
+ * When clamping forward to `min`, that month leads: the whole selectable window
+ * runs ahead of it. When clamping back to `max`, the last pane lands on `max`'s
+ * month instead — with `numberOfMonths={2}` opening on `[max, max + 1]` would
+ * spend half the calendar on a month that is entirely out of bounds. That
+ * shift never crosses `min`'s month.
+ */
+export function getInitialFocusDate(
+ options: InitialFocusDateOptions,
+): PlainDate {
+ const {focusDate, value, min, max, numberOfMonths, today} = options;
+
+ if (focusDate) {
+ return plainDateFromISO(focusDate);
+ }
+
+ if (value) {
+ return plainDateFromISO(typeof value === 'string' ? value : value.start);
+ }
+
+ const minDate = min ? plainDateFromISO(min) : null;
+ const maxDate = max ? plainDateFromISO(max) : null;
+
+ if (minDate && plainDateIsBefore(today, minDate)) {
+ return minDate;
+ }
+
+ if (maxDate && plainDateIsAfter(today, maxDate)) {
+ const lastPaneOffset = Math.max(0, numberOfMonths - 1);
+ const shifted = plainDateAddMonths(
+ plainDateSetFirstOfMonth(maxDate),
+ -lastPaneOffset,
+ );
+ if (
+ minDate &&
+ plainDateIsBefore(shifted, plainDateSetFirstOfMonth(minDate))
+ ) {
+ return minDate;
+ }
+ return shifted;
+ }
+
+ return today;
+}