An open source design system that's fully customizable and agent ready
TypeScript
fix(Calendar, DateRangeInput): today is read after hydration, so a server in another zone no longer causes a mismatch (#10226)
Cindy Zhanga26f7c45259a
diff --git a/.changeset/calendar-today-hydration.md b/.changeset/calendar-today-hydration.mdnew file mode 100644index 0000000000..1422bfe3e0--- /dev/null+++ b/.changeset/calendar-today-hydration.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `Calendar` and `DateRangeInput` no longer cause a hydration mismatch when the server and the browser are on different dates, for example a UTC server and a visitor already in tomorrow. Today is read only after hydration: a server-rendered Calendar shows no today marker until then, and a Calendar with no `focusDate` or value keeps its month grid's space empty until the browser's month is known. A DateRangeInput shows the year in its range text until then.++@cixzhangdiff --git a/apps/storybook/stories/CalendarTodayHydration.stories.tsx b/apps/storybook/stories/CalendarTodayHydration.stories.tsxnew file mode 100644index 0000000000..3807ceaf92--- /dev/null+++ b/apps/storybook/stories/CalendarTodayHydration.stories.tsx@@ -0,0 +1,81 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CalendarTodayHydration.stories.tsx+ * @input Calendar, React's server renderer and hydrateRoot, run in the page+ * @output A fixture that server-renders Calendar on one date and hydrates it+ * on another, for the browser lane; excluded from the visual matrix+ * @position Real-browser server render, hydration and post-hydration fixture+ * for component:Calendar FR12+ */++import type {Meta, StoryObj} from '@storybook/react';+import {useRef, useState, type ReactElement} from 'react';+import {hydrateRoot} from 'react-dom/client';+import {renderToString} from 'react-dom/server';+import {Calendar} from '@astryxdesign/core';++const meta = {+ title: 'Core/CalendarHydration',+ tags: ['no-visual', '!autodocs'],+ parameters: {layout: 'padded'},+} satisfies Meta;++export default meta;+type Story = StoryObj<typeof meta>;++/**+ * "Server render" writes the server markup with the page's current date.+ * The spec then moves the date and presses "Hydrate", so the server and the+ * browser disagree on today, as a UTC server and a visitor in another zone+ * do near midnight.+ */+function HydrationFixture({tree}: {tree: ReactElement}) {+ const hostRef = useRef<HTMLDivElement>(null);+ const [phase, setPhase] = useState<'idle' | 'server' | 'hydrated'>('idle');+ const [errors, setErrors] = useState<string[]>([]);+ return (+ <div>+ <button+ type="button"+ onClick={() => {+ if (hostRef.current == null) {+ return;+ }+ hostRef.current.innerHTML = renderToString(tree);+ setPhase('server');+ }}>+ Server render+ </button>+ <button+ type="button"+ onClick={() => {+ if (hostRef.current == null) {+ return;+ }+ const found: string[] = [];+ hydrateRoot(hostRef.current, tree, {+ onRecoverableError: error => {+ found.push(String(error));+ setErrors([...found]);+ },+ });+ setPhase('hydrated');+ }}>+ Hydrate+ </button>+ <output data-phase={phase} data-errors={errors.length}>+ {errors.join('\n')}+ </output>+ <div ref={hostRef} data-testid="host" />+ </div>+ );+}++export const OneMonth: Story = {+ render: () => <HydrationFixture tree={<Calendar />} />,+};++export const TwoMonths: Story = {+ render: () => <HydrationFixture tree={<Calendar numberOfMonths={2} />} />,+};diff --git a/docs/specs/components/Calendar/Calendar.spec.md b/docs/specs/components/Calendar/Calendar.spec.mdindex 1d34c1fdad..682b5c0721 100644--- a/docs/specs/components/Calendar/Calendar.spec.md+++ b/docs/specs/components/Calendar/Calendar.spec.md@@ -16,6 +16,9 @@ verified_by:packages/core/src/Calendar/getWeekdayHeaderNames.test.ts,packages/core/src/Calendar/Calendar.calendarSystems.test.tsx,packages/core/src/Calendar/Calendar.ssr.test.tsx,+ packages/core/src/Calendar/CalendarToday.ssr.test.tsx,+ packages/core/src/Calendar/__tests__/CalendarTodayHydration.interaction.browser.spec.ts,+ packages/core/src/Calendar/getInitialFocusDate.test.ts,packages/core/src/Calendar/hooks/calendarHooks.calendarSystems.test.tsx,packages/core/src/utils/calendarSystem.test.ts,packages/core/src/i18n/__tests__/calendarSystem.test.tsx,@@ -38,6 +41,7 @@ architecture:contributing: []system_specs:[+ spec:AST-013/FR9,spec:AST-013/FR12,spec:AST-020/FR15,spec:AST-085,@@ -130,6 +134,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR10 | `hasWeekNumbers` shows ISO 8601 week numbers in every calendar. | `spec:AST-111` FR8 || FR11 | The public `useCalendarDays` and `useCalendarNavigation` hooks take an optional `calendar` that defaults to `gregory`, and they never read the provider's calendar. With a calendar, `useCalendarDays` reads `year` and `month` as the calendar's year and the month's position in that year, as `Temporal.PlainDate` numbers them (1 through 13 in a Hebrew leap year); each day keeps its Gregorian date, and `dayNumber` is its day of the calendar month. `useCalendarNavigation` steps calendar months, writes `monthYearLabel` as the month header writes it, and reports each visible month in the calendar's numbers as `visibleCalendarMonths`, which `useCalendarDays` reads with the same `calendar`. `baseMonth` and `visibleMonths` stay the Gregorian first day of each month. Without `calendar`, both hooks show Gregorian months, exactly as with `calendar: 'gregory'`. | `spec:AST-111` FR4, FR5, FR20 || FR7 | When the visible month changes, by the month buttons, a Page key, an arrow across a month edge, or the handle, the new month (both months in a two-month view) is announced politely; the first render and a pick that leaves the month in place announce nothing. In `range` mode the first pick announces the start and prompts for an end, the second announces the completed range in chronological order, and picking the start again when `minRangeSpan` is above 1 announces the cleared start; Escape clears an in-progress range without an announcement. Every announcement uses the provider locale. | shipped source and focused tests |+| FR12 | Today is the browser's local date. During server render and the render that hydrates server markup, today is unknown (`spec:AST-013` FR9): no day is marked today or seeds the Tab stop, and without a `focusDate` or a value the month grid's space is reserved but empty (exactly, with the default six-row grid), with an empty month label and both month buttons unavailable. The next render shows today and, without them, its month, with no month announcement. |### Allowed variation@@ -290,6 +295,7 @@ button.| FR1 (labels) | `Calendar.test.tsx` ("starts each stand-alone month label with a capital in %s", "leaves the month label as Intl gives it where CLDR does not capitalize in %s"), `plainDate.test.ts` `plainDateFormatStandaloneMonthYear` | es, fr, pl, ru two-month view; vi, de, en | A lower-case stand-alone month where CLDR titlecases it, a capital where it does not, or a second month left lower case fails. | `audit:Calendar/behavior` || FR8–FR10, AR1 (calendars) | `Calendar.calendarSystems.test.tsx` ("lays out Aban 1405 with its calendar day numbers and labels", "keeps the fixed six-row grid", "reports a pick as a Gregorian ISO date", "steps one calendar month with Previous and Next", "pages one calendar month and clamps the day of the month", "bounds the month buttons by day", "shows ISO 8601 week numbers", "writes day numbers and labels in the locale", "shows Adar I and Adar II as distinct months of a leap year", "steps a year from Adar I to Adar with Shift+PageDown, clamped", "keeps six rows for the five-day thirteenth month", "gives the thirteenth month only its rows with hasVariableRowCount", "steps a year to the same month with Shift+PageUp", "names the era of each month", "names each day by the month and day the grid shows when Intl disagrees", Gregorian year-paging cases); `Calendar.ssr.test.tsx` server render and hydration with `Temporal` on both sides, neither side, and the browser only; `calendarSystem.test.ts` month structure at known dates, labels of every Gregorian-aligned calendar, and contiguity, length, and months-per-year invariants for every calendar from 1900 through 2100; `i18n/__tests__/calendarSystem.test.tsx` resolution order and the fallback without `Temporal`; real Chromium and Firefox runs with native `Temporal`, with a polyfill, and without `Temporal` | Persian, Hebrew leap year, Ethiopic thirteenth month, Japanese era change, Chinese leap month; `fa-IR` digits; no `Temporal` | A month start, length, label, or step that differs from `Temporal`, a vanished leap month, a non-ISO value, a non-ISO week number, or a crash or missing warning without `Temporal` fails. Evidence gap: no Safari or WebKit run. | `audit:Calendar/behavior` || FR11 (hooks) | `calendarHooks.calendarSystems.test.tsx` ("matches the released output for %s" against a fixed copy of the Gregorian grid algorithm, "gives the same output with calendar gregory", "lays out Aban 1405 in the Persian calendar", "reads Hebrew leap-year months as Temporal numbers them", "reads the year numbers of the Buddhist and Minguo calendars", "ignores the provider calendar" for both hooks, "matches the released months and label in %s", "steps Persian months and labels them in the calendar", "steps through Adar I, Adar II, and the thirteenth month", "labels %s months as Calendar heads them", "feeds visibleCalendarMonths into useCalendarDays in %s", "fall back to Gregorian months and warn once"); the unchanged `useCalendarDays.test.ts` and `useCalendarNavigation.test.ts` |+| FR12 (server) | `CalendarToday.ssr.test.tsx` (server markup with no today marker, a hidden grid, an empty month label and unavailable month buttons; no mismatch; the browser's month and today after hydration with no announcement; a two-month pick that keeps both months), `getInitialFocusDate.test.ts` ("waits for today when there is no focus date or value"), and the real-browser `CalendarTodayHydration.interaction.browser.spec.ts` over the Calendar Today Hydration fixture stories (server render on one date, hydration on the next) || FR2 (size) | Evidence gap: no test asserts day-button size or text growth | — | — | `audit:Calendar/layout` || DD1 | `Calendar.test.tsx` ("displays day names", "uses the provider locale for weekday header names", "rotates localized day names by numeric weekday index", "shows abbreviated weekday names in a locale where all seven fit in four characters", "keeps short weekday names in %s, where an abbreviated name runs past four characters" for `pt-PT` and `pl-PL`, "shows the platform abbreviated names for a locale with no shipped weekday data" for `id-ID`, "shows the platform narrow names for an unshipped locale whose abbreviated names run past four characters" for `sw-KE`); `getWeekdayHeaderNames.test.ts`; `scripts/generate-cldr-weekdays.test.mjs` ("matches every generated locale to its pinned raw CLDR source", "picks abbreviated names only where all seven fit in four characters") | English; a locale whose abbreviated names are all within four characters, such as `fr`; a locale above it, such as `pt-PT` or `pl`; `weekStartsOn` rotation; with week numbers | A locale within the limit showing short names, a locale above it showing abbreviated names, a row mixing the two, or a name cut short fails. | `audit:Calendar/layout` || AR1 (browser) | `Calendar.a11y.test.tsx` and `Calendar.a11y.chromium.spec.ts` over the shared grid states | Every representative state | A lost grid name, role, or start neighbourhood fails; browser-owned outcomes are reported. | `audit:Calendar/accessibility` |diff --git a/docs/specs/components/DateRangeInput/DateRangeInput.spec.md b/docs/specs/components/DateRangeInput/DateRangeInput.spec.mdindex b8729eeb1b..bf2ed0de64 100644--- a/docs/specs/components/DateRangeInput/DateRangeInput.spec.md+++ b/docs/specs/components/DateRangeInput/DateRangeInput.spec.md@@ -14,6 +14,7 @@ verified_by:[packages/core/src/DateRangeInput/DateRangeInput.test.tsx,packages/core/src/DateRangeInput/DateRangeInput.calendar.test.tsx,+ packages/core/src/DateRangeInput/DateRangeInput.ssr.test.tsx,packages/core/src/Calendar/Calendar.calendarSystems.test.tsx,packages/core/src/theme/themingTargets.test.ts,packages/core/src/DateRangeInput/__tests__/DateRangeInputReflow.interaction.browser.spec.ts,diff --git a/packages/core/src/Calendar/Calendar.tsx b/packages/core/src/Calendar/Calendar.tsxindex 2e8e070eb2..6b02939179 100644--- a/packages/core/src/Calendar/Calendar.tsx+++ b/packages/core/src/Calendar/Calendar.tsx@@ -44,7 +44,6 @@ import {plainDateFromISO,plainDateToISO,plainDateToDate,- plainDateToday,plainDateAddDays,plainDateDiffDays,plainDateIsAfter,@@ -71,6 +70,7 @@ import {mergeProps, composeEventHandlers, rtlStyles} from '../utils';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';import {usePressFeedback} from '../hooks/usePressFeedback';+import {useToday} from '../hooks/useToday';import {getInitialFocusDate} from './getInitialFocusDate';import {getWeekdayHeaders} from './getWeekdayHeaderNames';import {@@ -111,6 +111,10 @@ import english from '../i18n/generated-english/Calendar/Calendar.generated';registerEnglishFallback(english);+// The month math needs a date before the opening month is known (server+// render, hydration). The grid it lays out is hidden.+const UNKNOWN_MONTH_STAND_IN = plainDateFromISO('1970-01-01');+/** How a month navigation moves the focused day: by its row offset in days, or by whole calendar months or years. */type NavigationUnit = 'days' | 'months' | 'years';@@ -320,8 +324,9 @@ export function Calendar({ref, ...props}: CalendarProps) {// absurd number of month grids (e.g. `numberOfMonths={1000}`).const numberOfMonths = numberOfMonthsProp === 2 ? 2 : 1;- // Today's date (memoized)- const today = useMemo(() => plainDateToday(), []);+ // Today is unknown on the server and while hydrating, so the hydrating+ // render matches the server markup.+ const today = useToday();// Internal state for uncontrolled modeconst [internalValue, setInternalValue] = useState<@@ -342,10 +347,11 @@ export function Calendar({ref, ...props}: CalendarProps) {const effectiveValue =(value !== undefined ? value : internalValue) ?? undefined;- // Focus date state (which month is visible). Falls back to today, clamped+ // The month to open on: the focus date, else the value, else 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>(() =>+ // open on an all-disabled month. Without a focus date or a value it waits+ // for today, so it is unknown on the server and while hydrating.+ const getOpeningFocusDate = () =>getInitialFocusDate({focusDate: focusDateProp,value: effectiveValue,@@ -354,15 +360,33 @@ export function Calendar({ref, ...props}: CalendarProps) {numberOfMonths,today,calendar,- }),+ });++ // Focus date state (which month is visible). Null only while the opening+ // month waits for today.+ const [internalFocusDate, setInternalFocusDate] = useState<PlainDate | null>(+ getOpeningFocusDate,);// Use controlled focusDate if callback is provided, otherwise use internal stateconst isControlledFocus =focusDateProp !== undefined && onFocusDateChange !== undefined;- const focusDate = isControlledFocus+ // Store the opening month in the first render that knows today, so a later+ // pick or value change does not move the shown months.+ const openingFocusDate =+ !isControlledFocus && internalFocusDate == null && today != null+ ? getOpeningFocusDate()+ : null;+ if (openingFocusDate != null) {+ setInternalFocusDate(openingFocusDate);+ }+ const knownFocusDate = isControlledFocus? plainDateFromISO(focusDateProp)- : internalFocusDate;+ : (internalFocusDate ?? openingFocusDate);+ // Before the month is known the grid is hidden, and the month math below+ // uses a stand-in date that nothing can act on before hydration ends.+ const isMonthKnown = knownFocusDate != null;+ const focusDate = knownFocusDate ?? UNKNOWN_MONTH_STAND_IN;// Expose imperative handle for external navigationuseImperativeHandle(@@ -431,10 +455,12 @@ export function Calendar({ref, ...props}: CalendarProps) {// where the locale capitalizes one (FR1).const monthYearLabel = useMemo(() =>- visibleMonths- .map(m => formatCalendarMonthLabel(calendar, m, locale))- .join(' – '),- [calendar, visibleMonths, locale],+ isMonthKnown+ ? visibleMonths+ .map(m => formatCalendarMonthLabel(calendar, m, locale))+ .join(' – ')+ : '',+ [calendar, visibleMonths, locale, isMonthKnown],);// Announce the newly visible month to screen readers whenever it changes.@@ -449,8 +475,9 @@ export function Calendar({ref, ...props}: CalendarProps) {const announce = useAnnounce();const isInitialRenderRef = useRef(true);useEffect(() => {- if (isInitialRenderRef.current) {- isInitialRenderRef.current = false;+ // The first month shown, after a server render too, is not a change.+ if (isInitialRenderRef.current || monthYearLabel === '') {+ isInitialRenderRef.current = monthYearLabel === '';return;}announce(monthYearLabel);@@ -468,11 +495,13 @@ export function Calendar({ref, ...props}: CalendarProps) {// A month button is available while a day past the shown months is in range.const canNavigatePrevious =- minDateForKeys == null ||- plainDateIsBefore(minDateForKeys, baseMonth.start);+ isMonthKnown &&+ (minDateForKeys == null ||+ plainDateIsBefore(minDateForKeys, baseMonth.start));const canNavigateNext =- maxDateForKeys == null ||- plainDateIsAfter(maxDateForKeys, lastVisibleMonth.end);+ isMonthKnown &&+ (maxDateForKeys == null ||+ plainDateIsAfter(maxDateForKeys, lastVisibleMonth.end));// Navigation handlers// The same constraint view the grids use, so a key can resolve its target@@ -759,7 +788,16 @@ export function Calendar({ref, ...props}: CalendarProps) {/></div>{/* Month grids */}- <div {...stylex.props(calendarStyles.monthsContainer)}>+ {/* Before the month is known the grids keep their space but stay hidden+ and out of reach. With the default six-row grid, the month appears+ with no layout jump. */}+ <div+ aria-hidden={isMonthKnown ? undefined : true}+ inert={!isMonthKnown}+ {...stylex.props(+ calendarStyles.monthsContainer,+ !isMonthKnown && calendarStyles.monthsPending,+ )}>{visibleMonths.map(month => (<MonthGridkey={plainDateToISO(month.start)}@@ -822,7 +860,8 @@ interface MonthGridProps {weekStartsOn: DayOfWeek;onDayClick: (date: PlainDate) => void;onDayHover: (date: PlainDate | null) => void;- today: PlainDate;+ /** Today, or `null` on the server and while hydrating. */+ today: PlainDate | null;onNavigatePrevious?: (focusedDate: ISODateString,offset: number,@@ -921,8 +960,11 @@ function MonthGrid({}}- const isTodayInMonth = isInCalendarMonth(today, month);- if (isTodayInMonth && !isDateDisabled(today)) {+ if (+ today != null &&+ isInCalendarMonth(today, month) &&+ !isDateDisabled(today)+ ) {return plainDateToISO(today);}@@ -1239,7 +1281,7 @@ interface DayCellProps {rangeEnd: PlainDate | null;previewStart: PlainDate | null;previewEnd: PlainDate | null;- today: PlainDate;+ today: PlainDate | null;hasOutsideDays: boolean;isDisabled: boolean;/**diff --git a/packages/core/src/Calendar/CalendarToday.ssr.test.tsx b/packages/core/src/Calendar/CalendarToday.ssr.test.tsxnew file mode 100644index 0000000000..1b624852cf--- /dev/null+++ b/packages/core/src/Calendar/CalendarToday.ssr.test.tsx@@ -0,0 +1,133 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CalendarToday.ssr.test.tsx+ * @input Calendar server markup from a UTC server, hydrated in a browser whose+ * local date is already the next day+ * @output Proves hydration matches the server markup, and that today's marker+ * and the default month follow the browser's own date right after+ * @position SSR acceptance test for Calendar's reading of today+ */++import {act} from 'react';+import {fireEvent, within} from '@testing-library/react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {hydrateRoot} from 'react-dom/client';+import {renderToString} from 'react-dom/server';+import {Calendar} from './Calendar';++const originalTZ = process.env.TZ;++beforeEach(() => {+ vi.useFakeTimers({toFake: ['Date']});+ // 23:30 UTC on 30 November: still November in UTC, already 1 December+ // in a zone 14 hours ahead.+ vi.setSystemTime(new Date('2026-11-30T23:30:00Z'));+});++afterEach(() => {+ process.env.TZ = originalTZ;+ vi.useRealTimers();+ vi.restoreAllMocks();+ document.body.replaceChildren();+});++async function serverThenHydrate(tree: React.ReactElement) {+ process.env.TZ = 'UTC';+ const container = document.createElement('div');+ container.innerHTML = renderToString(tree);+ const serverMarkup = container.innerHTML;+ document.body.appendChild(container);++ process.env.TZ = 'Pacific/Kiritimati';+ const consoleErrors = vi.spyOn(console, 'error').mockImplementation(() => {});+ const recoverableErrors: unknown[] = [];+ let root!: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, tree, {+ onRecoverableError: error => recoverableErrors.push(error),+ });+ });+ const errors = [...recoverableErrors, ...consoleErrors.mock.calls];+ return {+ container,+ serverMarkup,+ errors,+ unmount: () => act(() => root.unmount()),+ };+}++describe('Calendar today across a server and a browser in different zones', () => {+ it('hydrates without a mismatch and then shows the browser’s month and today', async () => {+ const {container, serverMarkup, errors, unmount} = await serverThenHydrate(+ <Calendar />,+ );+ // The server knows no today: no day is marked, and the month grid keeps+ // its space but is hidden from everyone.+ expect(serverMarkup).not.toContain('aria-current');+ expect(serverMarkup).toContain('aria-hidden="true"');+ // The month label is empty and both month buttons are unavailable.+ const server = document.createElement('div');+ server.innerHTML = serverMarkup;+ const previous = within(server).getByRole('button', {+ name: 'Previous month',+ });+ const next = within(server).getByRole('button', {name: 'Next month'});+ for (const button of [previous, next]) {+ expect(button.matches(':disabled, [aria-disabled="true"]')).toBe(true);+ }+ const header = previous.parentElement!;+ expect(header.contains(next)).toBe(true);+ const headerText = [...header.childNodes]+ .filter(node => !node.contains(previous) && !node.contains(next))+ .map(node => node.textContent)+ .join('');+ expect(headerText).toBe('');+ expect(errors).toEqual([]);+ expect(+ container.querySelector('[role="grid"]')?.getAttribute('aria-label'),+ ).toBe('December 2026');+ expect(+ container+ .querySelector('[aria-current="date"]')+ ?.getAttribute('data-date'),+ ).toBe('2026-12-01');+ // The first month to appear is not a change, so nothing is announced.+ expect(+ document.querySelector('[data-astryx-live-region="polite"]'),+ ).toBeNull();+ unmount();+ });++ it('keeps both shown months when a day in the second month is picked after hydration', async () => {+ const {container, errors, unmount} = await serverThenHydrate(+ <Calendar numberOfMonths={2} />,+ );+ expect(errors).toEqual([]);+ const labels = () =>+ [...container.querySelectorAll('[role="grid"]')].map(grid =>+ grid.getAttribute('aria-label'),+ );+ expect(labels()).toEqual(['December 2026', 'January 2027']);+ await act(async () => {+ fireEvent.click(container.querySelector('[data-date="2027-01-15"]')!);+ });+ expect(labels()).toEqual(['December 2026', 'January 2027']);+ unmount();+ });++ it('hydrates without a mismatch on a shown month that holds both dates', async () => {+ const {container, errors, unmount} = await serverThenHydrate(+ <Calendar focusDate="2026-11-15" />,+ );+ expect(errors).toEqual([]);+ expect(+ container.querySelector('[role="grid"]')?.getAttribute('aria-label'),+ ).toBe('November 2026');+ // 1 December is an outside day here: no November day is today.+ expect(+ container.querySelector('[aria-current="date"][data-date^="2026-11"]'),+ ).toBeNull();+ unmount();+ });+});diff --git a/packages/core/src/Calendar/__tests__/CalendarTodayHydration.interaction.browser.spec.ts b/packages/core/src/Calendar/__tests__/CalendarTodayHydration.interaction.browser.spec.tsnew file mode 100644index 0000000000..51569a2f38--- /dev/null+++ b/packages/core/src/Calendar/__tests__/CalendarTodayHydration.interaction.browser.spec.ts@@ -0,0 +1,74 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CalendarTodayHydration.interaction.browser.spec.ts+ * @input The built CalendarHydration fixture stories and the page clock+ * @output In a real browser, Calendar markup rendered on 30 November hydrates+ * on 1 December with no recoverable error, then shows December with+ * 1 December as today; in a two-month view a pick in the second month keeps+ * both months+ * @position Real-browser server render, hydration and post-hydration evidence+ * for component:Calendar FR12; jsdom stands in only for the unit lane+ */++import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {openStory, withStorybook} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++test.use({timezoneId: 'UTC'});++const SERVER_TIME = new Date('2026-11-30T23:30:00Z');+const BROWSER_TIME = new Date('2026-12-01T00:30:00Z');++async function serverThenHydrate(page: Page, story: string) {+ await page.clock.setFixedTime(SERVER_TIME);+ await openStory(page, storybook(), story);+ await page.getByRole('button', {name: 'Server render'}).click();+ await expect(page.locator('output[data-phase="server"]')).toHaveCount(1);+ const host = page.getByTestId('host');+ // The server knows no today: no day is marked and the grid is hidden.+ await expect(host.locator('[aria-current="date"]')).toHaveCount(0);+ await expect(host.getByRole('grid')).toHaveCount(0);++ await page.clock.setFixedTime(BROWSER_TIME);+ await page.getByRole('button', {name: 'Hydrate'}).click();+ await expect(page.locator('output[data-phase="hydrated"]')).toHaveCount(1);+ return host;+}++test('Calendar markup from one date hydrates on the next date without an error, then shows the browser’s today', async ({+ page,+}) => {+ const host = await serverThenHydrate(+ page,+ 'core-calendarhydration--one-month',+ );+ await expect(host.getByRole('grid')).toHaveAttribute(+ 'aria-label',+ 'December 2026',+ );+ await expect(host.locator('[aria-current="date"]')).toHaveAttribute(+ 'data-date',+ '2026-12-01',+ );+ await expect(host.getByRole('button', {name: 'Next month'})).toBeEnabled();+ await expect(page.locator('output')).toHaveAttribute('data-errors', '0');+});++test('a pick in the second month of a hydrated two-month Calendar keeps both months', async ({+ page,+}) => {+ const host = await serverThenHydrate(+ page,+ 'core-calendarhydration--two-months',+ );+ const grids = host.getByRole('grid');+ await expect(grids).toHaveCount(2);+ await expect(grids.nth(0)).toHaveAttribute('aria-label', 'December 2026');+ await expect(grids.nth(1)).toHaveAttribute('aria-label', 'January 2027');+ await host.locator('[data-date="2027-01-15"]').click();+ await expect(grids.nth(0)).toHaveAttribute('aria-label', 'December 2026');+ await expect(grids.nth(1)).toHaveAttribute('aria-label', 'January 2027');+ await expect(page.locator('output')).toHaveAttribute('data-errors', '0');+});diff --git a/packages/core/src/Calendar/dayCellUtils.ts b/packages/core/src/Calendar/dayCellUtils.tsindex d945c10082..431474f60c 100644--- a/packages/core/src/Calendar/dayCellUtils.ts+++ b/packages/core/src/Calendar/dayCellUtils.ts@@ -26,7 +26,8 @@ export interface DayCellStateInput {rangeEnd: PlainDate | null;previewStart: PlainDate | null;previewEnd: PlainDate | null;- today: PlainDate;+ /** Today, or `null` on the server and while hydrating. */+ today: PlainDate | null;isDisabled: boolean;isOutside: boolean;}@@ -56,7 +57,7 @@ export function computeDayCellState(input: DayCellStateInput): DayCellState {return {effectivelyDisabled: isDisabled || isOutside,- isToday: !isOutside && plainDateIsEqual(date, today),+ isToday: !isOutside && today != null && plainDateIsEqual(date, today),isSelected: !!(!isOutside &&mode === 'single' &&diff --git a/packages/core/src/Calendar/getInitialFocusDate.test.ts b/packages/core/src/Calendar/getInitialFocusDate.test.tsindex 4b242a697e..c2884663e7 100644--- a/packages/core/src/Calendar/getInitialFocusDate.test.ts+++ b/packages/core/src/Calendar/getInitialFocusDate.test.ts@@ -16,12 +16,25 @@ 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}),- );+ const date = getInitialFocusDate({+ numberOfMonths: 1,+ today: TODAY,+ ...options,+ });+ return date == null ? null : plainDateToISO(date);}describe('getInitialFocusDate', () => {+ it('waits for today when there is no focus date or value', () => {+ expect(focusISO({today: null})).toBeNull();+ expect(focusISO({today: null, min: '2026-01-01'})).toBeNull();+ });++ it('opens on the focus date or the value while today is unknown', () => {+ expect(focusISO({today: null, focusDate: '2026-03-04'})).toBe('2026-03-04');+ expect(focusISO({today: null, value: '2026-05-06'})).toBe('2026-05-06');+ });+it('opens on today when there are no bounds', () => {expect(focusISO({})).toBe('2026-08-21');});diff --git a/packages/core/src/Calendar/getInitialFocusDate.ts b/packages/core/src/Calendar/getInitialFocusDate.tsindex a4cffd2cf2..a4197d51dd 100644--- a/packages/core/src/Calendar/getInitialFocusDate.ts+++ b/packages/core/src/Calendar/getInitialFocusDate.ts@@ -35,8 +35,11 @@ export interface InitialFocusDateOptions {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;+ /**+ * Today, injected so the caller keeps one source of "now"; `null` when it is+ * not known yet (server render, hydration).+ */+ today: PlainDate | null;/** The calendar system whose months the panes show. Default: `gregory`. */calendar?: CalendarSystem;}@@ -48,7 +51,8 @@ export interface InitialFocusDateOptions {* 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.+ * Otherwise the calendar opens on today, clamped into the `min`/`max` window,+ * or returns `null` while today is not known yet.* 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.@@ -61,7 +65,7 @@ export interface InitialFocusDateOptions {*/export function getInitialFocusDate(options: InitialFocusDateOptions,-): PlainDate {+): PlainDate | null {const {focusDate,value,@@ -80,6 +84,12 @@ export function getInitialFocusDate(return plainDateFromISO(typeof value === 'string' ? value : value.start);}+ // Without a focus date or a value the month follows today, which is not+ // known yet on the server and while hydrating.+ if (today == null) {+ return null;+ }+const minDate = min ? plainDateFromISO(min) : null;const maxDate = max ? plainDateFromISO(max) : null;diff --git a/packages/core/src/Calendar/styles.ts b/packages/core/src/Calendar/styles.tsindex 0d8a5f9a6e..eff1b52c03 100644--- a/packages/core/src/Calendar/styles.ts+++ b/packages/core/src/Calendar/styles.ts@@ -49,6 +49,10 @@ export const calendarStyles = stylex.create({fontSize: typeScaleVars['--text-label-size'],color: colorVars['--color-text-primary'],},+ // The month is not known yet (server render, hydration): keep the space.+ monthsPending: {+ visibility: 'hidden',+ },monthsContainer: {display: 'flex',// Wraps rather than overflowing: two months side by side need ~488px, sodiff --git a/packages/core/src/DateRangeInput/DateRangeInput.ssr.test.tsx b/packages/core/src/DateRangeInput/DateRangeInput.ssr.test.tsxnew file mode 100644index 0000000000..1d612a6973--- /dev/null+++ b/packages/core/src/DateRangeInput/DateRangeInput.ssr.test.tsx@@ -0,0 +1,64 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file DateRangeInput.ssr.test.tsx+ * @input DateRangeInput server markup from a UTC server, hydrated in a browser+ * whose local date is already in the next year+ * @output Proves the trigger's range text hydrates without a mismatch, and+ * drops the current year right after+ * @position SSR acceptance test for DateRangeInput's reading of today+ */++import {act} from 'react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {hydrateRoot} from 'react-dom/client';+import {renderToString} from 'react-dom/server';+import {DateRangeInput} from './DateRangeInput';++const originalTZ = process.env.TZ;++beforeEach(() => {+ vi.useFakeTimers({toFake: ['Date']});+ // 23:30 UTC on 31 December 2026: still 2026 in UTC, already 2027 in a zone+ // 14 hours ahead.+ vi.setSystemTime(new Date('2026-12-31T23:30:00Z'));+});++afterEach(() => {+ process.env.TZ = originalTZ;+ vi.useRealTimers();+ vi.restoreAllMocks();+ document.body.replaceChildren();+});++describe('DateRangeInput range text across a server and a browser in different zones', () => {+ it('hydrates without a mismatch and then drops the browser’s current year', async () => {+ const tree = (+ <DateRangeInput+ label="Trip"+ value={{start: '2027-01-04', end: '2027-01-08'}}+ onChange={() => {}}+ />+ );+ process.env.TZ = 'UTC';+ const container = document.createElement('div');+ container.innerHTML = renderToString(tree);+ document.body.appendChild(container);++ process.env.TZ = 'Pacific/Kiritimati';+ const consoleErrors = vi+ .spyOn(console, 'error')+ .mockImplementation(() => {});+ const recoverableErrors: unknown[] = [];+ let root!: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, tree, {+ onRecoverableError: error => recoverableErrors.push(error),+ });+ });+ expect([...recoverableErrors, ...consoleErrors.mock.calls]).toEqual([]);+ expect(container.textContent).toContain('Jan 4 – Jan 8');+ expect(container.textContent).not.toContain('2027');+ act(() => root.unmount());+ });+});diff --git a/packages/core/src/DateRangeInput/DateRangeInput.tsx b/packages/core/src/DateRangeInput/DateRangeInput.tsxindex 411de12303..f111d900cb 100644--- a/packages/core/src/DateRangeInput/DateRangeInput.tsx+++ b/packages/core/src/DateRangeInput/DateRangeInput.tsx@@ -29,7 +29,6 @@ import * as stylex from '@stylexjs/stylex';import {inputDisabledFocusStyles} from '../Field/inputDisabledFocus';import {plainDateFromISO,- plainDateToday,plainDateDiffDays,type PlainDate,DATE_FORMAT_SHORT,@@ -85,6 +84,7 @@ import {useSize} from '../SizeContext/SizeContext';import {useInputStatusIcon} from '../hooks/useInputStatusIcon';import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';import {useMergedRefs} from '../hooks/useMergedRefs';+import {useToday} from '../hooks/useToday';import {useResolvedRequired} from '../hooks/useResolvedRequired';import {themeProps} from '../utils/themeProps';import {focusOutlineStyles} from '../utils/focusOutline.stylex';@@ -274,6 +274,7 @@ function formatRangeDisplay(range: DateRange | null,locale: Locale,calendar: CalendarSystem,+ today: PlainDate | null,): string {if (!range) {return '';@@ -282,9 +283,11 @@ function formatRangeDisplay(const end = plainDateFromISO(range.end);const yearOf = (pd: PlainDate) =>calendarYearMonthOf(calendar, calendarMonthOf(calendar, pd)).year;- const currentYear = yearOf(plainDateToday());+ // While today is unknown (server render, hydration) the year shows.const sameYear =- yearOf(start) === yearOf(end) && yearOf(start) === currentYear;+ today != null &&+ yearOf(start) === yearOf(end) &&+ yearOf(start) === yearOf(today);const fmt = sameYear ? DATE_FORMAT_SHORT : DATE_FORMAT_SHORT_WITH_YEAR;return `${formatCalendarDate(calendar, start, fmt, locale)} – ${formatCalendarDate(calendar, end, fmt, locale)}`;@@ -664,9 +667,10 @@ export function DateRangeInput({.filter(Boolean).join(' ') || undefined;+ const today = useToday();const displayValue = useMemo(- () => formatRangeDisplay(optimisticValue, locale, calendar),- [optimisticValue, locale, calendar],+ () => formatRangeDisplay(optimisticValue, locale, calendar, today),+ [optimisticValue, locale, calendar, today],);const popover = usePopover({diff --git a/packages/core/src/hooks/useToday.ts b/packages/core/src/hooks/useToday.tsnew file mode 100644index 0000000000..0c31756898--- /dev/null+++ b/packages/core/src/hooks/useToday.ts@@ -0,0 +1,31 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useToday.ts+ * @input Uses useIsHydrating and the browser's local date+ * @output Exports useToday (internal; not re-exported from hooks/index.ts)+ * @position Internal utility; today's date for Calendar, DateRangeInput and+ * the sheet date fields+ */++import {useMemo} from 'react';+import {useIsHydrating} from './useIsHydrating';+import {+ plainDateFromISO,+ plainDateToISO,+ plainDateToday,+ type PlainDate,+} from '../utils/plainDate';++/**+ * Returns the browser's local date, or `null` during server render and the+ * render that hydrates server HTML. A server and a browser can be on different+ * dates, so a value read there would not match.+ */+export function useToday(): PlainDate | null {+ // A string stays equal for the whole day, so the memo holds.+ const iso = useIsHydrating() ? null : plainDateToISO(plainDateToday());+ return useMemo(() => (iso == null ? null : plainDateFromISO(iso)), [iso]);+}