An open source design system that's fully customizable and agent ready
TypeScript
fix(Wheel): a wheel that stops outside the bounds rests on the nearest value inside them (#8131)
Christopher Chedeau6658a4c8a31f
diff --git a/.changeset/wheel-nearest-valid.md b/.changeset/wheel-nearest-valid.mdnew file mode 100644index 0000000000..74bb222575--- /dev/null+++ b/.changeset/wheel-nearest-valid.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A picker wheel that stops on a value outside the bounds now settles on the nearest value inside them. Before, it bounced back to the value it started from. This applies to the wheels in the TimeInput, DateTimeInput and DateInput bottom sheets. For example, with `min="09:00"`, dragging the hour wheel from 10 to 7 settles on 9, as the iOS time picker does. A stop on a value inside the bounds is unchanged. Opening a sheet on a value outside the bounds commits nothing. When a bound changes a wheel's value while the sheet is open, as when the meridiem wheel turns past the maximum, that wheel turns onto the new value instead of jumping there. Under reduced motion, the wheel's own scrolls no longer glide. On a touch screen this travel, the step from an arrow key and a click on a row cross-fade, the rows landing while they are faded out; with a mouse or a trackpad they land at once, except the travel after a touch drag, which cross-fades on any screen.++@vjeuxdiff --git a/apps/storybook/stories/TimeInput.stories.tsx b/apps/storybook/stories/TimeInput.stories.tsxindex eaa0b16fd3..842e390fcf 100644--- a/apps/storybook/stories/TimeInput.stories.tsx+++ b/apps/storybook/stories/TimeInput.stories.tsx@@ -224,6 +224,27 @@ export const WithMinMax: Story = {},};+/**+ * The bottom-sheet wheels with bounds: hours outside 9 AM - 5 PM stay on the+ * wheel, greyed out, and a wheel that stops on one goes on to the nearest+ * hour inside the bounds.+ */+export const BottomSheetWithMinMax: Story = {+ render: args => {+ const [value, setValue] = useState<ISOTimeString | undefined>(+ '10:00' as ISOTimeString,+ );+ return <TimeInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Appointment time',+ presentation: 'bottom-sheet',+ min: '09:00' as ISOTimeString,+ max: '17:00' as ISOTimeString,+ description: 'Business hours: 9 AM - 5 PM',+ },+};+export const WithIncrement: Story = {render: args => {const [value, setValue] = useState<ISOTimeString | undefined>(diff --git a/docs/specs/components/DateInput/DateInput.spec.md b/docs/specs/components/DateInput/DateInput.spec.mdindex b5622dd3b2..bcf1212a5f 100644--- a/docs/specs/components/DateInput/DateInput.spec.md+++ b/docs/specs/components/DateInput/DateInput.spec.md@@ -18,13 +18,15 @@ verified_by:packages/core/src/DateInput/DateInputTouch.test.tsx,packages/core/src/DateInput/NativeDateField.test.tsx,packages/core/src/DateInput/Presentation.test.tsx,+ packages/core/src/DateInput/Wheel.test.tsx,+ packages/core/src/DateInput/__tests__/WheelRest.a11y.chromium.spec.ts,packages/core/src/__tests__/BusyOwnerAnnouncement.test.tsx,packages/core/src/theme/themingTargets.test.ts,scripts/check-knowledge.mjs,]modules: []families: [family:input-fields, family:overlay-dismissal]-design_specs: []+design_specs: [design:reduced-motion/DR2, design:reduced-motion/DR3]architecture:[architecture:component-theming-surface,@@ -41,15 +43,15 @@ system_specs:## Contract at a glance-| Area | Contract |-| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| Public contract | None. API shape and defaults are as shipped; every surface follows the input-field `changeAction`, disabled, and busy contracts. |-| Behavior | `presentation` selects the picker surface; an omitted value is `adaptive-native`; `presentation` wins over deprecated `nativePicker`; every committed path emits the same controlled ISO-date value and action feedback. |-| End-user impact | People type or pick one date using a surface suited to the primary pointer. Disabled and busy fields stay focusable; a busy field keeps its ordinary paint with a Spinner while new commits are blocked. |-| Builder impact | None. `changeAction` runs after `onChange` with optimistic busy feedback on every surface. |-| Compatibility/readiness | Records shipped behavior; no API, default, or DOM change. Caller handlers while disabled, fixed field height, the English-only typed parser, a clear control that drops focus, month paging in the touch calendar, and the touch wheels' rest, turn, and scroll input are listed under Current-state impact. |-| Review checks | Reject a surface-mapping change, lost constraint, callback-order change, unlabeled field, native `disabled`, disabled paint on a busy-only field, unreachable disabled reason, changed close behavior, or a theming target placed on the wrong owner. |-| Governing rules | `spec:AST-043/FR1–FR5`; `spec:AST-085/FR1–FR6`; `spec:AST-086/FR3, FR4, FR6, FR8`; `family:input-fields/FR1–FR6, FR8–FR11`; `family:overlay-dismissal/FR1–FR7`, including its recorded BottomSheet adoption gap; `spec:AST-020/FR15`; `spec:AST-102/FR4`; the four architecture records linked above. |+| Area | Contract |+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | None. API shape and defaults are as shipped; every surface follows the input-field `changeAction`, disabled, and busy contracts. |+| Behavior | `presentation` selects the picker surface; an omitted value is `adaptive-native`; `presentation` wins over deprecated `nativePicker`; every committed path emits the same controlled ISO-date value and action feedback. |+| End-user impact | People type or pick one date using a surface suited to the primary pointer. Disabled and busy fields stay focusable; a busy field keeps its ordinary paint with a Spinner while new commits are blocked. |+| Builder impact | None. `changeAction` runs after `onChange` with optimistic busy feedback on every surface. |+| Compatibility/readiness | Records shipped behavior; no API, default, or DOM change. Caller handlers while disabled, fixed field height, the English-only typed parser, a clear control that drops focus, month paging in the touch calendar, and the touch wheels' scroll input are listed under Current-state impact. |+| Review checks | Reject a surface-mapping change, lost constraint, callback-order change, unlabeled field, native `disabled`, disabled paint on a busy-only field, unreachable disabled reason, changed close behavior, or a theming target placed on the wrong owner. |+| Governing rules | `spec:AST-043/FR1–FR5`; `spec:AST-085/FR1–FR6`; `spec:AST-086/FR3, FR4, FR6, FR8`; `family:input-fields/FR1–FR6, FR8–FR11`; `family:overlay-dismissal/FR1–FR7`, including its recorded BottomSheet adoption gap; `spec:AST-020/FR15`; `spec:AST-102/FR4`; the four architecture records linked above. |This table is a review projection; the body below is authoritative.@@ -138,8 +140,8 @@ Consumer migration instructions belong in consumer docs and release notes.| FR10 | Standalone mode MUST compose Field; admitted InputGroup mode MUST remove competing Field chrome while preserving name, description, value, keyboard, focus, and editing semantics. The field has no root styling props; `control*` reaches the control box on every surface, and `container*` reaches the Field box where one renders (in a horizontal-labels FormLayout none renders and `container*` warns; inside an InputGroup it is dropped) (`family:input-fields` FR10). The field height is the shared element size for its size and MUST grow with a set text size (`spec:AST-102` FR4). Implementation gap: the height is fixed. | `family:input-fields` FR3, FR10; `spec:AST-102` FR4; current source and tests || FR11 | Clear MUST emit `undefined` through the ordinary change pipeline. The pointer and bottom-sheet surfaces restore field focus using their shipped timing; the native surface MUST NOT reclaim focus because doing so reopens the OS picker. Implementation gap: when the field becomes disabled or busy while its clear control holds focus, the control unmounts and focus falls to the document body; `spec:AST-085/FR4` requires focus to stay or move to a destination this record names. | Current source and focused clear tests; `spec:AST-085/FR4` || FR12 | No surface renders native `disabled`. A disabled field MUST stay focusable with `aria-disabled`, block typing, picking, clearing, and opening, describe its disabled reason when one is given, and take disabled paint. While busy (`isLoading` or a pending Action) the pointer and bottom-sheet surfaces expose `aria-disabled` and `aria-busy`, stay focusable, and block new commits; the native surface does the same for `isLoading`, and during a pending Action stays editable so the OS picker remains attached but rejects additional commits until the Action settles. A busy field that is not disabled keeps its ordinary paint and Spinner, shows no hover ring while commits are blocked, and keeps its keyboard focus ring. Caller handlers other than focus and blur MUST NOT run while the field is disabled (`spec:AST-085` FR2). Implementation gap: only a caller `onClick` is skipped while disabled; caller key, paste, and pointer handlers (such as `onKeyDown`, `onKeyUp`, `onPaste`, and `onPointerDown`) still run on every surface, the native field included. | `spec:AST-085/FR1–FR6`; `family:input-fields/FR4–FR6`; `family:buttons/FR4`; current source and focused tests |-| FR13 | A bottom-sheet picker wheel that comes to rest on a disabled row (outside `min`/`max`) MUST continue to the nearest enabled row, a tie going toward the committed row, and select it there. A wheel resting on its committed row MUST NOT select or commit, even when that row is outside the bounds, so opening a bounded sheet never changes an untouched value: a committed value outside the bounds stays, and an empty field stays empty. This holds for every wheel in the DateInput, TimeInput, and DateTimeInput sheets. Implementation gap: a wheel that rests on a disabled row returns to its committed row instead of continuing to the nearest enabled row. | DEC-1; UIDatePicker on the iOS 26.2 simulator; current source |-| FR14 | A shown bottom-sheet picker wheel whose value changes from outside, as when a bound clamps the time after another wheel turned, MUST turn onto the new row rather than jump to it. Implementation gap: a shown wheel jumps to a value changed from outside. | UIDatePicker on the iOS 26.2 simulator; current source |+| FR13 | A bottom-sheet picker wheel that comes to rest on a disabled row (outside `min`/`max`) MUST continue to the nearest enabled row, a tie going toward the committed row, and select it there. A wheel resting on its committed row MUST NOT select or commit, even when that row is outside the bounds, so opening a bounded sheet never changes an untouched value: a committed value outside the bounds stays, and an empty field stays empty. This holds for every wheel in the DateInput, TimeInput, and DateTimeInput sheets. | DEC-1; UIDatePicker on the iOS 26.2 simulator; current source |+| FR14 | A shown bottom-sheet picker wheel whose value changes from outside, as when a bound clamps the time after another wheel turned, MUST turn onto the new row rather than jump to it. | UIDatePicker on the iOS 26.2 simulator; current source || FR15 | Under a coarse primary pointer, a sheet wheel's pan takes a trackpad's two-finger scroll, as `spec:AST-094` FR43 allows a record to grant: the rows follow the fingers, coast on at the lift with the fingers' last speed, and rest on a row by FR13. A mouse-wheel notch turns the wheel one row, as an arrow key does, with no coast. A ctrl-scroll stays the page's zoom (`spec:AST-094` FR43). Implementation gap: the wheel is the browser's scroll-snap column for both inputs, so a trackpad's momentum runs at the browser's rate and a mouse-wheel notch moves the column by the browser's scroll step, several rows. | `spec:AST-094` FR43; current source |### Allowed variation@@ -301,26 +303,26 @@ clear-glyph target of its own.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |-| FR1, ORD2 | `DateInput.test.tsx` "displays formatted date when value is provided", "calls onChange on blur when input is valid", "calls onChange with undefined when input is cleared and blurred", "clears pending input when value changes externally"; `NativeDateField.test.tsx` "keeps the control's own value ISO", "fires onChange with the ISO date the control reports" | Typed, cleared, external value; native | A committed value kept beside `value`, a non-ISO change, or pending text that survives an external change fails. | `audit:DateInput/behavior` |-| FR2, FR3, FR4, ORD1 | `Presentation.test.tsx` cases; `DateInputTouch.test.tsx` surface-selection cases; `NativeDateField.test.tsx` nativePicker cases | Each presentation on fine and coarse pointers; deprecated mappings; tablet and touchscreen laptop | A wrong surface, a lost deprecated mapping, `nativePicker` winning, or width-based resolution fails. Evidence gap: no test asserts the development warning. | `audit:DateInput/behavior` |-| FR5 | `DateInput.test.tsx` min, max, and dateConstraints typed cases; `DateInputTouch.test.tsx` "disables days outside min/max and refuses to commit them", "honors custom date constraints"; `NativeDateField.test.tsx` "refuses an out-of-range date and announces it", "refuses a date dateConstraints rejects" | Typed, sheet, native; bounds and predicates | A constrained date that commits on any surface fails. Evidence gap: no test asserts constraints on a popover Calendar pick. | `audit:DateInput/behavior` |-| FR6 | `DateInput.test.tsx` format cases, including "updates when the InternationalizationProvider locale changes (#5074)" and "does not apply format to in-progress typed input"; `NativeDateField.test.tsx` format and locale cases; `DateInputTouch.test.tsx` "updates the field and open picker when the provider locale changes" | Named and function formats; locale change | A format that ignores the locale or rewrites typed text fails. Evidence gap: no test types a localized month name or non-ASCII digits (the FR6 gap). | `audit:DateInput/i18n` |-| FR7, ORD3 | `DateInput.test.tsx` "runs changeAction after onChange for a typed date"; `NativeDateField.test.tsx` "runs changeAction after onChange and exposes the pending state"; `DateInputTouch.test.tsx` "runs changeAction and shows a busy state"; `BusyOwnerAnnouncement.test.tsx` DateInput cases; `DateInputTouch.test.tsx` "announces a busy start from a pick inside the open sheet, not behind it (spec:AST-086 FR8, Platform support)" | Typed, native, sheet | An Action before `onChange`, a missing busy state, or a missing busy announcement fails. | `audit:DateInput/behavior` |-| FR8, AR2 | `DateInput.test.tsx` "opens the calendar popover on ArrowDown (keyboard, forms-13)", "opens the calendar popover on Alt+ArrowDown (keyboard, forms-13)", "input has aria-expanded attribute", "combobox input has aria-haspopup=\"dialog\" attribute", "moves focus into the calendar on each open from the toggle"; `DateInputTouch.test.tsx` "opens from the keyboard, APG combobox style"; `DateInput.test.tsx` "press inside and outside the open calendar" cases | Pointer and touch fields | A missing open path, combobox state, or focus move fails. Evidence gap: no test asserts Escape outside IME composition on the popover. | `audit:DateInput/accessibility` |-| FR9 | `DateInputTouch.test.tsx` "commits the tapped day and LEAVES the sheet open", "lets a second tap correct the first, still without closing", "Save closes the sheet without touching the value" | Sheet picks and Save | A sheet that closes on a pick or a Save that changes the value fails. Evidence gap: no test asserts that a popover Calendar pick closes the popover. | `audit:DateInput/behavior` |-| FR10 | `DateInput.fr10.test.tsx` styling and per-surface cases ("has no root styling props and has the container* and control* parts", "rejects root xstyle, className, and style at compile time", "keeps control* on the control box in a horizontal-labels FormLayout") and handler-composition cases; `DateInput.test.tsx` InputGroup cases; `DateInputTouch.test.tsx` "drops the Field wrapper inside an InputGroup" | Standalone, grouped, horizontal labels; every surface | A root styling prop, `control*` off the control box, or Field chrome inside a group fails. Evidence gap: no test asserts the field height or its growth with text size (the FR10 gap). | `audit:DateInput/layout` |-| FR11, ORD4 | `DateInput.test.tsx` hasClear cases; `DateInputTouch.test.tsx` "clears from the field", "returns focus to the field without letting the page scroll"; `NativeDateField.test.tsx` "clears the value without taking focus back", "runs clear through changeAction after onChange" | Pointer, sheet, native clear | A clear that does not emit `undefined`, a native clear that takes focus, or a clear shown while disabled fails. Evidence gap: no test covers the clear control unmounting under focus (the FR11 gap). | `audit:DateInput/behavior` |-| FR12, AR4 | `DateInput.test.tsx` disabled, loading, and disabledMessage cases (including "does not call a caller onClick while disabled (AST-085 FR2)" and "links the reason tooltip from the calendar button too (AST-085 FR5)"); `DateInputTouch.test.tsx` open-sheet disablement and disabled cases; `NativeDateField.test.tsx` "keeps a disabled control focusable and its toggle inert (AST-085 FR1, FR2)", "does not call a caller onClick while disabled (AST-085 FR2)"; `DateInput.test.tsx` disabled theme-state cases | Disabled with and without a reason; loading; open picker becoming disabled | Native `disabled`, a change or open while disabled, a caller `onClick` while disabled, a reason not linked from each focusable control, or a missing `aria-busy` fails. Evidence gap: no test asserts that caller key, paste, or pointer handlers are skipped while disabled (the FR12 gap) or the busy-only paint. | `audit:DateInput/accessibility` |-| AR1, AR3, AR5 | `DateInput.test.tsx` label, required, description, status, and invalid-input cases ("announces an alert message when typed input is invalid", "resolves the invalid-date announcement from the i18n catalog"); `NativeDateField.test.tsx` "keeps the overlay out of the accessibility tree", "keeps the field labelled, required-marked, and ref-forwarded"; `DateInputTouch.test.tsx` "associates the label natively, so the field is named without ARIA" | Every surface | A missing label, required, description, status, or invalid announcement, or an exposed native overlay, fails. | `audit:DateInput/accessibility` |-| AR6, AR8, PR1 | `DateInputTouch.test.tsx` calendar-surface cases ("mounts a window of months around the visible one, not the whole century", "leaves exactly one day per month tab-reachable", "gives a spilled date no tab stop in the pane that borrows it", "moves keyboard focus by date, across the month boundary", "follows the reading direction under RTL: ArrowLeft moves to the next day", "moves a week at a time with the vertical arrows", "labels the columns with three-letter weekday names", "marks the selection and today") and wheel cases ("is a single tab stop driven by the arrow keys", "shows exactly one footer action, and only the visible one is reachable") | Touch calendar and wheels; RTL | A second Tab stop per month, a wrong arrow move, reversed RTL arrows, an unbounded month window, or more than one reachable footer action fails. Evidence gap: no test asserts Home, End, PageUp, PageDown, Shift+PageUp, Shift+PageDown (the AR8 gap), or Enter and Space on a day. | `audit:DateInput/accessibility` |-| AR7 | `apps/storybook/rtl-audit/targets.json` DateInput entry; `DateInputTouch.test.tsx` RTL scroll-offset cases | RTL | A changed audit target or RTL offset fails. | `audit:DateInput/rtl` |-| PR2 | `MonthScrollerSettle.test.tsx` cases; `DateInputTouch.test.tsx` "a rest position between two months" cases | Settle and re-snap | A scroller that never settles or corrects mid-gesture fails. Evidence gap: no test asserts listener, frame, and observer cleanup on unmount, drags a month pager, or counts the visible-month reports per half-month (the PR2 gap). | `audit:DateInput/behavior` |-| FR13 | `DateInputTouch.test.tsx` "bounds the year wheel to the reachable range" (rows outside the bounds are disabled). Evidence gap: no test rests a wheel on a disabled row, breaks a tie, or opens a sheet on a value outside the bounds (the FR13 gap). | Below the minimum, above the maximum, on another disabled row; opened on a value outside the bounds and rested back on it after a drag; DateInput, TimeInput, and DateTimeInput sheets | A wheel that returns to its committed row, skips the nearest enabled row, breaks a tie away from the committed row, or commits on opening or on a rest back on its committed row fails. | `audit:DateInput/behavior` |-| FR14 | Evidence gap: no test changes a shown wheel's value from outside and follows the wheel frame by frame (the FR14 gap). | A bound clamping the value of a shown wheel after another wheel turned, in DateInput, TimeInput, and DateTimeInput sheets | A wheel that jumps to the new row fails. | `audit:DateInput/behavior` |-| FR15 | `WheelPinchZoom.a11y.chromium.spec.ts` "a pinch over an open picker wheel zooms the page and changes no value"; `DateInputTouch.test.tsx` "leaves a two-finger pinch to the page over the wheels". Evidence gap: no test drives a wheel with trackpad or mouse-wheel streams (the FR15 gap). | A trackpad scroll and its lift; a slow stopped trackpad drag; one and three mouse-wheel notches; a ctrl-scroll over an open wheel | A trackpad scroll that does not follow, a lift that stops dead or coasts at the browser's rate, a notch that turns more or less than one row or coasts, or a ctrl-scroll that turns the wheel fails. | `audit:DateInput/behavior` |-| Theming anatomy | `DateInput.test.tsx` clear-icon and calendar-toggle icon theme-target cases; `themingTargets.test.ts`; `scripts/check-knowledge.mjs` | Toggle, clear glyph, disabled root | A missing or moved target, or a stale anatomy mapping, fails. | `audit:DateInput/theming` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |+| FR1, ORD2 | `DateInput.test.tsx` "displays formatted date when value is provided", "calls onChange on blur when input is valid", "calls onChange with undefined when input is cleared and blurred", "clears pending input when value changes externally"; `NativeDateField.test.tsx` "keeps the control's own value ISO", "fires onChange with the ISO date the control reports" | Typed, cleared, external value; native | A committed value kept beside `value`, a non-ISO change, or pending text that survives an external change fails. | `audit:DateInput/behavior` |+| FR2, FR3, FR4, ORD1 | `Presentation.test.tsx` cases; `DateInputTouch.test.tsx` surface-selection cases; `NativeDateField.test.tsx` nativePicker cases | Each presentation on fine and coarse pointers; deprecated mappings; tablet and touchscreen laptop | A wrong surface, a lost deprecated mapping, `nativePicker` winning, or width-based resolution fails. Evidence gap: no test asserts the development warning. | `audit:DateInput/behavior` |+| FR5 | `DateInput.test.tsx` min, max, and dateConstraints typed cases; `DateInputTouch.test.tsx` "disables days outside min/max and refuses to commit them", "honors custom date constraints"; `NativeDateField.test.tsx` "refuses an out-of-range date and announces it", "refuses a date dateConstraints rejects" | Typed, sheet, native; bounds and predicates | A constrained date that commits on any surface fails. Evidence gap: no test asserts constraints on a popover Calendar pick. | `audit:DateInput/behavior` |+| FR6 | `DateInput.test.tsx` format cases, including "updates when the InternationalizationProvider locale changes (#5074)" and "does not apply format to in-progress typed input"; `NativeDateField.test.tsx` format and locale cases; `DateInputTouch.test.tsx` "updates the field and open picker when the provider locale changes" | Named and function formats; locale change | A format that ignores the locale or rewrites typed text fails. Evidence gap: no test types a localized month name or non-ASCII digits (the FR6 gap). | `audit:DateInput/i18n` |+| FR7, ORD3 | `DateInput.test.tsx` "runs changeAction after onChange for a typed date"; `NativeDateField.test.tsx` "runs changeAction after onChange and exposes the pending state"; `DateInputTouch.test.tsx` "runs changeAction and shows a busy state"; `BusyOwnerAnnouncement.test.tsx` DateInput cases; `DateInputTouch.test.tsx` "announces a busy start from a pick inside the open sheet, not behind it (spec:AST-086 FR8, Platform support)" | Typed, native, sheet | An Action before `onChange`, a missing busy state, or a missing busy announcement fails. | `audit:DateInput/behavior` |+| FR8, AR2 | `DateInput.test.tsx` "opens the calendar popover on ArrowDown (keyboard, forms-13)", "opens the calendar popover on Alt+ArrowDown (keyboard, forms-13)", "input has aria-expanded attribute", "combobox input has aria-haspopup=\"dialog\" attribute", "moves focus into the calendar on each open from the toggle"; `DateInputTouch.test.tsx` "opens from the keyboard, APG combobox style"; `DateInput.test.tsx` "press inside and outside the open calendar" cases | Pointer and touch fields | A missing open path, combobox state, or focus move fails. Evidence gap: no test asserts Escape outside IME composition on the popover. | `audit:DateInput/accessibility` |+| FR9 | `DateInputTouch.test.tsx` "commits the tapped day and LEAVES the sheet open", "lets a second tap correct the first, still without closing", "Save closes the sheet without touching the value" | Sheet picks and Save | A sheet that closes on a pick or a Save that changes the value fails. Evidence gap: no test asserts that a popover Calendar pick closes the popover. | `audit:DateInput/behavior` |+| FR10 | `DateInput.fr10.test.tsx` styling and per-surface cases ("has no root styling props and has the container* and control* parts", "rejects root xstyle, className, and style at compile time", "keeps control* on the control box in a horizontal-labels FormLayout") and handler-composition cases; `DateInput.test.tsx` InputGroup cases; `DateInputTouch.test.tsx` "drops the Field wrapper inside an InputGroup" | Standalone, grouped, horizontal labels; every surface | A root styling prop, `control*` off the control box, or Field chrome inside a group fails. Evidence gap: no test asserts the field height or its growth with text size (the FR10 gap). | `audit:DateInput/layout` |+| FR11, ORD4 | `DateInput.test.tsx` hasClear cases; `DateInputTouch.test.tsx` "clears from the field", "returns focus to the field without letting the page scroll"; `NativeDateField.test.tsx` "clears the value without taking focus back", "runs clear through changeAction after onChange" | Pointer, sheet, native clear | A clear that does not emit `undefined`, a native clear that takes focus, or a clear shown while disabled fails. Evidence gap: no test covers the clear control unmounting under focus (the FR11 gap). | `audit:DateInput/behavior` |+| FR12, AR4 | `DateInput.test.tsx` disabled, loading, and disabledMessage cases (including "does not call a caller onClick while disabled (AST-085 FR2)" and "links the reason tooltip from the calendar button too (AST-085 FR5)"); `DateInputTouch.test.tsx` open-sheet disablement and disabled cases; `NativeDateField.test.tsx` "keeps a disabled control focusable and its toggle inert (AST-085 FR1, FR2)", "does not call a caller onClick while disabled (AST-085 FR2)"; `DateInput.test.tsx` disabled theme-state cases | Disabled with and without a reason; loading; open picker becoming disabled | Native `disabled`, a change or open while disabled, a caller `onClick` while disabled, a reason not linked from each focusable control, or a missing `aria-busy` fails. Evidence gap: no test asserts that caller key, paste, or pointer handlers are skipped while disabled (the FR12 gap) or the busy-only paint. | `audit:DateInput/accessibility` |+| AR1, AR3, AR5 | `DateInput.test.tsx` label, required, description, status, and invalid-input cases ("announces an alert message when typed input is invalid", "resolves the invalid-date announcement from the i18n catalog"); `NativeDateField.test.tsx` "keeps the overlay out of the accessibility tree", "keeps the field labelled, required-marked, and ref-forwarded"; `DateInputTouch.test.tsx` "associates the label natively, so the field is named without ARIA" | Every surface | A missing label, required, description, status, or invalid announcement, or an exposed native overlay, fails. | `audit:DateInput/accessibility` |+| AR6, AR8, PR1 | `DateInputTouch.test.tsx` calendar-surface cases ("mounts a window of months around the visible one, not the whole century", "leaves exactly one day per month tab-reachable", "gives a spilled date no tab stop in the pane that borrows it", "moves keyboard focus by date, across the month boundary", "follows the reading direction under RTL: ArrowLeft moves to the next day", "moves a week at a time with the vertical arrows", "labels the columns with three-letter weekday names", "marks the selection and today") and wheel cases ("is a single tab stop driven by the arrow keys", "shows exactly one footer action, and only the visible one is reachable") | Touch calendar and wheels; RTL | A second Tab stop per month, a wrong arrow move, reversed RTL arrows, an unbounded month window, or more than one reachable footer action fails. Evidence gap: no test asserts Home, End, PageUp, PageDown, Shift+PageUp, Shift+PageDown (the AR8 gap), or Enter and Space on a day. | `audit:DateInput/accessibility` |+| AR7 | `apps/storybook/rtl-audit/targets.json` DateInput entry; `DateInputTouch.test.tsx` RTL scroll-offset cases | RTL | A changed audit target or RTL offset fails. | `audit:DateInput/rtl` |+| PR2 | `MonthScrollerSettle.test.tsx` cases; `DateInputTouch.test.tsx` "a rest position between two months" cases | Settle and re-snap | A scroller that never settles or corrects mid-gesture fails. Evidence gap: no test asserts listener, frame, and observer cleanup on unmount, drags a month pager, or counts the visible-month reports per half-month (the PR2 gap). | `audit:DateInput/behavior` |+| FR13 | `Wheel.test.tsx`, the wheel every sheet renders: "stopping below the minimum travels on to the minimum and commits it there", "stopping past the maximum travels back to the maximum", "a stop on another disabled row still travels to the bounds", "opening on a value outside the bounds parks on it without travelling or committing", "a drag that comes back to rest on a committed value outside the bounds stays there and commits nothing", "never commits a disabled row, even with nowhere valid to go", and `nearestEnabledIndex` "breaks a tie toward the committed row"; `WheelRest.a11y.chromium.spec.ts` in the TimeInput sheet: "a wheel dragged below the minimum comes to rest on the minimum", "a wheel dragged onto a row inside the bounds commits that row"; `DateInputTouch.test.tsx` "bounds the year wheel to the reachable range" (rows outside the bounds are disabled). | Below the minimum, above the maximum, on another disabled row; opened on a value outside the bounds and rested back on it after a drag; DateInput, TimeInput, and DateTimeInput sheets | A wheel that returns to its committed row, skips the nearest enabled row, breaks a tie away from the committed row, or commits on opening or on a rest back on its committed row fails. | `audit:DateInput/behavior` |+| FR14 | `Wheel.test.tsx` "turns onto a value set while it is shown, as a bound clamping the time after another wheel turned"; `WheelRest.a11y.chromium.spec.ts` in the TimeInput sheet: "a meridiem change past the maximum turns the hour wheel onto it, frame by frame". | A bound clamping the value of a shown wheel after another wheel turned, in DateInput, TimeInput, and DateTimeInput sheets | A wheel that jumps to the new row fails. | `audit:DateInput/behavior` |+| FR15 | `WheelPinchZoom.a11y.chromium.spec.ts` "a pinch over an open picker wheel zooms the page and changes no value"; `DateInputTouch.test.tsx` "leaves a two-finger pinch to the page over the wheels". Evidence gap: no test drives a wheel with trackpad or mouse-wheel streams (the FR15 gap). | A trackpad scroll and its lift; a slow stopped trackpad drag; one and three mouse-wheel notches; a ctrl-scroll over an open wheel | A trackpad scroll that does not follow, a lift that stops dead or coasts at the browser's rate, a notch that turns more or less than one row or coasts, or a ctrl-scroll that turns the wheel fails. | `audit:DateInput/behavior` |+| Theming anatomy | `DateInput.test.tsx` clear-icon and calendar-toggle icon theme-target cases; `themingTargets.test.ts`; `scripts/check-knowledge.mjs` | Toggle, clear glyph, disabled root | A missing or moved target, or a stale anatomy mapping, fails. | `audit:DateInput/theming` |## Current-state impact@@ -337,10 +339,6 @@ clear-glyph target of its own.- **Month paging (AR8).** PageUp and PageDown do not page the touch calendar bya month, and Shift+PageUp and Shift+PageDown do not move it by a year, as AR8states they do.-- **Wheel rest (FR13).** A sheet wheel that rests on a disabled row returns to- its committed row, so reaching the bound takes another scroll.-- **Wheel turn (FR14).** A shown sheet wheel jumps, rather than turns, to a value- changed from outside.- **Trackpad and mouse wheel on a sheet wheel (FR15).** A trackpad's momentumruns at the browser's rate, and one mouse-wheel notch moves the wheel severalrows.diff --git a/packages/core/src/DateInput/Wheel.test.tsx b/packages/core/src/DateInput/Wheel.test.tsxnew file mode 100644index 0000000000..ba75cac259--- /dev/null+++ b/packages/core/src/DateInput/Wheel.test.tsx@@ -0,0 +1,478 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Wheel.test.tsx+ * @input Uses Vitest, Testing Library and the Wheel column+ * @output Proves where a wheel rests when it stops on a row it cannot commit+ * @position Unit coverage for Wheel.tsx's rest rule; the wheels inside the+ * DateInput, DateTimeInput and TimeInput sheets are covered by their own+ * touch suites+ */++import {act, fireEvent, render, screen} from '@testing-library/react';+import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest';+import {nearestEnabledIndex, Wheel, type WheelOption} from './Wheel';+import {SCROLL_QUIET_MS} from './useScrollSettle';++const ROW = 28;++beforeAll(() => {+ // jsdom implements no scrolling; the wheel parks its committed row on mount.+ Element.prototype.scrollTo = vi.fn();+});++/** Hours 0-23 with 09:00-17:00 bounds: 0-8 and 18-23 are disabled. */+const HOURS: WheelOption[] = Array.from({length: 24}, (_, hour) => ({+ value: hour,+ label: String(hour).padStart(2, '0'),+ isDisabled: hour < 9 || hour > 17,+}));++describe('nearestEnabledIndex', () => {+ it('keeps an enabled row', () => {+ expect(nearestEnabledIndex(HOURS, 12, 10)).toBe(12);+ });++ it('goes to the bound on the side the wheel stopped on', () => {+ expect(nearestEnabledIndex(HOURS, 7, 10)).toBe(9);+ expect(nearestEnabledIndex(HOURS, 0, 10)).toBe(9);+ expect(nearestEnabledIndex(HOURS, 20, 10)).toBe(17);+ expect(nearestEnabledIndex(HOURS, 23, 10)).toBe(17);+ });++ it('breaks a tie toward the committed row', () => {+ const gap: WheelOption[] = [+ {value: 0, label: '0'},+ {value: 1, label: '1', isDisabled: true},+ {value: 2, label: '2'},+ ];+ expect(nearestEnabledIndex(gap, 1, 0)).toBe(0);+ expect(nearestEnabledIndex(gap, 1, 2)).toBe(2);+ });++ it('stays on the committed row when no row is enabled', () => {+ const none = HOURS.map(option => ({...option, isDisabled: true}));+ expect(nearestEnabledIndex(none, 3, 10)).toBe(10);+ });+});++describe('Wheel — where it comes to rest', () => {+ afterEach(() => {+ // @ts-expect-error - deleting the shadow restores Element's own getter+ delete HTMLElement.prototype.offsetHeight;+ });++ /**+ * jsdom has no layout, so each row gets a height here. This setup records+ * the scroller's scrollTop and scrollTo, so a test can stop the wheel on any+ * row.+ */+ function renderWheel(value: number) {+ Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {+ configurable: true,+ get(this: HTMLElement) {+ return this.getAttribute('role') === 'option' ? ROW : 0;+ },+ });+ const onChange = vi.fn();+ const scrollTo = vi.fn();+ const {rerender} = render(+ <Wheel label="Hour" options={HOURS} value={value} onChange={onChange} />,+ );+ const scroller = screen.getByRole('listbox', {name: 'Hour'});+ let top = value * ROW;+ Object.defineProperty(scroller, 'scrollTop', {+ configurable: true,+ get: () => top,+ set: (next: number) => {+ top = next;+ },+ });+ scroller.scrollTo = ((options: ScrollToOptions) => {+ scrollTo(options);+ }) as HTMLElement['scrollTo'];+ /** The wheel scrolls to `row` without stopping there (a drag passing it). */+ const moveTo = (row: number) => {+ act(() => {+ top = row * ROW;+ scroller.dispatchEvent(new Event('scroll'));+ });+ };+ /** The wheel scrolls to `row` and stops there. */+ const stopOn = (row: number) => {+ act(() => {+ top = row * ROW;+ scroller.dispatchEvent(new Event('scroll'));+ scroller.dispatchEvent(new Event('scrollend'));+ });+ };+ return {onChange, scrollTo, moveTo, stopOn, rerender};+ }++ it('commits an enabled row it stops on', () => {+ const {onChange, scrollTo, stopOn} = renderWheel(10);+ stopOn(12);+ expect(scrollTo).not.toHaveBeenCalled();+ expect(onChange).toHaveBeenCalledWith(12);+ });++ it('stopping below the minimum travels on to the minimum and commits it there', () => {+ const {onChange, scrollTo, stopOn} = renderWheel(10);+ stopOn(7);+ // Not back to the committed 10: on to 9, the nearest hour in bounds.+ expect(scrollTo).toHaveBeenCalledWith({top: 9 * ROW, behavior: 'smooth'});+ expect(onChange).not.toHaveBeenCalled();+ // The second rest, on 9, commits it.+ stopOn(9);+ expect(onChange).toHaveBeenCalledWith(9);+ });++ it('stopping past the maximum travels back to the maximum', () => {+ const {onChange, scrollTo, stopOn} = renderWheel(10);+ stopOn(21);+ expect(scrollTo).toHaveBeenCalledWith({+ top: 17 * ROW,+ behavior: 'smooth',+ });+ stopOn(17);+ expect(onChange).toHaveBeenCalledWith(17);+ });++ it('opening on a value outside the bounds parks on it without travelling or committing', () => {+ // 08:00 with 09:00-17:00 bounds: the sheet opens, the wheel parks on 8,+ // and the browser reports that scroll's rest. Nobody touched the wheel,+ // so nothing may move or commit.+ const {onChange, scrollTo, stopOn} = renderWheel(8);+ stopOn(8);+ expect(scrollTo).not.toHaveBeenCalled();+ expect(onChange).not.toHaveBeenCalled();+ });++ it('a drag that comes back to rest on a committed value outside the bounds stays there and commits nothing (component:DateInput FR13)', () => {+ // 08:00 with 09:00-17:00 bounds: a drag carries the wheel to 10 and back+ // onto 8 before it rests. Resting on the committed row is not a stop to+ // correct, even outside the bounds: it stays on 8 and commits nothing.+ const {onChange, scrollTo, moveTo, stopOn} = renderWheel(8);+ moveTo(10);+ stopOn(8);+ expect(scrollTo).not.toHaveBeenCalled();+ expect(onChange).not.toHaveBeenCalled();+ });++ it('turns onto a value set while it is shown, as a bound clamping the time after another wheel turned (component:DateInput FR14)', () => {+ // 22:00 is past the 17:00 maximum, so the field clamps to 17:00. The hour+ // wheel rests on 22 and turns onto 17, as UIDatePicker's does. It never+ // jumps there and commits nothing of its own.+ const {onChange, scrollTo, rerender} = renderWheel(22);+ scrollTo.mockClear();+ rerender(+ <Wheel label="Hour" options={HOURS} value={17} onChange={onChange} />,+ );+ expect(scrollTo).toHaveBeenCalledWith({top: 17 * ROW, behavior: 'smooth'});+ expect(scrollTo).not.toHaveBeenCalledWith({+ top: 17 * ROW,+ behavior: 'auto',+ });+ expect(onChange).not.toHaveBeenCalled();+ });++ it('a stop on another disabled row still travels to the bounds', () => {+ const {onChange, scrollTo, stopOn} = renderWheel(8);+ stopOn(6);+ expect(scrollTo).toHaveBeenCalledWith({top: 9 * ROW, behavior: 'smooth'});+ stopOn(9);+ expect(onChange).toHaveBeenCalledWith(9);+ });++ describe('under reduced motion', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+ });++ /** Reduced motion on, with a fine or a coarse primary pointer. */+ function stubReducedMotion(pointer: 'fine' | 'coarse') {+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches:+ query === '(prefers-reduced-motion: reduce)' ||+ (query === '(pointer: coarse)' && pointer === 'coarse'),+ media: query,+ addEventListener: () => {},+ removeEventListener: () => {},+ }));+ }++ it('lands on the nearest row in bounds at once with a mouse', () => {+ stubReducedMotion('fine');+ expect(window.matchMedia('(pointer: coarse)').matches).toBe(false);+ const {scrollTo, stopOn} = renderWheel(10);+ stopOn(7);+ expect(scrollTo).toHaveBeenCalledWith({top: 9 * ROW, behavior: 'auto'});+ expect(scrollTo).not.toHaveBeenCalledWith(+ expect.objectContaining({behavior: 'smooth'}),+ );+ });++ it('cross-fades onto it on a touch screen: opacity only, 200 ms', () => {+ stubReducedMotion('coarse');+ vi.useFakeTimers();+ const {scrollTo, stopOn} = renderWheel(10);+ const scroller = screen.getByRole('listbox', {name: 'Hour'});+ const animate = vi.fn();+ scroller.animate = animate as HTMLElement['animate'];+ stopOn(7);+ expect(animate).toHaveBeenCalledTimes(1);+ const [keyframes, timing] = animate.mock.calls[0];+ // Out and back in, opacity alone.+ expect((keyframes as Keyframe[]).map(frame => frame.opacity)).toEqual([+ 1, 0, 1,+ ]);+ for (const frame of keyframes as Keyframe[]) {+ expect(+ Object.keys(frame).filter(+ key => key !== 'offset' && key !== 'easing',+ ),+ ).toEqual(['opacity']);+ }+ expect(timing.duration).toBeLessThanOrEqual(200);+ // The rows land at the dip's midpoint, with no travel.+ expect(scrollTo).not.toHaveBeenCalled();+ act(() => {+ vi.advanceTimersByTime(timing.duration / 2);+ });+ expect(scrollTo).toHaveBeenCalledWith({top: 9 * ROW, behavior: 'auto'});+ });++ it('steps with the arrow keys at once with a keyboard', () => {+ stubReducedMotion('fine');+ const {scrollTo} = renderWheel(10);+ const scroller = screen.getByRole('listbox', {name: 'Hour'});+ act(() => {+ scroller.dispatchEvent(+ new KeyboardEvent('keydown', {key: 'ArrowDown', bubbles: true}),+ );+ });+ expect(scrollTo).toHaveBeenCalledWith({+ top: 11 * ROW,+ behavior: 'auto',+ });+ });++ /** Steps the wheel down one row with the keyboard. */+ function pressArrowDown() {+ const scroller = screen.getByRole('listbox', {name: 'Hour'});+ act(() => {+ scroller.dispatchEvent(+ new KeyboardEvent('keydown', {key: 'ArrowDown', bubbles: true}),+ );+ });+ }++ it('lands an arrow key step on a touch screen under its cross-fade, not before', () => {+ stubReducedMotion('coarse');+ vi.useFakeTimers();+ const {onChange, scrollTo, rerender} = renderWheel(10);+ const scroller = screen.getByRole('listbox', {name: 'Hour'});+ const animate = vi.fn();+ scroller.animate = animate as HTMLElement['animate'];+ pressArrowDown();+ expect(onChange).toHaveBeenCalledWith(11);+ // The parent takes the step. The new value must not move the rows+ // while they are still fully visible: they land under the dip.+ rerender(+ <Wheel label="Hour" options={HOURS} value={11} onChange={onChange} />,+ );+ expect(animate).toHaveBeenCalledTimes(1);+ expect(scrollTo).not.toHaveBeenCalled();+ const [, timing] = animate.mock.calls[0];+ act(() => {+ vi.advanceTimersByTime(timing.duration / 2);+ });+ expect(scrollTo.mock.calls).toEqual([+ [{top: 11 * ROW, behavior: 'auto'}],+ ]);+ });++ it('starts a second step’s dip where the first one’s fade-in has the column', () => {+ // design:reduced-motion DR2: a leaving element fades out where it is,+ // so a step during the last dip's fade-in never pops back to opaque.+ stubReducedMotion('coarse');+ vi.useFakeTimers();+ renderWheel(10);+ const scroller = screen.getByRole('listbox', {name: 'Hour'});+ const animate = vi.fn();+ scroller.animate = animate as HTMLElement['animate'];+ pressArrowDown();+ const [first, timing] = animate.mock.calls[0];+ expect((first as Keyframe[])[0].opacity).toBe(1);+ // Past the midpoint: the rows have landed and the column fades back in.+ act(() => {+ vi.advanceTimersByTime(timing.duration / 2 + 40);+ });+ scroller.style.opacity = '0.5';+ pressArrowDown();+ expect(animate).toHaveBeenCalledTimes(2);+ const [second] = animate.mock.calls[1];+ expect((second as Keyframe[]).map(frame => frame.opacity)).toEqual([+ 0.5, 0, 1,+ ]);+ });++ it('changes at once after an earlier touch on a fine pointer, for a key or a tap', () => {+ // This is a laptop's touch screen: its primary pointer is fine. Only a+ // touch drag's release fades. A key step or a row tap lands at once.+ stubReducedMotion('fine');+ const {scrollTo} = renderWheel(10);+ const scroller = screen.getByRole('listbox', {name: 'Hour'});+ const animate = vi.fn();+ scroller.animate = animate as HTMLElement['animate'];+ fireEvent.pointerDown(scroller, {pointerType: 'touch'});+ pressArrowDown();+ expect(scrollTo).toHaveBeenLastCalledWith({+ top: 11 * ROW,+ behavior: 'auto',+ });+ fireEvent.pointerDown(scroller, {pointerType: 'touch'});+ fireEvent.click(screen.getByRole('option', {name: '13'}));+ expect(scrollTo).toHaveBeenLastCalledWith({+ top: 13 * ROW,+ behavior: 'auto',+ });+ expect(animate).not.toHaveBeenCalled();+ });++ it('cross-fades the travel after a touch drag on a fine pointer', () => {+ stubReducedMotion('fine');+ vi.useFakeTimers();+ const {scrollTo, stopOn} = renderWheel(10);+ const scroller = screen.getByRole('listbox', {name: 'Hour'});+ const animate = vi.fn();+ scroller.animate = animate as HTMLElement['animate'];+ fireEvent.pointerDown(scroller, {pointerType: 'touch'});+ stopOn(7);+ expect(animate).toHaveBeenCalledTimes(1);+ expect(scrollTo).not.toHaveBeenCalled();+ act(() => {+ vi.advanceTimersByTime(animate.mock.calls[0][1].duration / 2);+ });+ expect(scrollTo).toHaveBeenCalledWith({top: 9 * ROW, behavior: 'auto'});+ });++ /** A primary mouse press, move or release, as usePointerDragScroll reads it. */+ const mouse = (type: string, y: number) => {+ const event = new Event(type, {bubbles: true, cancelable: true});+ Object.defineProperties(event, {+ clientY: {value: y},+ pointerId: {value: 1},+ pointerType: {value: 'mouse'},+ button: {value: 0},+ });+ return event;+ };++ /** jsdom has no pointer capture, which a mouse drag takes. */+ const capturable = (scroller: HTMLElement) => {+ scroller.setPointerCapture = () => {};+ scroller.releasePointerCapture = () => {};+ scroller.hasPointerCapture = () => true;+ };++ it('travels at once after a mouse drag that follows a touch, on a fine pointer', () => {+ // usePointerDragScroll stops a primary mouse press from bubbling, so that+ // it does not reach BottomSheet's drag. So the wheel reads the pointer in+ // the capture phase, before that.+ stubReducedMotion('fine');+ vi.useFakeTimers();+ const {scrollTo, stopOn} = renderWheel(10);+ const scroller = screen.getByRole('listbox', {name: 'Hour'});+ capturable(scroller);+ const animate = vi.fn();+ scroller.animate = animate as HTMLElement['animate'];+ fireEvent.pointerDown(scroller, {pointerType: 'touch'});+ act(() => {+ scroller.dispatchEvent(mouse('pointerdown', 200));+ // Pulled down three rows: 7, below the minimum.+ scroller.dispatchEvent(mouse('pointermove', 200 + 3 * ROW));+ scroller.dispatchEvent(mouse('pointerup', 200 + 3 * ROW));+ });+ stopOn(7);+ expect(animate).not.toHaveBeenCalled();+ expect(scrollTo).toHaveBeenLastCalledWith({+ top: 9 * ROW,+ behavior: 'auto',+ });+ });++ it('waits for a mouse drag’s release before travelling back inside the bounds', () => {+ // Each scrollTop the drag assigns ends in its own scrollend in Chromium,+ // and the hand can pause with the button down: neither is rest.+ stubReducedMotion('fine');+ vi.useFakeTimers();+ const {scrollTo, onChange} = renderWheel(10);+ const scroller = screen.getByRole('listbox', {name: 'Hour'});+ capturable(scroller);+ act(() => {+ scroller.dispatchEvent(mouse('pointerdown', 200));+ scroller.dispatchEvent(mouse('pointermove', 200 + 3 * ROW));+ scroller.dispatchEvent(new Event('scroll'));+ scroller.dispatchEvent(new Event('scrollend'));+ vi.advanceTimersByTime(SCROLL_QUIET_MS * 2);+ });+ expect(scrollTo).not.toHaveBeenCalled();+ expect(onChange).not.toHaveBeenCalled();+ act(() => {+ scroller.dispatchEvent(mouse('pointerup', 200 + 3 * ROW));+ scroller.dispatchEvent(new Event('scrollend'));+ });+ expect(scrollTo).toHaveBeenLastCalledWith({+ top: 9 * ROW,+ behavior: 'auto',+ });+ expect(onChange).not.toHaveBeenCalled();+ });++ it('travels at once after a trackpad scroll that follows a touch, on a fine pointer', () => {+ stubReducedMotion('fine');+ const {scrollTo, stopOn} = renderWheel(10);+ const scroller = screen.getByRole('listbox', {name: 'Hour'});+ const animate = vi.fn();+ scroller.animate = animate as HTMLElement['animate'];+ fireEvent.pointerDown(scroller, {pointerType: 'touch'});+ fireEvent.wheel(scroller, {deltaY: -120});+ stopOn(7);+ expect(animate).not.toHaveBeenCalled();+ expect(scrollTo).toHaveBeenCalledWith({top: 9 * ROW, behavior: 'auto'});+ });+ });++ it('never commits a disabled row, even with nowhere valid to go', () => {+ const none = HOURS.map(option => ({...option, isDisabled: true}));+ Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {+ configurable: true,+ get(this: HTMLElement) {+ return this.getAttribute('role') === 'option' ? ROW : 0;+ },+ });+ const onChange = vi.fn();+ render(+ <Wheel label="Hour" options={none} value={10} onChange={onChange} />,+ );+ const scroller = screen.getByRole('listbox', {name: 'Hour'});+ let top = 10 * ROW;+ Object.defineProperty(scroller, 'scrollTop', {+ configurable: true,+ get: () => top,+ });+ scroller.scrollTo = vi.fn() as HTMLElement['scrollTo'];+ act(() => {+ top = 4 * ROW;+ scroller.dispatchEvent(new Event('scroll'));+ scroller.dispatchEvent(new Event('scrollend'));+ });+ expect(scroller.scrollTo).toHaveBeenCalledWith({+ top: 10 * ROW,+ behavior: 'smooth',+ });+ expect(onChange).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/DateInput/Wheel.tsx b/packages/core/src/DateInput/Wheel.tsxindex 36c2590d70..ee99b403c6 100644--- a/packages/core/src/DateInput/Wheel.tsx+++ b/packages/core/src/DateInput/Wheel.tsx@@ -21,6 +21,11 @@* browser that does not understand `animation-timeline` would otherwise run* the same keyframes on the document timeline and simply play them once.*+ * Under Reduce Motion, the wheel's own scrolls (a step from a key or a click,+ * the travel to the nearest enabled row) land without travel. They cross-fade+ * on a touch screen and land at once otherwise. A finger's scroll and its+ * momentum stay the platform's.+ ** 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@@ -44,6 +49,7 @@ import {durationVars,} from '../theme/tokens.stylex';import {focusOutlineStyles} from '../utils';+import {reducedMotionFade} from '../motion/reducedMotion';import {dateInputTouchSizes, dateInputTouchGeometry} from './tokens.stylex';import {useOwnScrollGesture} from './useOwnScrollGesture';import {usePointerDragScroll} from './usePointerDragScroll';@@ -209,7 +215,10 @@ export interface WheelOption {value: number;/** Row text. */label: string;- /** Rows outside min/max stay visible but cannot be committed. */+ /**+ * Rows outside min/max stay visible but cannot be committed: a wheel that+ * stops on one travels on to the nearest enabled row.+ */isDisabled?: boolean;}@@ -229,6 +238,46 @@ export interface WheelProps {isActive?: boolean;}+/**+ * The enabled row nearest `index`: `index` itself when it is enabled,+ * otherwise the closest enabled row on either side. A tie goes to the side of+ * `towardIndex` (the committed row), and a wheel with no enabled row stays on+ * `towardIndex`.+ *+ * @example+ * ```+ * // Hours 0-23 with 09:00-17:00 bounds: stopping on 7 rests on 9.+ * nearestEnabledIndex(hourOptions, 7, 10); // 9+ * ```+ */+export function nearestEnabledIndex(+ options: ReadonlyArray<WheelOption>,+ index: number,+ towardIndex: number,+): number {+ const isEnabled = (i: number) =>+ i >= 0 && i < options.length && !options[i].isDisabled;+ if (isEnabled(index)) {+ return index;+ }+ for (let distance = 1; distance < options.length; distance++) {+ const below = index - distance;+ const above = index + distance;+ const isBelowEnabled = isEnabled(below);+ const isAboveEnabled = isEnabled(above);+ if (isBelowEnabled && isAboveEnabled) {+ return towardIndex < index ? below : above;+ }+ if (isBelowEnabled) {+ return below;+ }+ if (isAboveEnabled) {+ return above;+ }+ }+ return towardIndex;+}+/*** One snap-scrolling picker column.*@@ -275,20 +324,100 @@ export function Wheel({: 0;}, []);+ // What last started a scroll of the wheel: a pointer's type, or 'wheel'+ // for a mouse wheel or trackpad. Under Reduce Motion the release of a touch+ // drag cross-fades on any primary pointer. A key step, a row tap or a+ // trackpad's scroll cross-fades on a coarse primary pointer and lands at+ // once on a fine one.+ const lastPointerRef = useRef<string | null>(null);++ // A reduced-motion dip whose rows have not landed yet: its timer and the+ // row it lands on. While one is pending the rows stay put for it, so they+ // never move at full opacity, and a further step retargets it.+ const pendingFadeRef = useRef<{timer: number; top: number} | null>(null);+ // The running dip, so a step during its fade-in starts the next one where+ // the column is.+ const dipRef = useRef<Animation | null>(null);+ useEffect(+ () => () => {+ if (pendingFadeRef.current != null) {+ window.clearTimeout(pendingFadeRef.current.timer);+ pendingFadeRef.current = null;+ }+ },+ [],+ );+const scrollToIndex = useCallback(- (index: number, behavior: ScrollBehavior) => {+ (+ index: number,+ behavior: ScrollBehavior,+ {touchRelease = false}: {touchRelease?: boolean} = {},+ ) => {const scroller = scrollerRef.current;const size = itemBlockSize();if (scroller == null || size === 0) {return;}- scroller.scrollTo({top: index * size, behavior});+ const top = index * size;+ // Under Reduce Motion the wheel's own scroll lands without travel. It+ // dips on a touch screen or for a touch drag's release. Otherwise it+ // lands at once.+ const fadeTiming =+ behavior === 'smooth'+ ? reducedMotionFade(scroller, {touchRelease})+ : null;+ const pending = pendingFadeRef.current;+ if (fadeTiming == null) {+ if (pending != null) {+ window.clearTimeout(pending.timer);+ pendingFadeRef.current = null;+ }+ scroller.scrollTo({top, behavior});+ return;+ }+ if (fadeTiming.duration === 0 || typeof scroller.animate !== 'function') {+ if (pending != null) {+ window.clearTimeout(pending.timer);+ pendingFadeRef.current = null;+ }+ scroller.scrollTo({top, behavior: 'auto'});+ return;+ }+ if (pending != null) {+ // The dip is still fading out: its rows land here instead.+ pending.top = top;+ return;+ }+ const {duration, easing} = fadeTiming;+ // A step during the last dip's fade-in starts the new dip at the+ // column's current opacity, not at full opacity. A leaving element fades+ // out from where it is.+ const shown = Number.parseFloat(getComputedStyle(scroller).opacity);+ dipRef.current?.cancel();+ dipRef.current = scroller.animate(+ [+ {opacity: Number.isFinite(shown) ? shown : 1, easing},+ {opacity: 0, easing},+ {opacity: 1},+ ],+ {duration, easing: 'linear'},+ );+ const landing = {top, timer: 0};+ landing.timer = window.setTimeout(() => {+ pendingFadeRef.current = null;+ scroller.scrollTo({top: landing.top, behavior: 'auto'});+ }, duration / 2);+ pendingFadeRef.current = landing;},[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.+ // Commit on rest. A wheel that stops on a disabled row travels on to the+ // nearest enabled row, as UIDatePicker does. That second rest commits it.+ // A rest on the committed row is not a stop to correct. The park after the+ // sheet opens rests there with no touch. A committed value outside the+ // bounds stays until a person moves the wheel.//// Declared here, above the park effect, because that effect consults the// `isAtRestRef` this returns before it repositions anything.@@ -303,12 +432,18 @@ export function Wheel({options.length - 1,Math.max(0, Math.round(scroller.scrollTop / size)),);- const option = options[index];- if (option == null || option.isDisabled) {- scrollToIndex(selectedIndex, 'smooth');+ const restIndex =+ index === selectedIndex+ ? index+ : nearestEnabledIndex(options, index, selectedIndex);+ if (restIndex !== index) {+ scrollToIndex(restIndex, 'smooth', {+ touchRelease: lastPointerRef.current === 'touch',+ });return;}- if (option.value !== value) {+ const option = options[index];+ if (option != null && !option.isDisabled && option.value !== value) {onChange(option.value);}},@@ -316,8 +451,11 @@ export function Wheel({isDraggingRef,);- // 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).+ // Park the committed row under the band at once whenever the wheel is+ // shown. A value that changes from outside while the wheel is shown turns+ // the wheel onto its row instead. UIDatePicker turns onto its maximum the+ // same way, and never jumps there. For example, a bound clamps the time+ // after another wheel turned, or the calendar moved 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@@ -325,8 +463,15 @@ export function Wheel({// 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.+ const parkedRef = useRef(false);useEffect(() => {- if (!isActive || !isAtRestRef.current) {+ if (!isActive) {+ parkedRef.current = false;+ return;+ }+ // Nor while a reduced-motion dip is still to land its rows: they land+ // under it, on this row.+ if (!isAtRestRef.current || pendingFadeRef.current != null) {return;}const size = itemBlockSize();@@ -335,11 +480,16 @@ export function Wheel({return;}if (Math.round(scroller.scrollTop / size) !== selectedIndex) {- scroller.scrollTo({top: selectedIndex * size, behavior: 'auto'});+ if (parkedRef.current) {+ scrollToIndex(selectedIndex, 'smooth');+ } else {+ scroller.scrollTo({top: selectedIndex * size, behavior: 'auto'});+ }}+ parkedRef.current = true;// eslint-disable-next-line @eslint-react/set-state-in-effect -- the highlight follows a scroll position, which only exists after layoutsetActiveIndex(selectedIndex);- }, [isActive, selectedIndex, itemBlockSize, isAtRestRef]);+ }, [isActive, selectedIndex, itemBlockSize, isAtRestRef, scrollToIndex]);// Highlight follows the finger. rAF-throttled: a scroll can fire far more// often than the display refreshes, and this only feeds a repaint.@@ -446,6 +596,16 @@ export function Wheel({aria-activedescendant={`${id}-${options[activeIndex]?.value}`}tabIndex={0}onKeyDown={handleKeyDown}+ // Read in the capture phase. usePointerDragScroll stops a primary+ // mouse press from bubbling, so that it does not reach BottomSheet's+ // drag. A bubbling handler would never see a mouse, and would keep the+ // last touch.+ onPointerDownCapture={event => {+ lastPointerRef.current = event.pointerType;+ }}+ onWheel={() => {+ lastPointerRef.current = 'wheel';+ }}{...stylex.props(styles.scroller, focusOutlineStyles.focusVisible)}>{options.map((option, index) => (<divdiff --git a/packages/core/src/DateInput/__tests__/WheelRest.a11y.chromium.spec.ts b/packages/core/src/DateInput/__tests__/WheelRest.a11y.chromium.spec.tsnew file mode 100644index 0000000000..0e0d2ae563--- /dev/null+++ b/packages/core/src/DateInput/__tests__/WheelRest.a11y.chromium.spec.ts@@ -0,0 +1,215 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y always++/**+ * @file WheelRest.a11y.chromium.spec.ts+ * @input The built TimeInput bottom-sheet story with bounds, and real+ * Chromium touch input (CDP) on a phone profile+ * @output Browser evidence that a wheel dragged onto a row outside the bounds+ * comes to rest on the nearest row inside them and commits it+ * @position Real-engine proof for Wheel.tsx's rest rule: native scrolling,+ * CSS snapping and the browser's own end-of-scroll signal, none of which+ * jsdom has. Wheel.test.tsx holds the rule itself.+ */++import {expect, test, type Locator, type Page} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++test.use({+ hasTouch: true,+ isMobile: true,+ viewport: {width: 390, height: 844},+ deviceScaleFactor: 3,+});++const sleep = async (ms: number) =>+ new Promise(resolve => setTimeout(resolve, ms));++async function openHourWheel(page: Page) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-timeinput--bottom-sheet-with-min-max&viewMode=story`,+ );+ const field = page.getByRole('combobox', {name: 'Appointment time'});+ await expect(field).toHaveValue('10:00 AM');+ await field.tap();+ const hours = page.getByRole('listbox', {name: 'Hour'});+ await expect(hours).toBeVisible();+ // Let the sheet finish presenting, so the drag lands on a wheel at rest.+ await sleep(800);+ return {field, hours};+}++/** A slow one-finger drag: no fling, so the wheel snaps where it is let go. */+async function drag(page: Page, wheel: Locator, dy: number) {+ const box = await wheel.boundingBox();+ if (box == null) {+ throw new Error('no rendered bounds');+ }+ const x = box.x + box.width / 2;+ const y = box.y + box.height / 2;+ const cdp = await page.context().newCDPSession(page);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [{x, y, id: 1}],+ });+ const steps = 30;+ for (let i = 1; i <= steps; i++) {+ await sleep(16);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchMove',+ touchPoints: [{x, y: y + (dy * i) / steps, id: 1}],+ });+ }+ // Hold still before lifting, so the release carries no velocity.+ await sleep(200);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+}++const selectedHour = (hours: Locator) =>+ hours.locator('[role="option"][aria-selected="true"]');++/**+ * Chromium starts a touch scroll only after the finger has travelled its slop,+ * so a drag moves the content that much less than the finger. Each drag adds+ * this much so the wheel snaps to the intended row.+ */+const SCROLL_SLOP_ALLOWANCE = 16;++test('a wheel dragged below the minimum comes to rest on the minimum', async ({+ page,+}) => {+ const {field, hours} = await openHourWheel(page);+ const row = await hours+ .locator('[role="option"]')+ .first()+ .evaluate(el => el.getBoundingClientRect().height);+ // 10 → 7: three rows down, past 9 AM.+ await drag(page, hours, 3 * row + SCROLL_SLOP_ALLOWANCE);++ await expect(selectedHour(hours)).toHaveText('9', {timeout: 3000});+ await expect(field).toHaveValue('9:00 AM');+});++test('a wheel dragged onto a row inside the bounds commits that row', async ({+ page,+}) => {+ const {field, hours} = await openHourWheel(page);+ const row = await hours+ .locator('[role="option"]')+ .first()+ .evaluate(el => el.getBoundingClientRect().height);+ // 10 → 11: one row up, still inside the bounds.+ await drag(page, hours, -(row + SCROLL_SLOP_ALLOWANCE));++ await expect(selectedHour(hours)).toHaveText('11', {timeout: 3000});+ await expect(field).toHaveValue('11:00 AM');+});++test('under reduced motion an arrow key step lands under its cross-fade, never at full opacity', async ({+ page,+}) => {+ await page.emulateMedia({reducedMotion: 'reduce'});+ const {field, hours} = await openHourWheel(page);+ await hours.focus();+ // Record every frame from before the key until well after the 200 ms dip.+ // Each frame holds where the rows are drawn and how opaque they are. The+ // rows are the band copy's strip where the column has one, and its first+ // row otherwise.+ const frames = hours.evaluate(+ async column =>+ new Promise<{at: number; opacity: number}[]>(resolve => {+ const seen: {at: number; opacity: number}[] = [];+ const sample = () => {+ const strip = column.querySelector<HTMLElement>('[data-wheel-strip]');+ const rows =+ strip ?? column.querySelector<HTMLElement>('[role="option"]');+ const faded = strip?.parentElement ?? column;+ seen.push({+ at: Math.round(+ (rows?.getBoundingClientRect().top ?? 0) -+ column.getBoundingClientRect().top,+ ),+ opacity: Number(getComputedStyle(faded).opacity),+ });+ if (seen.length < 45) {+ requestAnimationFrame(sample);+ } else {+ resolve(seen);+ }+ };+ requestAnimationFrame(sample);+ }),+ );+ await sleep(50);+ await page.keyboard.press('ArrowDown');+ const seen = await frames;++ // The rows never move while they are fully visible: they land under the+ // dip (design:reduced-motion DR2), then fade back in on 11.+ const start = seen[0].at;+ const moved = seen.find(frame => frame.at !== start);+ expect(moved, JSON.stringify(seen)).toBeDefined();+ expect(moved?.opacity, JSON.stringify(seen)).toBeLessThan(1);+ expect(seen.at(-1)?.opacity).toBe(1);+ await expect(selectedHour(hours)).toHaveText('11');+ await expect(field).toHaveValue('11:00 AM');+});++test('a meridiem change past the maximum turns the hour wheel onto it, frame by frame (component:DateInput FR14)', async ({+ page,+}) => {+ const {field, hours} = await openHourWheel(page);+ const meridiem = page.getByRole('listbox', {name: 'AM/PM'});+ const labels = await hours.locator('[role="option"]').allTextContents();+ const row = await hours+ .locator('[role="option"]')+ .first()+ .evaluate(el => el.getBoundingClientRect().height);+ const from = labels.indexOf('10') * row;+ const to = labels.indexOf('5') * row;+ // The hour wheel's scroll position on every frame, from before the tap.+ await hours.evaluate(scroller => {+ const tops: number[] = [];+ (window as unknown as {hourTops: number[]}).hourTops = tops;+ const sample = () => {+ tops.push(scroller.scrollTop);+ if (tops.length < 150) {+ requestAnimationFrame(sample);+ }+ };+ requestAnimationFrame(sample);+ });+ // 10 PM is past the 5 PM maximum: the field clamps to it.+ await meridiem.getByRole('option', {name: 'PM'}).tap();+ await expect(field).toHaveValue('5:00 PM', {timeout: 3000});+ await sleep(1000);+ const tops = await page.evaluate(+ () => (window as unknown as {hourTops: number[]}).hourTops,+ );+ // From 10 onto 5 through the rows between, as UIDatePicker turns onto its+ // maximum, never a jump, and only ever one way.+ expect(Math.abs(tops[0] - from)).toBeLessThan(1);+ expect(Math.abs(tops[tops.length - 1] - to)).toBeLessThan(1);+ const between = tops.filter(top => top < from - 2 && top > to + 2);+ expect(between.length).toBeGreaterThanOrEqual(4);+ for (let i = 1; i < tops.length; i++) {+ expect(tops[i]).toBeLessThanOrEqual(tops[i - 1] + 0.5);+ }+});