Skip to content

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

TypeScript

feat(core)!: DateInput fits the pointer — a touch picker on a finger, the text field on a mouse (#5243)

Xinzi Zhou52720e0d8dfe
diff --git a/.changeset/date-input-touch-surface.md b/.changeset/date-input-touch-surface.md
new file mode 100644
index 0000000000..9549b1bc97
--- /dev/null
+++ b/.changeset/date-input-touch-surface.md
@@ -0,0 +1,64 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] DateInput fits the pointer: a touch picker on a finger, the text field
+on a mouse
+
+`DateInput` has always been a control for a mouse — a field you type into with
+a calendar in a popover beside it. On a phone or a tablet that is the wrong
+shape: the popover is a desktop calendar operated by thumb, and focusing the
+field summons a keyboard that covers the thing it is meant to fill in.
+
+The same component now renders a second surface where the primary pointer is a
+finger (`pointer: coarse`): a bottom sheet holding one month per screen, swiped
+sideways, with month and year wheels behind the header title for the far jumps
+swiping is bad at, arrows in the header corner for a single step, and every
+target floored at 44px. A day commits the moment it is tapped and leaves the
+sheet up, so a mistake can be corrected in place; Save closes the picker, and
+Reset puts it back to how it opened — no date, current month. The grid spills
+adjacent-month days, muted and unselectable, and the weekday header is three
+letters rather than two, both as the desktop calendar has them.
+
+The month and year wheels are one layer that fades in and out on top of the
+calendar. The calendar itself never fades — it is covered and uncovered, so
+the only thing moving is the thing arriving. The layer carries an opaque
+background of its own, which is what makes the fade uniform: it renders as a
+finished image and the fade applies to the image, rather than the wheels'
+translucent selection band compositing against a live grid on its own terms.
+
+Nothing changes at the call site. It is one component with two surfaces, not
+two components — same props, same values, no new import, no media query to
+write. Existing usage is untouched: with a mouse the rendered output is the
+control that was always there.
+
+The switch is the pointer alone, deliberately with no width bound. `pointer`
+means the PRIMARY device, so a touchscreen laptop reports `fine` and keeps the
+typable field (its keyboard is right there), while a narrowed desktop window is
+still a mouse. Adding a width test would only re-exclude tablets, which are the
+clearest case for a thumb picker.
+
+The public surface barely moves. One new export — `TOUCH_POINTER_QUERY`, the
+media query the switch uses, so an app can ask the same question the component
+does and lay out to match — plus six `@astryx.dateInput.*` catalog keys for
+the picker's header and footer.
+
+Nothing else is published, on purpose. There is no export that forces a
+surface: the touch picker is reachable by being on a touch device, which is
+the only place it is worth looking at. The picker's two sizes (the 44px day
+cell, the 28px wheel row) are compile-time constants rather than theme
+variables — the day size is an accessibility floor, and a variable a theme can
+quietly lower is not a floor. And the sheet's header button is addressed by a
+`data-` attribute rather than a theme target, because nothing has asked to
+restyle it. Each of those is additive later and awkward to withdraw once
+shipped.
+
+The wheels also answer a mouse now. A wheel is a scroll container, so a finger
+pans it for free; a mouse got nothing, because browsers do not drag-scroll an
+overflow container — pressing and pulling on the one control shaped like a
+thing you spin did nothing at all. Dragging with a mouse works, and fixes a
+related bug on the way: BottomSheet begins its own drag from a `pointerdown`
+on its body and captures the pointer for it, so a click on a wheel row that
+wobbled more than a pixel or two used to select nothing.
+
+@imdreamrunner
diff --git a/apps/storybook/stories/DateInput.stories.tsx b/apps/storybook/stories/DateInput.stories.tsx
index ccf81fd20e..6983f36961 100644
--- a/apps/storybook/stories/DateInput.stories.tsx
+++ b/apps/storybook/stories/DateInput.stories.tsx
@@ -11,6 +11,28 @@ const meta: Meta<typeof DateInput> = {
title: 'Core/DateInput',
component: DateInput,
tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'A date field that fits the pointer it is used with. Every story ' +
+ 'below shows the pointer surface — a text input you can type into ' +
+ 'with a calendar in a popover — because that is the right answer ' +
+ 'for the mouse you are reading this with.\n\n' +
+ 'Where the primary pointer is a finger (`pointer: coarse`), the ' +
+ 'same component renders a picker built for one instead: a bottom ' +
+ 'sheet of months swiped sideways, with month and year wheels ' +
+ 'behind the header title, and no text entry (the keyboard would ' +
+ 'cover the sheet it is meant to fill in). Same props either way — ' +
+ 'there is nothing to opt into.\n\n' +
+ '**Seeing the touch surface:** open any story below on a phone or ' +
+ 'tablet, or in a device-emulated tab reporting a coarse pointer. ' +
+ 'Every one of them renders it — they are the same stories, and ' +
+ 'that is the point. There is no separate touch story because there ' +
+ 'is no separate thing to adopt.',
+ },
+ },
+ },
argTypes: {
label: {
control: 'text',
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 6a8b94d5d2..3b871a9530 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -711,6 +711,30 @@
"defaultMessage": "Invalid date",
"description": "Screen-reader-only live-region alert in DateInput / DateTimeInput when the typed date cannot be parsed. The field silently reverts on blur, so this is the only rejection feedback a screen-reader user gets."
},
+ "@astryx.dateInput.resetPicking": {
+ "defaultMessage": "Reset",
+ "description": "Secondary button in the mobile date picker's footer, beside Save. Removes the chosen date AND returns the calendar to the current month — it undoes the picking done so far and puts the picker back to how it opens, so prefer a word covering both, not one that only means emptying a field. Not cancel: the picker stays open afterwards and nothing is dismissed."
+ },
+ "@astryx.dateInput.savePicking": {
+ "defaultMessage": "Save",
+ "description": "Full-width primary button that closes the mobile date picker, on the calendar. The date is already committed by the tap that chose it, so this only dismisses — but it is worded as saving because that is how the action reads to someone finishing a form. Use the word your platform uses for accepting and closing a sheet."
+ },
+ "@astryx.dateInput.doneChoosingMonth": {
+ "defaultMessage": "Done",
+ "description": "Full-width button under the month and year wheels in the mobile date picker. It does NOT close the picker — it returns to the calendar, having set the month. Word it as finishing this step, not as finishing the whole task; the calendar's own button is the one that closes."
+ },
+ "@astryx.dateInput.chooseMonthYear": {
+ "defaultMessage": "{monthYear}, Choose month and year",
+ "description": "Accessible name for the mobile date picker's header button, which swaps the calendar for month and year wheels. {monthYear} is the currently shown month and year, already localized (e.g. \"March 2026\"). The whole label is one string so the separator and word order can change per locale."
+ },
+ "@astryx.dateInput.monthWheel": {
+ "defaultMessage": "Month",
+ "description": "Accessible name for the scrollable month column in the mobile date picker. Single word; a calendar month, not a duration."
+ },
+ "@astryx.dateInput.yearWheel": {
+ "defaultMessage": "Year",
+ "description": "Accessible name for the scrollable year column in the mobile date picker. Single word; a calendar year, not a duration."
+ },
"@astryx.dateTimeInput.timeHint12h": {
"defaultMessage": "e.g., 2:30 PM",
"description": "Placeholder hint shown in the DateTimeInput time field when focused and empty with 12-hour format. Gives an example of expected input format."
diff --git a/packages/core/src/DateInput/DateInput.tsx b/packages/core/src/DateInput/DateInput.tsx
index c8b182ef60..6868ea65f7 100644
--- a/packages/core/src/DateInput/DateInput.tsx
+++ b/packages/core/src/DateInput/DateInput.tsx
@@ -59,8 +59,10 @@ import {
} from '../Calendar';
import {useCalendarConstraints} from '../Calendar/hooks';
import {useInputStatusIcon} from '../hooks/useInputStatusIcon';
+import {useMediaQuery} from '../hooks/useMediaQuery';
import {useResolvedRequired} from '../hooks/useResolvedRequired';
import {usePopover} from '../Popover';
+import {TouchDateField} from './TouchDateField';
import {useTooltip} from '../Tooltip';
import {getInputARIA, isImeKeyEvent, parseDateInput} from '../utils';
import {
@@ -358,18 +360,23 @@ export interface DateInputProps extends Omit<
}
/**
- * A date picker component combining a text input with a calendar popover.
+ * The pointer that decides which surface a `DateInput` renders.
*
- * @example
- * ```
- * <DateInput
- * label="Event date"
- * value={date}
- * onChange={setDate}
- * />
- * ```
+ * `pointer: coarse` is the *primary* pointing device, which is what makes it
+ * the whole test. A touchscreen laptop reports `fine` (its trackpad) with
+ * `any-pointer: coarse` alongside, so it keeps the typable field — right,
+ * because its keyboard is there. A tablet reports `coarse` and gets the
+ * picker, at any width. There is deliberately no width bound: it would only
+ * re-exclude the tablets, since a narrowed desktop window is still a mouse.
*/
-export function DateInput({
+export const TOUCH_POINTER_QUERY = '(pointer: coarse)';
+
+/**
+ * The pointer-driven field: a text input you can type into, with a calendar
+ * in a popover beside it. `DateInput` renders this whenever the primary
+ * pointer is not a finger — see {@link TOUCH_POINTER_QUERY}.
+ */
+function PointerDateField({
label,
isLabelHidden = false,
description,
@@ -824,4 +831,57 @@ export function DateInput({
);
}
+PointerDateField.displayName = 'PointerDateField';
+
+/**
+ * A date picker that fits the pointer it is being used with.
+ *
+ * With a mouse or trackpad this is a text input you can type into, with a
+ * calendar in a popover — unchanged, and still the surface every existing
+ * consumer gets. With a finger it is a picker built for one: a bottom sheet
+ * holding one month per screen, swiped sideways, with month and year wheels
+ * behind the header title for the far jumps swiping is bad at.
+ *
+ * The props are identical either way — this is one component with two
+ * surfaces, not two components — so nothing at the call site changes, and a
+ * date typed on a laptop and a date thumbed on a phone are the same value.
+ *
+ * ## Why a runtime switch and not CSS
+ *
+ * The two surfaces are structurally different — a popover anchored to a text
+ * field versus a full-width sheet holding a scroller — so "render both, hide
+ * one" would double the DOM, double the tab stops, and mount two calendars.
+ * The condition is not layout either: it is *which interaction is faster*,
+ * and that depends on the pointer, which CSS cannot hand to JS.
+ *
+ * They are two components rather than one with a branch inside because the
+ * hook lists differ; keeping them separate is what lets each own its own.
+ *
+ * ## Hydration
+ *
+ * `useMediaQuery` reports false during SSR, so server HTML is always the
+ * pointer field and the swap happens after hydration. That is deliberately
+ * unobservable: both surfaces render the SAME closed field — a bordered input
+ * with a calendar icon and the formatted date — and differ only in what
+ * opens. Nothing moves; the field just starts opening a sheet.
+ *
+ * @example
+ * ```
+ * <DateInput
+ * label="Event date"
+ * value={date}
+ * onChange={setDate}
+ * />
+ * ```
+ */
+export function DateInput(props: DateInputProps) {
+ const isTouch = useMediaQuery(TOUCH_POINTER_QUERY);
+
+ return isTouch ? (
+ <TouchDateField {...props} />
+ ) : (
+ <PointerDateField {...props} />
+ );
+}
+
DateInput.displayName = 'DateInput';
diff --git a/packages/core/src/DateInput/DateInputTouch.test.tsx b/packages/core/src/DateInput/DateInputTouch.test.tsx
new file mode 100644
index 0000000000..e480d461ba
--- /dev/null
+++ b/packages/core/src/DateInput/DateInputTouch.test.tsx
@@ -0,0 +1,2399 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DateInputTouch.test.tsx
+ * @input Uses vitest, @testing-library/react, DateInput and its helpers
+ * @output Behavior coverage for the responsive date picker
+ * @position Test file for /packages/core/src/DateInput/
+ *
+ * What jsdom can and cannot see here matters, and the split is deliberate:
+ *
+ * - The month math is pure, so it is tested directly and exhaustively.
+ * - Which surface is chosen, and the field contract each one honors, are
+ * tested through the DOM with `matchMedia` stubbed per test.
+ * - Snapping, momentum and the scroll-driven falloff are CSS the browser
+ * resolves and jsdom does not implement at all. Those are asserted on the
+ * style DEFINITION instead (the last describe block), which at least fails
+ * loudly if someone deletes the property; the real verification is a
+ * browser, and the values it produced are recorded in the doc file.
+ */
+
+import {
+ describe,
+ it,
+ expect,
+ vi,
+ beforeAll,
+ afterAll,
+ beforeEach,
+ afterEach,
+} from 'vitest';
+import {
+ render,
+ screen,
+ fireEvent,
+ within,
+ waitFor,
+} from '@testing-library/react';
+import {readFileSync} from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {useState} from 'react';
+import type {ISODateString} from '../utils';
+import {InputGroup} from '../InputGroup';
+import {stableClassName} from '../naming';
+import {DateInput, TOUCH_POINTER_QUERY} from './DateInput';
+import {
+ toMonthIndex,
+ monthIndexOf,
+ fromMonthIndex,
+ clampIndex,
+ rowAtScrollOffset,
+ scrollOffsetForRow,
+ paneWindow,
+ rowsIn,
+ DEFAULT_MONTH_REACH,
+} from './monthGeometry';
+import {SWIPE_DISTANCE} from './useOwnScrollGesture';
+import {DRAG_SLOP} from './usePointerDragScroll';
+
+// ---------------------------------------------------------------------------
+// jsdom scaffolding
+// ---------------------------------------------------------------------------
+
+class MockResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+/** An arbitrary pane size for the pure geometry tests. */
+const PANE = 264;
+/**
+ * What the month scrollport measures as. The scroller pages along the INLINE
+ * axis, so its pane size is a WIDTH — a phone's worth, since the value only
+ * has to be non-zero and consistent for the virtualization to mount panes.
+ */
+const SCROLLPORT_WIDTH = 360;
+
+/** Matches the repo-wide setup polyfill, so hover-gated behavior still works. */
+const HOVER_CAPABLE = /\(\s*hover\s*:\s*hover\s*\)/;
+
+/**
+ * Point the surface switch at a phone or at a desktop. Only
+ * {@link TOUCH_POINTER_QUERY} is forced; every other query keeps the answer
+ * the shared test setup gives it.
+ */
+/**
+ * Answer media queries the way a given device would.
+ *
+ * Width queries are answered HONESTLY against `width`, so a width bound
+ * creeping back into the surface switch fails a test rather than passing
+ * silently on a stub that ignores it.
+ */
+function stubMedia({
+ pointer,
+ anyPointer,
+ width,
+}: {
+ pointer: 'coarse' | 'fine';
+ anyPointer?: 'coarse' | 'fine';
+ width: number;
+}): void {
+ vi.stubGlobal('matchMedia', (query: string) => {
+ let matches: boolean;
+ const maxWidth = /\(\s*max-width:\s*(\d+)px\s*\)/.exec(query);
+ const minWidth = /\(\s*min-width:\s*(\d+)px\s*\)/.exec(query);
+ if (/any-pointer:\s*coarse/.test(query)) {
+ matches = (anyPointer ?? pointer) === 'coarse';
+ } else if (/pointer:\s*coarse/.test(query)) {
+ matches = pointer === 'coarse';
+ } else if (/pointer:\s*fine/.test(query)) {
+ matches = pointer === 'fine';
+ } else if (maxWidth) {
+ matches = width <= Number(maxWidth[1]);
+ } else if (minWidth) {
+ matches = width >= Number(minWidth[1]);
+ } else {
+ matches = HOVER_CAPABLE.test(query);
+ }
+ // A compound query is only true when every part of it is.
+ if (matches && maxWidth && query.includes('pointer:')) {
+ matches = width <= Number(maxWidth[1]);
+ }
+ return {
+ matches,
+ media: query,
+ onchange: null,
+ addListener: () => {},
+ removeListener: () => {},
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ dispatchEvent: () => false,
+ };
+ });
+}
+
+function setViewport(kind: 'mobile' | 'desktop'): void {
+ stubMedia(
+ kind === 'mobile'
+ ? {pointer: 'coarse', width: 393}
+ : {pointer: 'fine', width: 1280},
+ );
+}
+
+/**
+ * Run `fn` with the month scrollport reporting the height its CSS gives it.
+ *
+ * jsdom lays nothing out, so `clientHeight` is 0 and the scroller mounts no
+ * panes at all. The override is installed only around the work that needs it
+ * and torn down immediately: a getter left on `HTMLElement.prototype` makes
+ * EVERY later DOM read take a slow path, measured at ~2.4s per test here.
+ */
+/** One animation frame, for the rAF-throttled scroll handlers. */
+async function frame(): Promise<void> {
+ return new Promise(resolve => requestAnimationFrame(() => resolve()));
+}
+
+function withLayout<T>(fn: () => T): T {
+ // jsdom defines clientWidth on Element.prototype; shadowing it on
+ // HTMLElement.prototype and deleting the shadow afterwards restores the
+ // original getter without having to copy its descriptor.
+ 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;
+ }
+}
+
+beforeAll(() => {
+ Element.prototype.scrollTo = vi.fn();
+ // jsdom's <dialog> implements none of these.
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.open = true;
+ });
+ HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) {
+ this.open = true;
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.open = false;
+ });
+});
+
+afterAll(() => {
+ vi.useRealTimers();
+});
+
+beforeEach(() => {
+ vi.setSystemTime(new Date(2026, 2, 15)); // 15 March 2026, local
+ // Re-stubbed per test, not once at module scope: the afterEach below clears
+ // every stub, and matchMedia has to be re-pointed for each test anyway.
+ vi.stubGlobal('ResizeObserver', MockResizeObserver);
+ setViewport('mobile');
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+/**
+ * Bounded by default. Unbounded, the scroller mounts seven month panes — 294
+ * day buttons — for every render, and under jsdom with StyleX's dev runtime
+ * that is seconds a test. Three months exercises the same paths; the tests
+ * that are actually about the range pass their own.
+ */
+const DEFAULT_RANGE = {min: '2026-02-01', max: '2026-04-30'} as const;
+
+function Controlled({
+ initial,
+ onChange,
+ ...props
+}: {initial?: ISODateString} & Partial<
+ React.ComponentProps<typeof DateInput>
+>) {
+ const [value, setValue] = useState<ISODateString | undefined>(initial);
+ return (
+ <DateInput
+ label="Event date"
+ {...DEFAULT_RANGE}
+ {...props}
+ value={value}
+ // Composed, not overridden: spreading a test's `onChange` over this one
+ // used to replace the state setter, so the field silently stopped
+ // updating in exactly the tests that were watching it most closely.
+ onChange={next => {
+ setValue(next);
+ onChange?.(next);
+ }}
+ />
+ );
+}
+
+/** The closed field — a real input on both surfaces. */
+const field = (): HTMLInputElement => screen.getByRole('combobox');
+
+/** Render, then open the picker. Both mount panes, so both need the layout. */
+function renderAndOpen(
+ ui: React.ReactElement = <Controlled initial="2026-03-21" />,
+): void {
+ withLayout(() => {
+ render(ui);
+ fireEvent.click(field());
+ });
+}
+
+/**
+ * One month's grid. Panes for neighbouring months are mounted too, so every
+ * day query has to say which month it means.
+ */
+function pane(label: string): HTMLElement {
+ const grid = screen
+ .getAllByRole('grid')
+ .find(g => g.getAttribute('aria-label') === label);
+ if (grid == null) {
+ throw new Error(`no pane for ${label}`);
+ }
+ return grid;
+}
+
+/** The decorative weekday row: the only 7-cell aria-hidden block. */
+function weekdayRow(): HTMLElement {
+ const row = [...document.querySelectorAll('[aria-hidden="true"]')].find(
+ el => el.children.length === 7,
+ );
+ if (row == null) {
+ throw new Error('no weekday row');
+ }
+ return row as HTMLElement;
+}
+
+// ---------------------------------------------------------------------------
+// Which surface, and why
+// ---------------------------------------------------------------------------
+
+describe('DateInput — surface selection', () => {
+ it('switches on the pointer alone, so a tablet gets the picker too', () => {
+ // `pointer` is the PRIMARY device, which is what makes it the whole test:
+ // a touchscreen laptop reports `fine` (its trackpad) and keeps the
+ // typable field, and a narrowed desktop window is still a mouse. A width
+ // bound would only re-exclude tablets — the clearest case for a thumb
+ // picker there is — so there deliberately is not one.
+ expect(TOUCH_POINTER_QUERY).toBe('(pointer: coarse)');
+
+ // An 1194px tablet in landscape: coarse pointer, far wider than any
+ // handset breakpoint. It answers width queries honestly, so a width bound
+ // creeping back in would fail here rather than pass silently.
+ stubMedia({pointer: 'coarse', width: 1194});
+ render(<Controlled initial="2026-03-21" />);
+ expect(field()).toHaveAttribute('readonly');
+ });
+
+ it('keeps the typable field for a touchscreen laptop', () => {
+ // Touch available, but the trackpad is primary — so `pointer` is `fine`
+ // and only `any-pointer` is coarse. The keyboard is right there, and
+ // typing a date beats scrolling to it.
+ stubMedia({pointer: 'fine', anyPointer: 'coarse', width: 1366});
+ render(<Controlled initial="2026-03-21" />);
+ expect(field()).not.toHaveAttribute('readonly');
+ });
+
+ it('keeps the typable field in a narrowed desktop window', () => {
+ stubMedia({pointer: 'fine', width: 500});
+ render(<Controlled initial="2026-03-21" />);
+ expect(field()).not.toHaveAttribute('readonly');
+ });
+
+ it('renders the desktop DateInput when the query does not match', () => {
+ setViewport('desktop');
+ render(<Controlled initial="2026-03-21" />);
+ // The desktop control is a text field you can type into...
+ expect(field()).not.toHaveAttribute('readonly');
+ expect(field()).not.toHaveAttribute('inputmode');
+ // ...and it opens a popover, not a sheet.
+ expect(document.querySelector('dialog')).toBeNull();
+ });
+
+ it('accepts typed input on the desktop surface', () => {
+ setViewport('desktop');
+ const onChange = vi.fn();
+ render(
+ <DateInput label="Event date" onChange={onChange} min={undefined} />,
+ );
+ fireEvent.change(field(), {target: {value: '2026-03-25'}});
+ expect(onChange).toHaveBeenCalledWith('2026-03-25');
+ });
+
+ it('renders the touch field when the query matches', () => {
+ render(<Controlled initial="2026-03-21" />);
+ const input = field();
+ // Still an input — same element, same role, so `ref` stays honest and the
+ // label associates natively — but the picker is the only way to change it.
+ expect(input.tagName).toBe('INPUT');
+ expect(input).toHaveAttribute('readonly');
+ // What actually keeps the virtual keyboard from covering the sheet.
+ expect(input).toHaveAttribute('inputmode', 'none');
+ });
+
+ it('forwards ref to the input on both surfaces', () => {
+ const desktopRef = {current: null as HTMLInputElement | null};
+ setViewport('desktop');
+ const {unmount} = render(
+ <Controlled initial="2026-03-21" ref={desktopRef} />,
+ );
+ expect(desktopRef.current).toBeInstanceOf(HTMLInputElement);
+ unmount();
+
+ const mobileRef = {current: null as HTMLInputElement | null};
+ setViewport('mobile');
+ render(<Controlled initial="2026-03-21" ref={mobileRef} />);
+ expect(mobileRef.current).toBeInstanceOf(HTMLInputElement);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// The field contract, honored identically on the touch surface
+// ---------------------------------------------------------------------------
+
+describe('DateInput — field parity', () => {
+ it('shows a placeholder until a date is chosen, then the formatted value', () => {
+ const {rerender} = render(
+ <DateInput label="Ship date" onChange={() => {}} />,
+ );
+ expect(field()).toHaveValue('');
+ expect(field()).toHaveAttribute('placeholder', 'Select a date');
+ rerender(
+ <DateInput label="Ship date" value="2026-03-21" onChange={() => {}} />,
+ );
+ expect(field()).toHaveValue('March 21, 2026');
+ });
+
+ it('honors a named format', () => {
+ render(
+ <DateInput
+ label="Ship date"
+ value="2026-03-21"
+ format="system_date"
+ onChange={() => {}}
+ />,
+ );
+ expect(field()).toHaveValue('2026-03-21');
+ });
+
+ it('honors a function format', () => {
+ render(
+ <DateInput
+ label="Ship date"
+ value="2026-03-21"
+ format={iso => `ISO:${iso}`}
+ onChange={() => {}}
+ />,
+ );
+ expect(field()).toHaveValue('ISO:2026-03-21');
+ });
+
+ it('honors a custom placeholder', () => {
+ render(
+ <DateInput
+ label="Ship date"
+ placeholder="Pick a day"
+ onChange={() => {}}
+ />,
+ );
+ expect(field()).toHaveAttribute('placeholder', 'Pick a day');
+ });
+
+ it('clears from the field', () => {
+ const onChange = vi.fn();
+ render(
+ <DateInput
+ label="Ship date"
+ value="2026-03-21"
+ hasClear
+ onChange={onChange}
+ />,
+ );
+ fireEvent.click(screen.getByRole('button', {name: /Clear Ship date/}));
+ expect(onChange).toHaveBeenCalledWith(undefined);
+ });
+
+ it('does not open the picker until the field is tapped', () => {
+ withLayout(() => {
+ render(<DateInput label="Ship date" onChange={() => {}} />);
+ expect(field()).toHaveAttribute('aria-expanded', 'false');
+ expect(screen.queryByRole('grid')).not.toBeInTheDocument();
+ fireEvent.click(field());
+ expect(field()).toHaveAttribute('aria-expanded', 'true');
+ expect(screen.getAllByRole('grid').length).toBeGreaterThan(0);
+ });
+ });
+
+ it('opens from the keyboard, APG combobox style', () => {
+ withLayout(() => {
+ render(<Controlled initial="2026-03-21" />);
+ fireEvent.keyDown(field(), {key: 'ArrowDown'});
+ expect(field()).toHaveAttribute('aria-expanded', 'true');
+ });
+ });
+
+ it('is not openable while disabled', () => {
+ render(<DateInput label="Ship date" isDisabled onChange={() => {}} />);
+ expect(field()).toBeDisabled();
+ fireEvent.click(field());
+ expect(screen.queryByRole('grid')).not.toBeInTheDocument();
+ });
+
+ it('stays focusable and explains itself when disabled with a reason', () => {
+ render(
+ <DateInput
+ label="Ship date"
+ isDisabled
+ disabledMessage="You need the Editor role"
+ onChange={() => {}}
+ />,
+ );
+ // aria-disabled, not disabled: the reason has to be reachable by keyboard.
+ expect(field()).not.toBeDisabled();
+ expect(field()).toHaveAttribute('aria-disabled', 'true');
+ fireEvent.click(field());
+ expect(screen.queryByRole('grid')).not.toBeInTheDocument();
+ });
+
+ it('renders label, description and status through Field', () => {
+ render(
+ <DateInput
+ label="Ship date"
+ description="When it leaves the warehouse"
+ status={{type: 'error', message: 'Pick a date'}}
+ onChange={() => {}}
+ />,
+ );
+ expect(screen.getByText('Ship date')).toBeInTheDocument();
+ expect(
+ screen.getByText('When it leaves the warehouse'),
+ ).toBeInTheDocument();
+ expect(screen.getByText('Pick a date')).toBeInTheDocument();
+ expect(field()).toHaveAttribute('aria-invalid', 'true');
+ expect(field().getAttribute('aria-describedby')).toBeTruthy();
+ });
+
+ it('marks required for assistive technology', () => {
+ render(<DateInput label="Ship date" isRequired onChange={() => {}} />);
+ expect(field()).toHaveAttribute('aria-required', 'true');
+ });
+
+ it('associates the label natively, so the field is named without ARIA', () => {
+ render(<DateInput label="Ship date" onChange={() => {}} />);
+ expect(screen.getByLabelText('Ship date')).toBe(field());
+ });
+
+ it('runs changeAction and shows a busy state', async () => {
+ let resolve: () => void = () => {};
+ const changeAction = vi.fn(
+ async () =>
+ new Promise<void>(r => {
+ resolve = r;
+ }),
+ );
+ withLayout(() => {
+ render(
+ <DateInput
+ label="Ship date"
+ value="2026-03-10"
+ min="2026-03-01"
+ max="2026-03-31"
+ onChange={() => {}}
+ changeAction={changeAction}
+ />,
+ );
+ fireEvent.click(field());
+ fireEvent.click(
+ within(pane('March 2026')).getByRole('button', {
+ name: /March 25, 2026/,
+ }),
+ );
+ });
+ expect(changeAction).toHaveBeenCalledWith('2026-03-25');
+ resolve();
+ });
+
+ it('drops the Field wrapper inside an InputGroup', () => {
+ render(
+ <InputGroup label="Range">
+ <DateInput label="Start" onChange={() => {}} />
+ </InputGroup>,
+ );
+ // Named by the group label plus its own, the way core's inputs are.
+ expect(field().getAttribute('aria-labelledby')).toBeTruthy();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// The picker surface
+// ---------------------------------------------------------------------------
+
+describe('DateInput — calendar surface', () => {
+ it('opens on the selected month', () => {
+ renderAndOpen();
+ expect(pane('March 2026')).toBeInTheDocument();
+ });
+
+ it('opens on the current month when there is no value', () => {
+ renderAndOpen(<Controlled />);
+ expect(pane('March 2026')).toBeInTheDocument();
+ });
+
+ it('mounts a window of months around the visible one, not the whole century', () => {
+ // The one test that wants the full default reach.
+ renderAndOpen(
+ <Controlled initial="2026-03-21" min={undefined} max={undefined} />,
+ );
+ const grids = screen.getAllByRole('grid');
+ expect(grids.length).toBeGreaterThan(1);
+ expect(grids.length).toBeLessThanOrEqual(7);
+ expect(grids.map(g => g.getAttribute('aria-label'))).toContain(
+ 'March 2026',
+ );
+ });
+
+ it('renders every month as six rows, so panes cannot differ in height', () => {
+ renderAndOpen(<Controlled initial="2026-02-01" />);
+ // February 2026 needs only five rows; the pane still has six.
+ const february = within(pane('February 2026'));
+ expect(february.getAllByRole('row')).toHaveLength(6);
+ expect(february.getAllByRole('gridcell')).toHaveLength(42);
+ });
+
+ it('commits the tapped day and LEAVES the sheet open', () => {
+ const onChange = vi.fn();
+ renderAndOpen(<Controlled initial="2026-03-21" onChange={onChange} />);
+ fireEvent.click(
+ within(pane('March 2026')).getByRole('button', {name: /March 25, 2026/}),
+ );
+ // The tap is the commit. Staying open lets a mistake be corrected in
+ // place, and a nearby date reconsidered, without reopening.
+ expect(onChange).toHaveBeenCalledWith('2026-03-25');
+ expect(field()).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('lets a second tap correct the first, still without closing', () => {
+ const onChange = vi.fn();
+ renderAndOpen(<Controlled initial="2026-03-21" onChange={onChange} />);
+ const march = within(pane('March 2026'));
+ fireEvent.click(march.getByRole('button', {name: /March 25, 2026/}));
+ fireEvent.click(march.getByRole('button', {name: /March 26, 2026/}));
+ expect(onChange).toHaveBeenLastCalledWith('2026-03-26');
+ expect(field()).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('Save closes the sheet without touching the value', () => {
+ const onChange = vi.fn();
+ renderAndOpen(<Controlled initial="2026-03-21" onChange={onChange} />);
+ fireEvent.click(
+ within(pane('March 2026')).getByRole('button', {name: /March 25, 2026/}),
+ );
+ onChange.mockClear();
+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));
+ expect(field()).toHaveAttribute('aria-expanded', 'false');
+ // Named for what it means to someone finishing a form, not for what it
+ // does internally: the value was already committed by the tap that chose
+ // it, so this fires nothing of its own.
+ expect(onChange).not.toHaveBeenCalled();
+ expect(field()).toHaveValue('March 25, 2026');
+ });
+
+ it('Save closes even with no date chosen, committing nothing', () => {
+ const onChange = vi.fn();
+ withLayout(() => {
+ render(<DateInput label="Ship date" onChange={onChange} />);
+ fireEvent.click(field());
+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));
+ });
+ expect(field()).toHaveAttribute('aria-expanded', 'false');
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('has Save in the footer and no Today button', () => {
+ renderAndOpen();
+ expect(screen.getByRole('button', {name: 'Save'})).toBeInTheDocument();
+ // "Today" moved the calendar to the current month WITHOUT selecting it,
+ // which read as broken — the one thing the name promises is the thing it
+ // did not do. Removed until it can be navigate-or-select on purpose.
+ expect(screen.queryByRole('button', {name: 'Today'})).toBeNull();
+ });
+
+ it('marks the selection and today', () => {
+ renderAndOpen();
+ const march = within(pane('March 2026'));
+ expect(
+ march
+ .getByRole('button', {name: /March 21, 2026/})
+ .closest('[role="gridcell"]'),
+ ).toHaveAttribute('aria-selected', 'true');
+ expect(march.getByRole('button', {name: /March 15, 2026/})).toHaveAttribute(
+ 'aria-current',
+ 'date',
+ );
+ });
+
+ it('leaves exactly one day per month tab-reachable', () => {
+ renderAndOpen();
+ const tabbable = within(pane('March 2026'))
+ .getAllByRole('button')
+ .filter(b => b.getAttribute('tabindex') === '0');
+ expect(tabbable).toHaveLength(1);
+ // The selected day, when the month holds one.
+ expect(tabbable[0]).toHaveAttribute('data-date', '2026-03-21');
+ });
+
+ it('pages a month with the header arrows', () => {
+ renderAndOpen();
+ const header = () =>
+ document.querySelector<HTMLElement>('[data-title="month-year"]')!;
+ expect(header()).toHaveTextContent('March 2026');
+ fireEvent.click(screen.getByRole('button', {name: 'Next month'}));
+ expect(header()).toHaveTextContent('April 2026');
+ fireEvent.click(screen.getByRole('button', {name: 'Previous month'}));
+ expect(header()).toHaveTextContent('March 2026');
+ });
+
+ /**
+ * A programmatic scroll must not report its own arrival as if the user had
+ * scrolled there. Nothing needs the report — whatever asked for the scroll
+ * already knows the month — and trusting it turns a steer into a cycle.
+ *
+ * The case that bit: a wheel commit steers this scroller while it is hidden
+ * behind the wheels, and a hidden scroller does not reliably stay put. On
+ * iOS the position is re-snapped when the panel becomes visible again,
+ * firing a scroll just as the wheels close and reports start being trusted
+ * again — so the month drifted on the way back to the calendar.
+ */
+ it('does not report a scroll it was told to make', async () => {
+ await withLayout(async () => {
+ render(
+ <Controlled initial="2026-03-21" min="2026-01-01" max="2026-12-31" />,
+ );
+ fireEvent.click(field());
+ const header = () =>
+ document.querySelector<HTMLElement>('[data-title="month-year"]')!;
+ const scroller = document.querySelector<HTMLElement>(
+ '[data-scroller="months"]',
+ )!;
+
+ // An arrow steers it to April. The scroll that lands there is our own
+ // doing, so whatever it reports must not move the month again.
+ fireEvent.click(screen.getByRole('button', {name: 'Next month'}));
+ expect(header()).toHaveTextContent('April 2026');
+ // Row 3 of a range starting in January is April: the month the steer
+ // was aiming at, arriving.
+ scroller.scrollLeft = 3 * SCROLLPORT_WIDTH;
+ fireEvent.scroll(scroller);
+ await frame();
+ expect(header()).toHaveTextContent('April 2026');
+
+ // A finger ends the steering: from here the months it passes are the
+ // user's, and every one of them counts.
+ // jsdom has no constructible TouchEvent, and a bare Event carries no
+ // `touches` — which crashes the gesture hook that reads `touches[0]`.
+ // That crash is the fake event's fault, not the hook's: a browser's
+ // touchstart always has the list.
+ const touchStart = new Event('touchstart', {bubbles: true});
+ const point = {identifier: 1, clientX: 100, clientY: 100};
+ Object.defineProperties(touchStart, {
+ touches: {value: [point]},
+ targetTouches: {value: [point]},
+ changedTouches: {value: [point]},
+ });
+ scroller.dispatchEvent(touchStart);
+ scroller.scrollLeft = 5 * SCROLLPORT_WIDTH;
+ fireEvent.scroll(scroller);
+ // The report is made from inside a rAF callback, so the state update
+ // lands outside the act() that fireEvent wraps.
+ await waitFor(() => expect(header()).toHaveTextContent('June 2026'));
+ });
+ });
+
+ /**
+ * An arrow with nowhere to go is hidden, not greyed. A disabled control
+ * still says "this is a thing you could do", and at the edge of a range it
+ * is not — there is no state the user can reach where it becomes
+ * available, so a permanently greyed chevron just reads as broken.
+ *
+ * It keeps its box, though: `visibility: hidden` rather than unmounting,
+ * so the remaining arrow does not slide sideways as an edge is reached.
+ */
+ it('hides an arrow at the end of the reachable range', () => {
+ renderAndOpen(
+ <Controlled initial="2026-03-10" min="2026-03-01" max="2026-03-31" />,
+ );
+ // Queried by attribute, not by role: `visibility: hidden` is exactly what
+ // strips an element of its accessible name, so a role query cannot see
+ // these — which is the point of the assertion below.
+ const arrow = (name: string) =>
+ document.querySelector<HTMLElement>(
+ `dialog[open] button[aria-label="${name}"]`,
+ );
+ for (const name of ['Previous month', 'Next month']) {
+ // Still mounted, so the header cannot reflow...
+ expect(arrow(name)).toBeInTheDocument();
+ expect(arrow(name)).toBeDisabled();
+ // ...but gone from the accessibility tree, and so unreachable.
+ expect(screen.queryByRole('button', {name})).toBeNull();
+ }
+ });
+
+ it('shows both arrows when there is somewhere to go in each direction', () => {
+ renderAndOpen(
+ <Controlled initial="2026-03-10" min="2026-01-01" max="2026-12-31" />,
+ );
+ expect(
+ screen.getByRole('button', {name: 'Previous month'}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: 'Next month'}),
+ ).toBeInTheDocument();
+ });
+
+ it('does not change the selection when paging', () => {
+ const onChange = vi.fn();
+ renderAndOpen(<Controlled initial="2026-03-21" onChange={onChange} />);
+ fireEvent.click(screen.getByRole('button', {name: 'Next month'}));
+ // Navigating is not selecting — the mistake the old Today button made.
+ expect(onChange).not.toHaveBeenCalled();
+ expect(field()).toHaveValue('March 21, 2026');
+ });
+
+ it('disables days outside min/max and refuses to commit them', () => {
+ const onChange = vi.fn();
+ renderAndOpen(
+ <Controlled
+ initial="2026-03-10"
+ min="2026-03-05"
+ max="2026-03-20"
+ onChange={onChange}
+ />,
+ );
+ const outOfRange = within(pane('March 2026')).getByRole('button', {
+ name: /March 25, 2026/,
+ });
+ expect(outOfRange).toHaveAttribute('aria-disabled', 'true');
+ fireEvent.click(outOfRange);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('honors custom date constraints', () => {
+ renderAndOpen(
+ <Controlled
+ initial="2026-03-10"
+ dateConstraints={[date => date.getDay() !== 0]}
+ />,
+ );
+ // 2026-03-01 is a Sunday.
+ expect(
+ within(pane('March 2026')).getByRole('button', {name: /March 1, 2026/}),
+ ).toHaveAttribute('aria-disabled', 'true');
+ });
+
+ /**
+ * Spill days, the way the desktop calendar has them.
+ *
+ * These were left out at first, on the theory that a horizontal scroller
+ * would show the same date twice — greyed at the foot of one pane and
+ * again at the head of the next. Measured, that cannot happen: both panes
+ * are exactly the scrollport wide and share one 7-column grid, so a given
+ * weekday column is only ever visible in ONE pane at a time, and a date
+ * always sits in its weekday's column. Swept across a full pane boundary
+ * in 10% steps — 42 dates on screen throughout, zero duplicated.
+ */
+ it('renders adjacent-month days, muted, like the desktop calendar', () => {
+ renderAndOpen();
+ const march = within(pane('March 2026'));
+ // Every cell in the 6x7 grid is now a real day.
+ expect(march.getAllByRole('gridcell')).toHaveLength(42);
+ expect(march.getAllByRole('button')).toHaveLength(42);
+ // March 2026 begins on a Sunday, so it spills only forwards.
+ expect(
+ march.getByRole('button', {name: /April 1, 2026/}),
+ ).toBeInTheDocument();
+ });
+
+ it('spills backwards too, on a month that does not start the week', () => {
+ renderAndOpen(
+ <Controlled initial="2026-04-15" min="2026-01-01" max="2026-12-31" />,
+ );
+ const april = within(pane('April 2026'));
+ // April 2026 starts on a Wednesday: the first row opens with late March.
+ expect(
+ april.getByRole('button', {name: /March 29, 2026/}),
+ ).toBeInTheDocument();
+ expect(april.getAllByRole('button')).toHaveLength(42);
+ });
+
+ /**
+ * A spilled day is shown, not offered.
+ *
+ * It was pickable at first, on the reasoning that a date you can see is a
+ * date you should be able to tap. The desktop calendar disagrees — it makes
+ * its own outside days unselectable — and on a pane that IS the month, so
+ * does the interaction: committing April 1 from March's pane would move the
+ * calendar out from under the thumb that just tapped it. The swipe and the
+ * arrows say "next month" without that ambiguity.
+ */
+ it('does not commit an adjacent-month day', () => {
+ const onChange = vi.fn();
+ renderAndOpen(<Controlled initial="2026-03-21" onChange={onChange} />);
+ const april1 = within(pane('March 2026')).getByRole('button', {
+ name: /April 1, 2026/,
+ });
+ expect(april1).toHaveAttribute('aria-disabled', 'true');
+ fireEvent.click(april1);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ /**
+ * Being outside is enough on its own — a spill day inside the allowed range
+ * is still not a choice. Worth its own case because `isDateDisabled` says
+ * nothing about April 1 here, so only the outside test can be what disables
+ * it.
+ */
+ it('disables a spilled day the range would otherwise allow', () => {
+ renderAndOpen(
+ <Controlled initial="2026-03-21" min="2026-01-01" max="2026-12-31" />,
+ );
+ const march = within(pane('March 2026'));
+ // In range, and in its own pane it is perfectly pickable.
+ expect(
+ within(pane('April 2026')).getByRole('button', {name: /April 1, 2026/}),
+ ).not.toHaveAttribute('aria-disabled');
+ // Borrowed by March, it is not.
+ expect(march.getByRole('button', {name: /April 1, 2026/})).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+ });
+
+ /**
+ * The selection and today's ring belong to the month that owns the date.
+ * Calendar guards both on `!isOutside`; without the same guard a date would
+ * wear its puck twice, once in its own pane and once in the neighbour that
+ * only borrows it.
+ */
+ it('leaves the puck and the today ring with the month that owns the day', () => {
+ renderAndOpen(
+ <Controlled initial="2026-04-01" min="2026-01-01" max="2026-12-31" />,
+ );
+ const spilled = within(pane('March 2026')).getByRole('button', {
+ name: /April 1, 2026/,
+ });
+ const owned = within(pane('April 2026')).getByRole('button', {
+ name: /April 1, 2026/,
+ });
+ // Same date, same label — and only one of them is dressed as selected.
+ expect(owned.className).not.toBe(spilled.className);
+ expect(
+ within(pane('April 2026')).getAllByRole('gridcell', {selected: true}),
+ ).toHaveLength(1);
+ expect(
+ within(pane('March 2026')).queryAllByRole('gridcell', {selected: true}),
+ ).toHaveLength(0);
+ });
+
+ /**
+ * A date shown in two panes must not be two tab stops — the pane that owns
+ * it, and the neighbour that merely spills it. That holds because
+ * `tabbableISO` is resolved per pane and only names dates in that pane's
+ * own month, so it is worth pinning: the case below is the one that would
+ * break if it ever became global, since April 1 is both the selection and
+ * a spill day in March's pane.
+ */
+ it('gives a spilled date no tab stop in the pane that borrows it', () => {
+ renderAndOpen(
+ <Controlled initial="2026-04-01" min="2026-01-01" max="2026-12-31" />,
+ );
+ const tabbableIn = (label: string) =>
+ within(pane(label))
+ .getAllByRole('button')
+ .filter(b => b.getAttribute('tabindex') === '0')
+ .map(b => b.getAttribute('aria-label'));
+
+ // April owns the date, so its stop is the date itself.
+ expect(tabbableIn('April 2026')).toHaveLength(1);
+ expect(tabbableIn('April 2026')[0]).toMatch(/April 1, 2026/);
+ // March shows the same date, but its stop falls back to a March date —
+ // every pane keeps exactly one, and never on a day it does not own.
+ expect(tabbableIn('March 2026')).toHaveLength(1);
+ expect(tabbableIn('March 2026')[0]).toMatch(/March/);
+ });
+
+ const weekdayNames = () =>
+ [...weekdayRow().children].map(c => c.textContent?.trim());
+
+ /**
+ * Three letters, where Calendar's own header uses two.
+ *
+ * The sheet is full width — ~51px a column against Calendar's popover — so
+ * there is room for the form people actually read, and a picker driven by
+ * thumb should not make anyone decode "Tu" against "Th".
+ *
+ * Exact equality, not `toHaveTextContent`: that matches substrings, so it
+ * passes against "Sun" while asserting "Su" and would not have noticed this
+ * change at all.
+ */
+ it('labels the columns with three-letter weekday names', () => {
+ renderAndOpen();
+ expect(weekdayNames()).toEqual([
+ 'Sun',
+ 'Mon',
+ 'Tue',
+ 'Wed',
+ 'Thu',
+ 'Fri',
+ 'Sat',
+ ]);
+ });
+
+ it('rotates the weekday header with weekStartsOn', () => {
+ renderAndOpen(<Controlled initial="2026-03-21" weekStartsOn={1} />);
+ expect(weekdayNames()).toEqual([
+ 'Mon',
+ 'Tue',
+ 'Wed',
+ 'Thu',
+ 'Fri',
+ 'Sat',
+ 'Sun',
+ ]);
+ });
+
+ it('accepts weekStartsOn as a day name, like Calendar and DateInput', () => {
+ renderAndOpen(<Controlled initial="2026-03-21" weekStartsOn="sat" />);
+ expect(weekdayNames()[0]).toBe('Sat');
+ // The columns rotate with the header, or the grid would be mislabelled.
+ expect(
+ within(pane('March 2026'))
+ .getAllByRole('button')[0]
+ .getAttribute('aria-label'),
+ ).toMatch(/February 28, 2026|March/);
+ });
+
+ it('moves keyboard focus by date, across the month boundary', () => {
+ renderAndOpen(<Controlled initial="2026-03-31" />);
+ const last = within(pane('March 2026')).getByRole('button', {
+ name: /March 31, 2026/,
+ });
+ last.focus();
+ fireEvent.keyDown(last, {key: 'ArrowRight'});
+ expect(document.activeElement).toHaveAttribute('data-date', '2026-04-01');
+ });
+
+ it('moves a week at a time with the vertical arrows', () => {
+ renderAndOpen(<Controlled initial="2026-03-10" />);
+ const day = within(pane('March 2026')).getByRole('button', {
+ name: /March 10, 2026/,
+ });
+ day.focus();
+ fireEvent.keyDown(day, {key: 'ArrowDown'});
+ expect(document.activeElement).toHaveAttribute('data-date', '2026-03-17');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Month / year wheels
+// ---------------------------------------------------------------------------
+
+describe('DateInput — month/year wheels', () => {
+ /**
+ * The header title. Queried by attribute rather than by role and accessible
+ * name: every role query in here walks a tree of ~150 elements and computes
+ * a name for each, which dominates the runtime of these tests.
+ */
+ const title = () =>
+ document.querySelector<HTMLElement>('[data-title="month-year"]')!;
+
+ const openWheels = () => fireEvent.click(title());
+
+ /** The swap panel holding the calendar, or the one holding the wheels. */
+ const panel = (which: 'calendar' | 'wheels') =>
+ document.querySelector(`[data-panel="${which}"]`)!;
+
+ const ONE_YEAR = {min: '2026-01-01', max: '2026-12-31'} as const;
+ const FIVE_YEARS = {min: '2024-01-01', max: '2028-12-31'} as const;
+
+ it('the header title opens them, and says so', () => {
+ renderAndOpen();
+ expect(title()).toHaveAttribute('aria-expanded', 'false');
+ expect(panel('wheels')).toHaveAttribute('inert');
+ expect(panel('calendar')).not.toHaveAttribute('inert');
+ openWheels();
+ expect(title()).toHaveAttribute('aria-expanded', 'true');
+ expect(panel('wheels')).not.toHaveAttribute('inert');
+ expect(panel('calendar')).toHaveAttribute('inert');
+ expect(screen.getByRole('listbox', {name: 'Month'})).toBeInTheDocument();
+ expect(screen.getByRole('listbox', {name: 'Year'})).toBeInTheDocument();
+ });
+
+ /**
+ * The arrows step the calendar, and the calendar is not on screen. They
+ * keep their layout box rather than unmounting: they are the tallest thing
+ * in the header on a coarse pointer (44px against the title's 36), so
+ * dropping them would shorten it and shift the sheet mid-cross-fade.
+ */
+ it('hides the month arrows while the wheels are up', () => {
+ renderAndOpen();
+ const arrows = document.querySelector<HTMLElement>(
+ '[data-arrows="months"]',
+ )!;
+ expect(arrows).not.toHaveAttribute('inert');
+
+ openWheels();
+ expect(arrows).toHaveAttribute('inert');
+ // Still in the layout, so the header cannot change height.
+ expect(arrows).toBeInTheDocument();
+
+ fireEvent.click(title());
+ expect(arrows).not.toHaveAttribute('inert');
+ });
+
+ it('offers twelve months, with the current one selected', () => {
+ renderAndOpen();
+ openWheels();
+ const options = within(
+ screen.getByRole('listbox', {name: 'Month'}),
+ ).getAllByRole('option');
+ expect(options).toHaveLength(12);
+ expect(options[2]).toHaveTextContent('March');
+ expect(options[2]).toHaveAttribute('aria-selected', 'true');
+ });
+
+ it('tapping a wheel row moves the calendar to that month', () => {
+ renderAndOpen(<Controlled initial="2026-03-21" {...ONE_YEAR} />);
+ openWheels();
+ fireEvent.click(
+ within(screen.getByRole('listbox', {name: 'Month'})).getByText(
+ 'September',
+ ),
+ );
+ expect(title()).toHaveTextContent('September 2026');
+ });
+
+ /**
+ * A wheel commit steers the hidden calendar, and the calendar reports the
+ * month it lands on. Taking that report back while the wheels are open
+ * closes a cycle: commit -> echo -> the echo moves the wheel's selected row
+ * -> the wheel is repositioned -> that scroll reads as another commit.
+ *
+ * Whether it converges comes down to how precisely a browser says
+ * "scrolling stopped". Chrome has `scrollend` and settles at once; iOS
+ * below Safari 26 has none, and its momentum runs on after the finger
+ * lifts, so each lap committed the next month along and the month climbed
+ * on its own — reported from a device, invisible in Chrome.
+ *
+ * Driven here through the calendar's real scroll listener, which needs a
+ * measured scrollport (`withLayout`) and a `scrollLeft` far enough to land
+ * on another pane, then a frame for the rAF throttle. No timing assumptions:
+ * the echo either reaches the month or it does not.
+ */
+ it('ignores the calendar echo while the wheels are steering it', async () => {
+ await withLayout(async () => {
+ render(<Controlled initial="2026-03-21" {...FIVE_YEARS} />);
+ fireEvent.click(field());
+ openWheels();
+ fireEvent.click(
+ within(screen.getByRole('listbox', {name: 'Month'})).getByText(
+ 'January',
+ ),
+ );
+ expect(title()).toHaveTextContent('January 2026');
+
+ // The calendar, scrolling to January behind the wheels, reports each
+ // month it passes. None of it may move the month the wheels just set.
+ const scroller = document.querySelector<HTMLElement>(
+ '[data-scroller="months"]',
+ )!;
+ for (const row of [5, 6, 7, 8]) {
+ scroller.scrollLeft = row * SCROLLPORT_WIDTH;
+ fireEvent.scroll(scroller);
+ await frame();
+ }
+ expect(title()).toHaveTextContent('January 2026');
+ });
+ // The other direction — the calendar reporting its month when it IS the
+ // surface — is what every test in the calendar-surface block above
+ // depends on, so it is covered rather than restated here.
+ });
+
+ /**
+ * The reveal case, which is the one that was reported from a device.
+ *
+ * A wheel commit steers the calendar while it is hidden behind the wheels,
+ * and `visibility: hidden` keeps the layout box but does not guarantee the
+ * scroll position survives: iOS re-snaps the scroller when it becomes
+ * visible again, and not necessarily onto the pane it was put on. That
+ * fires a scroll exactly as the wheels close and reports start being
+ * trusted again — so the month drifted on the way back to the dates.
+ *
+ * Simulated here by moving the hidden scroller somewhere it was never sent,
+ * which is what the re-snap amounts to.
+ */
+ it('holds the month when the hidden calendar is re-snapped on reveal', async () => {
+ await withLayout(async () => {
+ render(<Controlled initial="2026-03-21" {...FIVE_YEARS} />);
+ fireEvent.click(field());
+ openWheels();
+ fireEvent.click(
+ within(screen.getByRole('listbox', {name: 'Month'})).getByText(
+ 'January',
+ ),
+ );
+ expect(title()).toHaveTextContent('January 2026');
+
+ // iOS moves the hidden scroller off the pane it was steered to.
+ const scroller = document.querySelector<HTMLElement>(
+ '[data-scroller="months"]',
+ )!;
+ scroller.scrollLeft += 4 * SCROLLPORT_WIDTH;
+
+ // Back to the dates. Two things have to hold: the stray position must
+ // not become the month, and the calendar must be put back on the pane
+ // the month names — or the header would say January over a different
+ // month's grid.
+ const scrollTo = vi.mocked(Element.prototype.scrollTo);
+ scrollTo.mockClear();
+ fireEvent.click(title());
+ fireEvent.scroll(scroller);
+ await frame();
+ await frame();
+ expect(title()).toHaveTextContent('January 2026');
+
+ // January 2026 is row 24 of a range that starts in January 2024.
+ expect(scrollTo).toHaveBeenCalledWith(
+ expect.objectContaining({left: 24 * SCROLLPORT_WIDTH}),
+ );
+ });
+ });
+
+ /**
+ * The wheels are a detour to reach a far month, not a mode. Reopening into
+ * them would answer a question the user has not asked yet, and hide the
+ * dates they came back for behind another tap.
+ */
+ it('always reopens on the calendar, whatever was showing last time', () => {
+ renderAndOpen();
+ openWheels();
+ expect(title()).toHaveAttribute('aria-expanded', 'true');
+
+ // Dismissed from the wheels, where Done is deliberately not offered —
+ // the handle, the scrim and Escape are the ways out.
+ fireEvent.keyDown(document.querySelector('dialog[open]')!, {key: 'Escape'});
+ expect(field()).toHaveAttribute('aria-expanded', 'false');
+
+ fireEvent.click(field());
+ expect(title()).toHaveAttribute('aria-expanded', 'false');
+ expect(panel('calendar')).not.toHaveAttribute('inert');
+ expect(panel('wheels')).toHaveAttribute('inert');
+ });
+
+ it('the year wheel keeps the month', () => {
+ renderAndOpen(<Controlled initial="2026-03-21" {...FIVE_YEARS} />);
+ openWheels();
+ fireEvent.click(
+ within(screen.getByRole('listbox', {name: 'Year'})).getByText('2025'),
+ );
+ expect(title()).toHaveTextContent('March 2025');
+ });
+
+ it('is a single tab stop driven by the arrow keys', () => {
+ renderAndOpen();
+ openWheels();
+ const months = screen.getByRole('listbox', {name: 'Month'});
+ expect(months).toHaveAttribute('tabindex', '0');
+ fireEvent.keyDown(months, {key: 'ArrowDown'});
+ expect(title()).toHaveTextContent('April 2026');
+ fireEvent.keyDown(months, {key: 'ArrowUp'});
+ expect(title()).toHaveTextContent('March 2026');
+ });
+
+ it('will not commit a row outside min/max', () => {
+ renderAndOpen(<Controlled initial="2026-03-10" />);
+ openWheels();
+ const december = within(screen.getByRole('listbox', {name: 'Month'}))
+ .getByText('December')
+ .closest('[role="option"]')!;
+ expect(december).toHaveAttribute('aria-disabled', 'true');
+ fireEvent.click(december);
+ expect(title()).toHaveTextContent('March 2026');
+ });
+
+ it('bounds the year wheel to the reachable range', () => {
+ renderAndOpen(
+ <Controlled initial="2026-03-10" min="2025-01-01" max="2027-12-31" />,
+ );
+ openWheels();
+ expect(
+ within(screen.getByRole('listbox', {name: 'Year'}))
+ .getAllByRole('option')
+ .map(o => o.textContent),
+ ).toEqual(['2025', '2026', '2027']);
+ });
+
+ it('the title is what closes them again', () => {
+ renderAndOpen();
+ openWheels();
+ expect(title()).toHaveAttribute('aria-expanded', 'true');
+ fireEvent.click(title());
+ expect(title()).toHaveAttribute('aria-expanded', 'false');
+ expect(panel('wheels')).toHaveAttribute('inert');
+ });
+
+ it('Reset empties the field and brings the calendar home', () => {
+ const onChange = vi.fn();
+ // Today is 15 March 2026 in these tests; open on a month away from it.
+ renderAndOpen(
+ <Controlled
+ initial="2026-08-21"
+ onChange={onChange}
+ min="2026-01-01"
+ max="2026-12-31"
+ />,
+ );
+ expect(title()).toHaveTextContent('August 2026');
+
+ fireEvent.click(screen.getByRole('button', {name: 'Reset'}));
+ expect(onChange).toHaveBeenCalledWith(undefined);
+ expect(field()).toHaveValue('');
+ // Clearing the date and leaving the calendar on the month of the date you
+ // just cleared is a half-finished action.
+ expect(title()).toHaveTextContent('March 2026');
+ // And it does not dismiss — the sheet is still there to pick again.
+ expect(field()).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ /**
+ * "If possible" is the whole subtlety. A range can exclude the current
+ * month entirely — a booking window that opens next quarter — and there is
+ * then no honest month to go to. Clamping would land on the nearest edge
+ * and present a different month as though it were today's, so the move is
+ * skipped and the calendar stays put. The value clears either way.
+ */
+ it('clears without moving when the current month is out of range', () => {
+ const onChange = vi.fn();
+ renderAndOpen(
+ <Controlled
+ initial="2027-05-10"
+ onChange={onChange}
+ min="2027-01-01"
+ max="2027-12-31"
+ />,
+ );
+ expect(title()).toHaveTextContent('May 2027');
+
+ fireEvent.click(screen.getByRole('button', {name: 'Reset'}));
+ expect(onChange).toHaveBeenCalledWith(undefined);
+ expect(field()).toHaveValue('');
+ expect(title()).toHaveTextContent('May 2027');
+ });
+
+ it('offers Reset only on the calendar, beside Save', () => {
+ renderAndOpen();
+ expect(screen.getByRole('button', {name: 'Reset'})).toBeInTheDocument();
+ openWheels();
+ // The wheels choose a month; there is no date there to clear.
+ expect(screen.queryByRole('button', {name: 'Reset'})).toBeNull();
+ });
+
+ it('Save closes the whole picker; Done only leaves the wheels', () => {
+ // Two finishes, deliberately different: Save ends the task, Done ends a
+ // step. They never appear together — each belongs to the surface it is
+ // shown on — so neither has to carry two meanings by position.
+ renderAndOpen();
+ openWheels();
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ // Back on the calendar, still open.
+ expect(field()).toHaveAttribute('aria-expanded', 'true');
+ expect(title()).toHaveAttribute('aria-expanded', 'false');
+
+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));
+ expect(field()).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ /**
+ * The two actions share one grid cell and take turns, so the footer is one
+ * button tall whichever is showing and the sheet never changes height
+ * mid-swap. `inert` is what keeps the hidden one out of the accessibility
+ * tree, rather than merely out of sight.
+ */
+ /**
+ * `inert` disables everything INSIDE it, so an inert ancestor is enough to
+ * kill a button that looks perfectly fine on its own.
+ *
+ * This is not hypothetical. The footer kept an `inert` from an earlier
+ * version where it was hidden wholesale on the wheels; once the wheels grew
+ * their own Done button inside that same footer, the button rendered,
+ * looked right, passed every attribute assertion — and did nothing when
+ * tapped.
+ *
+ * Nothing above caught it: `inert` has no behavioural effect in jsdom, so
+ * role queries still found the button, and the cell's own attribute was
+ * correct. The only honest check is to walk the ancestors, which is what
+ * this does.
+ */
+ it('leaves no inert ancestor over whichever action is showing', () => {
+ const inertAncestorsOf = (label: string) => {
+ const el = [...document.querySelectorAll('dialog[open] button')].find(
+ b => b.textContent?.trim() === label,
+ )!;
+ const blocking: string[] = [];
+ // Start above the button's own cell, which is legitimately inert for
+ // the action that is currently hidden.
+ let node = el.parentElement?.parentElement ?? null;
+ while (node != null && node.tagName !== 'BODY') {
+ if (node.hasAttribute('inert')) {
+ blocking.push(node.tagName.toLowerCase());
+ }
+ node = node.parentElement;
+ }
+ return blocking;
+ };
+
+ renderAndOpen();
+ expect(inertAncestorsOf('Save')).toEqual([]);
+ expect(inertAncestorsOf('Reset')).toEqual([]);
+
+ openWheels();
+ expect(inertAncestorsOf('Done')).toEqual([]);
+ });
+
+ it('shows exactly one footer action, and only the visible one is reachable', () => {
+ renderAndOpen();
+ // Queried off the DOM rather than by role: every role-with-name query
+ // walks this tree computing accessible names, and there are ~150
+ // elements in it. Same reason the title helper above does it this way.
+ const button = (label: string) =>
+ [...document.querySelectorAll('dialog[open] button')].find(
+ el => el.textContent?.trim() === label,
+ );
+ // Which ANCESTOR carries `inert`, not which parent — the wheels' action
+ // sits inside a fading wrapper, and asserting on `parentElement` would
+ // pass or fail on that nesting rather than on reachability.
+ const isBlocked = (label: string) =>
+ button(label)?.closest('[inert]') != null;
+
+ expect(isBlocked('Save')).toBe(false);
+ expect(isBlocked('Done')).toBe(true);
+ expect(screen.queryByRole('button', {name: 'Done'})).toBeNull();
+
+ openWheels();
+ expect(isBlocked('Save')).toBe(true);
+ expect(isBlocked('Done')).toBe(false);
+ expect(screen.queryByRole('button', {name: 'Save'})).toBeNull();
+
+ // Both stay mounted throughout, which is what keeps the row's height
+ // fixed across the swap.
+ expect(button('Save')).toBeInTheDocument();
+ expect(button('Done')).toBeInTheDocument();
+ });
+
+ it('the year wheel keeps the month', () => {
+ renderAndOpen(<Controlled initial="2026-03-21" {...FIVE_YEARS} />);
+ openWheels();
+ fireEvent.click(
+ within(screen.getByRole('listbox', {name: 'Year'})).getByText('2025'),
+ );
+ expect(title()).toHaveTextContent('March 2025');
+ });
+
+ it('is a single tab stop driven by the arrow keys', () => {
+ renderAndOpen();
+ openWheels();
+ const months = screen.getByRole('listbox', {name: 'Month'});
+ expect(months).toHaveAttribute('tabindex', '0');
+ fireEvent.keyDown(months, {key: 'ArrowDown'});
+ expect(title()).toHaveTextContent('April 2026');
+ fireEvent.keyDown(months, {key: 'ArrowUp'});
+ expect(title()).toHaveTextContent('March 2026');
+ });
+
+ it('will not commit a row outside min/max', () => {
+ renderAndOpen(<Controlled initial="2026-03-10" />);
+ openWheels();
+ const december = within(screen.getByRole('listbox', {name: 'Month'}))
+ .getByText('December')
+ .closest('[role="option"]')!;
+ expect(december).toHaveAttribute('aria-disabled', 'true');
+ fireEvent.click(december);
+ expect(title()).toHaveTextContent('March 2026');
+ });
+
+ it('bounds the year wheel to the reachable range', () => {
+ renderAndOpen(
+ <Controlled initial="2026-03-10" min="2025-01-01" max="2027-12-31" />,
+ );
+ openWheels();
+ expect(
+ within(screen.getByRole('listbox', {name: 'Year'}))
+ .getAllByRole('option')
+ .map(o => o.textContent),
+ ).toEqual(['2025', '2026', '2027']);
+ });
+
+ it('the title is what closes them again', () => {
+ renderAndOpen();
+ openWheels();
+ expect(title()).toHaveAttribute('aria-expanded', 'true');
+ fireEvent.click(title());
+ expect(title()).toHaveAttribute('aria-expanded', 'false');
+ expect(panel('wheels')).toHaveAttribute('inert');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Gesture ownership — the nested scrollers vs. the sheet's swipe-to-dismiss
+// ---------------------------------------------------------------------------
+
+describe('DateInput — nested scrollers keep their own touch gesture', () => {
+ /**
+ * Stand-in for `BottomSheet`'s swipe-to-dismiss listener: a NATIVE listener
+ * on an ancestor, in the bubble phase, which is exactly how the sheet
+ * attaches its own (`addEventListener('touchstart', …, {passive: true})` on
+ * its scrolling body). If an event reaches this, the sheet would have read
+ * it as a drag.
+ */
+ function watchAncestor(): {seen: string[]; stop: () => void} {
+ const seen: string[] = [];
+ const listener = (event: Event) => seen.push(event.type);
+ for (const type of ['touchstart', 'touchmove', 'touchend']) {
+ document.body.addEventListener(type, listener);
+ }
+ return {
+ seen,
+ stop: () => {
+ for (const type of ['touchstart', 'touchmove', 'touchend']) {
+ document.body.removeEventListener(type, listener);
+ }
+ },
+ };
+ }
+
+ /**
+ * A touch event realistic enough for a real listener to read.
+ *
+ * jsdom has no constructible `TouchEvent`, and a bare `Event` carries no
+ * `changedTouches` — which crashes any handler that reads one, including
+ * BottomSheet's (`event.changedTouches[0]`). That crash is an artifact of
+ * the fake event, not a bug: a browser's touchstart always has the list.
+ * The stand-in below carries it, so an event that DOES reach the sheet
+ * exercises the sheet rather than blowing up inside it.
+ */
+ const touch = (
+ el: Element,
+ type: string,
+ at: {x: number; y: number} = {x: 100, y: 200},
+ ) => {
+ const event = new Event(type, {
+ bubbles: true,
+ cancelable: type !== 'touchend',
+ });
+ const point = {identifier: 1, clientX: at.x, clientY: at.y, target: el};
+ Object.defineProperties(event, {
+ changedTouches: {value: [point]},
+ touches: {value: type === 'touchend' ? [] : [point]},
+ targetTouches: {value: type === 'touchend' ? [] : [point]},
+ });
+ return el.dispatchEvent(event);
+ };
+
+ /**
+ * A whole gesture: down at the origin, drag by (dx, dy), lift. Returns the
+ * scroller's stubbed `scrollBy`, which is how the paging fallback shows up
+ * (jsdom implements neither scrolling nor `scrollBy`).
+ */
+ const swipe = (
+ el: Element,
+ dx: number,
+ dy: number,
+ {scrollsBy = 0}: {scrollsBy?: number} = {},
+ ) => {
+ // jsdom has no layout, so `scrollLeft` never moves on its own. Shadow it
+ // on this instance for the gesture: a native pan is the browser moving
+ // the scroller mid-drag, and watching for exactly that is how the hook
+ // knows whether its claim was honoured. Instance-only and deleted after,
+ // per the prototype-getter cost noted at the top of this file.
+ let offset = 0;
+ const scrollBy = vi.fn();
+ Object.defineProperties(el, {
+ scrollLeft: {
+ configurable: true,
+ get: () => offset,
+ set: (value: number) => {
+ offset = value;
+ },
+ },
+ scrollBy: {configurable: true, value: scrollBy},
+ });
+ const origin = {x: 150, y: 200};
+ touch(el, 'touchstart', origin);
+ for (const step of [0.5, 1]) {
+ if (step === 0.5) {
+ offset += scrollsBy;
+ }
+ touch(el, 'touchmove', {
+ x: origin.x + dx * step,
+ y: origin.y + dy * step,
+ });
+ }
+ touch(el, 'touchend');
+ // @ts-expect-error - removing the shadows restores the prototype's
+ delete el.scrollLeft;
+ // @ts-expect-error - same
+ delete el.scrollBy;
+ return scrollBy;
+ };
+
+ it('lets a touch on the calendar reach the sheet, now that it pages sideways', () => {
+ renderAndOpen();
+ const scroller = document.querySelector('[data-scroller="months"]')!;
+ const ancestor = watchAncestor();
+ touch(scroller, 'touchstart');
+ touch(scroller, 'touchmove');
+ // The calendar used to claim the gesture, because it scrolled vertically
+ // and the sheet read every downward drag as a dismiss. Paging sideways
+ // removes the conflict: horizontal pans stay here and vertical ones go to
+ // the sheet, so a downward drag can go back to meaning swipe-to-dismiss.
+ // A move with no direction yet (the same point twice) is nobody's.
+ expect(ancestor.seen).toEqual(['touchstart', 'touchmove']);
+ ancestor.stop();
+ });
+
+ it('claims a horizontal drag on the calendar', () => {
+ renderAndOpen();
+ const scroller = document.querySelector('[data-scroller="months"]')!;
+ const ancestor = watchAncestor();
+ swipe(scroller, -80, 0);
+ // touchstart still propagates — 'inline' cannot know the direction yet —
+ // but every move after the axis locks is ours.
+ expect(ancestor.seen).not.toContain('touchmove');
+ ancestor.stop();
+ });
+
+ it('leaves a downward drag on the calendar to the sheet', () => {
+ renderAndOpen();
+ const scroller = document.querySelector('[data-scroller="months"]')!;
+ const ancestor = watchAncestor();
+ swipe(scroller, 0, 80);
+ expect(ancestor.seen).toContain('touchmove');
+ ancestor.stop();
+ });
+
+ it('keeps a diagonal drag, because a thumb arcs as it swipes', () => {
+ renderAndOpen();
+ const scroller = document.querySelector('[data-scroller="months"]')!;
+ const ancestor = watchAncestor();
+ // ~50° off horizontal: past the browser's own pan-x cone, still ours.
+ swipe(scroller, -60, 72);
+ expect(ancestor.seen).not.toContain('touchmove');
+ ancestor.stop();
+ });
+
+ /**
+ * The band between our claim and the browser's `pan-x` cone. The sheet has
+ * been told to keep off, and the compositor refuses to pan, so without the
+ * fallback these gestures would do nothing at all — measured as a dead zone
+ * from 45° to 60° on an iPhone 15 profile.
+ */
+ it('pages a month itself when the browser refuses to pan a claimed swipe', () => {
+ renderAndOpen();
+ const scroller = document.querySelector('[data-scroller="months"]')!;
+
+ const forward = swipe(scroller, -60, 72);
+ expect(forward).toHaveBeenCalledTimes(1);
+ expect(forward.mock.calls[0][0]).toMatchObject({behavior: 'smooth'});
+ // Swiping left advances: the offset moves towards the end of the line.
+ expect(forward.mock.calls[0][0].left).toBeGreaterThan(0);
+
+ const back = swipe(scroller, 60, 72);
+ expect(back.mock.calls[0][0].left).toBeLessThan(0);
+ });
+
+ it('stays out of the way when the browser did pan', () => {
+ renderAndOpen();
+ const scroller = document.querySelector('[data-scroller="months"]')!;
+ // Native momentum and snapping own this one; a second nudge would fight
+ // them. `scrollsBy` stands in for the compositor moving the scroller.
+ expect(swipe(scroller, -120, 0, {scrollsBy: 40})).not.toHaveBeenCalled();
+ });
+
+ it('ignores a claimed gesture too short to be a swipe', () => {
+ renderAndOpen();
+ const scroller = document.querySelector('[data-scroller="months"]')!;
+ expect(swipe(scroller, -SWIPE_DISTANCE + 4, 0)).not.toHaveBeenCalled();
+ });
+
+ it('never pages from a drag it gave to the sheet', () => {
+ renderAndOpen();
+ const scroller = document.querySelector('[data-scroller="months"]')!;
+ expect(swipe(scroller, -40, 200)).not.toHaveBeenCalled();
+ });
+
+ it('stops a touch on a wheel from reaching the sheet', () => {
+ renderAndOpen();
+ fireEvent.click(
+ document.querySelector<HTMLElement>('[data-title="month-year"]')!,
+ );
+ const wheel = screen.getByRole('listbox', {name: 'Month'});
+ const ancestor = watchAncestor();
+ touch(wheel, 'touchstart');
+ touch(wheel, 'touchmove');
+ expect(ancestor.seen).not.toContain('touchstart');
+ expect(ancestor.seen).not.toContain('touchmove');
+ ancestor.stop();
+ });
+
+ it('lets touchend through, so the sheet can reset its own bookkeeping', () => {
+ renderAndOpen();
+ const scroller = document.querySelector('[data-scroller="months"]')!;
+ const ancestor = watchAncestor();
+ touch(scroller, 'touchend');
+ expect(ancestor.seen).toContain('touchend');
+ ancestor.stop();
+ });
+
+ it('leaves the rest of the picker to the sheet', () => {
+ renderAndOpen();
+ // The header is not a scroller: a drag there is the sheet's to interpret,
+ // and it is one of the two places a dismiss can still start from.
+ const title = document.querySelector<HTMLElement>(
+ '[data-title="month-year"]',
+ )!;
+ const ancestor = watchAncestor();
+ touch(title, 'touchstart');
+ touch(title, 'touchmove');
+ expect(ancestor.seen).toEqual(['touchstart', 'touchmove']);
+ ancestor.stop();
+ });
+
+ it('does not swallow taps — stopPropagation must not reach click', () => {
+ const onChange = vi.fn();
+ renderAndOpen(<Controlled initial="2026-03-21" onChange={onChange} />);
+ fireEvent.click(
+ within(pane('March 2026')).getByRole('button', {name: /March 25, 2026/}),
+ );
+ expect(onChange).toHaveBeenCalledWith('2026-03-25');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Dragging a wheel with a mouse
+// ---------------------------------------------------------------------------
+
+/**
+ * A wheel is a scroll container, so a finger pans it for free. A mouse gets
+ * nothing: browsers do not drag-scroll an overflow container, so pressing and
+ * pulling on the one control shaped like a thing you spin did nothing at all.
+ *
+ * It matters on desktop specifically because that is where this surface is
+ * reviewed, themed and screenshotted.
+ */
+describe('DateInput — a mouse can drag a wheel', () => {
+ const title = () =>
+ document.querySelector<HTMLElement>('[data-title="month-year"]')!;
+
+ /** jsdom has no layout: give the rows a height and the wheel a scrollTop. */
+ function withWheelLayout<T>(fn: () => T): T {
+ Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {
+ configurable: true,
+ get(this: HTMLElement) {
+ return this.getAttribute('role') === 'option' ? 28 : 0;
+ },
+ });
+ try {
+ return fn();
+ } finally {
+ // @ts-expect-error - deleting the shadow restores Element's own getter
+ delete HTMLElement.prototype.offsetHeight;
+ }
+ }
+
+ const wheel = () => screen.getByRole('listbox', {name: 'Month'});
+
+ const pointer = (
+ type: string,
+ {y = 0, pointerType = 'mouse', button = 0, id = 1} = {},
+ ) => {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ Object.defineProperties(event, {
+ clientY: {value: y},
+ pointerId: {value: id},
+ pointerType: {value: pointerType},
+ button: {value: button},
+ });
+ return event;
+ };
+
+ /** Stubs jsdom's missing capture API and records scrollTop as it moves. */
+ function trackable(el: HTMLElement) {
+ let top = 0;
+ Object.defineProperty(el, 'scrollTop', {
+ configurable: true,
+ get: () => top,
+ set: (v: number) => {
+ top = v;
+ },
+ });
+ el.setPointerCapture = () => {};
+ el.releasePointerCapture = () => {};
+ el.hasPointerCapture = () => true;
+ el.scrollTo = ((opts: ScrollToOptions) => {
+ top = opts.top ?? top;
+ }) as HTMLElement['scrollTo'];
+ return {
+ get scrollTop() {
+ return top;
+ },
+ };
+ }
+
+ it('scrolls the wheel when a mouse drags it', () => {
+ renderAndOpen();
+ fireEvent.click(title());
+ withWheelLayout(() => {
+ const el = wheel();
+ const track = trackable(el);
+ el.dispatchEvent(pointer('pointerdown', {y: 200}));
+ el.dispatchEvent(pointer('pointermove', {y: 160}));
+ // Content follows the hand: pulling up scrolls further down the list.
+ expect(track.scrollTop).toBe(40);
+ el.dispatchEvent(pointer('pointerup', {y: 160}));
+ // And the release lands on a row boundary rather than between two.
+ expect(track.scrollTop % 28).toBe(0);
+ });
+ });
+
+ it('ignores movement too small to be a drag, so a click is still a click', () => {
+ renderAndOpen();
+ fireEvent.click(title());
+ withWheelLayout(() => {
+ const el = wheel();
+ const track = trackable(el);
+ el.dispatchEvent(pointer('pointerdown', {y: 200}));
+ el.dispatchEvent(pointer('pointermove', {y: 200 - (DRAG_SLOP - 1)}));
+ expect(track.scrollTop).toBe(0);
+ });
+ });
+
+ it('leaves touch and pen alone — they pan natively, and better', () => {
+ renderAndOpen();
+ fireEvent.click(title());
+ withWheelLayout(() => {
+ for (const pointerType of ['touch', 'pen']) {
+ const el = wheel();
+ const track = trackable(el);
+ el.dispatchEvent(pointer('pointerdown', {y: 200, pointerType}));
+ el.dispatchEvent(pointer('pointermove', {y: 120, pointerType}));
+ expect(track.scrollTop).toBe(0);
+ el.dispatchEvent(pointer('pointerup', {y: 120, pointerType}));
+ }
+ });
+ });
+
+ it('ignores a secondary button, which belongs to the context menu', () => {
+ renderAndOpen();
+ fireEvent.click(title());
+ withWheelLayout(() => {
+ const el = wheel();
+ const track = trackable(el);
+ el.dispatchEvent(pointer('pointerdown', {y: 200, button: 2}));
+ el.dispatchEvent(pointer('pointermove', {y: 120}));
+ expect(track.scrollTop).toBe(0);
+ });
+ });
+
+ /**
+ * `scroll-snap-type: y mandatory` re-snaps after every scroll, programmatic
+ * ones included. Measured with it left on: 7 of 8 five-pixel drag steps were
+ * yanked back to a snap position, so the wheel stuck to a row and then
+ * jumped a whole one.
+ */
+ it('suspends snapping for the drag, and restores it after', () => {
+ renderAndOpen();
+ fireEvent.click(title());
+ withWheelLayout(() => {
+ const el = wheel();
+ trackable(el);
+ expect(el.style.scrollSnapType).toBe('');
+ el.dispatchEvent(pointer('pointerdown', {y: 200}));
+ el.dispatchEvent(pointer('pointermove', {y: 160}));
+ expect(el.style.scrollSnapType).toBe('none');
+ el.dispatchEvent(pointer('pointerup', {y: 160}));
+ el.dispatchEvent(new Event('scrollend'));
+ expect(el.style.scrollSnapType).toBe('');
+ });
+ });
+
+ /**
+ * BottomSheet starts its own drag-to-dismiss from a `pointerdown` on its
+ * body and CAPTURES the pointer for it, which retargets every later pointer
+ * event — including the click. Measured before this: a click on a wheel row
+ * that wobbled more than a pixel selected nothing at all.
+ */
+ it('keeps the press away from the sheet, which would capture the pointer', () => {
+ renderAndOpen();
+ fireEvent.click(title());
+ withWheelLayout(() => {
+ const el = wheel();
+ trackable(el);
+ const seen: string[] = [];
+ const listener = (event: Event) => seen.push(event.type);
+ document.body.addEventListener('pointerdown', listener);
+ el.dispatchEvent(pointer('pointerdown', {y: 200}));
+ expect(seen).not.toContain('pointerdown');
+ document.body.removeEventListener('pointerdown', listener);
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Pure month arithmetic
+// ---------------------------------------------------------------------------
+
+describe('monthGeometry', () => {
+ it('round-trips a month through its index', () => {
+ for (const [year, month] of [
+ [2026, 1],
+ [2026, 12],
+ [1976, 7],
+ [2100, 2],
+ ] as const) {
+ expect(fromMonthIndex(toMonthIndex(year, month))).toEqual({year, month});
+ }
+ });
+
+ it('orders months across a year boundary', () => {
+ expect(toMonthIndex(2027, 1) - toMonthIndex(2026, 12)).toBe(1);
+ });
+
+ it('reads a month index off a PlainDate, ignoring the day', () => {
+ expect(monthIndexOf({year: 2026, month: 3, day: 1})).toBe(
+ monthIndexOf({year: 2026, month: 3, day: 31}),
+ );
+ });
+
+ it('clamps to the reachable range', () => {
+ expect(clampIndex(5, 10, 20)).toBe(10);
+ expect(clampIndex(25, 10, 20)).toBe(20);
+ expect(clampIndex(15, 10, 20)).toBe(15);
+ });
+
+ describe('rowAtScrollOffset', () => {
+ it('maps an exact offset to its row', () => {
+ expect(rowAtScrollOffset(0, PANE, 100)).toBe(0);
+ expect(rowAtScrollOffset(PANE * 7, PANE, 100)).toBe(7);
+ });
+
+ it('rounds to the nearest row mid-scroll', () => {
+ expect(rowAtScrollOffset(PANE * 7 + 10, PANE, 100)).toBe(7);
+ expect(rowAtScrollOffset(PANE * 7 - 10, PANE, 100)).toBe(7);
+ expect(rowAtScrollOffset(PANE * 6.6, PANE, 100)).toBe(7);
+ });
+
+ it('never leaves the list', () => {
+ expect(rowAtScrollOffset(-500, PANE, 100)).toBe(0);
+ expect(rowAtScrollOffset(PANE * 1000, PANE, 100)).toBe(99);
+ });
+
+ it('is 0 before the pane size is known, rather than dividing by zero', () => {
+ expect(rowAtScrollOffset(1234, 0, 100)).toBe(0);
+ });
+
+ it('reads RTL scrollLeft, which counts down from zero', () => {
+ // The spec puts the inline start at 0 and runs negative from there, so
+ // an unsigned read would pin an RTL calendar to month zero forever.
+ expect(rowAtScrollOffset(-PANE * 7, PANE, 100, true)).toBe(7);
+ expect(rowAtScrollOffset(-PANE * 7 - 10, PANE, 100, true)).toBe(7);
+ expect(rowAtScrollOffset(0, PANE, 100, true)).toBe(0);
+ });
+ });
+
+ describe('scrollOffsetForRow', () => {
+ it('is the inverse of rowAtScrollOffset, in both directions', () => {
+ for (const isRTL of [false, true]) {
+ for (const row of [0, 1, 7, 99]) {
+ const offset = scrollOffsetForRow(row, PANE, isRTL);
+ expect(rowAtScrollOffset(offset, PANE, 100, isRTL)).toBe(row);
+ }
+ }
+ });
+
+ it('runs negative under RTL', () => {
+ expect(scrollOffsetForRow(3, PANE, false)).toBe(PANE * 3);
+ expect(scrollOffsetForRow(3, PANE, true)).toBe(-PANE * 3);
+ });
+ });
+
+ describe('paneWindow', () => {
+ it('mounts the overscan on both sides', () => {
+ expect(paneWindow(50, 100, 3)).toEqual({start: 47, end: 53});
+ expect(rowsIn(paneWindow(50, 100, 1))).toEqual([49, 50, 51]);
+ });
+
+ it('truncates at the ends of the list instead of going out of bounds', () => {
+ expect(paneWindow(0, 100, 3)).toEqual({start: 0, end: 3});
+ expect(paneWindow(99, 100, 3)).toEqual({start: 96, end: 99});
+ });
+ });
+
+ it('reaches a century in each direction by default', () => {
+ expect(DEFAULT_MONTH_REACH).toBe(600);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Styles jsdom cannot resolve — assert the definition, not the effect
+// ---------------------------------------------------------------------------
+
+describe('DateInput — scroll CSS (definition-level)', () => {
+ const dir = path.dirname(fileURLToPath(import.meta.url));
+ const read = (file: string) => readFileSync(path.join(dir, file), 'utf8');
+
+ /**
+ * The declarations inside one named style object, comments stripped and
+ * trailing commas removed.
+ *
+ * Crude on purpose — a nested value object contributes its own inner lines
+ * too. Every caller looks for a specific property prefix, so the noise is
+ * harmless, and a real parser here would be more machinery than the
+ * question deserves.
+ */
+ const declarations = (source: string, object: string) => {
+ const open = source.indexOf(` ${object}: {`);
+ expect(open).toBeGreaterThan(-1);
+ return source
+ .slice(open, source.indexOf('\n },', open))
+ .replace(/\/\/.*$/gm, '')
+ .split('\n')
+ .map(line => line.trim())
+ .filter(line => line.endsWith(','))
+ .map(line => line.slice(0, -1));
+ };
+
+ /** The same, scoped to one `export const <group> = stylex.create({...})`. */
+ const declarationsIn = (source: string, group: string, object: string) => {
+ const at = source.indexOf(`export const ${group}`);
+ expect(at).toBeGreaterThan(-1);
+ return declarations(source.slice(at), object);
+ };
+
+ it('pages the month scroller one whole pane at a time, horizontally', () => {
+ const source = read('MonthScroller.tsx');
+ expect(source).toContain("scrollSnapType: 'x mandatory'");
+ expect(source).toContain("scrollSnapAlign: 'start'");
+ // pan-x is what splits the gesture by axis: horizontal pans stay with the
+ // calendar, vertical ones reach the sheet as swipe-to-dismiss. Without it
+ // the two would fight again, the way they did when this scrolled down.
+ expect(source).toContain("touchAction: 'pan-x'");
+ // The pane and the scrollport must come from the same expression, or a
+ // pane stops being exactly one screen and every snap offset drifts.
+ expect(
+ source.match(/blockSize: dateInputTouchGeometry\.paneBlockSize/g),
+ ).toHaveLength(2);
+ });
+
+ it('positions panes with logical properties, so RTL mirrors', () => {
+ const source = read('MonthScroller.tsx');
+ // Scoped to the style objects: `scrollTo({left})` is the DOM API and is
+ // supposed to say left — it is the CSS that must stay logical, because
+ // physical `left` would lay the months out identically in both directions
+ // while the scroll math mirrored, and the two would disagree under RTL.
+ const styles = source
+ .slice(
+ source.indexOf('const styles = stylex.create('),
+ source.indexOf('export interface MonthScrollerHandle'),
+ )
+ // Comments explain the rule ("insetInlineStart, not left") and would
+ // otherwise trip it.
+ .replace(/\/\/.*$/gm, '');
+ expect(styles).toContain('insetInlineStart');
+ expect(styles).not.toMatch(/\bleft:/);
+ expect(styles).not.toMatch(/\bright:/);
+ });
+
+ /**
+ * Adjacent days take the desktop calendar's exact treatment, and the point
+ * of reading BOTH files is that "exact" stays true if the desktop's changes.
+ *
+ * Calendar splits the treatment across two style objects — `dayCellTheme`
+ * carries the colour, `dayCellStyles` the opacity — so copying it by eye
+ * gets you one half and not the other. This pane took only the colour at
+ * first, and the spill days came out visibly heavier than the desktop's.
+ *
+ * Both surfaces now render the same three tiers, measured in a browser on
+ * the same story: 23 for a day you can pick, 185 for one the range rules
+ * out, 203 for a spilled day (which is outside AND therefore disabled, so
+ * it takes both). The enabled-adjacent tier that used to sit at 169 is gone
+ * with the tap that produced it.
+ */
+ it('mutes adjacent days exactly as the desktop calendar does', () => {
+ // The desktop's two halves, read out of its own source rather than
+ // restated here — so the check follows the desktop if its treatment
+ // moves, instead of freezing today's values into this file.
+ const desktop = read('../Calendar/styles.ts');
+ const structural = declarationsIn(desktop, 'dayCellStyles', 'dayOutside');
+ const theme = declarationsIn(desktop, 'dayCellTheme', 'dayOutside');
+ // Both halves must have found something, or the parity check below is
+ // `arrayContaining([])` and passes on anything at all.
+ expect(structural.length).toBeGreaterThan(0);
+ expect(theme.length).toBeGreaterThan(0);
+
+ // And the touch pane carries all of it, in its one object.
+ const touch = declarations(read('MonthScroller.tsx'), 'dayOutside');
+ expect(touch).toEqual(expect.arrayContaining([...structural, ...theme]));
+ });
+
+ /**
+ * Disabled days follow the desktop too, and this is the half that actually
+ * answered "the disabled dates and the adjacent ones look the same".
+ *
+ * The desktop FADES a disabled day rather than recolouring it: `opacity:
+ * 0.3` over whatever colour the day already had. This pane used to paint a
+ * flat `--color-text-disabled` instead, which on white put a disabled
+ * in-month day at ~163 and an ENABLED adjacent day at ~168 — five levels
+ * apart, indistinguishable, and with the disabled one the darker of the
+ * two, so the unpickable date read as the more solid one. Fading instead
+ * puts every disabled day lighter than every enabled one, which is the
+ * ordering a calendar needs.
+ */
+ it('fades disabled days as the desktop does, rather than recolouring them', () => {
+ const desktop = read('../Calendar/styles.ts');
+ const theme = declarationsIn(desktop, 'dayCellTheme', 'dayDisabled');
+ const touch = declarations(read('MonthScroller.tsx'), 'dayDisabled');
+
+ // Whatever opacity the desktop fades to, this pane fades to the same one.
+ const fade = theme.find(d => d.startsWith('opacity:'));
+ expect(fade).toBeDefined();
+ expect(touch).toContain(fade);
+
+ // And no colour of its own: a colour would override the secondary one a
+ // spilled day carries, collapsing "disabled" and "disabled and adjacent"
+ // into a single shade.
+ expect(touch.some(d => d.startsWith('color:'))).toBe(false);
+ // Parity, not a rule of this pane's own — if the desktop ever starts
+ // recolouring a disabled day, this fires and says to follow it.
+ expect(theme.some(d => d.startsWith('color:'))).toBe(false);
+ });
+
+ /**
+ * Order matters as much as the values: `dayDisabled` is applied AFTER
+ * `dayOutside`, so a spilled day beyond min/max paints disabled rather than
+ * merely outside. Reversed, an unselectable date would look more available
+ * than the selectable ones beside it.
+ */
+ it('lets disabled win over outside on a spilled day past min/max', () => {
+ const applied = read('MonthScroller.tsx');
+ const outside = applied.indexOf('day.isOutside && styles.dayOutside');
+ const disabled = applied.indexOf('isDisabled && styles.dayDisabled');
+ expect(outside).toBeGreaterThan(-1);
+ expect(outside).toBeLessThan(disabled);
+ });
+
+ it('keeps the month scroller and the wheels on border-box', () => {
+ // Load-bearing: clientHeight is the pane height, the snap offsets and the
+ // virtualization all at once.
+ expect(read('MonthScroller.tsx')).toContain("boxSizing: 'border-box'");
+ expect(read('Wheel.tsx')).toContain("boxSizing: 'border-box'");
+ });
+
+ it('sizes the wheel row tighter than a day cell, with larger text', () => {
+ const tokens = read('tokens.stylex.ts');
+ // Scroll-first rows: closer together than day cells and closer to the
+ // text they hold, the way a platform picker packs them.
+ expect(tokens).toContain("wheelItemSize: '28px'");
+ expect(read('Wheel.tsx')).toContain(
+ "fontSize: typeScaleVars['--text-large-size']",
+ );
+ });
+
+ it('centers wheel rows and pads both ends so either extreme can reach the band', () => {
+ const source = read('Wheel.tsx');
+ expect(source).toContain("scrollSnapType: 'y mandatory'");
+ expect(source).toContain("scrollSnapAlign: 'center'");
+ expect(source).toContain(
+ 'paddingBlock: dateInputTouchGeometry.wheelEdgePadding',
+ );
+ });
+
+ it('guards the scroll-driven falloff behind @supports', () => {
+ const source = read('Wheel.tsx');
+ // Without the guard, a browser that does not understand animation-timeline
+ // runs these keyframes once on the document timeline instead.
+ expect(source).toContain("'@supports (animation-timeline: view())'");
+ expect(source).toContain("animationTimeline: 'view(y)'");
+ expect(source).toContain("'@media (prefers-reduced-motion: reduce)'");
+ });
+
+ it('keeps the falloff off the snap area itself', () => {
+ // A transform moves the snap area, and the wheel then settles a few
+ // pixels off the row it is showing.
+ const source = read('Wheel.tsx');
+ const itemInner = source.slice(source.indexOf('itemInner: {'));
+ expect(itemInner).toContain("animationTimeline: 'view(y)'");
+ const item = source.slice(
+ source.indexOf(' item: {'),
+ source.indexOf('itemInner: {'),
+ );
+ expect(item).not.toContain('animationTimeline');
+ expect(item).not.toContain("overflow: 'hidden'");
+ });
+
+ it('insets the sheet content equally on every edge', () => {
+ const source = read('TouchDateField.tsx');
+ // One inset, and the header/footer must not add their own on top of it —
+ // that is what put the title and Done 4px off the day grid's line.
+ expect(source).toContain("paddingInline: spacingVars['--spacing-4']");
+ expect(source).toContain("paddingBlockEnd: spacingVars['--spacing-4']");
+ // The block-start is the documented exception: the grab handle floats out
+ // of flow, so the content wrapper owes it the height it occupies.
+ expect(source).toContain("paddingBlockStart: spacingVars['--spacing-6']");
+ const header = source.slice(
+ source.indexOf(' header: {'),
+ source.indexOf(' title: {'),
+ );
+ expect(header).not.toContain('paddingInline');
+ const footer = source.slice(
+ source.indexOf(' footer: {'),
+ source.indexOf(' sheetBody: {'),
+ );
+ expect(footer).not.toContain('paddingInline');
+ });
+
+ it('floors the touch target without discarding the size prop', () => {
+ const source = read('TouchDateField.tsx');
+ // Each size keeps its own height AND cannot render below a thumb's reach.
+ const sizeMap = source.slice(
+ source.indexOf('const sizeStyles = stylex.create('),
+ source.indexOf('const styles = stylex.create('),
+ );
+ expect(
+ sizeMap.match(
+ /minBlockSize: \{default: null, '@media \(pointer: coarse\)': TOUCH_TARGET\}/g,
+ ),
+ ).toHaveLength(3);
+ });
+
+ it('floors the month arrows too — Button tops out at 36px', () => {
+ const source = read('TouchDateField.tsx');
+ const arrow = source.slice(
+ source.indexOf(' monthArrow: {'),
+ source.indexOf(' monthArrowIcon: {'),
+ );
+ expect(arrow).toContain(
+ "minBlockSize: {default: null, '@media (pointer: coarse)': TOUCH_TARGET}",
+ );
+ expect(arrow).toContain(
+ "minInlineSize: {default: null, '@media (pointer: coarse)': TOUCH_TARGET}",
+ );
+ });
+
+ /**
+ * A bare inline wrapper puts the glyph on the text baseline, a few px above
+ * the button's optical centre. Core's Calendar carries the same rule on its
+ * own nav icons.
+ */
+ it('keeps the mirrored arrow glyph centred', () => {
+ const source = read('TouchDateField.tsx');
+ const icon = source.slice(source.indexOf(' monthArrowIcon: {'));
+ expect(icon.slice(0, icon.indexOf('}'))).toContain(
+ "display: 'inline-flex'",
+ );
+ });
+
+ /**
+ * The wheels are a layer that fades in and out on top; the calendar under
+ * them is covered and uncovered, and never seen to move.
+ *
+ * The swap used to take turns — the outgoing surface faded out over a first
+ * leg, the incoming one waited and faded in over a second — because the
+ * wheels' panel was transparent. Overlapping them put the wheels'
+ * translucent selection band over the live calendar grid and tinted one
+ * band-shaped strip of it: "the grey area animates differently from the
+ * content".
+ *
+ * An opaque plate INSIDE the fading layer fixes that at the root. The layer
+ * renders as one finished opaque image and the fade applies to the image,
+ * so the band crosses at the same rate as everything beside it. And once it
+ * is opaque, the calendar needs no fade of its own — animating it too would
+ * be animating the date picker rather than the thing arriving over it.
+ *
+ * What this pins is that split: the layer above gets opacity and a
+ * background, the layer beneath gets visibility and nothing else.
+ */
+ it('fades the wheels in and out over a calendar that does not animate', () => {
+ const source = read('TouchDateField.tsx');
+ const overlay = declarations(source, 'panelOverlay');
+ const beneath = declarations(source, 'panelBeneath');
+
+ // The layer fades, both directions — the transition is on the shown
+ // state, so entering and leaving it both animate.
+ expect(overlay).toContain("transitionProperty: 'opacity, visibility'");
+ expect(overlay).toContain('transitionDuration: SWAP_DURATION');
+ expect(declarations(source, 'panelOverlayHidden')).toContain('opacity: 0');
+
+ // And it is opaque while it does, in the token the sheet paints itself
+ // with, so the fade is uniform across the band and the text alike.
+ expect(overlay).toContain(
+ "backgroundColor: colorVars['--color-background-surface']",
+ );
+
+ // The layer beneath moves nothing that can be SEEN moving: visibility
+ // only, no opacity, so it is covered and uncovered rather than faded.
+ expect(beneath).toContain("transitionProperty: 'visibility'");
+ expect(beneath.some(d => d.startsWith('opacity'))).toBe(false);
+ expect(
+ declarations(source, 'panelBeneathHidden').some(d =>
+ d.startsWith('opacity'),
+ ),
+ ).toBe(false);
+
+ // Two of each, and never the same one twice: the calendar panel and the
+ // calendar's footer actions are beneath, the wheels and their Done above.
+ const count = (name: string) =>
+ source.match(new RegExp(`styles\\.${name},`, 'g'))?.length ?? 0;
+ expect(count('panelBeneath')).toBe(2);
+ expect(count('panelOverlay')).toBe(2);
+ });
+
+ /**
+ * The layer paints as a unit, which is what makes "opaque" mean "covers".
+ *
+ * Backgrounds and text paint in separate phases, so without a stacking
+ * context a later sibling's background lands UNDER an earlier sibling's
+ * text — the plate went in opaque and the calendar's day numbers showed
+ * straight through it. Measured before and after: ink inside the grid's box
+ * at full cover went from the calendar's 2.5% of pixels to the wheels' own.
+ *
+ * Easy to lose, because any opacity below 1 makes a stacking context by
+ * accident. It only breaks at the two ends of the fade, where opacity is
+ * exactly 1 — which is to say, whenever anyone is actually looking.
+ */
+ it('paints the layer as a unit, so the plate really covers', () => {
+ expect(declarations(read('TouchDateField.tsx'), 'panelOverlay')).toContain(
+ "isolation: 'isolate'",
+ );
+ });
+
+ /**
+ * The weekday row and the header arrows are the one part of the calendar
+ * the layer cannot cover — the plate starts below the header. They fade on
+ * the layer's own timing rather than clearing instantly, so the change
+ * reads as one motion instead of chrome blinking out a beat ahead of the
+ * grid being covered.
+ */
+ it('fades the uncovered chrome on the same timing as the layer', () => {
+ const source = read('TouchDateField.tsx');
+ for (const name of ['weekdays', 'monthArrows']) {
+ expect(declarations(source, name)).toContain(
+ 'transitionDuration: SWAP_DURATION',
+ );
+ expect(declarations(source, `${name}Hidden`)).toContain('opacity: 0');
+ }
+ });
+
+ /**
+ * Both footer actions span the sheet. A full-width primary is the shape a
+ * phone form ends with, and it puts the target under the thumb wherever
+ * the hand is.
+ */
+ it('spans the footer with its actions', () => {
+ const source = read('TouchDateField.tsx');
+ // Reset + Save share the calendar's cell; Done is the wheels'. Each
+ // fills the space it is given, so the row divides evenly rather than by
+ // label length.
+ expect(source.match(/width="100%"/g)).toHaveLength(3);
+ });
+
+ /**
+ * The selection band has to be visible enough that fading it reads as a
+ * fade. At `--color-background-muted` (4.7% alpha) the whole plate sat 17
+ * units of colour from the sheet behind it, so its animation had 17 units
+ * to happen in while the text beside it travelled 412 — it did not look
+ * like it was fading, it looked like it appeared at the end.
+ * `--color-neutral` (10%) doubles that to 36 and is still quiet enough to
+ * sit under text.
+ */
+ it('gives the wheel band enough contrast for its fade to read', () => {
+ const source = read('Wheel.tsx');
+ const band = source.slice(
+ source.indexOf(' band: {'),
+ source.indexOf('});', source.indexOf(' band: {')),
+ );
+ expect(band).toContain("backgroundColor: colorVars['--color-neutral']");
+ });
+
+ /**
+ * `--ease-standard` is `cubic-bezier(0.24, 1, 0.4, 1)`: right for something
+ * travelling a distance, wrong for a fade. Measured with it, opacity hit
+ * 50% in 91ms and 95% in 241ms of a 410ms transition — the fade was over
+ * long before the duration was, so lengthening the duration bought an
+ * imperceptible tail rather than a slower fade. A fade covers no distance,
+ * so its progress should simply be its progress.
+ *
+ * The title chevron is the exception and keeps the token: it rotates, and
+ * rotation is travel.
+ */
+ it('fades linearly, and eases only the thing that travels', () => {
+ const source = read('TouchDateField.tsx');
+ const styles = source.slice(
+ source.indexOf('const styles = stylex.create('),
+ );
+ const chevron = styles.slice(
+ styles.indexOf(' titleChevron: {'),
+ styles.indexOf(' titleChevronOpen: {'),
+ );
+ expect(chevron).toContain("transitionProperty: 'transform'");
+ expect(chevron).toContain(
+ "transitionTimingFunction: easeVars['--ease-standard']",
+ );
+ // The chevron is the only eased transition; every fade is linear.
+ expect(
+ styles.match(/transitionTimingFunction: easeVars\['--ease-standard'\]/g),
+ ).toHaveLength(1);
+ expect(styles.match(/transitionTimingFunction: 'linear'/g)).toHaveLength(3);
+ });
+
+ /**
+ * Everything in the swap runs for the same time, so it reads as one change
+ * rather than several. The chevron included — it used to run
+ * `--duration-medium` against a 220ms swap and was still turning well after
+ * the wheels had settled.
+ *
+ * A token rather than a literal, so a consumer's motion scale carries: the
+ * Storybook theme resolves `--duration-fast` to 125ms, not the default
+ * 175ms, and the swap follows it without knowing.
+ */
+ it('runs the whole swap on one duration', () => {
+ const source = read('TouchDateField.tsx');
+ const styles = source.slice(
+ source.indexOf('const styles = stylex.create('),
+ );
+ // The arrows, the weekday row, the layer beneath, the layer above, and
+ // the chevron.
+ expect(styles.match(/transitionDuration: SWAP_DURATION/g)).toHaveLength(5);
+ // And no leftover hand-rolled timing beside them.
+ expect(styles).not.toContain('PANEL_FADE_MS');
+ expect(source).toContain(
+ "const SWAP_DURATION = durationVars['--duration-fast']",
+ );
+ });
+
+ it('keeps the virtual keyboard down on the touch field', () => {
+ const source = read('TouchDateField.tsx');
+ // readOnly alone still opens the keyboard on some Android browsers.
+ expect(source).toContain('readOnly');
+ expect(source).toContain('inputMode="none"');
+ });
+});
diff --git a/packages/core/src/DateInput/MonthScroller.tsx b/packages/core/src/DateInput/MonthScroller.tsx
new file mode 100644
index 0000000000..fe293e73c1
--- /dev/null
+++ b/packages/core/src/DateInput/MonthScroller.tsx
@@ -0,0 +1,784 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file MonthScroller.tsx
+ * @input Month bounds, selected value, constraints, week start
+ * @output Exports MonthScroller and MonthScrollerHandle
+ * @position Internal component; consumed by TouchDateField.tsx
+ *
+ * The continuous surface: months stacked vertically in one scroller, each pane
+ * exactly as tall as the scrollport and snapped to its start. Two consequences
+ * fall out of that single geometric choice — the picker never changes height,
+ * and there is no resting position that shows half of two months.
+ *
+ * Every pane is a fixed six-row grid, including the months that only need
+ * four or five, because a pane whose height depended on its contents would
+ * make snap offsets vary from month to month and the scroll position drift.
+ *
+ * The list is long (a century by default) but only a few panes are ever
+ * mounted: a spacer holds the full scroll height and the visible panes are
+ * positioned into it absolutely. Nothing is stitched or recycled during a
+ * scroll, so snap offsets are constant and momentum is never interrupted —
+ * which is the failure mode of the usual "append months at the edge" approach.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/DateInput/TouchDateField.tsx
+ * - /packages/core/src/DateInput/DateInput.doc.mjs
+ * - /packages/core/src/DateInput/DateInputTouch.test.tsx
+ */
+
+import {
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {useCalendarDays} from '../Calendar';
+import {useDirection} from '../i18n';
+import {
+ colorVars,
+ radiusVars,
+ fontWeightVars,
+ typeScaleVars,
+ durationVars,
+ borderVars,
+} from '../theme/tokens.stylex';
+import {focusOutlineStyles} from '../utils';
+import {
+ type DayOfWeek,
+ type ISODateString,
+ type PlainDate,
+ plainDateAddDays,
+ plainDateDayOfWeek,
+ plainDateFormat,
+ plainDateIsEqual,
+ plainDateToISO,
+ DATE_FORMAT_MONTH_YEAR,
+ DATE_FORMAT_WITH_WEEKDAY,
+} from '../utils';
+import {dateInputTouchSizes, dateInputTouchGeometry} from './tokens.stylex';
+import {useOwnScrollGesture} from './useOwnScrollGesture';
+import {
+ fromMonthIndex,
+ monthIndexOf,
+ paneWindow,
+ rowAtScrollOffset,
+ rowsIn,
+ scrollOffsetForRow,
+} from './monthGeometry';
+
+const DAY_SIZE = dateInputTouchSizes.daySize;
+
+/**
+ * Panes mounted on each side of the visible one. Sized against a fast fling:
+ * the window widens once per animation frame, so it only fails if a single
+ * frame travels further than this — three months, about 800px at the default
+ * day size. Under `scroll-snap-type: mandatory`, landing on an unmounted pane
+ * would not merely show a gap, it would re-snap to the nearest mounted one.
+ */
+const OVERSCAN = 3;
+
+const styles = stylex.create({
+ scroller: {
+ position: 'relative',
+ blockSize: dateInputTouchGeometry.paneBlockSize,
+ // Stated, not inherited from the reset: the pane size, the snap offsets
+ // and the virtualization all key off the measured box, so a consumer
+ // without reset.css (or with a stray box-sizing rule — the reset's is
+ // zero-specificity `:where`) must not be able to change what it means.
+ boxSizing: 'border-box',
+ overflowX: 'auto',
+ overflowY: 'hidden',
+ // The paging behaviour, now along the inline axis. Every snap area is a
+ // full pane, so there is exactly one resting position per month.
+ scrollSnapType: 'x mandatory',
+ // Keeps a fling inside the picker rather than handing it to the page.
+ overscrollBehavior: 'contain',
+ scrollbarWidth: 'none',
+ // pan-x, so the browser keeps horizontal pans here and hands VERTICAL
+ // ones straight to the sheet. That is why this scroller no longer claims
+ // the gesture the way the wheels do: with the axes separated there is
+ // nothing to fight over, and a downward drag on the calendar can go back
+ // to meaning swipe-to-dismiss.
+ touchAction: 'pan-x',
+ },
+ spacer: {
+ position: 'relative',
+ blockSize: '100%',
+ },
+ pane: {
+ position: 'absolute',
+ insetBlock: 0,
+ blockSize: dateInputTouchGeometry.paneBlockSize,
+ scrollSnapAlign: 'start',
+ // No `scroll-snap-stop: always`. It would cap every fling at one month,
+ // which is tidy but stops the surface being continuous — "three months
+ // ahead" should be one throw, not three flicks. Momentum carrying past
+ // several panes is why OVERSCAN is what it is.
+ display: 'grid',
+ gridTemplateColumns: 'repeat(7, 1fr)',
+ gridTemplateRows: dateInputTouchGeometry.paneRows,
+ },
+ row: {
+ display: 'contents',
+ },
+ cell: {
+ position: 'relative',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ day: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ inlineSize: '100%',
+ blockSize: '100%',
+ minInlineSize: DAY_SIZE,
+ minBlockSize: DAY_SIZE,
+ padding: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ color: colorVars['--color-text-primary'],
+ fontSize: typeScaleVars['--text-body-size'],
+ fontWeight: fontWeightVars['--font-weight-normal'],
+ cursor: 'pointer',
+ // A tap on a 44px target should not also select the number inside it.
+ userSelect: 'none',
+ WebkitTapHighlightColor: 'transparent',
+ },
+ /**
+ * The circular hit/selection puck inside the tap target. Sizing the puck
+ * rather than the button keeps the touch target at the full cell while the
+ * visual stays a tidy circle.
+ */
+ puck: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ inlineSize: `calc(${DAY_SIZE} - 8px)`,
+ blockSize: `calc(${DAY_SIZE} - 8px)`,
+ borderRadius: radiusVars['--radius-full'],
+ borderWidth: borderVars['--border-width'],
+ borderStyle: 'solid',
+ borderColor: 'transparent',
+ backgroundColor: 'transparent',
+ transitionProperty: 'background-color, color, border-color',
+ transitionDuration: durationVars['--duration-fast'],
+ },
+ puckHoverable: {
+ // Two guards, for two different failure modes.
+ //
+ // `@media (hover: hover)`: on a touch screen a :hover tint sticks to the
+ // last tapped day until something else is tapped.
+ //
+ // `:where(:not(:disabled,[aria-disabled="true"]))`: a browser suppresses a
+ // disabled control's EVENTS, not its hover styling, so an unguarded
+ // :hover tints a day you cannot pick. The day's disabled state lives on
+ // the button (as `aria-disabled`, which keeps it focusable) and this puck
+ // is the span inside it, so today the working mechanism is the JS gate at
+ // the call site — this guard is what keeps the rule true if the styles
+ // ever move onto the button itself.
+ backgroundColor: {
+ default: 'transparent',
+ '@media (hover: hover)': {
+ default: 'transparent',
+ ':hover:where(:not(:disabled,[aria-disabled="true"]))':
+ colorVars['--color-overlay-hover'],
+ },
+ },
+ },
+ puckToday: {
+ borderColor: colorVars['--color-border-emphasized'],
+ fontWeight: fontWeightVars['--font-weight-semibold'],
+ },
+ puckSelected: {
+ backgroundColor: {
+ default: colorVars['--color-accent'],
+ // Holds the accent through hover, overriding puckHoverable's tint.
+ // Same guarded selector, so the two have equal specificity and
+ // application order decides — which is what puts this one on top.
+ ':hover:where(:not(:disabled,[aria-disabled="true"]))':
+ colorVars['--color-accent'],
+ },
+ borderColor: colorVars['--color-accent'],
+ color: colorVars['--color-on-accent'],
+ fontWeight: fontWeightVars['--font-weight-semibold'],
+ },
+ /**
+ * A day belonging to the month either side of this pane. Muted the way
+ * Calendar mutes its own, and unselectable for the same reason it is
+ * there: it exists to show where the month ends, not to offer a date. A
+ * pane is one month, and tapping out of it would move the calendar under
+ * your thumb; the swipe or the arrow says "next month" without ambiguity.
+ *
+ * It needs no special handling for the roving tab order: `tabbableISO` is
+ * resolved per pane and only ever names a date in THAT pane's own month,
+ * so an outside cell can never match it. Which is the property that keeps
+ * a date from having two tab stops — the pane that owns it, and the
+ * neighbour that merely shows it.
+ */
+ dayOutside: {
+ // Exactly what the desktop calendar does to its own spill days: the
+ // secondary text colour AND half opacity, which is what makes them read
+ // as background rather than as dimmer choices. (Calendar splits these
+ // across two style objects — `dayOutside` in its theme layer carries the
+ // colour, the one in its structural layer the opacity — so applying only
+ // the colour, as this did at first, was half the treatment.)
+ color: colorVars['--color-text-secondary'],
+ opacity: 0.5,
+ },
+ dayDisabled: {
+ // The desktop's disabled treatment, and deliberately not a disabled
+ // COLOUR: it fades whatever colour the day already had (0.3), so an
+ // in-month day and a spilled one stay a step apart while disabled, and
+ // both land LIGHTER than an enabled spill day rather than darker.
+ //
+ // A flat `--color-text-disabled` is what this had, and it put an enabled
+ // adjacent day at ~168 against a disabled in-month day at ~163 on white:
+ // five levels apart, which is no difference at all. That is the whole
+ // reason the two were hard to tell apart.
+ opacity: 0.3,
+ cursor: 'not-allowed',
+ },
+});
+
+const dynamic = stylex.create({
+ spacer: (inlineSize: number) => ({
+ inlineSize: `${inlineSize}px`,
+ }),
+ // insetInlineStart, not left: under RTL the panes have to lay out from the
+ // right, and the scroll math mirrors with them (see scrollOffsetForRow).
+ pane: (insetInlineStart: number, inlineSize: number) => ({
+ insetInlineStart: `${insetInlineStart}px`,
+ inlineSize: `${inlineSize}px`,
+ }),
+});
+
+export interface MonthScrollerHandle {
+ /** Bring a month to rest at the top of the scrollport. */
+ scrollToMonth: (monthIndex: number, behavior?: ScrollBehavior) => void;
+}
+
+export interface MonthScrollerProps {
+ /** Imperative handle for programmatic navigation (Today, the wheels). */
+ handleRef?: React.RefObject<MonthScrollerHandle | null>;
+ /** First reachable month, as a month index. */
+ minMonthIndex: number;
+ /** Last reachable month, as a month index. */
+ maxMonthIndex: number;
+ /** Month to rest on at mount. */
+ initialMonthIndex: number;
+ /** Fires as the scroller passes each month, settled or not. */
+ onVisibleMonthChange: (monthIndex: number) => void;
+ /** Currently selected date. */
+ selectedDate: PlainDate | null;
+ /** Today, for the `aria-current` marker. */
+ today: PlainDate;
+ /** Whether a date fails min/max or a custom constraint. */
+ isDateDisabled: (date: PlainDate) => boolean;
+ /** First column of the week. */
+ weekStartsOn: DayOfWeek;
+ /** Fired when a day is tapped. */
+ onSelect: (value: ISODateString) => void;
+}
+
+/**
+ * A vertically continuous, snap-paged run of month grids.
+ */
+export function MonthScroller({
+ handleRef,
+ minMonthIndex,
+ maxMonthIndex,
+ initialMonthIndex,
+ onVisibleMonthChange,
+ selectedDate,
+ today,
+ isDateDisabled,
+ weekStartsOn,
+ onSelect,
+}: MonthScrollerProps) {
+ const scrollerRef = useRef<HTMLDivElement | null>(null);
+ const rowCount = maxMonthIndex - minMonthIndex + 1;
+
+ // Pane WIDTH is read from layout, never assumed: it is whatever the CSS
+ // says the scrollport is, so the snap offsets and the virtualization follow
+ // a resize (rotation, a split-screen change) without re-deriving anything.
+ const [paneSize, setPaneSize] = useState(0);
+ // Which way the inline axis runs. Under RTL the panes lay out from the
+ // right and scrollLeft counts DOWN from 0, so every conversion between a
+ // row and a scroll offset has to know.
+ const isRTL = useDirection() === 'rtl';
+ const [centerRow, setCenterRow] = useState(initialMonthIndex - minMonthIndex);
+ // The visible row, mirrored so the scroll handler can tell "changed" from
+ // "same" without reading state, and notify the parent OUTSIDE a state
+ // updater — React runs updaters during render, where another component's
+ // setState is illegal.
+ const centerRowRef = useRef(centerRow);
+ // A row to scroll to once its pane is mounted; see scrollToMonth.
+ const pendingScrollRef = useRef<number | null>(null);
+
+ /**
+ * The row a programmatic scroll is heading for, so its own scroll events
+ * are not reported back as if the user had gone there. Null once a finger
+ * touches the scroller, or once the steered scroll has arrived.
+ */
+ const steeredRowRef = useRef<number | null>(null);
+
+ // Keyboard focus moves by date, not by cell index, so it crosses month
+ // boundaries the way a calendar should. Null until the user takes the grid
+ // with the keyboard.
+ const [focusedDate, setFocusedDate] = useState<PlainDate | null>(null);
+ const shouldRestoreFocusRef = useRef(false);
+
+ const onVisibleMonthChangeRef = useRef(onVisibleMonthChange);
+ onVisibleMonthChangeRef.current = onVisibleMonthChange;
+
+ useLayoutEffect(() => {
+ const scroller = scrollerRef.current;
+ if (scroller == null) {
+ return;
+ }
+ const measure = () => {
+ // Ignore zero: the picker can be mounted inside something not yet
+ // displayed (a closed BottomSheet), and a zero width would unmount
+ // every pane and lose the scroll position.
+ const measured = scroller.clientWidth;
+ if (measured > 0) {
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- pane width is a measurement; layout is the only place it exists
+ setPaneSize(measured);
+ }
+ };
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(scroller);
+ return () => observer.disconnect();
+ }, []);
+
+ // Land on the initial month before the first paint. Runs once the height is
+ // known; `hasPositioned` keeps a later resize from yanking the user back.
+ const hasPositionedRef = useRef(false);
+ useLayoutEffect(() => {
+ const scroller = scrollerRef.current;
+ if (scroller == null || paneSize === 0 || hasPositionedRef.current) {
+ return;
+ }
+ hasPositionedRef.current = true;
+ scroller.scrollLeft = scrollOffsetForRow(
+ initialMonthIndex - minMonthIndex,
+ paneSize,
+ isRTL,
+ );
+ }, [paneSize, initialMonthIndex, minMonthIndex, isRTL]);
+
+ const scrollToMonth = useCallback(
+ (monthIndex: number, behavior: ScrollBehavior = 'smooth') => {
+ const scroller = scrollerRef.current;
+ if (scroller == null || paneSize === 0) {
+ return;
+ }
+ const row = Math.min(
+ rowCount - 1,
+ Math.max(0, monthIndex - minMonthIndex),
+ );
+ if (Math.abs(row - centerRowRef.current) > OVERSCAN) {
+ // Beyond the mounted window there is no pane at the target offset, and
+ // `scroll-snap-type: mandatory` will not leave the scroller resting
+ // where no snap area is — it re-snaps to the nearest mounted pane, so
+ // a jump to another year lands one month away instead. Mount the
+ // target first and scroll once it exists (see the layout effect
+ // below); a jump that far is never worth animating either.
+ pendingScrollRef.current = row;
+ centerRowRef.current = row;
+ setCenterRow(row);
+ return;
+ }
+ steeredRowRef.current = row;
+ scroller.scrollTo({
+ left: scrollOffsetForRow(row, paneSize, isRTL),
+ behavior,
+ });
+ },
+ [paneSize, minMonthIndex, rowCount, isRTL],
+ );
+
+ // Deliberately un-keyed: it runs after every render, costs a null check, and
+ // must fire on whichever render finally mounts the pending row's pane.
+ useLayoutEffect(() => {
+ const row = pendingScrollRef.current;
+ const scroller = scrollerRef.current;
+ if (row == null || scroller == null || paneSize === 0) {
+ return;
+ }
+ pendingScrollRef.current = null;
+ scroller.scrollTo({
+ left: scrollOffsetForRow(row, paneSize, isRTL),
+ behavior: 'auto',
+ });
+ });
+
+ useImperativeHandle(handleRef, () => ({scrollToMonth}), [scrollToMonth]);
+
+ // Claim horizontal gestures, leave vertical ones to the sheet.
+ //
+ // `touch-action: pan-x` alone is NOT enough: it governs what the browser
+ // pans natively, and the sheet's listener is JavaScript whose
+ // preventDefault() cancels the scroll regardless. Measured — a swipe 9° off
+ // horizontal had every touchmove cancelled by the sheet and the month never
+ // changed. The axis lock is biased toward horizontal, because a thumb arcs
+ // as it swipes; `onSwipe` then pages the diagonals the browser itself
+ // declines to pan, so no angle is left doing nothing. See
+ // useOwnScrollGesture.
+ useOwnScrollGesture(scrollerRef, 'inline', {
+ onSwipe: direction => {
+ const scroller = scrollerRef.current;
+ if (scroller == null || paneSize === 0) {
+ return;
+ }
+ scroller.scrollBy({left: direction * paneSize, behavior: 'smooth'});
+ },
+ });
+
+ // rAF-throttled: a touch scroll fires far more scroll events than frames,
+ // and all this does is move a label and widen a window.
+ const frameRef = useRef<number | undefined>(undefined);
+ useEffect(() => {
+ const scroller = scrollerRef.current;
+ // Not before the height is known. A listener attached while it was zero
+ // would close over that zero and report row 0 for any scroll — and the
+ // scroll event fired by the initial positioning arrives just late enough
+ // to be handled by that stale listener. Every pane then unmounts except
+ // rows 0-2, and `scroll-snap-type: mandatory` yanks the scroller to the
+ // nearest surviving snap area, a century away from where it just landed.
+ if (scroller == null || paneSize === 0) {
+ return;
+ }
+ // A finger on the scroller ends any steering: from here the months it
+ // passes are the user's doing and every one of them is worth reporting.
+ const onTouchStart = () => {
+ steeredRowRef.current = null;
+ };
+
+ const onScroll = () => {
+ if (frameRef.current != null) {
+ return;
+ }
+ frameRef.current = requestAnimationFrame(() => {
+ frameRef.current = undefined;
+ const row = rowAtScrollOffset(
+ scroller.scrollLeft,
+ paneSize,
+ rowCount,
+ isRTL,
+ );
+ if (row === centerRowRef.current) {
+ return;
+ }
+ centerRowRef.current = row;
+ setCenterRow(row);
+ // Report nothing while a steer is in flight. `scrollToMonth` is only
+ // ever called by something that already knows the month — a wheel
+ // commit, a header arrow, the re-assert when the wheels close — so
+ // none of the scrolling it causes is news, including whatever the
+ // scroller passes through on the way.
+ //
+ // Reporting it is a feedback cycle, and worse on iOS. A wheel commit
+ // steers this scroller while it is hidden behind the wheels, and a
+ // hidden scroller does not reliably stay where it was put: iOS
+ // re-snaps it when the panel becomes visible again, firing scrolls at
+ // the exact moment reports start being trusted again. The month drifted
+ // on the way back to the calendar.
+ //
+ // Cleared on arrival, or by a touch below — once a finger is on the
+ // scroller the user owns it, and every month it passes is worth
+ // reporting.
+ if (steeredRowRef.current != null) {
+ if (steeredRowRef.current === row) {
+ steeredRowRef.current = null;
+ }
+ return;
+ }
+ onVisibleMonthChangeRef.current(minMonthIndex + row);
+ });
+ };
+ scroller.addEventListener('scroll', onScroll, {passive: true});
+ scroller.addEventListener('touchstart', onTouchStart, {passive: true});
+ return () => {
+ scroller.removeEventListener('scroll', onScroll);
+ scroller.removeEventListener('touchstart', onTouchStart);
+ if (frameRef.current != null) {
+ cancelAnimationFrame(frameRef.current);
+ frameRef.current = undefined;
+ }
+ };
+ }, [paneSize, rowCount, minMonthIndex, isRTL]);
+
+ // Move the keyboard focus by whole days and let the scroller follow. Paging
+ // by month is PageUp/PageDown; everything else is the APG grid vocabulary.
+ const moveFocus = useCallback(
+ (from: PlainDate, deltaDays: number) => {
+ const next = plainDateAddDays(from, deltaDays);
+ const nextIndex = monthIndexOf(next);
+ if (nextIndex < minMonthIndex || nextIndex > maxMonthIndex) {
+ return;
+ }
+ shouldRestoreFocusRef.current = true;
+ setFocusedDate(next);
+ if (nextIndex !== monthIndexOf(from)) {
+ scrollToMonth(nextIndex, 'smooth');
+ }
+ },
+ [minMonthIndex, maxMonthIndex, scrollToMonth],
+ );
+
+ const handleKeyDown = useCallback(
+ (event: React.KeyboardEvent, date: PlainDate) => {
+ // Column within the displayed week, which is what Home/End move to —
+ // not the day of the month.
+ const column = (plainDateDayOfWeek(date) - weekStartsOn + 7) % 7;
+ switch (event.key) {
+ case 'ArrowLeft':
+ event.preventDefault();
+ moveFocus(date, -1);
+ break;
+ case 'ArrowRight':
+ event.preventDefault();
+ moveFocus(date, 1);
+ break;
+ case 'ArrowUp':
+ event.preventDefault();
+ moveFocus(date, -7);
+ break;
+ case 'ArrowDown':
+ event.preventDefault();
+ moveFocus(date, 7);
+ break;
+ case 'Home':
+ event.preventDefault();
+ moveFocus(date, -column);
+ break;
+ case 'End':
+ event.preventDefault();
+ moveFocus(date, 6 - column);
+ break;
+ default:
+ break;
+ }
+ },
+ [moveFocus, weekStartsOn],
+ );
+
+ // The focused day may have been in an unmounted pane a frame ago; focus it
+ // once it exists, and only in response to a key press so a scroll never
+ // steals focus.
+ const focusedISO = focusedDate == null ? null : plainDateToISO(focusedDate);
+ useEffect(() => {
+ if (!shouldRestoreFocusRef.current || focusedISO == null) {
+ return;
+ }
+ const target = scrollerRef.current?.querySelector<HTMLElement>(
+ `[data-date="${focusedISO}"]`,
+ );
+ if (target != null) {
+ shouldRestoreFocusRef.current = false;
+ // preventScroll: the scroller is already snapping to this month; a
+ // browser scroll-into-view here would fight the snap and land between
+ // two panes.
+ target.focus({preventScroll: true});
+ }
+ }, [focusedISO]);
+
+ const visibleRows = paneWindow(centerRow, rowCount, OVERSCAN);
+
+ // A focus event fires for the programmatic focus above too; only take the
+ // date when it is actually a different day.
+ const handleDayFocus = useCallback((date: PlainDate) => {
+ setFocusedDate(previous =>
+ previous != null && plainDateIsEqual(previous, date) ? previous : date,
+ );
+ }, []);
+
+ return (
+ <div
+ ref={scrollerRef}
+ data-scroller="months"
+ {...stylex.props(styles.scroller)}>
+ <div
+ {...stylex.props(styles.spacer, dynamic.spacer(rowCount * paneSize))}>
+ {paneSize > 0 &&
+ rowsIn(visibleRows).map(row => (
+ <MonthPane
+ key={row}
+ monthIndex={minMonthIndex + row}
+ insetInlineStart={row * paneSize}
+ inlineSize={paneSize}
+ selectedDate={selectedDate}
+ focusedDate={focusedDate}
+ today={today}
+ isDateDisabled={isDateDisabled}
+ weekStartsOn={weekStartsOn}
+ onSelect={onSelect}
+ onDayKeyDown={handleKeyDown}
+ onDayFocus={handleDayFocus}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+MonthScroller.displayName = 'MonthScroller';
+
+interface MonthPaneProps {
+ monthIndex: number;
+ insetInlineStart: number;
+ inlineSize: number;
+ selectedDate: PlainDate | null;
+ focusedDate: PlainDate | null;
+ today: PlainDate;
+ isDateDisabled: (date: PlainDate) => boolean;
+ weekStartsOn: DayOfWeek;
+ onSelect: (value: ISODateString) => void;
+ onDayKeyDown: (event: React.KeyboardEvent, date: PlainDate) => void;
+ onDayFocus: (date: PlainDate) => void;
+}
+
+/**
+ * One month, as a six-row grid.
+ *
+ * There is no `role="columnheader"` row in here: the weekday names are a
+ * single sticky row outside the scroller (they would otherwise scroll away),
+ * so each day instead carries its weekday in its accessible name.
+ */
+function MonthPane({
+ monthIndex,
+ insetInlineStart,
+ inlineSize,
+ selectedDate,
+ focusedDate,
+ today,
+ isDateDisabled,
+ weekStartsOn,
+ onSelect,
+ onDayKeyDown,
+ onDayFocus,
+}: MonthPaneProps) {
+ const {year, month} = fromMonthIndex(monthIndex);
+ const {weeks} = useCalendarDays({
+ year,
+ month,
+ weekStartsOn,
+ // Always six rows: a variable grid would make pane heights differ, and
+ // with them every snap offset below this month.
+ hasVariableRowCount: false,
+ });
+
+ const monthLabel = plainDateFormat(
+ {year, month, day: 1},
+ DATE_FORMAT_MONTH_YEAR,
+ );
+
+ // Exactly one day per pane is tab-reachable, so Tab moves through the
+ // picker rather than through 42 buttons: the focused day if the keyboard
+ // owns one, else the selection, else the first of the month.
+ const tabbableISO = (() => {
+ if (
+ focusedDate != null &&
+ focusedDate.year === year &&
+ focusedDate.month === month
+ ) {
+ return plainDateToISO(focusedDate);
+ }
+ if (
+ selectedDate != null &&
+ selectedDate.year === year &&
+ selectedDate.month === month
+ ) {
+ return plainDateToISO(selectedDate);
+ }
+ return plainDateToISO({year, month, day: 1});
+ })();
+
+ return (
+ <div
+ role="grid"
+ aria-label={monthLabel}
+ data-month={monthLabel}
+ {...stylex.props(
+ styles.pane,
+ dynamic.pane(insetInlineStart, inlineSize),
+ )}>
+ {weeks.map(week => (
+ <div key={week[0].iso} role="row" {...stylex.props(styles.row)}>
+ {week.map(day => {
+ // A spilled day is context, not a choice. Calendar computes the
+ // same thing as `effectivelyDisabled: isDisabled || isOutside`,
+ // and guards today/selected on `!isOutside` beside it, so a date
+ // borrowed from a neighbouring month never carries a ring or a
+ // puck in the pane that is only showing it.
+ const isDisabled = day.isOutside || isDateDisabled(day.date);
+ const isSelected =
+ !day.isOutside &&
+ selectedDate != null &&
+ plainDateIsEqual(day.date, selectedDate);
+ const isToday = !day.isOutside && plainDateIsEqual(day.date, today);
+
+ return (
+ <div
+ key={day.iso}
+ role="gridcell"
+ aria-selected={isSelected || undefined}
+ {...stylex.props(styles.cell)}>
+ <button
+ type="button"
+ data-date={day.iso}
+ tabIndex={day.iso === tabbableISO ? 0 : -1}
+ aria-label={plainDateFormat(
+ day.date,
+ DATE_FORMAT_WITH_WEEKDAY,
+ )}
+ aria-disabled={isDisabled || undefined}
+ aria-current={isToday ? 'date' : undefined}
+ onClick={() => {
+ if (!isDisabled) {
+ onSelect(day.iso);
+ }
+ }}
+ onFocus={() => onDayFocus(day.date)}
+ onKeyDown={event => onDayKeyDown(event, day.date)}
+ {...stylex.props(
+ styles.day,
+ focusOutlineStyles.focusVisible,
+ // Outside FIRST, so disabled wins where both apply: a
+ // spilled day past the range is unselectable, and must
+ // not be painted more available than the in-month days
+ // beside it.
+ day.isOutside && styles.dayOutside,
+ isDisabled && styles.dayDisabled,
+ )}>
+ <span
+ {...stylex.props(
+ styles.puck,
+ !isDisabled && styles.puckHoverable,
+ isToday && styles.puckToday,
+ isSelected && styles.puckSelected,
+ )}>
+ {day.dayNumber}
+ </span>
+ </button>
+ </div>
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ );
+}
+
+MonthPane.displayName = 'MonthPane';
diff --git a/packages/core/src/DateInput/MonthYearWheels.tsx b/packages/core/src/DateInput/MonthYearWheels.tsx
new file mode 100644
index 0000000000..6ff9e2532a
--- /dev/null
+++ b/packages/core/src/DateInput/MonthYearWheels.tsx
@@ -0,0 +1,147 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file MonthYearWheels.tsx
+ * @input A month index, the reachable month bounds, a change callback
+ * @output Exports MonthYearWheels — the month + year wheel pair
+ * @position Internal component; consumed by TouchDateField.tsx
+ *
+ * The shortcut out of continuous scrolling. Scrolling is the right gesture for
+ * "a month or two either way" and the wrong one for "December 2019", so the
+ * header title opens this instead: two wheels, one flick each.
+ *
+ * It occupies exactly the same box as the month scroller, so opening it never
+ * changes the picker's height.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/DateInput/TouchDateField.tsx
+ * - /packages/core/src/DateInput/DateInput.doc.mjs
+ * - /packages/core/src/DateInput/DateInputTouch.test.tsx
+ */
+
+import {useMemo} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {DATE_FORMAT_MONTH_ONLY, plainDateFormat} from '../utils';
+import {spacingVars} from '../theme/tokens.stylex';
+import {dateInputTouchGeometry} from './tokens.stylex';
+import {Wheel, type WheelOption} from './Wheel';
+import {fromMonthIndex, toMonthIndex} from './monthGeometry';
+
+const styles = stylex.create({
+ wheels: {
+ display: 'flex',
+ blockSize: dateInputTouchGeometry.paneBlockSize,
+ gap: spacingVars['--spacing-2'],
+ },
+});
+
+export interface MonthYearWheelsProps {
+ /** The month the wheels currently show. */
+ monthIndex: number;
+ /** First reachable month. */
+ minMonthIndex: number;
+ /** Last reachable month. */
+ maxMonthIndex: number;
+ /** Fired when either wheel comes to rest on a new month. */
+ onChange: (monthIndex: number) => void;
+ /** Accessible name for the month wheel. */
+ monthLabel: string;
+ /** Accessible name for the year wheel. */
+ yearLabel: string;
+ /** False while the panel is hidden. */
+ isActive?: boolean;
+}
+
+/**
+ * Month and year wheels, bounded by the same range as the scroller.
+ */
+export function MonthYearWheels({
+ monthIndex,
+ minMonthIndex,
+ maxMonthIndex,
+ onChange,
+ monthLabel,
+ yearLabel,
+ isActive = true,
+}: MonthYearWheelsProps) {
+ const {year, month} = fromMonthIndex(monthIndex);
+
+ // Day 15 of a fixed year: no timezone can push it into an adjacent month
+ // the way day 1 or day 31 can.
+ //
+ // `plainDateFormat` rather than a raw `Intl.DateTimeFormat`, which the
+ // shared lint rule forbids and which would duplicate the format vocabulary
+ // besides. It resolves the locale itself, so there is nothing here for the
+ // memo to depend on — the same is true of Calendar's own month labels, and
+ // is why this list is constant for the life of the component.
+ const monthNames = useMemo(
+ () =>
+ Array.from({length: 12}, (_, index) =>
+ plainDateFormat(
+ {year: 2021, month: index + 1, day: 15},
+ DATE_FORMAT_MONTH_ONLY,
+ ),
+ ),
+ [],
+ );
+
+ // Months outside the range stay on the wheel rather than vanishing: a list
+ // whose length changes with the year would jump under the finger.
+ const monthOptions: WheelOption[] = useMemo(
+ () =>
+ monthNames.map((name, index) => {
+ const candidate = toMonthIndex(year, index + 1);
+ return {
+ value: index + 1,
+ label: name,
+ isDisabled: candidate < minMonthIndex || candidate > maxMonthIndex,
+ };
+ }),
+ [monthNames, year, minMonthIndex, maxMonthIndex],
+ );
+
+ const yearOptions: WheelOption[] = useMemo(() => {
+ const first = fromMonthIndex(minMonthIndex).year;
+ const last = fromMonthIndex(maxMonthIndex).year;
+ const options: WheelOption[] = [];
+ for (let candidate = first; candidate <= last; candidate++) {
+ options.push({
+ value: candidate,
+ label: String(candidate),
+ // A year is reachable when any of its months is.
+ isDisabled:
+ toMonthIndex(candidate, 12) < minMonthIndex ||
+ toMonthIndex(candidate, 1) > maxMonthIndex,
+ });
+ }
+ return options;
+ }, [minMonthIndex, maxMonthIndex]);
+
+ return (
+ <div {...stylex.props(styles.wheels)}>
+ <Wheel
+ label={monthLabel}
+ options={monthOptions}
+ value={month}
+ isActive={isActive}
+ onChange={nextMonth => onChange(toMonthIndex(year, nextMonth))}
+ />
+ <Wheel
+ label={yearLabel}
+ options={yearOptions}
+ value={year}
+ isActive={isActive}
+ onChange={nextYear => {
+ // Jan 31 -> Feb has no equivalent here (months carry no day), but a
+ // year change can still land outside the range; clamp to it.
+ const candidate = toMonthIndex(nextYear, month);
+ onChange(Math.min(Math.max(candidate, minMonthIndex), maxMonthIndex));
+ }}
+ />
+ </div>
+ );
+}
+
+MonthYearWheels.displayName = 'MonthYearWheels';
diff --git a/packages/core/src/DateInput/TouchDateField.tsx b/packages/core/src/DateInput/TouchDateField.tsx
new file mode 100644
index 0000000000..ae27ae58b9
--- /dev/null
+++ b/packages/core/src/DateInput/TouchDateField.tsx
@@ -0,0 +1,1214 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file TouchDateField.tsx
+ * @input Uses React, Field, BottomSheet, Button, Icon, Calendar hooks, MonthScroller, MonthYearWheels
+ * @output Exports TouchDateField — the touch surface behind DateInput
+ * @position Internal component; consumed by DateInput.tsx
+ *
+ * The touch half of `DateInput`, holding `DateInput`'s whole prop
+ * contract so the two are interchangeable. Everything field-shaped —
+ * `Field` wrapper, status treatment, optimistic `changeAction`, the
+ * disabled-reason tooltip, `InputGroup` membership — behaves exactly as it
+ * does on the desktop control; only the picker differs.
+ *
+ * ## The closed field is deliberately the same control
+ *
+ * It is a real `<input>`, not a button: same element, same `role="combobox"`,
+ * same border, same clear button, so `ref` (typed `Ref<HTMLInputElement>` by
+ * `DateInputProps`) is honestly a reference to an input, the label's `for`
+ * names it natively, and the switch between surfaces moves nothing on screen.
+ *
+ * It just cannot be typed into: `readOnly` blocks entry, and `inputMode="none"`
+ * stops the virtual keyboard from opening over the sheet. Text entry is the
+ * one part of the desktop control that has no place here — the keyboard it
+ * summons would cover the picker it is meant to fill in.
+ *
+ * ## Three ideas in the picker
+ *
+ * 1. One month per screen. Every pane is exactly the height of the scrollport
+ * and snaps to its start, so the picker is a fixed height and there is no
+ * resting position showing half of two months. See MonthScroller.
+ * 2. Swiping is the month control, and the arrows are the backup. A flick
+ * reaches a neighbouring month in the direction you already think of it;
+ * the pair of arrows in the header's trailing corner is there for a
+ * deliberate single step, and for anyone not swiping at all.
+ * 3. The title is the escape hatch. Tap it and the same box becomes a month
+ * wheel and a year wheel — a flick each to reach 2019 instead of forty.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/DateInput/DateInput.tsx
+ * - /packages/core/src/DateInput/DateInput.doc.mjs
+ * - /packages/core/src/DateInput/DateInputTouch.test.tsx
+ */
+
+import {
+ useCallback,
+ useEffect,
+ useId,
+ useMemo,
+ useOptimistic,
+ useRef,
+ useState,
+ useTransition,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {BottomSheet} from '../BottomSheet';
+import {Button} from '../Button';
+import {useCalendarConstraints} from '../Calendar';
+import type {DateInputProps} from './DateInput';
+import {
+ Field,
+ InputClearButton,
+ inputWrapperStyles,
+ inputStatusBorderStyles,
+ inputStatusHoverShadowStyles,
+ inputStatusFocusWithinStyles,
+} from '../Field';
+import {useInputStatusIcon} from '../hooks';
+import {useResolvedRequired} from '../hooks/useResolvedRequired';
+import {Icon} from '../Icon';
+import {IconButton} from '../IconButton';
+import {useTranslator} from '../i18n';
+import {useInputGroup} from '../InputGroup';
+import {groupStyles} from '../InputGroup/groupStyles';
+import {stableClassName} from '../naming';
+import {useSize} from '../SizeContext';
+import {Spinner} from '../Spinner';
+import {
+ colorVars,
+ spacingVars,
+ radiusVars,
+ sizeVars,
+ borderVars,
+ fontWeightVars,
+ typeScaleVars,
+ typographyVars,
+ durationVars,
+ easeVars,
+} from '../theme/tokens.stylex';
+import {useTooltip} from '../Tooltip';
+import {VisuallyHidden} from '../VisuallyHidden';
+import {
+ focusOutlineStyles,
+ getInputARIA,
+ isImeKeyEvent,
+ mergeProps,
+ mergeRefs,
+ rtlStyles,
+ themeProps,
+ formatSharedDate,
+ plainDateFromISO,
+ plainDateToday,
+ plainDateFormat,
+ DATE_FORMAT_MONTH_YEAR,
+ DATE_FORMAT_WEEKDAY_ONLY,
+ type ISODateString,
+} from '../utils';
+import {normalizeDayOfWeek} from '../utils/dateTypes';
+import {MonthScroller, type MonthScrollerHandle} from './MonthScroller';
+import {MonthYearWheels} from './MonthYearWheels';
+import {
+ DEFAULT_MONTH_REACH,
+ clampIndex,
+ fromMonthIndex,
+ monthIndexOf,
+} from './monthGeometry';
+import {dateInputTouchSizes, dateInputTouchGeometry} from './tokens.stylex';
+
+/**
+ * The comfortable minimum tap target on both iOS and Android. Applied as a
+ * FLOOR under the size prop rather than replacing it: `size` still means what
+ * it means, it just cannot produce a control a thumb misses.
+ */
+const TOUCH_TARGET = dateInputTouchSizes.daySize;
+
+/**
+ * The whole surface swap, in one leg.
+ *
+ * It used to be two: the outgoing surface faded out, then the incoming one
+ * faded in, 110ms each. The sequencing existed for one reason — the wheels'
+ * panel was transparent, so overlapping the two put the wheels' translucent
+ * selection band over the calendar grid and tinted a band-shaped strip of it,
+ * which read as "the grey area animates differently from the content".
+ *
+ * Giving the wheels an opaque background removes the reason. Nothing shows
+ * through them, so they can simply fade in ON TOP of a calendar that does not
+ * move at all — no empty middle, no outgoing animation, and one duration
+ * instead of a wait plus a fade.
+ *
+ * `--duration-fast` rather than a literal now that this is a whole duration
+ * and not half of one.
+ */
+const SWAP_DURATION = durationVars['--duration-fast'];
+
+const sizeStyles = stylex.create({
+ sm: {
+ height: sizeVars['--size-element-sm'],
+ minWidth: 180,
+ minBlockSize: {default: null, '@media (pointer: coarse)': TOUCH_TARGET},
+ },
+ md: {
+ height: sizeVars['--size-element-md'],
+ minWidth: 180,
+ minBlockSize: {default: null, '@media (pointer: coarse)': TOUCH_TARGET},
+ },
+ lg: {
+ height: sizeVars['--size-element-lg'],
+ minWidth: 180,
+ minBlockSize: {default: null, '@media (pointer: coarse)': TOUCH_TARGET},
+ },
+});
+
+const styles = stylex.create({
+ // ---- the closed field ----
+ wrapper: {
+ gap: spacingVars['--spacing-2'],
+ },
+ iconButton: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: 0,
+ margin: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ cursor: 'pointer',
+ borderRadius: radiusVars['--radius-element'],
+ },
+ iconButtonDisabled: {
+ cursor: 'not-allowed',
+ },
+ input: {
+ display: 'block',
+ flex: 1,
+ minWidth: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ padding: 0,
+ fontFamily: typographyVars['--font-family-body'],
+ // Below 16px iOS zooms the page on focus. The field is focusable even
+ // though it is not typable, so it needs the same floor DateInput has.
+ fontSize: {
+ default: typeScaleVars['--text-body-size'],
+ '@media (pointer: coarse)': `max(1rem, ${typeScaleVars['--text-body-size']})`,
+ },
+ lineHeight: typeScaleVars['--text-body-leading'],
+ color: colorVars['--color-text-primary'],
+ backgroundColor: 'transparent',
+ outline: 'none',
+ // It opens a picker; it does not take text. The caret would say otherwise.
+ caretColor: 'transparent',
+ cursor: 'pointer',
+ userSelect: 'none',
+ '::placeholder': {
+ color: colorVars['--color-text-secondary'],
+ },
+ },
+ inputDisabled: {
+ cursor: 'not-allowed',
+ },
+
+ // ---- the picker surface ----
+ surface: {
+ display: 'flex',
+ flexDirection: 'column',
+ inlineSize: '100%',
+ },
+ header: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: spacingVars['--spacing-2'],
+ blockSize: sizeVars['--size-element-lg'],
+ // No inline padding of its own: the content box owns the inset, and any
+ // extra here would push the arrows off the line the day grid sits on.
+ },
+ /**
+ * Both arrows together, at the trailing corner. `IconButton` draws each
+ * one — a hand-rolled button had the glyph off-centre, and matching
+ * Button's optical centring by hand is exactly the sort of thing a shared
+ * component is for.
+ */
+ monthArrows: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-0-5'],
+ // The pair is the trailing item; the title takes the space before it.
+ marginInlineStart: 'auto',
+ // The plate starts below the header, so these two are the one part of the
+ // calendar the layer above cannot cover. They fade on its timing instead,
+ // both directions, so the change reads as one motion rather than chrome
+ // blinking out a beat before the grid is covered.
+ transitionProperty: 'opacity, visibility',
+ transitionDuration: SWAP_DURATION,
+ transitionTimingFunction: 'linear',
+ '@media (prefers-reduced-motion: reduce)': {
+ transitionDuration: '0.01s',
+ },
+ },
+ /**
+ * Hidden while the wheels are up: they step the calendar, and the calendar
+ * is not on screen. Hidden rather than unmounted because they are the
+ * tallest thing in the header — dropping them would shorten it by 8px and
+ * shift the whole sheet just as the panels cross-fade.
+ *
+ * `visibility: hidden` also takes them out of the tab order and the
+ * accessibility tree, so there is nothing to reach that cannot be seen.
+ */
+ /**
+ * An arrow with nowhere to go. Hidden, not unmounted, and not merely
+ * disabled — it keeps its 44px so the remaining arrow does not slide
+ * sideways as the range's edge is reached, and `visibility: hidden` takes
+ * it out of the tab order and the accessibility tree so nothing invisible
+ * is reachable.
+ */
+ monthArrowUnavailable: {
+ visibility: 'hidden',
+ },
+ monthArrowsHidden: {
+ visibility: 'hidden',
+ opacity: 0,
+ pointerEvents: 'none',
+ },
+ /**
+ * `Button`'s own sizes top out at 36px, which is fine for a mouse and short
+ * of the 44px every other target in this sheet honours. Floor it on a
+ * coarse pointer, the same way the field and the day cells do.
+ */
+ monthArrow: {
+ minBlockSize: {default: null, '@media (pointer: coarse)': TOUCH_TARGET},
+ minInlineSize: {default: null, '@media (pointer: coarse)': TOUCH_TARGET},
+ },
+ /**
+ * The wrapper the RTL mirror rides on has to be a flex box. A bare inline
+ * span puts the glyph on the text baseline, which lifts it a few px off the
+ * button's optical centre — the whole reason these are `IconButton`s now.
+ * Core's Calendar carries the identical `navIcon` rule.
+ */
+ monthArrowIcon: {
+ display: 'inline-flex',
+ },
+ /**
+ * The month and year, and the toggle into the wheels. Leading, so it reads
+ * first and sits on the same line as the day grid below it.
+ */
+ title: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-1'],
+ blockSize: '100%',
+ paddingInline: spacingVars['--spacing-2'],
+ // Pulls the text back onto the grid's line: the button's own padding
+ // would otherwise inset the label past it.
+ marginInlineStart: `calc(-1 * ${spacingVars['--spacing-2']})`,
+ borderWidth: 0,
+ borderStyle: 'none',
+ borderRadius: radiusVars['--radius-element'],
+ backgroundColor: {
+ default: 'transparent',
+ '@media (hover: hover)': {
+ default: 'transparent',
+ ':hover:where(:not(:disabled,[aria-disabled="true"]))':
+ colorVars['--color-overlay-hover'],
+ },
+ ':active': colorVars['--color-overlay-pressed'],
+ },
+ color: colorVars['--color-text-primary'],
+ fontSize: typeScaleVars['--text-large-size'],
+ fontWeight: fontWeightVars['--font-weight-semibold'],
+ cursor: 'pointer',
+ whiteSpace: 'nowrap',
+ },
+ titleChevron: {
+ display: 'inline-flex',
+ // The one part of the swap that keeps `--ease-standard`, because it is
+ // the one part that travels: a rotation has a distance to cover, and
+ // fast-out-slow-in is what that curve is for. Same duration as the
+ // surface it announces, so the two land together.
+ transitionProperty: 'transform',
+ transitionDuration: SWAP_DURATION,
+ transitionTimingFunction: easeVars['--ease-standard'],
+ '@media (prefers-reduced-motion: reduce)': {
+ transitionDuration: '0.01s',
+ },
+ },
+ titleChevronOpen: {
+ transform: 'rotate(180deg)',
+ },
+ weekdays: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(7, 1fr)',
+ blockSize: sizeVars['--size-element-sm'],
+ alignItems: 'center',
+ // Same as the arrows: above the plate's reach, so it fades on the layer's
+ // timing rather than clearing on its own.
+ transitionProperty: 'opacity, visibility',
+ transitionDuration: SWAP_DURATION,
+ transitionTimingFunction: 'linear',
+ '@media (prefers-reduced-motion: reduce)': {
+ transitionDuration: '0.01s',
+ },
+ },
+ weekdaysHidden: {
+ // Hidden, not unmounted: the row still owes the surface its height, or
+ // opening the wheels would make the picker shorter.
+ visibility: 'hidden',
+ opacity: 0,
+ },
+ weekday: {
+ textAlign: 'center',
+ fontSize: typeScaleVars['--text-supporting-size'],
+ fontWeight: fontWeightVars['--font-weight-normal'],
+ color: colorVars['--color-text-secondary'],
+ },
+ body: {
+ display: 'grid',
+ blockSize: dateInputTouchGeometry.paneBlockSize,
+ position: 'relative',
+ },
+ /**
+ * The two panels share one grid cell, and the wheels are the one on top.
+ */
+ panel: {
+ gridArea: '1 / 1',
+ minWidth: 0,
+ },
+ /**
+ * The layer underneath — the calendar, and the calendar's footer actions.
+ *
+ * It has no opacity and never fades. `visibility` is the only thing that
+ * moves, and giving it the layer's own duration is what times it: CSS
+ * interpolates `visibility` discretely, holding `visible` for the whole
+ * transition whenever either end is `visible` and taking the final value
+ * only at the finish. So it disappears exactly when the cover completes,
+ * and on the way back it is there from the first frame, revealed as the
+ * layer above fades off it. Nothing about it is ever seen changing.
+ *
+ * It is not merely decorative to hide it: `inert` keeps it off the tab
+ * order, but a layer that is only COVERED is still `visible` to a screen
+ * reader, so the two footer actions would both be announced.
+ *
+ * `visibility` (not `display`) also keeps the month scroller laid out while
+ * the wheels are up, so its scroll offset survives the round trip and the
+ * wheels can steer it before it is shown again.
+ */
+ panelBeneath: {
+ transitionProperty: 'visibility',
+ transitionDuration: SWAP_DURATION,
+ '@media (prefers-reduced-motion: reduce)': {
+ transitionDuration: '0.01s',
+ },
+ },
+ panelBeneathHidden: {
+ visibility: 'hidden',
+ pointerEvents: 'none',
+ },
+ /**
+ * The month and year, as one layer that fades in and out on top.
+ *
+ * The calendar underneath does not fade with it — this layer is opaque, so
+ * covering it is enough, and animating it too would be animating the date
+ * picker rather than the thing arriving over it.
+ *
+ * Three properties carry the whole design:
+ *
+ * `backgroundColor` is what makes the fade uniform. Without it the wheels
+ * are a translucent selection band and some text, each compositing against
+ * a live calendar grid on its own terms — so the band area faded unlike the
+ * rest and read as "the grey area animates differently from the content".
+ * With the plate inside the fading group, the group renders opaque first
+ * and the fade applies to the finished image, so every pixel of it crosses
+ * at the same rate.
+ *
+ * `isolation` is what makes the plate actually cover. Backgrounds and text
+ * paint in separate phases, so without a stacking context a later sibling's
+ * background lands UNDER an earlier sibling's text — the plate went in
+ * opaque and the calendar's day numbers showed straight through it. Easy to
+ * lose, because any opacity below 1 makes a stacking context anyway: the
+ * cover only breaks at the two ends of the fade, where opacity is exactly
+ * 1, which is to say whenever anyone is actually looking.
+ *
+ * `visibility` rides along with `opacity`, on the same rule as the layer
+ * beneath: it stays `visible` for the whole transition, so fading out is
+ * seen rather than cut on the first frame, and the layer still leaves the
+ * a11y tree and the hit testing at the end of it.
+ *
+ * Easing is `linear`, not `--ease-standard`. That token is
+ * `cubic-bezier(0.24, 1, 0.4, 1)`, which is right for something travelling
+ * a distance and wrong for a fade: measured, it put the opacity at 50% in
+ * 91ms and 95% in 241ms of a 410ms transition, so the fade was over long
+ * before the duration was, and lengthening the duration bought an
+ * imperceptible tail rather than a slower fade. A fade has no distance to
+ * cover, so its progress should be its progress.
+ */
+ panelOverlay: {
+ backgroundColor: colorVars['--color-background-surface'],
+ isolation: 'isolate',
+ transitionProperty: 'opacity, visibility',
+ transitionDuration: SWAP_DURATION,
+ transitionTimingFunction: 'linear',
+ '@media (prefers-reduced-motion: reduce)': {
+ transitionDuration: '0.01s',
+ },
+ },
+ panelOverlayHidden: {
+ visibility: 'hidden',
+ opacity: 0,
+ pointerEvents: 'none',
+ },
+ footer: {
+ paddingBlockStart: spacingVars['--spacing-2'],
+ // Same reason as the header: the content box owns the inline inset, so
+ // Done's edge lines up with the grid's rather than sitting 4px inside it.
+ // One grid cell, so the two actions stack and the row is as tall as one
+ // button whichever is showing.
+ display: 'grid',
+ gridTemplateColumns: '1fr',
+ },
+ /**
+ * One footer action. Both occupy the same cell, and the wheels' one is a
+ * layer over the calendar's pair exactly as the panels above are. The row
+ * never changes height either way.
+ */
+ footerAction: {
+ gridArea: '1 / 1',
+ // Side by side and equal: the calendar's cell holds Reset and Save, the
+ // wheels' holds one button. `1fr` each rather than content width, so
+ // neither label's length decides how the row is divided.
+ display: 'flex',
+ gap: spacingVars['--spacing-2'],
+ },
+ sheetBody: {
+ // One inset on every edge. The block-start is the exception and has to
+ // be: the sheet's grab handle floats out of flow, costing no layout
+ // height of its own, so the content wrapper owes it the 24px it occupies
+ // — which reads as the same inset, because the handle sits in it.
+ paddingInline: spacingVars['--spacing-4'],
+ paddingBlockStart: spacingVars['--spacing-6'],
+ paddingBlockEnd: spacingVars['--spacing-4'],
+ },
+ divider: {
+ blockSize: borderVars['--border-width'],
+ backgroundColor: colorVars['--color-border'],
+ marginBlockStart: spacingVars['--spacing-1'],
+ },
+});
+
+/**
+ * The touch surface. Takes `DateInput`'s props verbatim; see
+ * {@link DateInput} for when it is chosen over the desktop control.
+ */
+export function TouchDateField({
+ label,
+ isLabelHidden = false,
+ description,
+ isOptional = false,
+ isRequired = false,
+ isDisabled = false,
+ disabledMessage,
+ value,
+ onChange,
+ changeAction,
+ isLoading = false,
+ min,
+ max,
+ dateConstraints,
+ placeholder: placeholderFromProps,
+ size: sizeProp,
+ status,
+ statusVariant = 'attached',
+ labelTooltip,
+ hasClear = false,
+ // Desktop-only: the scroller is a single continuously paged column, so a
+ // second month would be the month already one flick away. Accepted (the
+ // prop types are shared) and ignored.
+ numberOfMonths: _numberOfMonths,
+ weekStartsOn: weekStartsOnProp = 0,
+ format = 'date_long',
+ width,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...rest
+}: DateInputProps) {
+ const t = useTranslator();
+ const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});
+ const placeholder =
+ placeholderFromProps ?? t('@astryx.dateInput.placeholder');
+ const size = useSize(sizeProp, 'md');
+ const weekStartsOn = normalizeDayOfWeek(weekStartsOnProp);
+
+ const id = useId();
+ const inputLabelID = useId();
+ const descriptionID = useId();
+ const statusMessageID = useId();
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const inputGroup = useInputGroup();
+
+ const [, startTransition] = useTransition();
+ const [optimisticValue, setOptimisticValue] = useOptimistic(value);
+ const isBusy = isLoading || optimisticValue !== value;
+ const isEffectivelyDisabled = isDisabled || isBusy;
+
+ // Disabled-reason tooltip, same contract as DateInput: a disabled control
+ // swallows pointer events, so the listeners attach to the wrapper and the
+ // input stays focusable via aria-disabled rather than the disabled
+ // attribute. Only the persistent disabled state surfaces a reason, never
+ // the transient busy one.
+ const showsDisabledMessage = isDisabled && !!disabledMessage;
+ const disabledMessageTooltip = useTooltip({
+ placement: 'above',
+ focusTrigger: 'always',
+ isEnabled: showsDisabledMessage,
+ });
+
+ const {isDateDisabled} = useCalendarConstraints({min, max, dateConstraints});
+
+ const {statusIcon, describedBy: statusTooltipDescribedBy} =
+ useInputStatusIcon({
+ status,
+ statusVariant,
+ isInGroup: !!inputGroup,
+ });
+
+ const {ariaLabelledBy, ariaDescribedBy} = getInputARIA(
+ inputLabelID,
+ [
+ description ? descriptionID : null,
+ statusVariant !== 'tooltip' && status?.message ? statusMessageID : null,
+ statusTooltipDescribedBy,
+ showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
+ ],
+ inputGroup,
+ );
+
+ const [isSheetOpen, setIsSheetOpen] = useState(false);
+ const [isWheelOpen, setIsWheelOpen] = useState(false);
+ const scrollerHandleRef = useRef<MonthScrollerHandle | null>(null);
+
+ const today = useMemo(() => plainDateToday(), []);
+ const selectedDate = useMemo(
+ () =>
+ optimisticValue != null && /^\d{4}-\d{2}-\d{2}$/.test(optimisticValue)
+ ? plainDateFromISO(optimisticValue)
+ : null,
+ [optimisticValue],
+ );
+
+ // 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.
+ const [anchorMonthIndex] = useState(() =>
+ monthIndexOf(
+ value != null && /^\d{4}-\d{2}-\d{2}$/.test(value)
+ ? plainDateFromISO(value)
+ : plainDateToday(),
+ ),
+ );
+ const minMonthIndex =
+ min != null
+ ? monthIndexOf(plainDateFromISO(min))
+ : anchorMonthIndex - DEFAULT_MONTH_REACH;
+ const maxMonthIndex =
+ max != null
+ ? monthIndexOf(plainDateFromISO(max))
+ : anchorMonthIndex + DEFAULT_MONTH_REACH;
+
+ const [monthIndex, setMonthIndex] = useState(() =>
+ clampIndex(anchorMonthIndex, minMonthIndex, maxMonthIndex),
+ );
+
+ const {year, month} = fromMonthIndex(monthIndex);
+
+ /**
+ * Three-letter weekday names — "Sun", not Calendar's "Su".
+ *
+ * The sheet is full width and the columns are ~51px, so there is room for
+ * the form people actually read, and a picker operated by thumb should not
+ * make anyone decode "Tu" against "Th".
+ *
+ * This is CLDR's `abbreviated` width, which `Intl` produces natively — no
+ * truncation, so the 28 non-English locales stay correct rather than being
+ * sliced to three characters. (Verified against the CLDR tables for all 30
+ * locales in the catalog.) Calendar's 2-letter row is CLDR's *short* width,
+ * which `Intl` cannot express, which is exactly why that surface needs a
+ * generated table and this one does not.
+ *
+ * Built here rather than taken from `useCalendarDays`, which supplies the
+ * short form for Calendar's own header. The rotation matches: day 4 of
+ * January 1970 was a Sunday, so offsetting from it by `weekStartsOn` walks
+ * the week in the same order the panes lay out their columns.
+ */
+ const dayNames = useMemo(
+ () =>
+ Array.from({length: 7}, (_, offset) =>
+ plainDateFormat(
+ {year: 1970, month: 1, day: 4 + ((weekStartsOn + offset) % 7)},
+ DATE_FORMAT_WEEKDAY_ONLY,
+ ),
+ ),
+ [weekStartsOn],
+ );
+ const monthYearLabel = plainDateFormat(
+ {year, month, day: 1},
+ DATE_FORMAT_MONTH_YEAR,
+ );
+
+ // Formats the committed value only. A function format is called with the ISO
+ // value; a named one reuses Timestamp's shared date mapping, so the same
+ // literal renders the same shape here and on the desktop control.
+ const displayValue =
+ optimisticValue != null && /^\d{4}-\d{2}-\d{2}$/.test(optimisticValue)
+ ? typeof format === 'function'
+ ? format(optimisticValue)
+ : formatSharedDate(plainDateFromISO(optimisticValue), format)
+ : '';
+
+ const fireChange = useCallback(
+ (newValue: ISODateString | undefined) => {
+ if (isBusy) {
+ return;
+ }
+ onChange?.(newValue);
+ if (changeAction) {
+ startTransition(async () => {
+ setOptimisticValue(newValue);
+ await changeAction(newValue);
+ });
+ }
+ },
+ [isBusy, onChange, changeAction, startTransition, setOptimisticValue],
+ );
+
+ const openSheet = useCallback(() => {
+ if (!isEffectivelyDisabled) {
+ // Always onto the calendar, whatever was showing last time. The wheels
+ // are a detour taken to reach a far month, not a mode to be left in:
+ // reopening into them would answer a question the user has not asked
+ // yet, and hide the dates they came back for behind another tap.
+ setIsWheelOpen(false);
+ setIsSheetOpen(true);
+ }
+ }, [isEffectivelyDisabled]);
+
+ const handleClear = useCallback(() => {
+ fireChange(undefined);
+ inputRef.current?.focus();
+ }, [fireChange]);
+
+ /**
+ * Put the picker back to how it opens: no date, current month.
+ *
+ * Two things, because clearing a date and then being left staring at the
+ * month of the date you just cleared is a half-finished action — the
+ * calendar should look the way it does before anything is chosen.
+ *
+ * "If possible" is load-bearing: a range can exclude the current month
+ * entirely (a booking window starting next quarter), and there is no
+ * honest place to go in that case. `clampIndex` would silently land on the
+ * nearest edge, which is a different month presented as if it were today's,
+ * so the move is skipped instead and the calendar stays where it is. The
+ * value is still cleared either way — that half never depends on the range.
+ */
+ const handleResetInSheet = useCallback(() => {
+ fireChange(undefined);
+ const currentMonth = monthIndexOf(today);
+ if (currentMonth < minMonthIndex || currentMonth > maxMonthIndex) {
+ return;
+ }
+ if (currentMonth === monthIndex) {
+ return;
+ }
+ setMonthIndex(currentMonth);
+ scrollerHandleRef.current?.scrollToMonth(currentMonth, 'smooth');
+ }, [fireChange, today, monthIndex, minMonthIndex, maxMonthIndex]);
+
+ // Selection commits on the tap and leaves the sheet up, so a mistake can be
+ // corrected in place and a nearby date reconsidered without reopening.
+ // Dismissal is the footer's Done (and the handle, the scrim, Escape) — none
+ // of which commit anything, because this already has.
+ const handleSelect = useCallback(
+ (next: ISODateString) => {
+ fireChange(next);
+ },
+ [fireChange],
+ );
+
+ // Whether there is anywhere to step. An arrow with nowhere to go is hidden
+ // rather than disabled: a disabled control still says "this is a thing you
+ // could do", and at the end of a range it is not — the range is the whole
+ // truth, and there is no state the user can reach where it becomes
+ // available. A greyed chevron sitting there permanently reads as broken.
+ const canStepBack = monthIndex > minMonthIndex;
+ const canStepForward = monthIndex < maxMonthIndex;
+
+ // One month either way, clamped to the reachable range. Goes through the
+ // same scrollToMonth the swipe settles on, so the arrows and the gesture
+ // cannot disagree about where a month rests.
+ const stepMonth = useCallback(
+ (delta: number) => {
+ const target = clampIndex(
+ monthIndex + delta,
+ minMonthIndex,
+ maxMonthIndex,
+ );
+ if (target === monthIndex) {
+ return;
+ }
+ setMonthIndex(target);
+ scrollerHandleRef.current?.scrollToMonth(target, 'smooth');
+ },
+ [monthIndex, minMonthIndex, maxMonthIndex],
+ );
+
+ // A wheel commit steers the scroller immediately, even though it is behind
+ // the wheels: it keeps its layout box while hidden, so by the time the
+ // wheels close it is already resting on the new month.
+ const handleWheelChange = useCallback((next: number) => {
+ setMonthIndex(next);
+ scrollerHandleRef.current?.scrollToMonth(next, 'auto');
+ }, []);
+
+ /**
+ * The calendar reports the month it has scrolled to — but only while it is
+ * the surface being scrolled.
+ *
+ * While the wheels are up the wheels are the source of truth, and the
+ * calendar is being STEERED by them: a wheel commit calls `scrollToMonth`
+ * above, the calendar scrolls, and it would report that month straight back
+ * here. That closes a cycle — wheel commits, calendar echoes, the echo moves
+ * the wheel's selected row, the wheel is repositioned onto it, and the
+ * resulting scroll reads as another commit.
+ *
+ * Whether that cycle converges depends on how precisely a browser reports
+ * "scrolling stopped", which is not something to rely on. With `scrollend`
+ * (Chrome) it settles at once; on iOS below Safari 26 there is no
+ * `scrollend` and momentum runs on for a second or more after the finger
+ * lifts, so each lap committed the next month along and the value climbed
+ * on its own. Ignoring the echo removes the cycle instead of damping it.
+ */
+ const handleVisibleMonthChange = useCallback(
+ (next: number) => {
+ if (isWheelOpen) {
+ return;
+ }
+ setMonthIndex(next);
+ },
+ [isWheelOpen],
+ );
+
+ /**
+ * Put the calendar back where it belongs when the wheels close.
+ *
+ * The wheels steer it while it is hidden, and a hidden scroller is not a
+ * reliable place to leave a scroll position: `visibility: hidden` keeps the
+ * layout box, but iOS re-snaps the scroller when it becomes visible again,
+ * and it does not necessarily re-snap to the pane we put it on. That fires
+ * a scroll at the exact moment reports start being trusted again — which is
+ * why the month drifted on the way back to the dates.
+ *
+ * Re-asserting is cheap when nothing moved (the scroller is already there,
+ * so nothing scrolls) and exactly right when something did. `scrollToMonth`
+ * marks the target as steered, so this correction does not report itself
+ * back either.
+ */
+ // Read through a ref so this effect depends on the surface change alone.
+ // Listing `monthIndex` would re-run it on every month the user swipes to,
+ // yanking the scroller back mid-gesture.
+ const monthIndexRef = useRef(monthIndex);
+ monthIndexRef.current = monthIndex;
+ useEffect(() => {
+ if (isWheelOpen) {
+ return;
+ }
+ scrollerHandleRef.current?.scrollToMonth(monthIndexRef.current, 'auto');
+ }, [isWheelOpen]);
+
+ // APG combobox keys. The field takes no text, so every printable key is
+ // free — but only the documented openers are wired, so a stray keystroke
+ // does not pop a sheet.
+ const handleInputKeyDown = useCallback(
+ (event: React.KeyboardEvent) => {
+ // Same guard core's pointer surface carries. This field is readOnly and
+ // takes no composition of its own, but an IME sitting over it still
+ // sends its committing Enter here first — and opening a date sheet on
+ // the keystroke that finishes a Korean syllable is the same wrong
+ // answer. See utils/ime.ts.
+ if (isImeKeyEvent(event.nativeEvent)) {
+ return;
+ }
+ if (
+ event.key === 'ArrowDown' ||
+ event.key === 'Enter' ||
+ event.key === ' ' ||
+ event.key === 'Spacebar'
+ ) {
+ event.preventDefault();
+ openSheet();
+ }
+ },
+ [openSheet],
+ );
+
+ const surface = (
+ <div {...stylex.props(styles.surface)}>
+ <div {...stylex.props(styles.header)}>
+ <button
+ type="button"
+ onClick={() => setIsWheelOpen(open => !open)}
+ aria-expanded={isWheelOpen}
+ // One string, not a template: the comma and the word order are
+ // the translator's to choose, not English's.
+ aria-label={t('@astryx.dateInput.chooseMonthYear', {
+ monthYear: monthYearLabel,
+ })}
+ // A `data-` hook rather than a theme target. `themeProps` would
+ // publish `astryx-date-input-touch-title` as a themeable selector,
+ // and this is internal structure of the sheet — the field and its
+ // toggle icon are the documented targets, and nothing has asked to
+ // restyle the header button. Adding a target later is additive;
+ // withdrawing one is not.
+ data-title="month-year"
+ {...stylex.props(styles.title, focusOutlineStyles.focusVisible)}>
+ <span>{monthYearLabel}</span>
+ <Icon
+ icon="chevronDown"
+ size="sm"
+ color="secondary"
+ // The transform rides on the Icon itself, not a wrapper span, so
+ // the element a theme can target is the element that moves.
+ xstyle={[
+ styles.titleChevron,
+ isWheelOpen && styles.titleChevronOpen,
+ ]}
+ />
+ </button>
+ {/* Both arrows at the trailing corner, as a pair — and only while the
+ calendar is the surface they step. `IconButton` gives them
+ Button's optical centring, focus ring, disabled treatment and hit
+ area; the hand-rolled version had the glyph off-centre.
+
+ Mirrored under RTL by the shared helper: "previous" is the earlier
+ month, which sits on the right when the inline axis runs that way,
+ and the panes mirror with it. */}
+ <span
+ data-arrows="months"
+ // `inert` as well as the hidden styling: the fade keeps them
+ // `visible` until it finishes, and a control that is on its way out
+ // should not answer a click or a Tab in the meantime.
+ inert={isWheelOpen ? true : undefined}
+ {...stylex.props(
+ styles.monthArrows,
+ isWheelOpen && styles.monthArrowsHidden,
+ )}>
+ <IconButton
+ variant="ghost"
+ size="sm"
+ xstyle={[
+ styles.monthArrow,
+ !canStepBack && styles.monthArrowUnavailable,
+ ]}
+ isDisabled={!canStepBack}
+ onClick={() => stepMonth(-1)}
+ label={t('@astryx.calendar.previousMonth')}
+ icon={
+ <span {...stylex.props(styles.monthArrowIcon, rtlStyles.mirror)}>
+ <Icon icon="chevronLeft" size="sm" color="inherit" />
+ </span>
+ }
+ />
+ <IconButton
+ variant="ghost"
+ size="sm"
+ xstyle={[
+ styles.monthArrow,
+ !canStepForward && styles.monthArrowUnavailable,
+ ]}
+ isDisabled={!canStepForward}
+ onClick={() => stepMonth(1)}
+ label={t('@astryx.calendar.nextMonth')}
+ icon={
+ <span {...stylex.props(styles.monthArrowIcon, rtlStyles.mirror)}>
+ <Icon icon="chevronRight" size="sm" color="inherit" />
+ </span>
+ }
+ />
+ </span>
+ </div>
+
+ {/* Decorative: each day carries its weekday in its accessible name, so
+ this row is not a header row for assistive technology — and it must
+ live outside the scroller, or it would scroll away with the month. */}
+ <div
+ aria-hidden="true"
+ {...stylex.props(
+ styles.weekdays,
+ isWheelOpen && styles.weekdaysHidden,
+ )}>
+ {dayNames.map(name => (
+ <div key={name} {...stylex.props(styles.weekday)}>
+ {name}
+ </div>
+ ))}
+ </div>
+
+ <div {...stylex.props(styles.body)}>
+ <div
+ data-panel="calendar"
+ // `inert` as well as the hidden styling: the panel keeps its layout
+ // box (so the scroller holds its position and the wheels can steer
+ // it), which means without this it would still be tabbable behind
+ // the layer on top.
+ inert={isWheelOpen ? true : undefined}
+ {...stylex.props(
+ styles.panel,
+ styles.panelBeneath,
+ isWheelOpen && styles.panelBeneathHidden,
+ )}>
+ <MonthScroller
+ key={`${minMonthIndex}:${maxMonthIndex}`}
+ handleRef={scrollerHandleRef}
+ minMonthIndex={minMonthIndex}
+ maxMonthIndex={maxMonthIndex}
+ initialMonthIndex={monthIndex}
+ onVisibleMonthChange={handleVisibleMonthChange}
+ selectedDate={selectedDate}
+ today={today}
+ isDateDisabled={isDateDisabled}
+ weekStartsOn={weekStartsOn}
+ onSelect={handleSelect}
+ />
+ </div>
+ <div
+ data-panel="wheels"
+ inert={isWheelOpen ? undefined : true}
+ {...stylex.props(
+ styles.panel,
+ styles.panelOverlay,
+ !isWheelOpen && styles.panelOverlayHidden,
+ )}>
+ <MonthYearWheels
+ monthIndex={monthIndex}
+ minMonthIndex={minMonthIndex}
+ maxMonthIndex={maxMonthIndex}
+ onChange={handleWheelChange}
+ monthLabel={t('@astryx.dateInput.monthWheel')}
+ yearLabel={t('@astryx.dateInput.yearWheel')}
+ isActive={isWheelOpen}
+ />
+ </div>
+ </div>
+
+ {/* Done does NOT commit: a tap on a day has already fired onChange by
+ the time it is reachable. It is a close button, exactly equivalent
+ to the grab handle, the scrim and Escape — which is why it is safe
+ for those to remain, and why there is no Cancel to pair it with.
+
+ It sits alone. A "Today" button was here and only moved the calendar
+ to the current month WITHOUT selecting it, which read as broken: the
+ one thing a button called Today should obviously do is the thing it
+ did not. Navigating and selecting are two different intents and it
+ conflated them, so it is gone until it can be one or the other on
+ purpose. Reaching today by scrolling still works. */}
+ {/* No `inert` here: the two cells below take turns, so the footer as a
+ whole is always live. It carried one while the footer was hidden
+ entirely on the wheels, and leaving it behind made the wheels' own
+ Done button unreachable — an inert ancestor disables everything
+ inside it. */}
+ <div {...stylex.props(styles.footer)}>
+ {/* Both actions share one grid cell, the same way the panels above
+ them do, and follow the same base/overlay rule — so the footer
+ never changes height and the two never read as superimposed. Each
+ belongs to a surface: Save finishes on the calendar, Done finishes
+ the detour through the wheels. */}
+ <div
+ inert={isWheelOpen ? true : undefined}
+ {...stylex.props(
+ styles.footerAction,
+ styles.panelBeneath,
+ isWheelOpen && styles.panelBeneathHidden,
+ )}>
+ <Button
+ variant="secondary"
+ size="md"
+ width="100%"
+ label={t('@astryx.dateInput.resetPicking')}
+ onClick={handleResetInSheet}
+ />
+ <Button
+ variant="primary"
+ // md, not sm: it is the action a thumb reaches for, so it gets
+ // the comfortable size rather than the compact one the header's
+ // ghost buttons use.
+ size="md"
+ width="100%"
+ label={t('@astryx.dateInput.savePicking')}
+ onClick={() => setIsSheetOpen(false)}
+ />
+ </div>
+ <div
+ inert={isWheelOpen ? undefined : true}
+ {...stylex.props(
+ styles.footerAction,
+ styles.panelOverlay,
+ !isWheelOpen && styles.panelOverlayHidden,
+ )}>
+ <Button
+ // secondary, not primary: this one does not finish the task, it
+ // finishes a step. Giving both surfaces a primary button would
+ // say the wheels are somewhere you can complete from.
+ variant="secondary"
+ size="md"
+ width="100%"
+ label={t('@astryx.dateInput.doneChoosingMonth')}
+ onClick={() => setIsWheelOpen(false)}
+ />
+ </div>
+ </div>
+ </div>
+ );
+
+ const inputWrapper = (
+ <div
+ ref={el => {
+ // Anchor + hover/focus listeners for the disabled-message tooltip.
+ // Gated internally by isEnabled, so attaching unconditionally is safe.
+ disabledMessageTooltip.ref(el);
+ }}
+ {...rest}
+ {...mergeProps(
+ themeProps('date-input', {
+ size,
+ status: status?.type ?? null,
+ disabled: isDisabled ? 'disabled' : null,
+ }),
+ stylex.props(
+ inputWrapperStyles.base,
+ sizeStyles[size],
+ styles.wrapper,
+ isEffectivelyDisabled && inputWrapperStyles.disabled,
+ status && inputStatusBorderStyles[status.type],
+ status &&
+ !isEffectivelyDisabled &&
+ inputStatusHoverShadowStyles[status.type],
+ status && inputStatusFocusWithinStyles[status.type],
+ inputGroup && groupStyles.inGroup,
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ {inputGroup && <VisuallyHidden id={inputLabelID}>{label}</VisuallyHidden>}
+ <button
+ type="button"
+ onClick={openSheet}
+ disabled={isEffectivelyDisabled}
+ aria-label={t('@astryx.dateInput.openCalendar')}
+ tabIndex={-1}
+ {...stylex.props(
+ focusOutlineStyles.focusVisible,
+ styles.iconButton,
+ isEffectivelyDisabled && styles.iconButtonDisabled,
+ )}>
+ <Icon
+ icon="calendar"
+ size="sm"
+ color="secondary"
+ {...themeProps('date-input-toggle-icon', {
+ state: isSheetOpen ? 'expanded' : 'collapsed',
+ })}
+ />
+ </button>
+ <input
+ ref={mergeRefs(ref, inputRef)}
+ id={id}
+ type="text"
+ role="combobox"
+ value={displayValue}
+ // No typing on this surface: the picker is the input method, and the
+ // virtual keyboard would cover the sheet it is meant to fill in.
+ // readOnly blocks entry; inputMode="none" is what actually keeps the
+ // keyboard down when the field takes focus.
+ readOnly
+ inputMode="none"
+ onChange={() => {}}
+ onClick={openSheet}
+ onKeyDown={handleInputKeyDown}
+ placeholder={placeholder}
+ disabled={isEffectivelyDisabled && !showsDisabledMessage}
+ aria-disabled={showsDisabledMessage ? 'true' : undefined}
+ aria-labelledby={ariaLabelledBy}
+ aria-describedby={ariaDescribedBy}
+ aria-required={isEffectivelyRequired ? 'true' : undefined}
+ aria-invalid={status?.type === 'error' ? 'true' : undefined}
+ aria-busy={isBusy || undefined}
+ aria-expanded={isSheetOpen}
+ aria-haspopup="dialog"
+ aria-autocomplete="none"
+ autoComplete="off"
+ {...stylex.props(
+ styles.input,
+ isEffectivelyDisabled && styles.inputDisabled,
+ )}
+ />
+ {hasClear && value !== undefined && !isEffectivelyDisabled && (
+ <InputClearButton
+ label={t('@astryx.dateInput.clear', {label})}
+ onClick={handleClear}
+ iconClassName={stableClassName('date-input-clear-icon')}
+ />
+ )}
+ {isBusy && <Spinner size="sm" />}
+ {statusIcon}
+ <BottomSheet
+ isOpen={isSheetOpen}
+ onOpenChange={setIsSheetOpen}
+ label={t('@astryx.dateInput.dialogLabel')}
+ // The picker is a fixed height by construction, so the sheet should be
+ // exactly as tall as it is rather than claiming a viewport budget.
+ height="hug">
+ <div {...stylex.props(styles.sheetBody)}>{surface}</div>
+ </BottomSheet>
+ {showsDisabledMessage &&
+ disabledMessageTooltip.renderTooltip(disabledMessage)}
+ </div>
+ );
+
+ if (inputGroup) {
+ return inputWrapper;
+ }
+
+ return (
+ <Field
+ label={label}
+ isLabelHidden={isLabelHidden}
+ description={description}
+ inputID={id}
+ descriptionID={description ? descriptionID : undefined}
+ isOptional={isOptional}
+ isRequired={isRequired}
+ isDisabled={isDisabled}
+ status={
+ status
+ ? {
+ type: status.type,
+ message: status.message,
+ messageID: status.message ? statusMessageID : undefined,
+ }
+ : undefined
+ }
+ statusVariant={statusVariant}
+ labelTooltip={labelTooltip}
+ width={width}>
+ {inputWrapper}
+ </Field>
+ );
+}
+
+TouchDateField.displayName = 'TouchDateField';
diff --git a/packages/core/src/DateInput/Wheel.tsx b/packages/core/src/DateInput/Wheel.tsx
new file mode 100644
index 0000000000..2d179f6c53
--- /dev/null
+++ b/packages/core/src/DateInput/Wheel.tsx
@@ -0,0 +1,470 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file Wheel.tsx
+ * @input Option list, selected value, change callback
+ * @output Exports Wheel — a snap-scrolling picker column
+ * @position Internal component; consumed by MonthYearWheels.tsx
+ *
+ * A wheel is a scroll container, not a custom gesture surface. Momentum,
+ * rubber-banding, and the settle animation are the platform's; all this adds
+ * is `scroll-snap-align: center` on each option, half a viewport of padding at
+ * each end so the first and last option can reach the middle, and a commit
+ * when the scrolling stops.
+ *
+ * The falloff (rows fading and tipping away from the centre) is a CSS
+ * scroll-driven animation on a `view()` timeline — the browser interpolates it
+ * against each row's own position in the scrollport, so it stays glued to the
+ * finger with no JS in the frame loop. It is guarded by `@supports`, because a
+ * browser that does not understand `animation-timeline` would otherwise run
+ * the same keyframes on the document timeline and simply play them once.
+ *
+ * Accessibility: this is a listbox, not a novel widget. It is one tab stop
+ * with arrow/Home/End/PageUp/PageDown keys, `aria-activedescendant` tracking
+ * the active row, and every row reachable by tap — none of which depends on
+ * the scroll-driven decoration.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/DateInput/TouchDateField.tsx
+ * - /packages/core/src/DateInput/DateInput.doc.mjs
+ * - /packages/core/src/DateInput/DateInputTouch.test.tsx
+ */
+
+import {useCallback, useEffect, useId, useRef, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ radiusVars,
+ fontWeightVars,
+ typeScaleVars,
+ spacingVars,
+ durationVars,
+} from '../theme/tokens.stylex';
+import {focusOutlineStyles} from '../utils';
+import {dateInputTouchSizes, dateInputTouchGeometry} from './tokens.stylex';
+import {useOwnScrollGesture} from './useOwnScrollGesture';
+import {usePointerDragScroll} from './usePointerDragScroll';
+import {useScrollSettle} from './useScrollSettle';
+
+const ITEM_BLOCK_SIZE = dateInputTouchSizes.wheelItemSize;
+
+/**
+ * Rows tip away from the centre of the wheel. 0% is a row just entering at the
+ * bottom of the scrollport, 50% is a row centred in it, 100% is a row leaving
+ * at the top — which is what a `view()` timeline over the `cover` range means,
+ * and why this reads as a cylinder rotating under the finger.
+ */
+const falloff = stylex.keyframes({
+ '0%': {
+ opacity: 0.3,
+ transform: 'rotateX(52deg) scale(0.86)',
+ },
+ '50%': {
+ opacity: 1,
+ transform: 'rotateX(0deg) scale(1)',
+ },
+ '100%': {
+ opacity: 0.3,
+ transform: 'rotateX(-52deg) scale(0.86)',
+ },
+});
+
+/** Motion-free equivalent: the depth cue survives as opacity alone. */
+const fadeOnly = stylex.keyframes({
+ '0%': {opacity: 0.3},
+ '50%': {opacity: 1},
+ '100%': {opacity: 0.3},
+});
+
+const styles = stylex.create({
+ column: {
+ position: 'relative',
+ flex: '1 1 0',
+ minWidth: 0,
+ },
+ scroller: {
+ blockSize: dateInputTouchGeometry.paneBlockSize,
+ // Load-bearing, and stated rather than inherited from the reset (whose
+ // rule is zero-specificity `:where`): with content-box the end padding
+ // below would be added to the scrollport instead of sitting inside it,
+ // and every snap position would be wrong.
+ boxSizing: 'border-box',
+ overflowY: 'auto',
+ overflowX: 'hidden',
+ // Snap every row to the middle of the scrollport, where the selection band
+ // sits. `mandatory` (not `proximity`) because a wheel has no valid resting
+ // position between two options.
+ scrollSnapType: 'y mandatory',
+ overscrollBehavior: 'contain',
+ // Room for row 0 and row n-1 to reach the centre.
+ paddingBlock: dateInputTouchGeometry.wheelEdgePadding,
+ // Gives the rotateX falloff somewhere to recede to.
+ perspective: '520px',
+ transformStyle: 'preserve-3d',
+ scrollbarWidth: 'none',
+ outline: 'none',
+ touchAction: 'pan-y',
+ },
+ item: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ blockSize: ITEM_BLOCK_SIZE,
+ paddingInline: spacingVars['--spacing-2'],
+ scrollSnapAlign: 'center',
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ // Larger than body text, and larger than the calendar's day numbers: on
+ // a wheel the value under the band is the whole interface, and the rows
+ // above and below are read at a glance while moving.
+ fontSize: typeScaleVars['--text-large-size'],
+ fontWeight: fontWeightVars['--font-weight-normal'],
+ color: colorVars['--color-text-primary'],
+ whiteSpace: 'nowrap',
+ // NO `overflow: hidden` here. It would make the row itself a scroll
+ // container, and `view()` binds to the subject's nearest ancestor scroll
+ // container — the falloff would measure the row against itself and sit
+ // frozen at 50% forever. Clipping belongs on the inner element.
+ cursor: 'pointer',
+ userSelect: 'none',
+ transitionProperty: 'color, font-weight',
+ transitionDuration: durationVars['--duration-fast'],
+ },
+ /**
+ * The falloff rides an inner element, never the row itself.
+ *
+ * A snap area is the element's TRANSFORMED border box, so animating the row
+ * would move the very positions the scroller is snapping to — the wheel
+ * settles a few pixels off, and the offset feeds back into the animation.
+ * Transforming a child leaves the row's box, and every snap offset, exact.
+ */
+ itemInner: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ inlineSize: '100%',
+ blockSize: '100%',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ // The wheel look. Held behind @supports so browsers without scroll-driven
+ // animations get a plain, fully legible list instead of these keyframes
+ // playing themselves out once on the document timeline. Under reduced
+ // motion the same timeline drives opacity only — the depth cue survives,
+ // the tipping does not.
+ animationName: {
+ default: null,
+ '@supports (animation-timeline: view())': {
+ default: falloff,
+ '@media (prefers-reduced-motion: reduce)': fadeOnly,
+ },
+ },
+ animationTimeline: 'view(y)',
+ animationRange: 'cover 0% cover 100%',
+ animationFillMode: 'both',
+ animationDuration: 'auto',
+ animationTimingFunction: 'linear',
+ backfaceVisibility: 'hidden',
+ },
+ itemActive: {
+ color: colorVars['--color-text-accent'],
+ fontWeight: fontWeightVars['--font-weight-semibold'],
+ },
+ itemDisabled: {
+ color: colorVars['--color-text-disabled'],
+ cursor: 'not-allowed',
+ },
+ /**
+ * The selection band: a single centred row-height plate behind the options.
+ * Purely decorative — the committed value is announced by `aria-selected`.
+ */
+ band: {
+ position: 'absolute',
+ insetInline: 0,
+ insetBlockStart: `calc(50% - (${ITEM_BLOCK_SIZE} / 2))`,
+ blockSize: ITEM_BLOCK_SIZE,
+ borderRadius: radiusVars['--radius-element'],
+ // `--color-neutral`, not `--color-background-muted`. Muted is 4.7% alpha,
+ // which puts the whole plate 17 units of colour away from the sheet
+ // behind it — so when the wheels fade in, the band's animation has 17
+ // units to happen in while the text beside it travels 412. It did not
+ // read as fading, it read as appearing. Neutral is 10%, which doubles the
+ // range to 36 and is still quiet enough to sit under text.
+ backgroundColor: colorVars['--color-neutral'],
+ pointerEvents: 'none',
+ },
+});
+
+export interface WheelOption {
+ /** Stable numeric identity of the row (a month 1-12, or a year). */
+ value: number;
+ /** Row text. */
+ label: string;
+ /** Rows outside min/max stay visible but cannot be committed. */
+ isDisabled?: boolean;
+}
+
+export interface WheelProps {
+ /** Accessible name for the column, e.g. "Month". */
+ label: string;
+ /** Rows, top to bottom. */
+ options: ReadonlyArray<WheelOption>;
+ /** Committed value; must match one option's `value`. */
+ value: number;
+ /** Fired when the wheel comes to rest on a different, enabled row. */
+ onChange: (value: number) => void;
+ /**
+ * False while the wheel is hidden — scroll offsets of a display:none
+ * scroller are meaningless, so listeners and the initial scroll wait.
+ */
+ isActive?: boolean;
+}
+
+/**
+ * One snap-scrolling picker column.
+ *
+ * @example
+ * ```
+ * <Wheel
+ * label="Month"
+ * options={monthOptions}
+ * value={month}
+ * onChange={setMonth}
+ * />
+ * ```
+ */
+export function Wheel({
+ label,
+ options,
+ value,
+ onChange,
+ isActive = true,
+}: WheelProps) {
+ const id = useId();
+ const scrollerRef = useRef<HTMLDivElement | null>(null);
+ const selectedIndex = Math.max(
+ 0,
+ options.findIndex(option => option.value === value),
+ );
+ // Which row is under the band right now. Tracks the finger during a scroll;
+ // `selectedIndex` only catches up when the wheel settles.
+ const [activeIndex, setActiveIndex] = useState(selectedIndex);
+
+ // Row height in px, read from layout rather than assumed, so a theme that
+ // retunes --date-input-touch-wheel-item-size still lands on the right row.
+ const itemBlockSize = useCallback((): number => {
+ const first = scrollerRef.current?.firstElementChild;
+ return first instanceof HTMLElement && first.offsetHeight > 0
+ ? first.offsetHeight
+ : 0;
+ }, []);
+
+ const scrollToIndex = useCallback(
+ (index: number, behavior: ScrollBehavior) => {
+ const scroller = scrollerRef.current;
+ const size = itemBlockSize();
+ if (scroller == null || size === 0) {
+ return;
+ }
+ scroller.scrollTo({top: index * size, behavior});
+ },
+ [itemBlockSize],
+ );
+
+ // Commit on rest. A disabled row is bounced back to the committed one
+ // rather than silently keeping a value the wheel is not showing.
+ //
+ // Declared here, above the park effect, because that effect consults the
+ // `isAtRestRef` this returns before it repositions anything.
+ const {isAtRestRef} = useScrollSettle(
+ scrollerRef,
+ scroller => {
+ const size = itemBlockSize();
+ if (size === 0) {
+ return;
+ }
+ const index = Math.min(
+ options.length - 1,
+ Math.max(0, Math.round(scroller.scrollTop / size)),
+ );
+ const option = options[index];
+ if (option == null || option.isDisabled) {
+ scrollToIndex(selectedIndex, 'smooth');
+ return;
+ }
+ if (option.value !== value) {
+ onChange(option.value);
+ }
+ },
+ isActive,
+ );
+
+ // Park the committed row under the band whenever the wheel is shown, or the
+ // value is changed from outside (the calendar scrolled to another month).
+ //
+ // NEVER while the wheel is still moving. A scroller that is mid-gesture or
+ // still carrying momentum is the user's, and repositioning it does not stop
+ // the momentum — on iOS it feeds a cycle where the scroll this causes reads
+ // as a new settle, commits the next row along, and parks again. See
+ // useScrollSettle. The settle handler re-checks the position afterwards, so
+ // a correction that is genuinely needed still happens, just at rest.
+ useEffect(() => {
+ if (!isActive || !isAtRestRef.current) {
+ return;
+ }
+ const size = itemBlockSize();
+ const scroller = scrollerRef.current;
+ if (scroller == null || size === 0) {
+ return;
+ }
+ if (Math.round(scroller.scrollTop / size) !== selectedIndex) {
+ scroller.scrollTo({top: selectedIndex * size, behavior: 'auto'});
+ }
+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- the highlight follows a scroll position, which only exists after layout
+ setActiveIndex(selectedIndex);
+ }, [isActive, selectedIndex, itemBlockSize, isAtRestRef]);
+
+ // Highlight follows the finger. rAF-throttled: a scroll can fire far more
+ // often than the display refreshes, and this only feeds a repaint.
+ const frameRef = useRef<number | undefined>(undefined);
+ useEffect(() => {
+ const scroller = scrollerRef.current;
+ if (scroller == null || !isActive) {
+ return;
+ }
+ const onScroll = () => {
+ if (frameRef.current != null) {
+ return;
+ }
+ frameRef.current = requestAnimationFrame(() => {
+ frameRef.current = undefined;
+ const size = itemBlockSize();
+ if (size === 0) {
+ return;
+ }
+ const index = Math.min(
+ options.length - 1,
+ Math.max(0, Math.round(scroller.scrollTop / size)),
+ );
+ setActiveIndex(index);
+ });
+ };
+ scroller.addEventListener('scroll', onScroll, {passive: true});
+ return () => {
+ scroller.removeEventListener('scroll', onScroll);
+ if (frameRef.current != null) {
+ cancelAnimationFrame(frameRef.current);
+ frameRef.current = undefined;
+ }
+ };
+ }, [isActive, options.length, itemBlockSize]);
+
+ // Keep the finger. Inside a BottomSheet the sheet would otherwise read a
+ // downward drag here as swipe-to-dismiss; see useOwnScrollGesture. Gated on
+ // isActive because the hidden panel keeps its layout box.
+ // 'all': a wheel scrolls vertically, the same axis the sheet wants, so
+ // there is no way to share — it takes every touch that lands on it.
+ useOwnScrollGesture(scrollerRef, 'all', {isEnabled: isActive});
+
+ // A mouse cannot drag a scroll container, so without this the wheel ignores
+ // the one gesture its shape invites. Touch is untouched — it pans natively,
+ // with momentum this could not match. See usePointerDragScroll.
+ usePointerDragScroll(scrollerRef, isActive);
+
+ const moveBy = useCallback(
+ (delta: number) => {
+ const next = Math.min(
+ options.length - 1,
+ Math.max(0, activeIndex + delta),
+ );
+ const option = options[next];
+ if (option == null || option.isDisabled) {
+ return;
+ }
+ setActiveIndex(next);
+ scrollToIndex(next, 'smooth');
+ if (option.value !== value) {
+ onChange(option.value);
+ }
+ },
+ [activeIndex, options, scrollToIndex, value, onChange],
+ );
+
+ const handleKeyDown = useCallback(
+ (event: React.KeyboardEvent) => {
+ switch (event.key) {
+ case 'ArrowDown':
+ event.preventDefault();
+ moveBy(1);
+ break;
+ case 'ArrowUp':
+ event.preventDefault();
+ moveBy(-1);
+ break;
+ case 'PageDown':
+ event.preventDefault();
+ moveBy(10);
+ break;
+ case 'PageUp':
+ event.preventDefault();
+ moveBy(-10);
+ break;
+ case 'Home':
+ event.preventDefault();
+ moveBy(-activeIndex);
+ break;
+ case 'End':
+ event.preventDefault();
+ moveBy(options.length - 1 - activeIndex);
+ break;
+ default:
+ break;
+ }
+ },
+ [moveBy, activeIndex, options.length],
+ );
+
+ return (
+ <div {...stylex.props(styles.column)}>
+ <div aria-hidden="true" {...stylex.props(styles.band)} />
+ <div
+ ref={scrollerRef}
+ role="listbox"
+ aria-label={label}
+ aria-activedescendant={`${id}-${options[activeIndex]?.value}`}
+ tabIndex={0}
+ onKeyDown={handleKeyDown}
+ {...stylex.props(styles.scroller, focusOutlineStyles.focusVisible)}>
+ {options.map((option, index) => (
+ <div
+ key={option.value}
+ id={`${id}-${option.value}`}
+ role="option"
+ aria-selected={option.value === value}
+ aria-disabled={option.isDisabled || undefined}
+ onClick={() => {
+ if (option.isDisabled) {
+ return;
+ }
+ setActiveIndex(index);
+ scrollToIndex(index, 'smooth');
+ if (option.value !== value) {
+ onChange(option.value);
+ }
+ }}
+ {...stylex.props(
+ styles.item,
+ index === activeIndex && styles.itemActive,
+ option.isDisabled && styles.itemDisabled,
+ )}>
+ <span {...stylex.props(styles.itemInner)}>{option.label}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+Wheel.displayName = 'Wheel';
diff --git a/packages/core/src/DateInput/index.ts b/packages/core/src/DateInput/index.ts
index eed5271fd2..e69fb6cdd0 100644
--- a/packages/core/src/DateInput/index.ts
+++ b/packages/core/src/DateInput/index.ts
@@ -9,7 +9,7 @@
* @position Package entry point for DateInput
*/
-export {DateInput} from './DateInput';
+export {DateInput, TOUCH_POINTER_QUERY} from './DateInput';
export type {
DateInputProps,
DateInputSize,
diff --git a/packages/core/src/DateInput/monthGeometry.ts b/packages/core/src/DateInput/monthGeometry.ts
new file mode 100644
index 0000000000..62e5fa47d6
--- /dev/null
+++ b/packages/core/src/DateInput/monthGeometry.ts
@@ -0,0 +1,118 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file monthGeometry.ts
+ * @input PlainDate values, scroll offsets, pane heights
+ * @output Pure month-index arithmetic and the virtualized pane window
+ * @position Internal helper; consumed by MonthScroller.tsx and DateInput.tsx
+ *
+ * A "month index" is a single integer that totally orders calendar months:
+ * `year * 12 + (month - 1)`. The scroller is a list of equal-width panes, so
+ * one integer converts freely between a month, a row in that list, and a
+ * scroll offset — which is the whole trick behind continuous scrolling.
+ *
+ * These are pure functions on purpose: the scroll math is the part most likely
+ * to be wrong, and it is testable without a layout engine.
+ *
+ * SYNC: When modified, update DateInputTouch.test.tsx.
+ */
+
+import type {PlainDate} from '../utils';
+
+/** How many months are reachable in either direction when unbounded. */
+export const DEFAULT_MONTH_REACH = 600;
+
+/** `year * 12 + (month - 1)`, for a 1-based month. */
+export function toMonthIndex(year: number, month: number): number {
+ return year * 12 + (month - 1);
+}
+
+/** The month index of a PlainDate. */
+export function monthIndexOf(date: PlainDate): number {
+ return toMonthIndex(date.year, date.month);
+}
+
+/** Inverse of {@link toMonthIndex}; month comes back 1-based. */
+export function fromMonthIndex(index: number): {year: number; month: number} {
+ return {
+ year: Math.floor(index / 12),
+ month: (((index % 12) + 12) % 12) + 1,
+ };
+}
+
+/** `value` limited to `[min, max]`. */
+export function clampIndex(value: number, min: number, max: number): number {
+ return Math.min(Math.max(value, min), max);
+}
+
+/**
+ * The month a scrollport is resting on (or nearest to, mid-scroll).
+ *
+ * Returns a row offset from the start of the list, not a month index — add
+ * `minMonthIndex` for that.
+ *
+ * `scrollOffset` is `scrollLeft` for the horizontal scroller. Under RTL that
+ * is NEGATIVE — the spec has the inline start at 0 and scrolling run down
+ * from there — so the sign is normalized away here rather than at each call
+ * site, where forgetting it would silently pin the calendar to month zero.
+ */
+export function rowAtScrollOffset(
+ scrollOffset: number,
+ paneSize: number,
+ rowCount: number,
+ isRTL: boolean = false,
+): number {
+ if (paneSize <= 0) {
+ return 0;
+ }
+ const distance = isRTL ? -scrollOffset : scrollOffset;
+ return clampIndex(Math.round(distance / paneSize), 0, rowCount - 1);
+}
+
+/**
+ * The scroll offset that brings `row` to rest, ready for `scrollTo`. The
+ * inverse of {@link rowAtScrollOffset}, including its RTL sign.
+ */
+export function scrollOffsetForRow(
+ row: number,
+ paneSize: number,
+ isRTL: boolean = false,
+): number {
+ const distance = row * paneSize;
+ return isRTL ? -distance : distance;
+}
+
+export interface PaneWindow {
+ /** First rendered row, inclusive. */
+ start: number;
+ /** Last rendered row, inclusive. */
+ end: number;
+}
+
+/**
+ * The slice of rows to actually mount around `centerRow`.
+ *
+ * Only a handful of panes exist in the DOM at a time; the rest of the list is
+ * a spacer. `overscan` is how many extra panes ride along on each side so a
+ * fast fling never lands on an unmounted one — which under `scroll-snap-type:
+ * mandatory` would be visible as a jump.
+ */
+export function paneWindow(
+ centerRow: number,
+ rowCount: number,
+ overscan: number,
+): PaneWindow {
+ return {
+ start: Math.max(0, centerRow - overscan),
+ end: Math.min(rowCount - 1, centerRow + overscan),
+ };
+}
+
+/** `[start, end]` inclusive, as an array of rows. */
+export function rowsIn({start, end}: PaneWindow): number[] {
+ const rows: number[] = [];
+ for (let row = start; row <= end; row++) {
+ rows.push(row);
+ }
+ return rows;
+}
diff --git a/packages/core/src/DateInput/tokens.stylex.ts b/packages/core/src/DateInput/tokens.stylex.ts
new file mode 100644
index 0000000000..47ca2b193e
--- /dev/null
+++ b/packages/core/src/DateInput/tokens.stylex.ts
@@ -0,0 +1,99 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file tokens.stylex.ts
+ * @input StyleX variable and constant definitions
+ * @output Exports DateInput layout constants and derived geometry
+ * @position Lab component tokens consumed by DateInput.tsx, MonthScroller.tsx, Wheel.tsx, MonthYearWheels.tsx
+ *
+ * The picker's whole geometry derives from two numbers, which is what makes
+ * the fixed height and the scroll snapping exact:
+ *
+ * pane height = weeks x day size (one month, always 6 rows)
+ * body height = pane height (calendar body AND wheel body)
+ * wheel pad = (body height - item) / 2 (so row 0 can rest centered)
+ *
+ * Every month pane is the same height as the scrollport, so `scroll-snap-align:
+ * start` produces a paged scroller with no partial rest positions, and the
+ * wheel overlay swaps in without the component changing size.
+ *
+ * The derived values are `defineConsts`, not plain exported strings: StyleX
+ * inlines a constant at build time only through `defineVars`/`defineConsts`
+ * from a `.stylex.ts` file. A plain `export const` fails the build with
+ * "a style value can only contain an array, string or number".
+ *
+ */
+
+import * as stylex from '@stylexjs/stylex';
+
+/**
+ * Week rows per month pane. Fixed at 6 — the most any month needs — so every
+ * pane is identical in height and no snap offset ever shifts. Not a themeable
+ * variable: it is a fact about the Gregorian calendar, and `repeat()` cannot
+ * take a custom property as its count.
+ */
+export const WEEKS_PER_PANE = 6;
+
+/**
+ * The picker's two size inputs.
+ *
+ * `defineConsts`, not `defineVars`: these are inlined at build time and emit
+ * no CSS custom property, so they are internal geometry rather than public
+ * theming API. That is deliberate for both of them.
+ *
+ * The day size is an accessibility floor — 44px is the comfortable minimum
+ * tap target on iOS and Android, and every other target in the sheet is held
+ * to it. Exposing it as a variable would let a theme quietly lower the floor,
+ * which is not a knob a design system should hand out.
+ *
+ * The wheel row height is only meaningful against the day size (see below),
+ * so tuning one without the other produces a picker whose panes no longer
+ * agree — a variable that is only safe to change in lockstep with another is
+ * not really a variable.
+ *
+ * If a real need to theme either appears, promoting a const to a var is an
+ * additive change; removing a var that consumers have started setting is not.
+ */
+export const dateInputTouchSizes = stylex.defineConsts({
+ /**
+ * Height of one day row, and the minimum touch target of a day. 44px is the
+ * comfortable minimum tap target on both iOS and Android.
+ */
+ daySize: '44px',
+ /**
+ * Height of one wheel option row, and so the spacing between options and
+ * the height of the selection band.
+ *
+ * 28px against a day's 44px: a wheel row is scroll-first — a value is
+ * chosen by bringing it under the band, and tapping one is a shortcut
+ * rather than the mechanism — so it does not carry a day cell's tap-target
+ * duty, and a mis-tap costs nothing, because the neighbouring rows are the
+ * same control and the result is visible immediately.
+ *
+ * The row is deliberately close to the text it holds (17px), the way a
+ * platform picker packs them: the list should read as one continuous
+ * column of values, not as a stack of buttons with air between them. At
+ * this height ~9 options are on screen.
+ */
+ wheelItemSize: '28px',
+});
+
+// Local aliases for the derived values below. StyleX resolves a `defineConsts`
+// member through an import, so consumers read `dateInputTouchSizes.*` directly
+// rather than a re-exported plain const, which its static analysis cannot
+// follow across files.
+const DAY_SIZE = dateInputTouchSizes.daySize;
+const WHEEL_ITEM_SIZE = dateInputTouchSizes.wheelItemSize;
+
+/** Geometry derived from the sizes above, shared across the component. */
+export const dateInputTouchGeometry = stylex.defineConsts({
+ /** One month pane — and therefore the scrollport, and the wheel body. */
+ paneBlockSize: `calc(${WEEKS_PER_PANE} * ${DAY_SIZE})`,
+ /** The six equal week rows inside a pane. */
+ paneRows: `repeat(${WEEKS_PER_PANE}, 1fr)`,
+ /**
+ * Padding above the first and below the last wheel option, so either end
+ * can come to rest under the centered selection band.
+ */
+ wheelEdgePadding: `calc((${WEEKS_PER_PANE} * ${DAY_SIZE} - ${WHEEL_ITEM_SIZE}) / 2)`,
+});
diff --git a/packages/core/src/DateInput/useOwnScrollGesture.ts b/packages/core/src/DateInput/useOwnScrollGesture.ts
new file mode 100644
index 0000000000..ad5b5d0823
--- /dev/null
+++ b/packages/core/src/DateInput/useOwnScrollGesture.ts
@@ -0,0 +1,227 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useOwnScrollGesture.ts
+ * @input A scroll container ref and which axis it owns
+ * @output Stops touch gestures on that container from reaching an ancestor
+ * @position Internal behavior hook; consumed by Wheel.tsx and MonthScroller.tsx
+ *
+ * Lets a nested scroller keep the finger that lands on it.
+ *
+ * ## The conflict
+ *
+ * `BottomSheet` implements swipe-to-dismiss by watching touches on its
+ * scrolling body: at the body's scroll top, a downward pull stops being a
+ * scroll and becomes a sheet drag. The test is `body.scrollTop`, and the body
+ * of a sheet sized to hug its content never scrolls, so it reads as "at the
+ * top" forever — every downward-ish drag anywhere inside promotes to a drag.
+ *
+ * `touch-action` does NOT protect against this. It governs what the BROWSER
+ * will pan natively; the sheet's listener is JavaScript, and its
+ * `preventDefault()` cancels the native scroll whatever `touch-action` says.
+ * Measured: with `touch-action: pan-x` on the month scroller, a swipe just 9°
+ * off horizontal (120px across, 20px down — an ordinary thumb arc) had every
+ * `touchmove` cancelled by the sheet, so the calendar did not move at all and
+ * the sheet sprang back. The month simply would not change.
+ *
+ * ## Two ways to own a gesture
+ *
+ * - `'all'` — the wheels. They scroll vertically, exactly the axis the sheet
+ * wants, so there is no way to share: the scroller takes every touch that
+ * lands on it and the sheet is dismissed from the handle, the header or the
+ * scrim instead.
+ *
+ * - `'inline'` — the month scroller. It pages sideways, so the two CAN share
+ * by direction: lock the axis on the first significant move, claim the
+ * gesture only when it is horizontal, and let vertical ones through so
+ * swipe-to-dismiss still works on the calendar.
+ *
+ * ## Where the line falls, and the gestures that fall past it
+ *
+ * A thumb swiping sideways travels in an arc, not a line — a "horizontal"
+ * swipe routinely drifts 10-30° down, and sometimes further. So an `'inline'`
+ * scroller claims generously: vertical has to beat horizontal by
+ * {@link VERTICAL_DOMINANCE} before the sheet gets the gesture, which puts the
+ * split near 63° rather than at the diagonal.
+ *
+ * That is wider than the browser will pan. `touch-action: pan-x` pans only
+ * while `|dx| > |dy|` and refuses the moment a gesture tips past 45°, so the
+ * band between the two lines used to be the worst outcome available: measured
+ * on an iPhone 15 profile, a 200px swipe at 45-60° neither paged a month nor
+ * dismissed the sheet, because we had told the sheet to keep off a gesture the
+ * compositor then declined to pan. Nothing moved at all.
+ *
+ * {@link OwnScrollGestureOptions.onSwipe} closes that band, and it does not
+ * need to know where the browser's line is: if the element's scroll offset
+ * never changed across a claimed gesture, the browser declined it, and a
+ * swipe that cleared {@link SWIPE_DISTANCE} is reported so the caller can page
+ * itself. Native pans keep their momentum and snapping and report nothing.
+ *
+ * The remaining asymmetry is deliberate and in the direction the scroller
+ * needs: it is generous about distance too, paging on a 30px flick where the
+ * sheet asks for ~200px of pull before it dismisses.
+ *
+ * ## Why native listeners
+ *
+ * React delegates its events at the root container, which is an ANCESTOR of
+ * the sheet body — so a React `onTouchStart` would run after the body's own
+ * listener had already claimed the gesture. `stopPropagation` has to happen on
+ * a listener attached to the element itself, during the real bubble phase,
+ * before the event ever reaches the body.
+ *
+ * Nothing here calls `preventDefault`, so the listeners stay passive and the
+ * scroller keeps native momentum, snapping and rubber-banding.
+ *
+ * SYNC: When modified, update DateInputTouch.test.tsx.
+ */
+
+import {useEffect, useRef} from 'react';
+
+/**
+ * How much a gesture's vertical travel must exceed its horizontal travel
+ * before an `'inline'` scroller gives it up. Above 1, so horizontal wins the
+ * ambiguous middle; see the file header for why the split is deliberately
+ * unfair, and how the gestures past the browser's own 45° line are handled.
+ */
+export const VERTICAL_DOMINANCE = 2;
+
+/** Movement below this is noise, not a direction. */
+const AXIS_LOCK_SLOP = 6;
+
+/**
+ * Horizontal travel a claimed-but-unpanned gesture needs before it counts as
+ * a swipe. Roughly the shortest flick the browser itself will page on.
+ */
+export const SWIPE_DISTANCE = 32;
+
+export type OwnedAxis = 'all' | 'inline';
+
+export type OwnScrollGestureOptions = {
+ /** Skip while the scroller is hidden; a hidden panel keeps its layout box,
+ * so its listeners would otherwise still be live. */
+ isEnabled?: boolean;
+ /**
+ * Called when a claimed gesture ended without the browser having scrolled
+ * the element at all — the diagonal swipes `touch-action: pan-x` refuses.
+ *
+ * `direction` is the sign to move the scroll offset by, so it composes
+ * directly: `scrollBy({left: direction * pageWidth})`. It is physical, and
+ * therefore correct in both directions of writing.
+ *
+ * Only fires for `'inline'`. A gesture the browser panned reports nothing,
+ * so momentum and snapping are never second-guessed.
+ */
+ onSwipe?: (direction: 1 | -1) => void;
+};
+
+/**
+ * Claim touch gestures that start on `ref`'s element, so an ancestor cannot
+ * reinterpret them as its own drag.
+ *
+ * @param ref - the scroll container
+ * @param axis - `'all'` to take every touch, `'inline'` to take only the
+ * horizontal ones and leave vertical drags to the sheet
+ * @param options - see {@link OwnScrollGestureOptions}
+ */
+export function useOwnScrollGesture(
+ ref: React.RefObject<HTMLElement | null>,
+ axis: OwnedAxis = 'all',
+ options: OwnScrollGestureOptions = {},
+): void {
+ const {isEnabled = true, onSwipe} = options;
+
+ // Read through a ref so a caller need not memoize the callback: re-running
+ // this effect would tear the listeners off mid-gesture.
+ const onSwipeRef = useRef(onSwipe);
+ onSwipeRef.current = onSwipe;
+
+ useEffect(() => {
+ const element = ref.current;
+ if (element == null || !isEnabled) {
+ return;
+ }
+
+ // null = not yet decided; true = ours for the rest of this gesture.
+ let claimed: boolean | null = null;
+ let originX = 0;
+ let originY = 0;
+ let lastX = 0;
+ let offsetAtStart = 0;
+ // Whether the browser actually panned the element during this gesture.
+ // Sampled per move rather than compared once at the end, because a short
+ // pan that snaps back finishes at the offset it started from.
+ let didPan = false;
+
+ const onStart = (event: TouchEvent) => {
+ const touch = event.touches[0];
+ originX = touch?.clientX ?? 0;
+ originY = touch?.clientY ?? 0;
+ lastX = originX;
+ offsetAtStart = element.scrollLeft;
+ didPan = false;
+ // 'all' decides at touchstart, before the sheet's own touchstart
+ // listener records an armed edge. 'inline' cannot decide yet — a touch
+ // has no direction until it moves — so it lets touchstart through and
+ // locks on the first move that clears the slop.
+ claimed = axis === 'all' ? true : null;
+ if (claimed) {
+ event.stopPropagation();
+ }
+ };
+
+ const onMove = (event: TouchEvent) => {
+ if (claimed === false) {
+ return;
+ }
+ const touch = event.touches[0];
+ if (touch == null) {
+ return;
+ }
+ if (claimed == null) {
+ const dx = Math.abs(touch.clientX - originX);
+ const dy = Math.abs(touch.clientY - originY);
+ if (Math.max(dx, dy) < AXIS_LOCK_SLOP) {
+ return;
+ }
+ claimed = dy <= dx * VERTICAL_DOMINANCE;
+ if (!claimed) {
+ return;
+ }
+ }
+ lastX = touch.clientX;
+ didPan ||= Math.abs(element.scrollLeft - offsetAtStart) >= 1;
+ event.stopPropagation();
+ };
+
+ const onEnd = () => {
+ // A gesture we claimed that the browser then refused to pan: the sheet
+ // was told to keep off it, so unless it is acted on here it does
+ // nothing at all. See the file header.
+ if (
+ claimed === true &&
+ axis === 'inline' &&
+ !didPan &&
+ Math.abs(lastX - originX) >= SWIPE_DISTANCE
+ ) {
+ onSwipeRef.current?.(lastX < originX ? 1 : -1);
+ }
+ // touchend/touchcancel deliberately propagate: they carry no
+ // interpretation, and letting them through is what resets the sheet's
+ // bookkeeping.
+ claimed = null;
+ };
+
+ element.addEventListener('touchstart', onStart, {passive: true});
+ element.addEventListener('touchmove', onMove, {passive: true});
+ element.addEventListener('touchend', onEnd, {passive: true});
+ element.addEventListener('touchcancel', onEnd, {passive: true});
+ return () => {
+ element.removeEventListener('touchstart', onStart);
+ element.removeEventListener('touchmove', onMove);
+ element.removeEventListener('touchend', onEnd);
+ element.removeEventListener('touchcancel', onEnd);
+ };
+ }, [ref, axis, isEnabled]);
+}
diff --git a/packages/core/src/DateInput/usePointerDragScroll.ts b/packages/core/src/DateInput/usePointerDragScroll.ts
new file mode 100644
index 0000000000..f4770f30e5
--- /dev/null
+++ b/packages/core/src/DateInput/usePointerDragScroll.ts
@@ -0,0 +1,220 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file usePointerDragScroll.ts
+ * @input A scroll container ref
+ * @output Lets a mouse drag the container's contents the way a finger does
+ * @position Internal behavior hook; consumed by Wheel.tsx
+ *
+ * ## Why this exists
+ *
+ * A wheel is a scroll container, which is what makes it feel right under a
+ * finger: the platform supplies panning, momentum, rubber-banding and the
+ * snap. A mouse gets none of that. Browsers do not drag-scroll an overflow
+ * container — press and pull on one and nothing happens at all, which is
+ * exactly what a wheel invites you to try.
+ *
+ * That leaves the mouse with the scroll wheel and a click on a visible row.
+ * Both work, and neither is the gesture the control is shaped like. It
+ * matters more than "mouse users are not the target": the touch surface is
+ * reviewed, themed and screenshotted on desktop browsers, where a wheel that
+ * ignores the pointer reads as broken rather than as touch-only.
+ *
+ * ## Mouse only, deliberately
+ *
+ * Touch and pen already pan natively, and this hook would be strictly worse
+ * than what they get — no momentum, no rubber-banding, no compositor
+ * threading. So it ignores every pointer type but `mouse` and leaves those
+ * gestures untouched.
+ *
+ * ## Snap has to be suspended for the duration
+ *
+ * `scroll-snap-type: y mandatory` re-snaps after every scroll, including a
+ * programmatic one, so a drag that assigns `scrollTop` is fighting it on
+ * every frame. Measured: dragging 5px at a time with mandatory snap on, 7 of
+ * 8 steps were yanked back to a snap position — the wheel sticks to a row and
+ * then jumps a whole one. The drag therefore suspends snapping, and restores
+ * it once the release has settled somewhere legal.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/DateInput/Wheel.tsx
+ * - /packages/core/src/DateInput/DateInputTouch.test.tsx
+ */
+
+import {useEffect, useRef} from 'react';
+
+/**
+ * Movement below this stays a click. A mouse shifts a pixel or two under the
+ * press of the button itself, and a wheel row is a click target.
+ */
+export const DRAG_SLOP = 4;
+
+/** How long to wait for a release's settle before restoring snapping. */
+const SETTLE_FALLBACK_MS = 260;
+
+/**
+ * Let a mouse drag `ref`'s contents, on a container that already scrolls and
+ * snaps for touch.
+ *
+ * @param ref - the scroll container
+ * @param isEnabled - skip while the wheel is hidden; a hidden panel keeps its
+ * layout box, so its listeners would otherwise still be live
+ */
+export function usePointerDragScroll(
+ ref: React.RefObject<HTMLElement | null>,
+ isEnabled: boolean = true,
+): void {
+ useEffect(() => {
+ const element = ref.current;
+ if (element == null || !isEnabled) {
+ return;
+ }
+
+ let pointerId: number | null = null;
+ let originY = 0;
+ let originScrollTop = 0;
+ let isDragging = false;
+ // Survives from the drag's end to the click it produces, which is the
+ // whole reason it is not just `isDragging`.
+ let wasDragged = false;
+ let restoreTimer: number | undefined;
+
+ const restoreSnap = () => {
+ window.clearTimeout(restoreTimer);
+ element.removeEventListener('scrollend', restoreSnap);
+ // Back to the stylesheet's value rather than a hardcoded one, so this
+ // cannot drift from Wheel's own `scrollSnapType`.
+ element.style.removeProperty('scroll-snap-type');
+ };
+
+ const suspendSnap = () => {
+ window.clearTimeout(restoreTimer);
+ element.removeEventListener('scrollend', restoreSnap);
+ element.style.scrollSnapType = 'none';
+ };
+
+ const onPointerDown = (event: PointerEvent) => {
+ // Touch and pen pan natively, and better. Secondary buttons are for the
+ // context menu.
+ if (event.pointerType !== 'mouse' || event.button !== 0) {
+ return;
+ }
+ // Keep the press away from BottomSheet, which starts its own
+ // drag-to-dismiss from a `pointerdown` on its body and CAPTURES the
+ // pointer for it. Two things go wrong if it gets there first: the drag
+ // below is fighting the sheet for the same gesture, and — measured on
+ // the calendar too, so this is not new — every later pointer event
+ // retargets to the sheet body, which means a click that wobbles more
+ // than a pixel or two never reaches the row under it and selects
+ // nothing at all.
+ //
+ // A native listener during the real bubble phase is what it takes:
+ // the sheet's handler is a React prop, delegated at the root container,
+ // which is an ANCESTOR of this element. Same reasoning as
+ // useOwnScrollGesture, and the same trade — mouse drag-to-dismiss now
+ // starts from the grab handle, the header or the scrim rather than
+ // from inside a wheel, which is where a picker sheet puts it anyway.
+ event.stopPropagation();
+ pointerId = event.pointerId;
+ originY = event.clientY;
+ originScrollTop = element.scrollTop;
+ isDragging = false;
+ // Not captured yet: a press that never moves has to stay a click on the
+ // row under it, and capturing here would retarget that click.
+ };
+
+ const onPointerMove = (event: PointerEvent) => {
+ if (pointerId !== event.pointerId) {
+ return;
+ }
+ const delta = event.clientY - originY;
+ if (!isDragging) {
+ if (Math.abs(delta) < DRAG_SLOP) {
+ return;
+ }
+ isDragging = true;
+ element.setPointerCapture(event.pointerId);
+ suspendSnap();
+ // Dragging across rows would otherwise select their text, leaving the
+ // wheel looking highlighted after the gesture.
+ element.style.userSelect = 'none';
+ }
+ // Content follows the hand: pull up and the list moves up, which means
+ // scrolling further down it.
+ element.scrollTop = originScrollTop - delta;
+ };
+
+ const onPointerEnd = (event: PointerEvent) => {
+ if (pointerId !== event.pointerId) {
+ return;
+ }
+ pointerId = null;
+ if (!isDragging) {
+ return;
+ }
+ isDragging = false;
+ wasDragged = true;
+ element.style.removeProperty('user-select');
+ if (element.hasPointerCapture(event.pointerId)) {
+ element.releasePointerCapture(event.pointerId);
+ }
+
+ // The release lands mid-row. Glide to the nearest one and only then let
+ // snapping back on — restoring it here instead would jump the distance
+ // rather than travel it, and a jump is what this hook exists to avoid.
+ const rowHeight = firstRowHeight(element);
+ if (rowHeight > 0) {
+ const nearest = Math.round(element.scrollTop / rowHeight) * rowHeight;
+ element.scrollTo({top: nearest, behavior: 'smooth'});
+ }
+ // `scrollend` is the honest signal; the timer covers browsers that do
+ // not fire it, and the case where the glide had nowhere to go.
+ // Not `{once: true}`: a listener that never fires is never removed by
+ // it, so a component unmounted mid-glide would leave one attached.
+ // `restoreSnap` removes it itself, whichever of the two gets there
+ // first, and the cleanup below calls `restoreSnap` on unmount.
+ //
+ // eslint-disable-next-line @eslint-react/web-api-no-leaked-event-listener -- removed by restoreSnap, which the cleanup calls
+ element.addEventListener('scrollend', restoreSnap);
+ restoreTimer = window.setTimeout(restoreSnap, SETTLE_FALLBACK_MS);
+ };
+
+ // A drag ends over whichever row the mouse happens to be on, and that row
+ // would take the click as a selection. Swallow it — but only the one, and
+ // only after a real drag, so an ordinary click still selects.
+ const onClickCapture = (event: MouseEvent) => {
+ if (!wasDragged) {
+ return;
+ }
+ wasDragged = false;
+ event.stopPropagation();
+ event.preventDefault();
+ };
+
+ element.addEventListener('pointerdown', onPointerDown);
+ element.addEventListener('pointermove', onPointerMove);
+ element.addEventListener('pointerup', onPointerEnd);
+ element.addEventListener('pointercancel', onPointerEnd);
+ element.addEventListener('click', onClickCapture, {capture: true});
+ return () => {
+ element.removeEventListener('pointerdown', onPointerDown);
+ element.removeEventListener('pointermove', onPointerMove);
+ element.removeEventListener('pointerup', onPointerEnd);
+ element.removeEventListener('pointercancel', onPointerEnd);
+ element.removeEventListener('click', onClickCapture, {capture: true});
+ restoreSnap();
+ };
+ }, [ref, isEnabled]);
+}
+
+/**
+ * The pitch of the rows, read off the first one. Taken from layout rather
+ * than the token so a themed `--date-input-touch-wheel-item-size` is honoured
+ * without this hook having to know the variable exists.
+ */
+function firstRowHeight(element: HTMLElement): number {
+ const row = element.querySelector('[role="option"]');
+ return row instanceof HTMLElement ? row.offsetHeight : 0;
+}
diff --git a/packages/core/src/DateInput/useScrollSettle.ts b/packages/core/src/DateInput/useScrollSettle.ts
new file mode 100644
index 0000000000..06c53a69f0
--- /dev/null
+++ b/packages/core/src/DateInput/useScrollSettle.ts
@@ -0,0 +1,164 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useScrollSettle.ts
+ * @input A scroll container ref and a settle callback
+ * @output Calls back once, after scrolling (including momentum) stops
+ * @position Internal behavior hook; consumed by Wheel.tsx and MonthScroller.tsx
+ *
+ * A snap scroller commits its value when it comes to rest, so it needs a
+ * "scrolling stopped" signal. `scrollend` is that signal, but it is recent
+ * enough that mobile Safari below 26 does not have it — and it is exactly the
+ * browser this component targets. So: listen for `scrollend` where it exists,
+ * and fall back to a quiet-period timer everywhere else. The same
+ * belt-and-braces pattern is in core's `useScrollSpy`.
+ *
+ * ## The two things the timer must not mistake for rest
+ *
+ * A quiet period is a guess, and on iOS it guesses wrong twice unless it is
+ * told otherwise. Both mistakes were behind the same bug: opening the
+ * month/year wheels, flicking to an earlier month, and watching the month
+ * climb on its own afterwards — on real iOS and the simulator, never in
+ * Chrome.
+ *
+ * 1. **A finger resting mid-drag is not rest.** Hold a wheel still for a
+ * moment without lifting and the scroll events stop, so the timer fires
+ * and the value commits to whatever is under the band. Chrome hides this
+ * because it has `scrollend`, which does not fire until the touch is
+ * released.
+ *
+ * 2. **Momentum is not rest either.** iOS momentum runs on the UI thread and
+ * keeps going for a second or more after the finger is gone, and its scroll
+ * events arrive irregularly — the gaps in the slow tail routinely exceed
+ * any sane quiet period. Chrome's compositor-driven momentum fires evenly,
+ * so the same timer never trips there.
+ *
+ * A premature settle is not just a wrong value; it feeds back. The commit
+ * moves the value, the value moves the scroller back onto the committed row,
+ * that programmatic scroll does not stop the momentum still running
+ * underneath, and the fresh scroll events start the next premature settle —
+ * each one landing a row further along, which is why the month climbed.
+ *
+ * So: the settle waits for the touch to end, and then for a quiet period
+ * measured from the LAST scroll event, which is what makes it outlast
+ * momentum however long it runs. {@link useScrollSettle} also reports whether
+ * the scroller is at rest, so a caller can refuse to reposition one that is
+ * still moving.
+ *
+ * SYNC: When modified, update DateInputTouch.test.tsx.
+ */
+
+import {useEffect, useRef} from 'react';
+
+/**
+ * How long the scroller must be quiet before a settle is assumed. Long enough
+ * to outlast the browser's own snap animation (~150-300ms after the finger
+ * lifts), or a wheel would commit to whichever option it was passing rather
+ * than the one it settles on.
+ */
+export const SCROLL_QUIET_MS = 220;
+
+/** What {@link useScrollSettle} reports back about the scroller's state. */
+export type ScrollSettleState = {
+ /**
+ * False from the first touch until the scroller has genuinely stopped —
+ * momentum included. Read it before repositioning the scroller: doing that
+ * mid-flight fights the platform and, on iOS, restarts the cycle described
+ * in the file header.
+ */
+ isAtRestRef: React.RefObject<boolean>;
+};
+
+/**
+ * Run `onSettle` when `ref`'s element stops scrolling.
+ *
+ * @param ref - the scroll container
+ * @param onSettle - called with the settled element; may change every render
+ * @param isEnabled - skip attaching while false (e.g. a hidden panel)
+ */
+export function useScrollSettle(
+ ref: React.RefObject<HTMLElement | null>,
+ onSettle: (element: HTMLElement) => void,
+ isEnabled: boolean = true,
+): ScrollSettleState {
+ // The callback closes over render-fresh values (the option list, the current
+ // value); keeping it in a ref means the listeners attach once instead of
+ // re-attaching mid-scroll, which would drop an in-flight settle.
+ const onSettleRef = useRef(onSettle);
+ onSettleRef.current = onSettle;
+
+ const isAtRestRef = useRef(true);
+
+ useEffect(() => {
+ const element = ref.current;
+ if (element == null || !isEnabled) {
+ isAtRestRef.current = true;
+ return;
+ }
+
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let hasSettled = false;
+ let isTouching = false;
+
+ const settle = () => {
+ // A finger still on the glass is not rest, however quiet the scroller
+ // has gone. The release re-arms this.
+ if (hasSettled || isTouching) {
+ return;
+ }
+ hasSettled = true;
+ isAtRestRef.current = true;
+ clearTimeout(timer);
+ onSettleRef.current(element);
+ };
+
+ const arm = () => {
+ clearTimeout(timer);
+ timer = setTimeout(settle, SCROLL_QUIET_MS);
+ };
+
+ const onScroll = () => {
+ // A fresh scroll re-opens the window: whatever we settle on now is
+ // stale, and the settle that matters is the one after this gesture.
+ // Momentum keeps arriving here, so the quiet period is measured from
+ // the last of it however long it runs.
+ hasSettled = false;
+ isAtRestRef.current = false;
+ arm();
+ };
+
+ const onTouchStart = () => {
+ isTouching = true;
+ hasSettled = false;
+ isAtRestRef.current = false;
+ clearTimeout(timer);
+ };
+
+ const onTouchEnd = () => {
+ isTouching = false;
+ // Momentum may carry on from here and will re-arm this on its own; the
+ // timer covers the case where the finger lifted without a fling, which
+ // produces no further scroll events at all.
+ arm();
+ };
+
+ element.addEventListener('scroll', onScroll, {passive: true});
+ element.addEventListener('scrollend', settle);
+ element.addEventListener('touchstart', onTouchStart, {passive: true});
+ element.addEventListener('touchend', onTouchEnd, {passive: true});
+ element.addEventListener('touchcancel', onTouchEnd, {passive: true});
+
+ return () => {
+ clearTimeout(timer);
+ element.removeEventListener('scroll', onScroll);
+ element.removeEventListener('scrollend', settle);
+ element.removeEventListener('touchstart', onTouchStart);
+ element.removeEventListener('touchend', onTouchEnd);
+ element.removeEventListener('touchcancel', onTouchEnd);
+ };
+ }, [ref, isEnabled]);
+
+ return {isAtRestRef};
+}
diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts
index 8975453b0d..276b382228 100644
--- a/packages/core/src/utils/index.ts
+++ b/packages/core/src/utils/index.ts
@@ -47,6 +47,8 @@ export {
DATE_FORMAT_SHORT_WITH_WEEKDAY,
DATE_FORMAT_LONG,
DATE_FORMAT_MONTH_YEAR,
+ DATE_FORMAT_MONTH_ONLY,
+ DATE_FORMAT_WEEKDAY_ONLY,
DATE_FORMAT_SHORT,
DATE_FORMAT_SHORT_WITH_YEAR,
SHARED_DATE_FORMAT_OPTIONS,
diff --git a/packages/core/src/utils/plainDate.ts b/packages/core/src/utils/plainDate.ts
index 1c48964461..36ee5ea588 100644
--- a/packages/core/src/utils/plainDate.ts
+++ b/packages/core/src/utils/plainDate.ts
@@ -278,6 +278,22 @@ export const DATE_FORMAT_MONTH_YEAR: Intl.DateTimeFormatOptions = {
month: 'long',
};
+// e.g. "Sun" (locale-dependent) — the weekday on its own, abbreviated.
+//
+// This is CLDR's `abbreviated` width, which `Intl` reaches natively. Note
+// that Calendar's 2-letter header ("Su") is CLDR's *short* width, a
+// different thing that `Intl` cannot express at all — which is why that one
+// needs the generated lookup table beside it and this one does not.
+export const DATE_FORMAT_WEEKDAY_ONLY: Intl.DateTimeFormatOptions = {
+ weekday: 'short',
+};
+
+// e.g. "January" (locale-dependent) — the month on its own, for a control
+// that shows a list of months and carries the year separately.
+export const DATE_FORMAT_MONTH_ONLY: Intl.DateTimeFormatOptions = {
+ month: 'long',
+};
+
// e.g. "Jan 25" (locale-dependent)
export const DATE_FORMAT_SHORT: Intl.DateTimeFormatOptions = {
month: 'short',