An open source design system that's fully customizable and agent ready
TypeScript
fix(DateInput, DateTimeInput): the sheet's calendar waits for today, so hydration matches (#10400)
Cindy Zhang36c29737fccb
diff --git a/.changeset/date-sheet-today-hydration.md b/.changeset/date-sheet-today-hydration.mdnew file mode 100644index 0000000000..98e616e500--- /dev/null+++ b/.changeset/date-sheet-today-hydration.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A `DateInput` or `DateTimeInput` with `presentation="bottom-sheet"` no longer causes a hydration mismatch when the server and the browser are on different dates. The closed sheet's calendar now renders right after hydration, once the browser's today is known.++@cixzhangdiff --git a/apps/storybook/stories/CalendarTodayHydration.stories.tsx b/apps/storybook/stories/CalendarTodayHydration.stories.tsxindex 3807ceaf92..f14ee3ce8a 100644--- a/apps/storybook/stories/CalendarTodayHydration.stories.tsx+++ b/apps/storybook/stories/CalendarTodayHydration.stories.tsx@@ -3,17 +3,18 @@/*** @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+ * @output A fixture that server-renders Calendar, or a sheet DateInput or+ * DateTimeInput, 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+ * for component:Calendar FR12 and the sheet fields of spec:AST-013 FR9*/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';+import {Calendar, DateInput, DateTimeInput} from '@astryxdesign/core';const meta = {title: 'Core/CalendarHydration',@@ -79,3 +80,31 @@ export const OneMonth: Story = {export const TwoMonths: Story = {render: () => <HydrationFixture tree={<Calendar numberOfMonths={2} />} />,};++export const SheetDateInput: Story = {+ render: () => (+ <HydrationFixture+ tree={+ <DateInput+ label="Due"+ presentation="bottom-sheet"+ onChange={() => {}}+ />+ }+ />+ ),+};++export const SheetDateTimeInput: Story = {+ render: () => (+ <HydrationFixture+ tree={+ <DateTimeInput+ label="Starts"+ presentation="bottom-sheet"+ onChange={() => {}}+ />+ }+ />+ ),+};diff --git a/docs/specs/components/DateInput/DateInput.spec.md b/docs/specs/components/DateInput/DateInput.spec.mdindex 3bcec81c67..6cececd94c 100644--- a/docs/specs/components/DateInput/DateInput.spec.md+++ b/docs/specs/components/DateInput/DateInput.spec.md@@ -14,6 +14,7 @@ verified_by:[packages/core/src/DateInput/MonthScrollerSettle.test.tsx,packages/core/src/DateInput/DateInput.test.tsx,+ packages/core/src/DateInput/TouchDateToday.ssr.test.tsx,packages/core/src/DateInput/DateInput.fr10.test.tsx,packages/core/src/DateInput/DateInput.calendar.test.tsx,packages/core/src/DateInput/DateInput.calendarPresentation.test.tsx,@@ -47,6 +48,7 @@ architecture:contributing: []system_specs:[+ spec:AST-013/FR9,spec:AST-013/FR12,spec:AST-020/FR15,spec:AST-043,diff --git a/docs/specs/components/DateTimeInput/DateTimeInput.spec.md b/docs/specs/components/DateTimeInput/DateTimeInput.spec.mdindex 41e8769094..ef92b139bd 100644--- a/docs/specs/components/DateTimeInput/DateTimeInput.spec.md+++ b/docs/specs/components/DateTimeInput/DateTimeInput.spec.md@@ -13,6 +13,7 @@ review_triggers: [public-api, behavior, layout, theming, accessibility]verified_by:[packages/core/src/DateTimeInput/DateTimeInput.test.tsx,+ packages/core/src/DateInput/TouchDateToday.ssr.test.tsx,packages/core/src/DateTimeInput/DateTimeInputTouch.test.tsx,packages/core/src/DateTimeInput/NativePickerSegments.test.tsx,packages/core/src/DateTimeInput/Presentation.test.tsx,@@ -37,6 +38,7 @@ architecture:contributing: []system_specs:[+ spec:AST-013/FR9,spec:AST-013/FR12,spec:AST-043,spec:AST-085,diff --git a/packages/core/src/Calendar/__tests__/CalendarTodayHydration.interaction.browser.spec.ts b/packages/core/src/Calendar/__tests__/CalendarTodayHydration.interaction.browser.spec.tsindex 51569a2f38..0430242cdd 100644--- a/packages/core/src/Calendar/__tests__/CalendarTodayHydration.interaction.browser.spec.ts+++ b/packages/core/src/Calendar/__tests__/CalendarTodayHydration.interaction.browser.spec.ts@@ -6,9 +6,10 @@* @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+ * both months; a sheet DateInput and DateTimeInput do the same when opened* @position Real-browser server render, hydration and post-hydration evidence- * for component:Calendar FR12; jsdom stands in only for the unit lane+ * for component:Calendar FR12 and the sheet fields of spec:AST-013 FR9;+ * jsdom stands in only for the unit lane*/import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';@@ -72,3 +73,29 @@ test('a pick in the second month of a hydrated two-month Calendar keeps both monawait expect(grids.nth(1)).toHaveAttribute('aria-label', 'January 2027');await expect(page.locator('output')).toHaveAttribute('data-errors', '0');});++for (const [name, story, opener] of [+ ['DateInput', 'core-calendarhydration--sheet-date-input', {name: 'Due'}],+ [+ 'DateTimeInput',+ 'core-calendarhydration--sheet-date-time-input',+ // A DateTimeInput also has a "Starts time" combobox.+ {name: 'Starts', exact: true},+ ],+] as const) {+ test(`a sheet ${name} from one date hydrates on the next date without an error, then opens on the browser’s today`, async ({+ page,+ }) => {+ const host = await serverThenHydrate(page, story);+ await host.getByRole('combobox', opener).click();+ const sheet = page.locator('dialog[open]');+ await expect(+ sheet.getByRole('button', {name: 'December 2026', exact: false}).first(),+ ).toBeVisible();+ await expect(sheet.locator('[aria-current="date"]')).toHaveAttribute(+ 'data-date',+ '2026-12-01',+ );+ await expect(page.locator('output')).toHaveAttribute('data-errors', '0');+ });+}diff --git a/packages/core/src/DateInput/MonthScroller.tsx b/packages/core/src/DateInput/MonthScroller.tsxindex 29c6dac321..5bf595f1e4 100644--- a/packages/core/src/DateInput/MonthScroller.tsx+++ b/packages/core/src/DateInput/MonthScroller.tsx@@ -300,8 +300,11 @@ export interface MonthScrollerProps {onVisibleMonthChange: (monthIndex: number) => void;/** Currently selected date. */selectedDate: PlainDate | null;- /** Today, for the `aria-current` marker. */- today: PlainDate;+ /**+ * Today, for the `aria-current` marker; `null` while it is not known yet+ * (server render, hydration).+ */+ today: PlainDate | null;/** Whether a date fails min/max or a custom constraint. */isDateDisabled: (date: PlainDate) => boolean;/** First column of the week. */@@ -894,7 +897,8 @@ interface MonthPaneProps {inlineSize: number;selectedDate: PlainDate | null;focusedDate: PlainDate | null;- today: PlainDate;+ /** Today, or `null` while it is not known yet (server render, hydration). */+ today: PlainDate | null;isDateDisabled: (date: PlainDate) => boolean;weekStartsOn: DayOfWeek;onSelect: (value: ISODateString) => void;@@ -975,7 +979,10 @@ function MonthPane({!day.isOutside &&selectedDate != null &&plainDateIsEqual(day.date, selectedDate);- const isToday = !day.isOutside && plainDateIsEqual(day.date, today);+ const isToday =+ !day.isOutside &&+ today != null &&+ plainDateIsEqual(day.date, today);return (<divdiff --git a/packages/core/src/DateInput/TouchDateField.tsx b/packages/core/src/DateInput/TouchDateField.tsxindex 1f17bcdbb5..653efb140d 100644--- a/packages/core/src/DateInput/TouchDateField.tsx+++ b/packages/core/src/DateInput/TouchDateField.tsx@@ -76,6 +76,7 @@ import {} from '../Field';import {useInputStatusIcon, useMergedRefs} from '../hooks';import {useResolvedRequired} from '../hooks/useResolvedRequired';+import {useToday} from '../hooks/useToday';import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';import {Icon} from '../Icon';import {IconButton} from '../IconButton';@@ -140,6 +141,10 @@ import {} from '../i18n/useComponentTranslator';import english from '../i18n/generated-english/DateInput/TouchDateField.generated';+// The month math needs a date before today is known (server render,+// hydration). The sheet's content, which shows the month, waits for today.+const UNKNOWN_TODAY_STAND_IN = plainDateFromISO('1970-01-01');+registerEnglishFallback(english);/**@@ -700,7 +705,9 @@ export function TouchDateField({[],);- const today = useMemo(() => plainDateToday(), []);+ // Unknown on the server and while hydrating. The sheet's content waits for+ // it, so hydration matches the server markup.+ const today = useToday();const selectedDate = useMemo(() =>optimisticValue != null && /^\d{4}-\d{2}-\d{2}$/.test(optimisticValue)@@ -710,18 +717,28 @@ export function TouchDateField({);// The reachable range. Explicit bounds win; otherwise the scroller reaches a- // century in each direction from wherever it opened. Anchored once, in a- // state initializer: recomputing it as the selection moves would shift every- // pane's scroll offset under the user mid-gesture.+ // century in each direction from wherever it opened. It is anchored once:+ // recomputing it as the selection moves would shift every pane's scroll+ // offset under the user mid-gesture.// Indexes belong to the calendar, so DateInput remounts this surface when// the calendar changes.- const [anchorMonthIndex] = useState(() =>- monthModel.indexOf(- value != null && /^\d{4}-\d{2}-\d{2}$/.test(value)- ? plainDateFromISO(value)- : plainDateToday(),- ),+ // Without a value, the sheet opens on today's month. A hydrated sheet stores+ // that month in the first render that knows today. Then a later render after+ // a month-end midnight does not move an open sheet.+ const [anchoredMonthIndex, setAnchoredMonthIndex] = useState<number | null>(+ () => {+ const opening =+ value != null && /^\d{4}-\d{2}-\d{2}$/.test(value)+ ? plainDateFromISO(value)+ : today;+ return opening == null ? null : monthModel.indexOf(opening);+ },);+ if (anchoredMonthIndex == null && today != null) {+ setAnchoredMonthIndex(monthModel.indexOf(today));+ }+ const anchorMonthIndex =+ anchoredMonthIndex ?? monthModel.indexOf(today ?? UNKNOWN_TODAY_STAND_IN);const minMonthIndex =min != null? monthModel.indexOf(plainDateFromISO(min))@@ -731,9 +748,15 @@ export function TouchDateField({? monthModel.indexOf(plainDateFromISO(max)): anchorMonthIndex + DEFAULT_MONTH_REACH;- const [monthIndex, setMonthIndex] = useState(() =>- clampIndex(anchorMonthIndex, minMonthIndex, maxMonthIndex),+ // Set once the person moves the month; until then the opening month.+ const [chosenMonthIndex, setMonthIndex] = useState<number | null>(() =>+ anchoredMonthIndex == null+ ? null+ : clampIndex(anchoredMonthIndex, minMonthIndex, maxMonthIndex),);+ const monthIndex =+ chosenMonthIndex ??+ clampIndex(anchorMonthIndex, minMonthIndex, maxMonthIndex);const weekdayHeaders = useMemo(() => getWeekdayHeaders(locale, weekStartsOn),@@ -848,7 +871,7 @@ export function TouchDateField({return;}fireChange(undefined);- const currentMonth = monthModel.indexOf(today);+ const currentMonth = monthModel.indexOf(plainDateToday());if (currentMonth < minMonthIndex || currentMonth > maxMonthIndex) {return;}@@ -861,7 +884,6 @@ export function TouchDateField({isDisabled,fireChange,monthModel,- today,monthIndex,minMonthIndex,maxMonthIndex,@@ -1420,7 +1442,7 @@ export function TouchDateField({// sheetBody owns the inset, including the band under the grab handle.padding={0}><div ref={sheetBodyRef} {...stylex.props(styles.sheetBody)}>- {surface}+ {today != null && surface}</div></BottomSheet>{showsDisabledMessage &&diff --git a/packages/core/src/DateInput/TouchDateToday.ssr.test.tsx b/packages/core/src/DateInput/TouchDateToday.ssr.test.tsxnew file mode 100644index 0000000000..feea135723--- /dev/null+++ b/packages/core/src/DateInput/TouchDateToday.ssr.test.tsx@@ -0,0 +1,194 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TouchDateToday.ssr.test.tsx+ * @input DateInput and DateTimeInput sheet markup from a UTC server, hydrated+ * in a browser whose local date is already the next month+ * @output Proves hydration matches the server markup+ * @position SSR acceptance test for the sheet date fields' reading of today+ */++import {act, useState} from 'react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {fireEvent} from '@testing-library/react';+import {hydrateRoot} from 'react-dom/client';+import {renderToString} from 'react-dom/server';+import {DateInput} from './DateInput';+import {DateTimeInput} from '../DateTimeInput/DateTimeInput';++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'));+ // jsdom has no ResizeObserver; the month scroller measures with one.+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+});++afterEach(() => {+ process.env.TZ = originalTZ;+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ document.body.replaceChildren();+});++async function hydrationErrors(tree: React.ReactElement) {+ 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),+ });+ });+ const errors = [...recoverableErrors, ...consoleErrors.mock.calls];+ act(() => root.unmount());+ return errors;+}++describe('sheet date fields across a server and a browser in different zones', () => {+ it('hydrates a sheet DateInput without a mismatch', async () => {+ expect(+ await hydrationErrors(+ <DateInput+ label="Due"+ presentation="bottom-sheet"+ onChange={() => {}}+ />,+ ),+ ).toEqual([]);+ });++ it('hydrates a sheet DateTimeInput without a mismatch', async () => {+ expect(+ await hydrationErrors(+ <DateTimeInput+ label="Starts"+ presentation="bottom-sheet"+ onChange={() => {}}+ />,+ ),+ ).toEqual([]);+ });+});++// The sheet opens on today's month. After hydration that month is stored in+// the first render that knows today, so an open sheet keeps its month when a+// later render runs past midnight at a month end.+describe('sheet date fields after hydration, across a month-end midnight', () => {+ const SCROLLPORT_WIDTH = 360;++ // jsdom lays nothing out, so the month scrollport reports its CSS width+ // only while the test renders and opens the sheet.+ function withLayout<T>(fn: () => T): T {+ Object.defineProperty(HTMLElement.prototype, 'clientWidth', {+ configurable: true,+ get(this: HTMLElement) {+ return this.dataset?.scroller === 'months' ? SCROLLPORT_WIDTH : 0;+ },+ });+ try {+ return fn();+ } finally {+ delete (HTMLElement.prototype as {clientWidth?: unknown}).clientWidth;+ }+ }++ beforeEach(() => {+ Element.prototype.scrollTo = vi.fn();+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.open = true;+ });+ HTMLDialogElement.prototype.close = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.open = false;+ });+ });++ // The heading button in the open sheet names the shown month.+ const monthTitle = () =>+ [+ ...document.querySelectorAll<HTMLButtonElement>(+ 'dialog[open] button[aria-expanded]',+ ),+ ]+ .map(button => button.textContent)+ .join(' | ');++ async function openThenCrossMidnight(+ opener: string,+ field: (renderCount: number) => React.ReactElement,+ ) {+ process.env.TZ = 'UTC';+ let rerender!: () => void;+ function Host() {+ const [renderCount, setRenderCount] = useState(0);+ rerender = () => setRenderCount(count => count + 1);+ return field(renderCount);+ }+ const container = document.createElement('div');+ container.innerHTML = renderToString(<Host />);+ document.body.appendChild(container);+ let root!: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, <Host />);+ });+ withLayout(() => fireEvent.click(container.querySelector(opener)!));+ const before = monthTitle();+ // 00:30 UTC on 1 December: the next render reads a new today.+ vi.setSystemTime(new Date('2026-12-01T00:30:00Z'));+ withLayout(() => act(() => rerender()));+ const after = monthTitle();+ act(() => root.unmount());+ return {before, after};+ }++ it('keeps an open sheet DateInput on its month', async () => {+ const {before, after} = await openThenCrossMidnight(+ '[role="combobox"]',+ renderCount => (+ <DateInput+ label={renderCount > 0 ? 'Due date' : 'Due'}+ presentation="bottom-sheet"+ onChange={() => {}}+ />+ ),+ );+ expect(before).toContain('November 2026');+ expect(after).toContain('November 2026');+ });++ it('keeps an open sheet DateTimeInput on its month', async () => {+ const {before, after} = await openThenCrossMidnight(+ 'input[inputmode="none"]',+ renderCount => (+ <DateTimeInput+ label={renderCount > 0 ? 'Start time' : 'Starts'}+ presentation="bottom-sheet"+ onChange={() => {}}+ />+ ),+ );+ expect(before).toContain('November 2026');+ expect(after).toContain('November 2026');+ });+});diff --git a/packages/core/src/DateTimeInput/TouchDateTimeField.tsx b/packages/core/src/DateTimeInput/TouchDateTimeField.tsxindex 1f7db5d87f..d63b3d0b49 100644--- a/packages/core/src/DateTimeInput/TouchDateTimeField.tsx+++ b/packages/core/src/DateTimeInput/TouchDateTimeField.tsx@@ -48,6 +48,7 @@ import {} from '../Field';import {useInputStatusIcon, useMergedRefs} from '../hooks';import {useResolvedRequired} from '../hooks/useResolvedRequired';+import {useToday} from '../hooks/useToday';import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';import {Icon} from '../Icon';import {IconButton} from '../IconButton';@@ -130,6 +131,10 @@ import {import {InternationalizationContext} from '../i18n/InternationalizationContext';import english from '../i18n/generated-english/DateTimeInput/TouchDateTimeField.generated';+// The month math needs a date before today is known (server render,+// hydration). The sheet's content, which shows the month, waits for today.+const UNKNOWN_TODAY_STAND_IN = plainDateFromISO('1970-01-01');+registerEnglishFallback(english);function splitDateTime(dt: ISODateTimeString | undefined): {@@ -566,7 +571,9 @@ export function TouchDateTimeField({normalizeISOTime(splitDateTime(value).time, hasSeconds),);- const today = useMemo(() => plainDateToday(), []);+ // Unknown on the server and while hydrating. The sheet's content waits for+ // it, so hydration matches the server markup.+ const today = useToday();const selectedDate = useMemo(() => parseValidISODate(valueParts.date),[valueParts.date],@@ -609,9 +616,20 @@ export function TouchDateTimeField({// Indexes belong to the calendar, so DateTimeInput remounts this surface// when the calendar changes.- const [anchorMonthIndex] = useState(() =>- monthModel.indexOf(selectedDate ?? plainDateToday()),+ // Without a value, the sheet opens on today's month. A hydrated sheet stores+ // that month in the first render that knows today. Then a later render after+ // a month-end midnight does not move an open sheet.+ const [anchoredMonthIndex, setAnchoredMonthIndex] = useState<number | null>(+ () => {+ const opening = selectedDate ?? today;+ return opening == null ? null : monthModel.indexOf(opening);+ },);+ if (anchoredMonthIndex == null && today != null) {+ setAnchoredMonthIndex(monthModel.indexOf(today));+ }+ const anchorMonthIndex =+ anchoredMonthIndex ?? monthModel.indexOf(today ?? UNKNOWN_TODAY_STAND_IN);const minMonthIndex =calendarMin != null? monthModel.indexOf(plainDateFromISO(calendarMin))@@ -620,22 +638,27 @@ export function TouchDateTimeField({calendarMax != null? monthModel.indexOf(plainDateFromISO(calendarMax)): anchorMonthIndex + DEFAULT_MONTH_REACH;- const [monthIndex, setMonthIndex] = useState(() =>- clampIndex(anchorMonthIndex, minMonthIndex, maxMonthIndex),+ // Set once the person moves the month; until then the opening month.+ const [chosenMonthIndex, setMonthIndex] = useState<number | null>(() =>+ anchoredMonthIndex == null+ ? null+ : clampIndex(anchoredMonthIndex, minMonthIndex, maxMonthIndex),);// min/max can narrow underneath the mounted sheet. Keep the visible month in// range during render, so no commit shows an out-of-range month; the month// scroller is keyed on the range and remounts at the clamped month.- const clampedMonthIndex = clampIndex(- monthIndex,- minMonthIndex,- maxMonthIndex,- );+ const clampedChosenMonthIndex =+ chosenMonthIndex == null+ ? null+ : clampIndex(chosenMonthIndex, minMonthIndex, maxMonthIndex);// Object.is, matching the dependency comparison of the effect this replaces// (a NaN index would otherwise never compare equal and re-render forever).- if (!Object.is(clampedMonthIndex, monthIndex)) {- setMonthIndex(clampedMonthIndex);+ if (!Object.is(clampedChosenMonthIndex, chosenMonthIndex)) {+ setMonthIndex(clampedChosenMonthIndex);}+ const monthIndex =+ clampedChosenMonthIndex ??+ clampIndex(anchorMonthIndex, minMonthIndex, maxMonthIndex);const canStepBack = monthIndex > minMonthIndex;const canStepForward = monthIndex < maxMonthIndex;@@ -768,13 +791,13 @@ export function TouchDateTimeField({const handleResetInSheet = useCallback(() => {fireChange(undefined);setDraftTime(undefined);- const currentMonth = monthModel.indexOf(today);+ const currentMonth = monthModel.indexOf(plainDateToday());if (currentMonth < minMonthIndex || currentMonth > maxMonthIndex) {return;}setMonthIndex(currentMonth);scrollerHandleRef.current?.scrollToMonth(currentMonth, 'smooth');- }, [fireChange, monthModel, today, minMonthIndex, maxMonthIndex]);+ }, [fireChange, monthModel, minMonthIndex, maxMonthIndex]);const handleDateSelect = useCallback((nextDate: ISODateString) => {@@ -1459,7 +1482,7 @@ export function TouchDateTimeField({// handle.padding={0}><div ref={sheetBodyRef} {...stylex.props(styles.touchSheetBody)}>- {surface}+ {today != null && surface}</div></BottomSheet>{showsDisabledMessage &&