An open source design system that's fully customizable and agent ready
TypeScript
feat(Wheel): UIPickerView's motion under a finger, with flat rows (#8159)
Christopher Chedeau593f96f764ef
diff --git a/.changeset/wheel-interaction-proofs.md b/.changeset/wheel-interaction-proofs.mdnew file mode 100644index 0000000000..2f9ad8ab99--- /dev/null+++ b/.changeset/wheel-interaction-proofs.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: browser proofs for the touch picker wheel in Chromium and WebKit, which a finger gets on every engine. A flick coasts on UIKit's curve onto the row it projects and commits on arrival. A finger landing on a coasting wheel stops it, and it then eases onto the nearest row. A storyboard films a flick and its coast. In Chromium, the coast also keeps advancing every frame while the main thread is blocked, and does no Layout or Paint per frame. Under reduced motion, a flick still coasts as momentum with its rows flat, and a tap cross-fades onto its row, animating opacity alone for 200 ms or less. Opening the month and year wheels writes no element per year, and each year is drawn once. Under a mouse, a drag still scrolls today's column onto a row.++@vjeuxdiff --git a/.changeset/wheel-keys-time-order.md b/.changeset/wheel-keys-time-order.mdnew file mode 100644index 0000000000..4a4e472c77--- /dev/null+++ b/.changeset/wheel-keys-time-order.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] In the DateInput, TimeInput and DateTimeInput bottom sheets, a wheel's Arrow, Page, Home and End keys move through its enabled values in time order, skipping disabled ones, and stop at the first or last enabled value, with a mouse as with a finger. On a 12-hour hour wheel 12 PM comes before 1 PM, so ArrowDown from 12 PM moves to 1 PM, and a key past the last allowed hour commits nothing.++@vjeuxdiff --git a/.changeset/wheel-listbox-hook.md b/.changeset/wheel-listbox-hook.mdnew file mode 100644index 0000000000..a729141a51--- /dev/null+++ b/.changeset/wheel-listbox-hook.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: the Wheel's two presentations, the scrolling column under a mouse and the picker wheel under a finger, share one listbox hook for their ids, ARIA attributes, Arrow, Page, Home and End keys, and row clicks. Each keeps where its moves start: the scrolling column steps from the row under its band, and the picker wheel from the row it is heading to.++@vjeuxdiff --git a/.changeset/wheel-trackpad-notch.md b/.changeset/wheel-trackpad-notch.mdnew file mode 100644index 0000000000..b4c7629fcd--- /dev/null+++ b/.changeset/wheel-trackpad-notch.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] On a touch device with a trackpad or a mouse, such as a tablet with a keyboard, the picker wheels in the TimeInput, DateTimeInput and DateInput bottom sheets now take a trackpad's two-finger scroll as a finger: the rows follow the fingers, coast on at their lift, and rest on a row. One mouse-wheel notch turns a wheel one row, as an arrow key does, with no coast. Before, both moved the rows by each scroll's own distance, so a trackpad's momentum ran at the browser's rate and one notch moved several rows. A ctrl-scroll still zooms the page.++@vjeuxdiff --git a/.changeset/wheel-uikit-picker-values.md b/.changeset/wheel-uikit-picker-values.mdnew file mode 100644index 0000000000..b34f78c616--- /dev/null+++ b/.changeset/wheel-uikit-picker-values.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: UIPickerView's values measured on iOS 26.2 join the touch motion tables as internal constants: the row pitch, the picker's height and its rubber band, the coast's stop speed and velocity floor, the snap at rest, the tap spin and the selection tick. The pure math a wheel moves with comes with them. It projects the row a release rests on as UIScrollView sums its deceleration, coasts with the rate re-solved to stop on that row, snaps, bounces at an end, rubber-bands, and spins to a tapped row. It is checked against UIKit's recorded frames. Nothing public changes: none of it is exported from the package entry point, and themes do not set these values.++@vjeuxdiff --git a/.changeset/wheel-uikit-picker.md b/.changeset/wheel-uikit-picker.mdnew file mode 100644index 0000000000..be37b67bb8--- /dev/null+++ b/.changeset/wheel-uikit-picker.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] Under a coarse primary pointer, as on a phone or a tablet, the picker wheels in the TimeInput, DateTimeInput and DateInput bottom sheets now move like UIPickerView. Their rows keep the 28 px pitch and lie flat, fading toward the edges of the column in every browser; the scrolling column under a mouse tilts and fades its rows only where the browser supports scroll-driven animations, and shows a plain list elsewhere. The row under the band is in semibold accent text on its plate while the wheel rests and while a finger drags it; no row is marked while the wheel coasts, snaps or turns. A flick coasts at UIKit's deceleration onto the row UIKit's projection picks. A finger landing on a moving wheel stops it. A tap on a row turns it onto the band, and a value changed from outside while the sheet is open, as when a bound clamps the time, turns the wheel onto its row instead of jumping there. Past the first or last row, a drag rubber-bands and the wheel bounces back. As on iOS, the value commits when the wheel comes to rest, and the coast keeps running while the page's main thread is busy. Arrow keys and clicks on a row still commit at once. Under reduced motion a flick still coasts, as scrolling does; a tap, a key or a slow release cross-fades onto its row. `presentation="popover"` keeps the previous surface; no value keeps the native-scroll column under a finger. Each row that reaches the band ticks with a short vibration where the browser supports it, as on Android; iOS Safari has no vibration. Under a fine primary pointer, as with a mouse on a desktop, the wheels keep the scrolling column.++@vjeuxdiff --git a/apps/storybook/stories/DateInput.stories.tsx b/apps/storybook/stories/DateInput.stories.tsxindex bc793a78f1..2a535ab047 100644--- a/apps/storybook/stories/DateInput.stories.tsx+++ b/apps/storybook/stories/DateInput.stories.tsx@@ -861,3 +861,39 @@ export const StylingParts: Story = {</div>),};++/**+ * The bottom sheet with two centuries of years: the year wheel has 200 rows.+ * Under a finger, opening the month and year wheels costs about the same as+ * for two years: each year is drawn once, as a flat row.+ */+export const BottomSheetWideRange: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateString | undefined>(+ '2026-03-15' as ISODateString,+ );+ return <DateInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Date of birth',+ presentation: 'bottom-sheet',+ min: '1900-01-01' as ISODateString,+ max: '2099-12-31' as ISODateString,+ },+};++/** The same sheet with two years: the year wheel has 2 rows. */+export const BottomSheetNarrowRange: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateString | undefined>(+ '2026-03-15' as ISODateString,+ );+ return <DateInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Date of birth',+ presentation: 'bottom-sheet',+ min: '2026-01-01' as ISODateString,+ max: '2027-12-31' as ISODateString,+ },+};diff --git a/apps/storybook/stories/WheelProofs.stories.tsx b/apps/storybook/stories/WheelProofs.stories.tsxnew file mode 100644index 0000000000..2137757018--- /dev/null+++ b/apps/storybook/stories/WheelProofs.stories.tsx@@ -0,0 +1,84 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file WheelProofs.stories.tsx+ * @input Uses React and the internal Wheel (packages/core/src/DateInput)+ * @output The Wheel alone, for its browser proofs: a 60-row minute column at+ * 00, its committed minute shown in a read-only field; and the touch column+ * alone, whatever the primary pointer, for the trackpad proofs+ * @position A checked-in reproduction path for+ * packages/core/src/DateInput/__tests__/Wheel.interaction.browser.spec.ts.+ * The proofs test the Wheel itself, so they open a column that stays a plain+ * Wheel whatever rules the sheets that use it add (looping, bounds, a date+ * that moves with the month).+ */++import type {Meta, StoryObj} from '@storybook/react';+import {useState} from 'react';+import {PickerWheel} from '../../../packages/core/src/DateInput/PickerWheel';+import {Wheel} from '../../../packages/core/src/DateInput/Wheel';++const MINUTES = Array.from({length: 60}, (_, minute) => ({+ value: minute,+ label: String(minute).padStart(2, '0'),+}));++const meta = {+ title: 'Core/Wheel',+ tags: ['no-visual', '!autodocs'],+ parameters: {layout: 'centered'},+} satisfies Meta;++export default meta;+type Story = StoryObj<typeof meta>;++/**+ * A finger gets the touch column, a mouse the scrolling column; either commits+ * into the field above it.+ */+export const Minutes: Story = {+ render: () => {+ const [minute, setMinute] = useState(0);+ return (+ <div style={{display: 'grid', gap: 16, inlineSize: 160}}>+ <input+ aria-label="Committed minute"+ readOnly+ value={String(minute).padStart(2, '0')}+ />+ <Wheel+ label="Minute"+ options={MINUTES}+ value={minute}+ onChange={setMinute}+ />+ </div>+ );+ },+};++/**+ * The touch column alone, whatever the primary pointer: WebKit's driver sends+ * a trackpad's precise deltas only from a desktop context, whose primary+ * pointer is fine, and its mobile emulation sends no wheel at all.+ */+export const TouchMinutes: Story = {+ render: () => {+ const [minute, setMinute] = useState(0);+ return (+ <div style={{display: 'grid', gap: 16, inlineSize: 160}}>+ <input+ aria-label="Committed minute"+ readOnly+ value={String(minute).padStart(2, '0')}+ />+ <PickerWheel+ label="Minute"+ options={MINUTES}+ value={minute}+ onChange={setMinute}+ />+ </div>+ );+ },+};diff --git a/docs/specs/AST-094-touch-presentations/motion-roles.md b/docs/specs/AST-094-touch-presentations/motion-roles.mdindex 901a50eefd..b15b263194 100644--- a/docs/specs/AST-094-touch-presentations/motion-roles.md+++ b/docs/specs/AST-094-touch-presentations/motion-roles.md@@ -6,6 +6,7 @@ Every motion role a registered table lists (`spec:AST-094` FR4, DEC-5): its kind| Role | Kind | Default | Named by || ------------------------------- | -------- | --------------------------------------------------------------- | ----------------------- |+| `picker.tapSpin.durationMs` | duration | 300 ms | `component:DateInput` || `progress.curves.fill` | curve | cubic-bezier(0, 0, 1, 1) | `component:ProgressBar` || `progress.fillTrackMs` | duration | 1000 ms | `component:ProgressBar` || `progress.reducedMotionPulseMs` | duration | 2000 ms | `component:ProgressBar` |diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.mdindex 0cf34e5135..fe4b16cb99 100644--- a/docs/specs/AST-094-touch-presentations/spec.md+++ b/docs/specs/AST-094-touch-presentations/spec.md@@ -184,6 +184,10 @@ a measured, sourced difference exists.integrator, its 300 ms animated scroll and that scroll's sinusoidal curve,DEC-25) plays from internal constants and is not yet a named role.+ Implementation gap: the sheet picker wheel's snap rate (UIKit's measured+ picker deceleration) plays from an internal constant and is not yet a named+ role; a role kind for rates comes with a later change.+### Motion- **FR5 — Motion runs on the compositor.** Every release and everydiff --git a/docs/specs/components/DateInput/DateInput.spec.md b/docs/specs/components/DateInput/DateInput.spec.mdindex 378bc3436e..034adc5c5d 100644--- a/docs/specs/components/DateInput/DateInput.spec.md+++ b/docs/specs/components/DateInput/DateInput.spec.md@@ -17,6 +17,7 @@ verified_by:packages/core/src/DateInput/DateInput.fr10.test.tsx,packages/core/src/DateInput/DateInputTouch.test.tsx,packages/core/src/DateInput/NativeDateField.test.tsx,+ packages/core/src/DateInput/PickerWheel.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,@@ -33,10 +34,21 @@ architecture:architecture:interaction-modality,architecture:internationalization,architecture:public-component-api,+ architecture:public-component-api/INV16,+ architecture:react-component-runtime/INV13,]contributing: []system_specs:- [spec:AST-020/FR15, spec:AST-043, spec:AST-085, spec:AST-086, spec:AST-102]+ [+ spec:AST-020/FR15,+ spec:AST-043,+ spec:AST-085,+ spec:AST-086,+ spec:AST-094/FR5,+ spec:AST-094/FR10,+ spec:AST-094/FR43,+ spec:AST-102,+ ]---# DateInput component contract@@ -49,7 +61,7 @@ system_specs:| 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. |+| 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, and month paging in the touch calendar 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. |@@ -107,8 +119,8 @@ Consumer migration instructions belong in consumer docs and release notes.- Cross-component picker vocabulary and deprecated-prop migration — owned by`spec:AST-043`.- Browser/OS picker appearance, locale, momentum, or hit areas.-- A cylinder or other 3D wheel look: under a finger, each sheet wheel is the same- flat scrolling column it is under a mouse (DEC-2).+- A cylinder or other 3D wheel look: under a finger each sheet wheel's rows lie+ flat, and under a mouse the scrolling column keeps its tilt (DEC-2).## Public concepts@@ -141,9 +153,11 @@ Consumer migration instructions belong in consumer docs and release notes.| 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. | 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 |+| 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. The turn plays the internal motion role `picker.tapSpin.durationMs`, UIKit's measured 300 ms, on `timing.curves.move`, as a tap on a row does. | 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). | `spec:AST-094` FR43; current source || FR16 | Enter in the pointer field's text input commits typed text that has not been committed and is then held back, so a form never submits the value from before the commit. With no typed text pending, Enter is not prevented, so a form submits as it does from any text field, except on a disabled or busy field, where Enter does nothing (`spec:AST-085` FR2). |+| FR17 | In a sheet wheel, Arrow, Page, Home and End move through the wheel's enabled values in time order, skipping disabled ones, and stop at the first or last enabled value; a key with no enabled value in its direction commits nothing, under every presentation. On a 12-hour hour wheel, time order follows the full time (12 PM comes before 1 PM), not the column's row order. | Owner decision (cixzhang, 2026-11-02); current source |+| FR18 | While a wheel coasts, snaps or turns, no row carries the selection band's accent mark; the mark returns on the row that comes to rest, as UIPickerView does (`spec:AST-094` FR3). | Owner decision (cixzhang, 2026-11-02); UIDatePicker on the iOS 26.2 simulator; current source |### Allowed variation@@ -304,27 +318,29 @@ 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" and "typing a day-first date in en-GB never reports a month-first date"; `dateParser.test.ts` "in a day-first locale, never reads numeric text month-first outside the locale-ordered forms"; `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` |-| FR16 | `DateInput.test.tsx` "Enter submits the form when nothing is typed, and commits typed text without submitting" "Enter on a disabled field does not submit the form" and "Enter on a busy field does not submit the form" | Nothing typed; typed text; disabled; busy (`isLoading`) | An Enter that is prevented with nothing typed, or that submits before typed text commits, fails. | — |-| 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" and "typing a day-first date in en-GB never reports a month-first date"; `dateParser.test.ts` "in a day-first locale, never reads numeric text month-first outside the locale-ordered forms"; `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"; `PickerWheel.test.tsx`, the wheel under a finger: "turns on to the minimum after resting below it, and commits that", "opening on a value outside the bounds commits nothing", "rests back on a committed value outside the bounds and commits nothing"; `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"; `PickerWheel.test.tsx`, the wheel under a finger: "turns the wheel onto its row, as a bound clamping the time", "turns on from where the wheel is drawn when the value changes again during that turn", "plays a tapped row’s turn on the tap spin’s motion role". | 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". `PickerWheel.test.tsx` "follows a trackpad’s fingers, coasts on at their lift and rests on a row, as a finger’s flick does", "rests on the nearest row after a slow trackpad drag that stops, without coasting", "turns one row for a mouse wheel’s notch, as an arrow key does, with no coast", "turns three rows for three notches, one each", "leaves a ctrl-wheel, a trackpad pinch, to the page"; `Wheel.interaction.browser.spec.ts` "one mouse-wheel notch turns the touch column one row, as an arrow key does; three turn it three" (Chromium) and the trackpad flick and slow stopped drag (WebKit, whose driver sends a trackpad's deltas). | 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` |+| FR16 | `DateInput.test.tsx` "Enter submits the form when nothing is typed, and commits typed text without submitting" "Enter on a disabled field does not submit the form" and "Enter on a busy field does not submit the form" | Nothing typed; typed text; disabled; busy (`isLoading`) | An Enter that is prevented with nothing typed, or that submits before typed text commits, fails. | — |+| FR17 | `TimeInput/Presentation.test.tsx`: "at a 12:00–17:00 bound, ArrowDown from 5 PM commits nothing and ArrowDown from 12 PM commits 1 PM, under a finger", "… under a mouse". `Wheel.test.tsx`, the column under a mouse, and `PickerWheel.test.tsx`, the wheel under a finger: "at a 12:00–17:00 bound, moves a key to the next enabled row and stops at the last one", "at a 12:00–17:00 bound on a 12-hour hour wheel, steps in time order: nothing after 5 PM, and 1 PM after 12 PM", "moves a key from a row outside the bounds onto the first enabled row in its direction". | At a 12:00–17:00 bound, ArrowDown from 5 PM commits nothing and ArrowDown from 12 PM commits 1 PM, under a finger and a mouse | A key that commits a disabled value, leaves time order, or strands 12 PM fails. | `audit:DateInput/behavior` |+| FR18 | `PickerWheel.test.tsx` "marks no row while a fling coasts, then the row it rests on", "marks no row while the wheel snaps or turns, then the row it rests on". | A fling's coast, a slow release's snap and a key's turn, each to its rest | A row that carries the band's accent mark while the wheel moves, or a rest with no marked row, 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@@ -338,12 +354,13 @@ clear-glyph target of its own.shown, against `architecture:internationalization` INV1a and INV8.- **Clear control under focus (FR11).** A clear control that unmounts whilefocused drops focus to the page, against `spec:AST-085` FR4.+- **Selection tick haptics.** Under a finger each row that reaches the band+ ticks with a short vibration where the browser has the Vibration API, as on+ Android. iOS Safari has none, so the tick is silent there (`spec:AST-094`+ FR23).- **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.-- **Trackpad and mouse wheel on a sheet wheel (FR15).** A trackpad's momentum- runs at the browser's rate, and one mouse-wheel notch moves the wheel several- rows.- **Month pager (PR2).** Under a finger the touch calendar moves through thenative month scroller rather than a drag-driven pager.@@ -367,14 +384,15 @@ empty.Rejected: returning to the previous row, which makes the person scroll again toreach the bound.-### DEC-2 — The sheet wheels keep the flat scrolling column under a finger+### DEC-2 — The sheet wheels' rows lie flat under a finger**Reference:** `component:DateInput/DEC-2`**Decider:** cixzhang, 2026-11-01-Every sheet wheel in DateInput, TimeInput, and DateTimeInput looks the same under-a finger as under a mouse: one flat scrolling column whose rows tip back and fade-away from the committed row.+Under a finger, each sheet wheel in DateInput, TimeInput, and DateTimeInput lays+its rows flat at the scrolling column's pitch and fades them toward its edges,+without tipping or shrinking. Under a mouse, the scrolling column tips and fades+its rows on a scroll timeline.Rejected: a UIPickerView-style cylinder look.diff --git a/packages/core/src/DateInput/DateInputTouch.test.tsx b/packages/core/src/DateInput/DateInputTouch.test.tsxindex e81cac4e14..5ddeaabc77 100644--- a/packages/core/src/DateInput/DateInputTouch.test.tsx+++ b/packages/core/src/DateInput/DateInputTouch.test.tsx@@ -55,6 +55,7 @@ import {rowsIn,DEFAULT_MONTH_REACH,} from './monthGeometry';+import {WHEEL_ROW_HEIGHT} from './wheelOptions';import {SWIPE_DISTANCE} from './useOwnScrollGesture';import {DRAG_SLOP} from './usePointerDragScroll';import {SCROLL_QUIET_MS} from './useScrollSettle';@@ -2215,6 +2216,19 @@ describe('DateInput — a mouse can drag a wheel', () => {const title = () =>document.querySelector<HTMLElement>('[data-title="month-year"]')!;+ // Today's column is the fine pointer's (a finger gets the touch column):+ // a desktop whose field asks for the sheet.+ beforeEach(() => {+ setViewport('desktop');+ });++ function openWheels() {+ renderAndOpen(+ <Controlled initial="2026-03-21" presentation="bottom-sheet" />,+ );+ fireEvent.click(title());+ }+/** 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', {@@ -2271,8 +2285,7 @@ describe('DateInput — a mouse can drag a wheel', () => {}it('scrolls the wheel when a mouse drags it', () => {- renderAndOpen();- fireEvent.click(title());+ openWheels();withWheelLayout(() => {const el = wheel();const track = trackable(el);@@ -2287,8 +2300,7 @@ describe('DateInput — a mouse can drag a wheel', () => {});it('ignores movement too small to be a drag, so a click is still a click', () => {- renderAndOpen();- fireEvent.click(title());+ openWheels();withWheelLayout(() => {const el = wheel();const track = trackable(el);@@ -2299,8 +2311,7 @@ describe('DateInput — a mouse can drag a wheel', () => {});it('leaves touch and pen alone — they pan natively, and better', () => {- renderAndOpen();- fireEvent.click(title());+ openWheels();withWheelLayout(() => {for (const pointerType of ['touch', 'pen']) {const el = wheel();@@ -2314,8 +2325,7 @@ describe('DateInput — a mouse can drag a wheel', () => {});it('ignores a secondary button, which belongs to the context menu', () => {- renderAndOpen();- fireEvent.click(title());+ openWheels();withWheelLayout(() => {const el = wheel();const track = trackable(el);@@ -2332,8 +2342,7 @@ describe('DateInput — a mouse can drag a wheel', () => {* jumped a whole one.*/it('suspends snapping for the drag, and restores it after', () => {- renderAndOpen();- fireEvent.click(title());+ openWheels();withWheelLayout(() => {const el = wheel();trackable(el);@@ -2358,7 +2367,12 @@ describe('DateInput — a mouse can drag a wheel', () => {try {// A year of months, so May is reachable (the default range ends in April).renderAndOpen(- <Controlled initial="2026-03-21" min="2026-01-01" max="2026-12-31" />,+ <Controlled+ initial="2026-03-21"+ min="2026-01-01"+ max="2026-12-31"+ presentation="bottom-sheet"+ />,);fireEvent.click(title());withWheelLayout(() => {@@ -2398,8 +2412,7 @@ describe('DateInput — a mouse can drag a wheel', () => {* 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());+ openWheels();withWheelLayout(() => {const el = wheel();trackable(el);@@ -2714,6 +2727,29 @@ describe('DateInput — scroll CSS (definition-level)', () => {expect(item).not.toContain("overflow: 'hidden'");});+ it('keeps the published tokens module to its released names', async () => {+ // @astryxdesign/core/DateInput/tokens.stylex is a public subpath: the touch+ // wheel's geometry lives in an unexported module beside it.+ const tokens = await import('./tokens.stylex');+ expect(Object.keys(tokens).sort()).toEqual([+ 'WEEKS_PER_PANE',+ 'dateInputTouchGeometry',+ 'dateInputTouchSizes',+ ]);+ });++ it('sizes the touch wheels as today’s column, with the large text of the theme', () => {+ // The wheel's row pitch is today's token, in numbers (`wheelItemSize`),+ // and its column is today's pane of six day rows.+ const tokens = read('tokens.stylex.ts');+ expect(tokens).toContain(`wheelItemSize: '${WHEEL_ROW_HEIGHT}px'`);+ expect(tokens).toContain("daySize: '44px'");+ expect(tokens).toContain('export const WEEKS_PER_PANE = 6;');+ const source = read('PickerWheel.tsx');+ expect(source).toContain('blockSize: dateInputTouchGeometry.paneBlockSize');+ expect(source).toContain("fontSize: typeScaleVars['--text-large-size']");+ });+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 —diff --git a/packages/core/src/DateInput/PickerWheel.test.tsx b/packages/core/src/DateInput/PickerWheel.test.tsxnew file mode 100644index 0000000000..1e28d6db38--- /dev/null+++ b/packages/core/src/DateInput/PickerWheel.test.tsx@@ -0,0 +1,1218 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file PickerWheel.test.tsx+ * @input Uses Vitest, Testing Library, the touch picker column and touch events+ * dispatched through the gesture system with a fake clock+ * @output Proves what a wheel commits and when: a drag, a release onto a row,+ * past the bounds, a fling, a tap, a finger catching a moving wheel, the+ * keyboard, a click, a programmatic spin, a custom rest rule+ * @position Unit coverage for PickerWheel.tsx (the Wheel under a finger;+ * Wheel.test.tsx covers the switch and today's column); the curves themselves are proven in+ * wheelPhysics.test.ts, the strip's motion in wheelStrip.test.ts, and on+ * screen by the browser specs+ */++import {act, fireEvent, render, screen} from '@testing-library/react';+import {Profiler, useState} from 'react';+import {+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from 'vitest';+import {motionRole} from '../motion/roles';+import {picker, timing} from '../motion/uikit';+import {fontWeightVars} from '../theme/tokens.stylex';+import {PickerWheel} from './PickerWheel';+import {+ WHEEL_ROW_HEIGHT,+ type WheelOption,+ type WheelProps,+} from './wheelOptions';++const ROW = WHEEL_ROW_HEIGHT;+/** The column is laid out 216 px tall, its band's centre 108 px down. */+const CENTRE = 108;++/** 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,+}));++const MINUTES: WheelOption[] = Array.from({length: 60}, (_, minute) => ({+ value: minute,+ label: String(minute).padStart(2, '0'),+}));++// One fake clock serves the whole file. The gesture system is one per document+// and keeps its own timeline, so time must never run backwards between tests.+beforeAll(() => {+ vi.useFakeTimers({+ toFake: [+ 'setTimeout',+ 'clearTimeout',+ 'performance',+ 'Date',+ 'requestAnimationFrame',+ 'cancelAnimationFrame',+ ],+ });+});++// The touch column draws only where the primary pointer is coarse, and only+// there does the gesture host take input (spec:AST-094 FR19). Every case runs+// under a coarse primary pointer, as on a phone or a tablet.+beforeEach(() => {+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches: query === '(pointer: coarse)',+ media: query,+ addEventListener: () => {},+ removeEventListener: () => {},+ }));+});++afterEach(() => {+ // Let every motion and gesture timer of the test run out.+ vi.advanceTimersByTime(10_000);+ vi.unstubAllGlobals();+});++afterAll(() => {+ vi.useRealTimers();+});++/** A wheel whose owner commits each change, as a field does. */+function OwnedWheel({+ options,+ initial,+ onChange,+}: {+ options: WheelOption[];+ initial: number;+ onChange: (value: number) => void;+}) {+ const [value, setValue] = useState(initial);+ return (+ <PickerWheel+ label="Hour"+ options={options}+ value={value}+ onChange={next => {+ onChange(next);+ setValue(next);+ }}+ />+ );+}++function renderOwnedWheel(options: WheelOption[], initial: number) {+ const onChange = vi.fn();+ render(+ <OwnedWheel options={options} initial={initial} onChange={onChange} />,+ );+ return {column: screen.getByRole('listbox', {name: 'Hour'}), onChange};+}++function renderWheel(props: Partial<WheelProps> = {}) {+ const onChange = vi.fn();+ const view = render(+ <PickerWheel+ label="Hour"+ options={HOURS}+ value={10}+ onChange={onChange}+ {...props}+ />,+ );+ const column = screen.getByRole('listbox', {name: props.label ?? 'Hour'});+ column.getBoundingClientRect = () => ({+ top: 0,+ bottom: 216,+ left: 0,+ right: 120,+ width: 120,+ height: 216,+ x: 0,+ y: 0,+ toJSON() {},+ });+ const option = (label: string): HTMLElement =>+ screen.getByRole('option', {name: label});+ return {...view, onChange, column, option};+}++/** Each finger gets its own identifier, as a new contact does. */+let nextFinger = 1;+let finger = 0;++/** One touch event at the fake clock's time. */+function touch(+ type: 'touchstart' | 'touchmove' | 'touchend',+ target: Element,+ y: number,+) {+ if (type === 'touchstart') {+ finger = nextFinger++;+ }+ const event = new Event(type, {bubbles: true, cancelable: true});+ const entry = {identifier: finger, clientX: 60, clientY: y, target};+ Object.defineProperty(event, 'changedTouches', {value: [entry]});+ Object.defineProperty(event, 'touches', {+ value: type === 'touchend' ? [] : [entry],+ });+ Object.defineProperty(event, 'timeStamp', {value: performance.now()});+ act(() => {+ target.dispatchEvent(event);+ });+}++/**+ * A finger that lands at `from`, moves to `to` in `steps` events `interval`+ * ms apart, optionally holds still, and lifts.+ */+function drag(+ target: Element,+ from: number,+ to: number,+ {steps = 10, interval = 16, hold = 0} = {},+) {+ touch('touchstart', target, from);+ for (let i = 1; i <= steps; i++) {+ act(() => {+ vi.advanceTimersByTime(interval);+ });+ touch('touchmove', target, from + ((to - from) * i) / steps);+ }+ if (hold > 0) {+ act(() => {+ vi.advanceTimersByTime(hold);+ });+ }+ touch('touchend', target, to);+}++/**+ * Advances the clock with the promise callbacks between its timers run: the+ * animator dates a Reduce Motion landing from its start promise.+ */+async function advanceAsync(ms: number) {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(ms);+ });+}++function advance(ms: number) {+ act(() => {+ vi.advanceTimersByTime(ms);+ });+}++/**+ * How far below the band's centre a row is drawn: its place along the+ * strip, and the strip's translation (the `translate` the animator writes).+ */+function distanceOf(element: Element): number {+ const row = element as HTMLElement;+ const strip = row.parentElement!;+ const index = Array.prototype.indexOf.call(strip.children, row);+ const [, y = '0'] = strip.style+ .getPropertyValue('translate')+ .trim()+ .split(/\s+/);+ return index * ROW + (Number.parseFloat(y) || 0);+}++describe('PickerWheel — at rest', () => {+ it('is a listbox with one option per row, each label once', () => {+ const {column} = renderWheel();+ expect(screen.getAllByRole('option')).toHaveLength(24);+ // Each option is drawn once, as its own row.+ expect(screen.getAllByText('10')).toHaveLength(1);+ expect(column).toHaveAttribute('tabindex', '0');+ });++ it('parks the committed row under the band, the others above and below it', () => {+ const {option, column} = renderWheel();+ expect(distanceOf(option('10'))).toBeCloseTo(0, 4);+ expect(distanceOf(option('11'))).toBeCloseTo(ROW, 2);+ expect(distanceOf(option('09'))).toBeCloseTo(-ROW, 2);+ expect(column.getAttribute('aria-activedescendant')).toBe(option('10').id);+ });++ it('points the active row at a value set from outside in the same commit', () => {+ // One entry per commit: the active descendant the listbox shows then.+ const commits: (string | null)[] = [];+ const onRender = () => {+ commits.push(+ screen+ .getByRole('listbox', {name: 'Hour'})+ .getAttribute('aria-activedescendant'),+ );+ };+ const wheel = (value: number) => (+ <Profiler id="wheel" onRender={onRender}>+ <PickerWheel+ label="Hour"+ options={HOURS}+ value={value}+ onChange={() => {}}+ />+ </Profiler>+ );+ const {rerender} = render(wheel(10));+ commits.length = 0;+ rerender(wheel(12));+ expect(commits).toEqual([screen.getByRole('option', {name: '12'}).id]);+ });++ describe('a value changed from outside while it is shown', () => {+ /** The strip's place along each frame of every animation it was given. */+ let strips: number[][];++ beforeEach(() => {+ strips = [];+ // jsdom runs no Web Animations: record what the wheel asks of its strip.+ Element.prototype.animate = vi.fn(function animate(+ this: Element,+ keyframes: Keyframe[],+ ) {+ if (this.hasAttribute('data-wheel-strip')) {+ strips.push(+ keyframes.map(frame => {+ const [, y = '0'] = String(frame.translate ?? '')+ .trim()+ .split(/\s+/);+ return Number.parseFloat(y) || 0;+ }),+ );+ }+ return {cancel: () => {}} as unknown as Animation;+ });+ });++ afterEach(() => {+ Reflect.deleteProperty(Element.prototype, 'animate');+ });++ it('turns the wheel onto its row, as a bound clamping the time (component:DateInput FR14)', () => {+ const {rerender, option, onChange} = renderWheel();+ advance(2000);+ strips.length = 0;+ rerender(+ <PickerWheel+ label="Hour"+ options={HOURS}+ value={14}+ onChange={onChange}+ />,+ );+ // From 10 onto 14 through the rows between: a turn, never a jump.+ expect(strips).toHaveLength(1);+ const [turn] = strips;+ expect(turn[0]).toBeCloseTo(-10 * ROW, 1);+ expect(turn[turn.length - 1]).toBeCloseTo(-14 * ROW, 1);+ expect(+ turn.filter(y => y < -10 * ROW - 1 && y > -14 * ROW + 1).length,+ ).toBeGreaterThanOrEqual(4);+ advance(2000);+ expect(distanceOf(option('14'))).toBeCloseTo(0, 1);+ expect(isMarked(option('14'))).toBe(true);+ expect(onChange).not.toHaveBeenCalled();+ });++ it('turns on from where the wheel is drawn when the value changes again during that turn', () => {+ const {rerender, option, onChange} = renderWheel();+ advance(2000);+ const wheel = (value: number) => (+ <PickerWheel+ label="Hour"+ options={HOURS}+ value={value}+ onChange={onChange}+ />+ );+ strips.length = 0;+ rerender(wheel(14));+ advance(Math.round(picker.tapSpin.durationMs / 2));+ rerender(wheel(16));+ expect(strips).toHaveLength(2);+ const [, second] = strips;+ // The second turn starts between 10 and 14, where the first has it+ // drawn, and ends on 16.+ expect(second[0]).toBeLessThan(-10 * ROW - 1);+ expect(second[0]).toBeGreaterThan(-14 * ROW + 1);+ expect(second[second.length - 1]).toBeCloseTo(-16 * ROW, 1);+ advance(2000);+ expect(distanceOf(option('16'))).toBeCloseTo(0, 1);+ expect(onChange).not.toHaveBeenCalled();+ });+ });++ it('opening on a value outside the bounds commits nothing', () => {+ const {onChange, column, option} = renderWheel({value: 8});+ advance(2000);+ expect(onChange).not.toHaveBeenCalled();+ expect(column.getAttribute('aria-activedescendant')).toBe(option('08').id);+ });++ it('rests back on a committed value outside the bounds and commits nothing', () => {+ // component:DateInput FR13: a wheel resting on its committed row commits+ // nothing, even outside the bounds, as the scrolling column keeps it.+ const {column, option, onChange} = renderWheel({value: 8});+ advance(2000);+ // One gesture: up a row onto 09 (enabled), back down onto 08, held+ // still, lifted.+ const away = 10 + ROW;+ touch('touchstart', column, 100);+ for (let i = 1; i <= 15; i++) {+ advance(40);+ touch('touchmove', column, 100 - (away * i) / 15);+ }+ for (let i = 1; i <= 15; i++) {+ advance(40);+ touch('touchmove', column, 100 - away + (away * i) / 15);+ }+ advance(300);+ touch('touchend', column, 100);+ advance(2000);+ expect(onChange).not.toHaveBeenCalled();+ expect(distanceOf(option('08'))).toBeCloseTo(0, 4);+ // Back on the row it left, the band's mark is back on it too.+ expect(isMarked(option('08'))).toBe(true);+ });++ it('parks a value set while it is hidden at once when it is shown again', () => {+ const {rerender, option, onChange} = renderWheel();+ const wheel = (value: number, isActive: boolean) => (+ <PickerWheel+ label="Hour"+ options={HOURS}+ value={value}+ onChange={onChange}+ isActive={isActive}+ />+ );+ rerender(wheel(10, false));+ rerender(wheel(14, false));+ rerender(wheel(14, true));+ expect(distanceOf(option('14'))).toBeCloseTo(0, 4);+ });+});++/** Whether a row carries the band's mark: painted, or styled in render and not overridden. */+function isMarked(row: HTMLElement): boolean {+ if (row.style.fontWeight !== '') {+ return row.style.fontWeight === fontWeightVars['--font-weight-semibold'];+ }+ return row.className.includes('rowActive');+}++describe('PickerWheel — a finger', () => {+ it('turns text selection off while a finger holds it (spec:AST-094 FR41)', () => {+ // A held finger turns the wheel, so its pan takes the selection lock.+ // Outside iOS WebKit (jsdom here) the lock refuses a selection that+ // starts under the finger by cancelling `selectstart`, and writes no+ // style.+ const {column, option} = renderWheel();+ const refuses = () => {+ const event = new Event('selectstart', {bubbles: true, cancelable: true});+ option('10').dispatchEvent(event);+ return event.defaultPrevented;+ };+ expect(refuses()).toBe(false);+ touch('touchstart', column, CENTRE);+ expect(refuses()).toBe(true);+ expect(column.style.getPropertyValue('user-select')).toBe('');+ advance(300);+ touch('touchend', column, CENTRE);+ expect(refuses()).toBe(false);+ });++ it('marks no row while a fling coasts, then the row it rests on', () => {+ const {column, onChange} = renderWheel({+ options: MINUTES,+ value: 10,+ label: 'Minute',+ });+ const marked = () =>+ screen+ .getAllByRole('option')+ .filter(isMarked)+ .map(row => row.textContent);+ expect(marked()).toEqual(['10']);+ drag(column, 180, 60, {steps: 6, interval: 16});+ // The coast plays (jsdom shows its end inline, but no row is marked).+ expect(marked()).toEqual([]);+ advance(4000);+ expect(onChange).toHaveBeenCalledTimes(1);+ const rested = String(onChange.mock.calls[0][0]).padStart(2, '0');+ expect(marked()).toEqual([rested]);+ });++ it('marks no row while the wheel snaps or turns, then the row it rests on', () => {+ const {column} = renderWheel();+ const marked = () =>+ screen+ .getAllByRole('option')+ .filter(isMarked)+ .map(row => row.textContent);+ // A slow release snaps onto 11.+ drag(column, 150, 100, {steps: 25, interval: 40, hold: 300});+ expect(marked()).toEqual([]);+ advance(1000);+ expect(marked()).toEqual(['11']);+ // A key turns the wheel on to 12.+ fireEvent.keyDown(column, {key: 'ArrowDown'});+ expect(marked()).toEqual([]);+ advance(1000);+ expect(marked()).toEqual(['12']);+ });++ it('drags the rows with it, without committing until the wheel rests', () => {+ const {column, option, onChange} = renderWheel();+ touch('touchstart', column, 150);+ for (let i = 1; i <= 8; i++) {+ advance(16);+ touch('touchmove', column, 150 - i * 6);+ }+ // 48 px of travel, 10 of it the pan's hysteresis: 38 px up.+ expect(distanceOf(option('10'))).toBeCloseTo(-38, 1);+ expect(onChange).not.toHaveBeenCalled();+ touch('touchend', column, 102);+ advance(2000);+ });++ it('eases onto the nearest row after a slow release and commits it there', () => {+ const {column, onChange} = renderWheel();+ // 10 px of hysteresis + 40 px: 1.25 rows, held still, lifted.+ drag(column, 150, 100, {steps: 25, interval: 40, hold: 300});+ expect(onChange).not.toHaveBeenCalled();+ advance(1000);+ expect(onChange).toHaveBeenCalledWith(11);+ });++ it('keeps the band’s mark on the committed row after a nudge that eases back onto it', () => {+ const {column, option, onChange} = renderWheel();+ expect(isMarked(option('10'))).toBe(true);+ // 10 px of hysteresis + a third of a row, held still, lifted.+ drag(column, 150, 150 - (10 + ROW / 3), {+ steps: 10,+ interval: 40,+ hold: 300,+ });+ advance(2000);+ expect(onChange).not.toHaveBeenCalled();+ expect(distanceOf(option('10'))).toBeCloseTo(0, 4);+ expect(isMarked(option('10'))).toBe(true);+ });++ it('turns on to the minimum after resting below it, and commits that', () => {+ const {column, option, onChange} = renderWheel();+ // Down 3 rows (+10 px of hysteresis): the wheel rests on 07, disabled.+ drag(column, 60, 60 + 10 + 3 * ROW, {steps: 30, interval: 40, hold: 300});+ advance(100);+ expect(onChange).not.toHaveBeenCalled();+ advance(2000);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(9);+ expect(distanceOf(option('09'))).toBeCloseTo(0, 4);+ });++ it('flings across several rows before committing', () => {+ const {column, onChange} = renderWheel({+ options: MINUTES,+ value: 10,+ label: 'Minute',+ });+ drag(column, 180, 60, {steps: 6, interval: 16});+ advance(200);+ expect(onChange).not.toHaveBeenCalled();+ advance(4000);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange.mock.calls[0][0]).toBeGreaterThan(15);+ });++ it('rubber-bands past the last row and returns to it', () => {+ const {column, option, onChange} = renderWheel({value: 17});+ // Up far past hour 23.+ drag(column, 200, 20, {steps: 30, interval: 30, hold: 300});+ // Past the end, the last row has moved above the band by less than the+ // finger travelled.+ advance(3000);+ // It rests on 23 (disabled), then turns back onto 17.+ advance(2000);+ expect(onChange).not.toHaveBeenCalledWith(23);+ expect(distanceOf(option('17'))).toBeCloseTo(0, 4);+ });++ it('is held where it shows by a finger that catches it in its rubber band, then follows that finger (spec:AST-094 FR6)', () => {+ const {column, option} = renderWheel({+ options: MINUTES,+ value: 59,+ label: 'Minute',+ });+ /** The wheel's offset, from where its last row is drawn. */+ const offsetOf = () => 59 * ROW - distanceOf(option('59'));+ // Up past the last row (10 px of hysteresis and 180 more), held, lifted:+ // the wheel starts back out of its rubber band.+ drag(column, 200, 10, {steps: 30, interval: 30, hold: 300});+ // A finger lands while the return is still far out: the wheel stops+ // there, drawn where it was.+ advance(16);+ touch('touchstart', column, 150);+ advance(16);+ const caught = offsetOf();+ expect(caught - 59 * ROW).toBeGreaterThan(40);+ // The hysteresis, then 6 px more up: the band gives a little of it, never+ // a jump.+ touch('touchmove', column, 140);+ advance(16);+ touch('touchmove', column, 134);+ advance(16);+ const moved = offsetOf() - caught;+ expect(moved).toBeGreaterThan(0.5);+ expect(moved).toBeLessThan(6);+ touch('touchend', column, 134);+ advance(2000);+ });++ it('is stopped where it is by a finger that lands on it, and commits nothing', () => {+ const {column, option, onChange} = renderWheel({+ options: MINUTES,+ value: 10,+ label: 'Minute',+ });+ drag(column, 180, 60, {steps: 6, interval: 16});+ advance(150);+ // jsdom runs no animations: a motion shows its end inline.+ const heading = distanceOf(option('10'));+ touch('touchstart', column, 100);+ const caught = distanceOf(option('10'));+ // Stopped where it was on screen, well short of where it was heading,+ // and held there.+ expect(Math.abs(caught - heading)).toBeGreaterThan(ROW);+ advance(50);+ expect(Math.abs(distanceOf(option('10')) - caught)).toBeLessThan(1);+ touch('touchend', column, 100);+ // A catch is not a tap: no turn onto the touched row, only the snap.+ advance(1000);+ expect(onChange).toHaveBeenCalledTimes(1);+ const rested = onChange.mock.calls[0][0] as number;+ expect(Math.abs(distanceOf(option(String(rested).padStart(2, '0'))))).toBe(+ 0,+ );+ });++ it('turns onto a tapped row and commits it on arrival', () => {+ const {column, onChange} = renderWheel();+ const below = CENTRE + ROW;+ touch('touchstart', column, below);+ advance(60);+ touch('touchend', column, below);+ expect(onChange).not.toHaveBeenCalled();+ advance(310);+ expect(onChange).toHaveBeenCalledWith(11);+ });++ it('plays a tapped row’s turn on the tap spin’s motion role', () => {+ const {column} = renderWheel();+ const below = CENTRE + ROW;+ touch('touchstart', column, below);+ advance(60);+ touch('touchend', column, below);+ expect(motionRole('picker.tapSpin.durationMs')).toMatchObject({+ kind: 'duration',+ value: picker.tapSpin.durationMs,+ });+ });++ it('a finger’s tap turns once: its lift is cancelled, so the browser sends no click', () => {+ // spec:AST-094 FR19: the tap recognizer owns a finger's tap, and the+ // row's click handler is left to keys, assistive technology and a mouse.+ const {column, onChange} = renderWheel();+ const below = CENTRE + ROW;+ touch('touchstart', column, below);+ advance(60);+ const lift = new Event('touchend', {bubbles: true, cancelable: true});+ const entry = {+ identifier: finger,+ clientX: 60,+ clientY: below,+ target: column,+ };+ Object.defineProperty(lift, 'changedTouches', {value: [entry]});+ Object.defineProperty(lift, 'touches', {value: []});+ Object.defineProperty(lift, 'timeStamp', {value: performance.now()});+ act(() => {+ column.dispatchEvent(lift);+ });+ expect(lift.defaultPrevented).toBe(true);+ advance(310);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(11);+ });++ it('does nothing for a tap on the band’s row', () => {+ const {column, onChange} = renderWheel();+ touch('touchstart', column, CENTRE);+ advance(60);+ touch('touchend', column, CENTRE);+ advance(500);+ expect(onChange).not.toHaveBeenCalled();+ });++ it('drops a drag it is hidden in, and parks the committed row when shown again', () => {+ const {column, onChange, option, rerender} = renderWheel();+ const props = {label: 'Hour', options: HOURS, value: 10, onChange};+ // A finger drags the rows two rows up; the wheel is hidden before it lifts.+ touch('touchstart', column, 150);+ for (let i = 1; i <= 6; i++) {+ advance(16);+ touch('touchmove', column, 150 - 12 * i);+ }+ expect(distanceOf(option('10'))).not.toBeCloseTo(0, 2);+ rerender(<PickerWheel {...props} isActive={false} />);+ touch('touchend', column, 78);+ advance(1000);+ rerender(<PickerWheel {...props} isActive />);+ advance(100);+ expect(onChange).not.toHaveBeenCalled();+ expect(distanceOf(option('10'))).toBeCloseTo(0, 4);+ });++ it('ignores fingers while hidden', () => {+ const {column, option, onChange} = renderWheel({isActive: false});+ const before = option('10').style.transform;+ drag(column, 150, 60, {steps: 10, interval: 16});+ advance(3000);+ expect(onChange).not.toHaveBeenCalled();+ expect(option('10').style.transform).toBe(before);+ });+});++describe('PickerWheel — keyboard and clicks', () => {+ it('commits each arrow key at once, stepping from the row it is heading to', () => {+ const {column, onChange} = renderWheel();+ fireEvent.keyDown(column, {key: 'ArrowDown'});+ expect(onChange).toHaveBeenLastCalledWith(11);+ fireEvent.keyDown(column, {key: 'ArrowDown'});+ expect(onChange).toHaveBeenLastCalledWith(12);+ });++ it('skips disabled rows and stops at the bounds', () => {+ const {column, onChange} = renderWheel({value: 9});+ fireEvent.keyDown(column, {key: 'ArrowUp'});+ expect(onChange).not.toHaveBeenCalled();+ fireEvent.keyDown(column, {key: 'End'});+ expect(onChange).toHaveBeenLastCalledWith(17);+ });++ it('at a 12:00–17:00 bound, moves a key to the next enabled row and stops at the last one', () => {+ const bound = HOURS.map(option => ({+ ...option,+ isDisabled: option.value < 12 || option.value > 17,+ }));+ const {column, onChange} = renderOwnedWheel(bound, 17);+ // No enabled row lies below 17: these keys commit nothing.+ for (const key of ['ArrowDown', 'PageDown', 'End']) {+ fireEvent.keyDown(column, {key});+ }+ expect(onChange).not.toHaveBeenCalled();+ // PageUp's target, 7, is past the bound: the key stops at 12.+ fireEvent.keyDown(column, {key: 'PageUp'});+ expect(onChange).toHaveBeenLastCalledWith(12);+ fireEvent.keyDown(column, {key: 'ArrowUp'});+ fireEvent.keyDown(column, {key: 'Home'});+ expect(onChange).toHaveBeenCalledTimes(1);+ fireEvent.keyDown(column, {key: 'End'});+ expect(onChange).toHaveBeenLastCalledWith(17);+ });++ it('at a 12:00–17:00 bound on a 12-hour hour wheel, steps in time order: nothing after 5 PM, and 1 PM after 12 PM', () => {+ // The PM hours as the 12-hour wheel lists them, 1 to 12, each standing for+ // its full hour: 12 (noon) comes before 1. Noon to 5 PM are in the bound.+ const pmHours = Array.from({length: 12}, (_, index) => {+ const hour = index + 1;+ const hour24 = hour === 12 ? 12 : hour + 12;+ return {+ value: hour,+ label: String(hour),+ order: hour24,+ isDisabled: hour24 > 17,+ };+ });+ const {column, onChange} = renderOwnedWheel(pmHours, 5);+ for (const key of ['ArrowDown', 'PageDown', 'End']) {+ fireEvent.keyDown(column, {key});+ }+ expect(onChange).not.toHaveBeenCalled();+ fireEvent.keyDown(column, {key: 'Home'});+ expect(onChange).toHaveBeenLastCalledWith(12);+ fireEvent.keyDown(column, {key: 'ArrowDown'});+ expect(onChange).toHaveBeenLastCalledWith(1);+ fireEvent.keyDown(column, {key: 'ArrowUp'});+ expect(onChange).toHaveBeenLastCalledWith(12);+ });++ it('lets a turn onto the last allowed row finish when a key during it has nowhere to go', () => {+ const bound = HOURS.map(option => ({+ ...option,+ isDisabled: option.value < 12 || option.value > 17,+ }));+ const {column, onChange} = renderOwnedWheel(bound, 16);+ fireEvent.keyDown(column, {key: 'ArrowDown'});+ expect(onChange).toHaveBeenLastCalledWith(17);+ // Mid-turn, a second ArrowDown finds no allowed row past 17.+ advance(100);+ fireEvent.keyDown(column, {key: 'ArrowDown'});+ advance(1000);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(distanceOf(screen.getByRole('option', {name: '17'}))).toBeCloseTo(+ 0,+ 4,+ );+ });++ it('moves a key from a row outside the bounds onto the first enabled row in its direction', () => {+ const bound = HOURS.map(option => ({+ ...option,+ isDisabled: option.value < 12 || option.value > 17,+ }));+ const {column, onChange} = renderOwnedWheel(bound, 20);+ fireEvent.keyDown(column, {key: 'ArrowDown'});+ expect(onChange).not.toHaveBeenCalled();+ fireEvent.keyDown(column, {key: 'ArrowUp'});+ expect(onChange).toHaveBeenLastCalledWith(17);+ });++ it('keeps the band’s mark on the last row when a key has nowhere further to go', () => {+ const {column, option, onChange} = renderWheel({+ options: MINUTES,+ value: 59,+ label: 'Minute',+ });+ fireEvent.keyDown(column, {key: 'ArrowDown'});+ advance(1000);+ expect(onChange).not.toHaveBeenCalled();+ expect(distanceOf(option('59'))).toBeCloseTo(0, 4);+ expect(isMarked(option('59'))).toBe(true);+ });++ it('takes Home and End to the first and last enabled rows, even mid-coast', () => {+ const {column, onChange} = renderWheel({+ options: MINUTES,+ value: 10,+ label: 'Minute',+ });+ drag(column, 180, 60, {steps: 6, interval: 16});+ advance(200);+ // Still coasting, towards a row well past 10.+ expect(onChange).not.toHaveBeenCalled();+ fireEvent.keyDown(column, {key: 'Home'});+ expect(onChange).toHaveBeenLastCalledWith(0);+ fireEvent.keyDown(column, {key: 'End'});+ expect(onChange).toHaveBeenLastCalledWith(59);+ });++ it('commits a clicked row at once and never a disabled one', () => {+ const {option, onChange} = renderWheel();+ fireEvent.click(option('07'));+ expect(onChange).not.toHaveBeenCalled();+ fireEvent.click(option('13'));+ expect(onChange).toHaveBeenCalledWith(13);+ });+});++describe('PickerWheel — a mouse', () => {+ /** One mouse pointer event at the fake clock's time. */+ function mouse(+ type: 'pointerdown' | 'pointermove' | 'pointerup',+ target: Element,+ y: number,+ {button = 0, buttons = 1}: {button?: number; buttons?: number} = {},+ ) {+ const event = new PointerEvent(type, {+ bubbles: true,+ cancelable: true,+ composed: true,+ pointerId: 41,+ pointerType: 'mouse',+ isPrimary: true,+ clientX: 60,+ clientY: y,+ button,+ buttons,+ });+ Object.defineProperty(event, 'timeStamp', {value: performance.now()});+ act(() => {+ target.dispatchEvent(event);+ });+ }++ /**+ * A slow drag up by `distance` px with `button` held, then a release. The+ * drag stays well under the release velocity floor, so the wheel rests where+ * it is let go.+ */+ function mouseDrag(target: Element, distance: number, button = 0) {+ const buttons = button === 0 ? 1 : 2;+ mouse('pointerdown', target, 150, {button, buttons});+ for (let i = 1; i <= 25; i++) {+ advance(40);+ mouse('pointermove', target, 150 - (distance * i) / 25, {+ button: -1,+ buttons,+ });+ }+ advance(300);+ mouse('pointerup', target, 150 - distance, {button, buttons: 0});+ }++ it('turns with a primary-button drag and commits where it rests', () => {+ // A mouse on a touch device (a tablet's trackpad): the primary pointer+ // stays coarse.+ expect(window.matchMedia('(pointer: coarse)').matches).toBe(true);+ const {column, onChange} = renderWheel();+ // 10 px of hysteresis + 40 px: 1.25 rows.+ mouseDrag(column, 50);+ advance(1000);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(11);+ });++ it('does nothing for a secondary-button drag', () => {+ // A mouse on a touch device (a tablet's trackpad): the primary pointer+ // stays coarse.+ expect(window.matchMedia('(pointer: coarse)').matches).toBe(true);+ const {column, onChange} = renderWheel();+ mouseDrag(column, 50, 2);+ advance(2000);+ expect(onChange).not.toHaveBeenCalled();+ });+});++describe('PickerWheel — a scroll wheel and a trackpad', () => {+ /**+ * One wheel event over the column at the fake clock's time; returns whether+ * it was cancelled. `legacy` is the `wheelDeltaX`/`wheelDeltaY` that Chromium+ * and WebKit send. A mouse wheel's notch is 120 a step, and a trackpad's+ * precise delta is three times its own. The gesture host reads which it is.+ */+ function wheel(+ target: Element,+ init: {+ dx?: number;+ dy?: number;+ mode?: number;+ ctrl?: boolean;+ legacy?: {x: number; y: number};+ },+ ): boolean {+ const event = new WheelEvent('wheel', {+ bubbles: true,+ cancelable: true,+ composed: true,+ clientX: 60,+ clientY: CENTRE,+ deltaX: init.dx ?? 0,+ deltaY: init.dy ?? 0,+ deltaMode: init.mode ?? 0,+ ctrlKey: init.ctrl ?? false,+ });+ Object.defineProperty(event, 'timeStamp', {value: performance.now()});+ if (init.legacy != null) {+ Object.defineProperty(event, 'wheelDeltaX', {value: init.legacy.x});+ Object.defineProperty(event, 'wheelDeltaY', {value: init.legacy.y});+ }+ act(() => {+ target.dispatchEvent(event);+ });+ return event.defaultPrevented;+ }+ /** A mouse wheel's notch down, as Chromium sends one. */+ const notch = (target: Element) =>+ wheel(target, {dy: 100, legacy: {x: 0, y: -120}});+ /** A trackpad's precise delta down, as Chromium and WebKit send one. */+ const trackpad = (target: Element, dy: number) =>+ wheel(target, {dy, legacy: {x: 0, y: -3 * dy}});++ it('turns one row for a mouse wheel’s notch, as an arrow key does, with no coast (component:DateInput FR15)', () => {+ const {column, option, onChange} = renderWheel();+ expect(notch(column)).toBe(true);+ // As an arrow key: the next row commits at once.+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenLastCalledWith(11);+ advance(2000);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(distanceOf(option('11'))).toBeCloseTo(0, 1);+ });++ it('turns three rows for three notches, one each', () => {+ const {column, option, onChange} = renderWheel();+ for (let i = 0; i < 3; i++) {+ expect(notch(column)).toBe(true);+ advance(40);+ }+ expect(onChange.mock.calls).toEqual([[11], [12], [13]]);+ advance(2000);+ expect(distanceOf(option('13'))).toBeCloseTo(0, 1);+ });++ it('turns one row for a line-mode notch, as Firefox sends', () => {+ const {column, onChange} = renderWheel();+ expect(wheel(column, {dy: 3, mode: 1})).toBe(true);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenLastCalledWith(11);+ });++ it('leaves a ctrl-wheel, a trackpad pinch, to the page (spec:AST-094 FR10, FR43)', () => {+ const {column, onChange} = renderWheel();+ expect(wheel(column, {dy: 100, ctrl: true, legacy: {x: 0, y: -120}})).toBe(+ false,+ );+ advance(1000);+ expect(onChange).not.toHaveBeenCalled();+ });++ it('leaves a sideways scroll to the page', () => {+ const {column, onChange} = renderWheel();+ expect(wheel(column, {dx: 100, legacy: {x: -120, y: 0}})).toBe(false);+ advance(1000);+ expect(onChange).not.toHaveBeenCalled();+ });++ it('follows a trackpad’s fingers, coasts on at their lift and rests on a row, as a finger’s flick does (component:DateInput FR15)', () => {+ const {column, option, onChange} = renderWheel({+ options: MINUTES,+ value: 10,+ label: 'Minute',+ });+ /** The wheel's offset, from where minute 10 is drawn. */+ const offsetOf = () => 10 * ROW - distanceOf(option('10'));+ // The fingers: 12 px a frame for 12 frames.+ for (let i = 0; i < 12; i++) {+ expect(trackpad(column, 12)).toBe(true);+ advance(16);+ }+ const atLift = offsetOf();+ // The rows followed the fingers' travel.+ expect(atLift).toBeGreaterThan(10 * ROW + 60);+ expect(onChange).not.toHaveBeenCalled();+ // The momentum the platform sends after the lift: a shrinking run.+ for (const dy of [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) {+ trackpad(column, dy);+ advance(16);+ }+ advance(3000);+ // It coasted on past the fingers' travel at UIKit's deceleration, much+ // farther than the platform's momentum. That momentum (66 px) never moves+ // it. It rests on a row there, committed once.+ expect(onChange).toHaveBeenCalledTimes(1);+ const [[rested]] = onChange.mock.calls as [[number]];+ expect(rested * ROW - atLift).toBeGreaterThan(5 * ROW);+ expect(distanceOf(option(String(rested).padStart(2, '0')))).toBeCloseTo(+ 0,+ 1,+ );+ });++ it('rests on the nearest row after a slow trackpad drag that stops, without coasting', () => {+ const {column, option, onChange} = renderWheel({+ options: MINUTES,+ value: 10,+ label: 'Minute',+ });+ const offsetOf = () => 10 * ROW - distanceOf(option('10'));+ // 2 px a frame for 20 frames, then the fingers stop on the pad.+ for (let i = 0; i < 20; i++) {+ trackpad(column, 2);+ advance(16);+ }+ const stopped = offsetOf();+ advance(3000);+ expect(onChange).toHaveBeenCalledTimes(1);+ const [[rested]] = onChange.mock.calls as [[number]];+ expect(Math.abs(rested * ROW - stopped)).toBeLessThanOrEqual(ROW / 2 + 1);+ });+});++describe('PickerWheel — under reduced motion', () => {+ const FADE_MS = timing.reducedMotionCrossFadeMs;+ /** Every animation the wheel started, with its keyframes and timing. */+ let animations: {keyframes: Keyframe[]; options: KeyframeAnimationOptions}[];++ beforeEach(() => {+ animations = [];+ vi.stubGlobal('matchMedia', (query: string) => ({+ // The touch column draws under a coarse primary pointer.+ matches:+ query === '(prefers-reduced-motion: reduce)' ||+ query === '(pointer: coarse)',+ media: query,+ addEventListener: () => {},+ removeEventListener: () => {},+ }));+ // jsdom runs no Web Animations: record what the wheel asks for.+ Element.prototype.animate = vi.fn(function animate(+ keyframes: Keyframe[],+ options: KeyframeAnimationOptions,+ ) {+ animations.push({keyframes, options});+ return {cancel: () => {}} as unknown as Animation;+ });+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ Reflect.deleteProperty(Element.prototype, 'animate');+ });++ /**+ * Nothing travels on the animator's Reduce Motion cross-fade+ * (design:reduced-motion DR2). The strip's opacity dips out over half the+ * fade, and its rows land on their row while it is transparent. No animation+ * moves the strip.+ */+ function expectFadesOnly() {+ expect(animations.length).toBeGreaterThan(0);+ for (const {keyframes} of animations) {+ const properties = new Set(+ keyframes.flatMap(frame =>+ Object.keys(frame).filter(+ key => key !== 'offset' && key !== 'easing',+ ),+ ),+ );+ expect([...properties]).toEqual(['opacity']);+ }+ const [dip] = animations;+ const out = dip.keyframes.find(frame => Number(frame.opacity) === 0);+ expect(out).toBeDefined();+ expect(Number(out?.offset) * Number(dip.options.duration)).toBeCloseTo(+ FADE_MS / 2,+ 0,+ );+ }++ it('coasts a fling as momentum, its rows flat, then commits it', () => {+ // design:reduced-motion DR2: the momentum that continues a throw is+ // direct movement, not a transition, so it plays.+ const {column, onChange} = renderWheel({+ options: MINUTES,+ value: 10,+ label: 'Minute',+ });+ drag(column, 180, 60, {steps: 6, interval: 16});+ expect(animations.length).toBeGreaterThan(0);+ for (const {keyframes, options} of animations) {+ expect(options.duration).toBeGreaterThan(FADE_MS);+ // The strip travels, and nothing fades.+ expect(keyframes.some(frame => 'translate' in frame)).toBe(true);+ expect(keyframes.some(frame => 'opacity' in frame)).toBe(false);+ }+ expect(onChange).not.toHaveBeenCalled();+ advance(4000);+ expect(onChange).toHaveBeenCalledTimes(1);+ // The row the fling projects, as without the preference.+ expect(onChange.mock.calls[0][0]).toBeGreaterThan(15);+ });++ it('fades a slow release onto its row', () => {+ // A release that snaps is a transition the wheel starts: it cross-fades.+ const {column, onChange} = renderWheel();+ drag(column, 60, 60 + 10 + 1.4 * ROW, {steps: 20, interval: 40, hold: 300});+ expectFadesOnly();+ advance(FADE_MS);+ expect(onChange).toHaveBeenLastCalledWith(9);+ });++ it('fades for a tap and a key', async () => {+ const {column, onChange} = renderWheel();+ const below = CENTRE + ROW;+ touch('touchstart', column, below);+ advance(60);+ touch('touchend', column, below);+ await advanceAsync(FADE_MS);+ expect(onChange).toHaveBeenLastCalledWith(11);+ // A key steps from the row the wheel rests on (the tap's 11).+ fireEvent.keyDown(column, {key: 'ArrowDown'});+ expect(onChange).toHaveBeenLastCalledWith(12);+ await advanceAsync(FADE_MS);+ expectFadesOnly();+ });+});++describe('PickerWheel — mechanics for its owners', () => {+ it('keeps a finger that lands on it from an enclosing sheet', () => {+ // A sheet arms its pull-down on its body's pointerdown.+ const onPointerDown = vi.fn();+ const onChange = vi.fn();+ render(+ <div onPointerDown={onPointerDown}>+ <PickerWheel+ label="Minute"+ options={MINUTES}+ value={10}+ onChange={onChange}+ />+ </div>,+ );+ const column = screen.getByRole('listbox', {name: 'Minute'});+ fireEvent.pointerDown(column, {+ pointerId: 7,+ pointerType: 'touch',+ isPrimary: true,+ button: 0,+ });+ expect(onPointerDown).not.toHaveBeenCalled();+ });++ it('keeps coasting when its owner hands it a copy of the same rows', () => {+ const {column, rerender, onChange} = renderWheel({+ options: MINUTES,+ value: 10,+ label: 'Minute',+ });+ drag(column, 180, 60, {steps: 6, interval: 16});+ advance(200);+ rerender(+ <PickerWheel+ label="Minute"+ options={MINUTES.map(option => ({...option}))}+ value={10}+ onChange={onChange}+ />,+ );+ advance(4000);+ // It came to rest on a row and committed it, as without the re-render.+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange.mock.calls[0][0]).toBeGreaterThan(15);+ });+});++describe('PickerWheel — markup', () => {+ // Written before the listbox wiring moved into useWheelListbox: the+ // snapshot holds the touch column to its markup.+ it('fades its rows on a layer inside the column, so the focus ring the column draws stays whole', () => {+ const {column} = renderWheel();+ const fade = column.querySelector('[data-wheel-fade]');+ expect(fade).not.toBeNull();+ expect(fade?.parentElement).toBe(column);+ expect(fade?.querySelector('[data-wheel-strip]')).not.toBeNull();+ });++ it('keeps the touch column’s markup', () => {+ const {column} = renderWheel();+ // React's generated ids depend on how many renders ran before.+ expect(+ column.parentElement?.innerHTML.replace(/_r_[0-9a-z]+_/g, '_r_id_'),+ ).toMatchSnapshot();+ });+});diff --git a/packages/core/src/DateInput/PickerWheel.tsx b/packages/core/src/DateInput/PickerWheel.tsxnew file mode 100644index 0000000000..8deee68ef9--- /dev/null+++ b/packages/core/src/DateInput/PickerWheel.tsx@@ -0,0 +1,765 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file PickerWheel.tsx+ * @input Wheel's props (wheelOptions.ts): options, value and change callback+ * @output PickerWheel: one picker column that moves like UIPickerView+ * @position Internal component; the Wheel under a finger (Wheel.tsx picks it)+ *+ * It moves on the gesture system and the shared animator, not on a native+ * scroller. One strip holds the rows and is the only element that moves.+ *+ * SYNC: When modified, update PickerWheel.test.tsx, Wheel.tsx,+ * DateInputTouch.test.tsx, DateInput.doc.mjs and TimeInput.doc.mjs.+ */++import {useCallback, useEffect, useMemo, useRef, useState} from 'react';+import * as stylex from '@stylexjs/stylex';+import {scrollTypeOf} from '../gestures/GestureHost';+import {PanGestureRecognizer} from '../gestures/PanGestureRecognizer';+import {TapGestureRecognizer} from '../gestures/TapGestureRecognizer';+import {useGestureRecognizer} from '../gestures/useGestureRecognizer';+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';+import {rubberBandInverse} from '../motion/rubberBand';+import {resolveMotion} from '../motion/resolveMotion';+import {picker, registerPickerTable} from '../motion/uikit/picker';+import {registerScrollTable, scroll} from '../motion/uikit/scroll';+import {registerTimingTable, timing} from '../motion/uikit/timing';+import {+ colorVars,+ fontWeightVars,+ radiusVars,+ spacingVars,+ typeScaleVars,+} from '../theme/tokens.stylex';+import {focusOutlineStyles} from '../utils/focusOutline.stylex';+import {lockSelection} from '../gestures/selectionLock';+import {dateInputTouchGeometry, dateInputTouchSizes} from './tokens.stylex';+import {useOwnScrollGesture} from './useOwnScrollGesture';+import {useWheelListbox} from './useWheelListbox';+import {createWheelStrip, type PlayOptions} from './wheelStrip';+import {+ dragOffset,+ nearestIndex,+ offsetBounds,+ planRelease,+ spinCurve,+ type WheelCurve,+ type WheelLayout,+} from './wheelPhysics';+import {+ endIndex,+ nearestEnabledIndex,+ steppedIndex,+ WHEEL_ROW_HEIGHT,+ type WheelProps,+} from './wheelOptions';++/** Row pitch, px: the touch column keeps the scrolling column's pitch. */+const ROW_HEIGHT = WHEEL_ROW_HEIGHT;+/** UIKit's picker measures scaled to that pitch (UIKit's row is 32 pt). */+const UIKIT_SCALE = ROW_HEIGHT / picker.geometry.rowHeight;+/** UIKit's rubber band dimension for the picker's table, at that pitch. */+const RUBBER_BAND_DIMENSION = picker.geometry.rubberBandDimension * UIKIT_SCALE;++const styles = stylex.create({+ // The scrolling column's box, band and rows (Wheel.tsx), moved by the+ // gesture system and the compositor instead of a native scroller.+ column: {+ position: 'relative',+ flex: '1 1 0',+ minInlineSize: 0,+ blockSize: dateInputTouchGeometry.paneBlockSize,+ overflow: 'hidden',+ outline: 'none',+ WebkitTapHighlightColor: 'transparent',+ },+ // The rows fade toward the column's edges, from the scrolling column's 0.3+ // to fully opaque at the band and back. The scrolling column fades them the+ // same way under reduced motion. A static mask: nothing paints it again as+ // the strip moves. It sits inside the column, so it never clips the+ // column's focus ring.+ fade: {+ position: 'absolute',+ inset: 0,+ pointerEvents: 'none',+ maskImage:+ 'linear-gradient(to bottom, rgb(0 0 0 / 0.3), rgb(0 0 0) 50%, rgb(0 0 0 / 0.3))',+ },+ /**+ * The selection band: a centred row-height plate behind the rows.+ * Decorative: the committed value is announced by `aria-selected`.+ */+ band: {+ position: 'absolute',+ insetInline: 0,+ insetBlockStart: `calc(50% - (${dateInputTouchSizes.wheelItemSize} / 2))`,+ blockSize: dateInputTouchSizes.wheelItemSize,+ borderRadius: radiusVars['--radius-element'],+ backgroundColor: colorVars['--color-neutral'],+ pointerEvents: 'none',+ },+ /**+ * The strip holds the rows at their places along the wheel, with its top on+ * the band's row. It moves by minus the wheel's offset, and the animator+ * writes its `translate`. Also what a reduced-motion cross-fade fades.+ */+ strip: {+ position: 'absolute',+ insetInline: 0,+ insetBlockStart: `calc(50% - (${dateInputTouchSizes.wheelItemSize} / 2))`,+ pointerEvents: 'none',+ },+ /** One row: an option at its place along the strip, flat. */+ row: {+ position: 'absolute',+ insetInline: 0,+ blockSize: dateInputTouchSizes.wheelItemSize,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ paddingInline: spacingVars['--spacing-2'],+ boxSizing: 'border-box',+ fontSize: typeScaleVars['--text-large-size'],+ fontWeight: fontWeightVars['--font-weight-normal'],+ color: colorVars['--color-text-primary'],+ whiteSpace: 'nowrap',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ userSelect: 'none',+ // The mark has no transition, unlike the scrolling column's. A colour or+ // weight that animates lays out and paints every frame on the main thread.+ // A mark set as a drag lets go would do so through the coast.+ },+ /** The row under the band, as the scrolling column marks it. */+ rowActive: {+ color: colorVars['--color-text-accent'],+ fontWeight: fontWeightVars['--font-weight-semibold'],+ },+ rowDisabled: {+ color: colorVars['--color-text-disabled'],+ },+ /** A row at its place along the strip. */+ rowAt: (top: string) => ({insetBlockStart: top}),+});++/**+ * The motion tables the wheel resolves internal roles from: the timing curve,+ * the scroll bounce and the picker's tap spin. Nothing registers on import+ * (motion/roles.ts) and each register is idempotent, so the wheel calls this+ * right before it resolves a role.+ */+function registerWheelTables(): void {+ registerTimingTable();+ registerScrollTable();+ registerPickerTable();+}++/**+ * A turn onto `to` on the picker's tap spin: its duration and its curve, as+ * resolved under `column` when the turn starts.+ */+function turnCurve(+ column: Element | null,+ from: number,+ to: number,+): WheelCurve {+ registerWheelTables();+ return spinCurve(+ from,+ to,+ resolveMotion(column, picker.tapSpin, 'durationMs') / 1000,+ resolveMotion(column, timing.curves.move),+ );+}++interface DragState {+ /** The finger's offset at the pan's start, before any rubber band. */+ readonly start: number;+}++/**+ * One UIPickerView column: the Wheel under a finger. It does not scroll+ * natively. WebKit gives every scroll-snapping scroller the fast deceleration+ * rate, and a scroller's momentum cannot be caught or measured. A busy main+ * thread does not stop or jump a motion here. Under Reduce Motion a throw's+ * momentum still plays, as iOS scrolling does. Every other motion+ * cross-fades onto its row.+ *+ * @example+ * ```+ * <PickerWheel label="Month" options={monthOptions} value={month} onChange={setMonth} />+ * ```+ */+export function PickerWheel({+ label,+ options,+ value,+ onChange,+ isActive = true,+}: WheelProps) {+ const columnRef = useRef<HTMLDivElement | null>(null);+ const rowsRef = useRef<HTMLDivElement | null>(null);+ const rowCount = options.length;+ const layout = useMemo<WheelLayout>(+ () => ({rowHeight: ROW_HEIGHT, rowCount}),+ [rowCount],+ );+ const [motion] = useState(() => createWheelStrip(layout));+ const selectedIndex = Math.max(+ 0,+ options.findIndex(option => option.value === value),+ );+ const dragRef = useRef<DragState | null>(null);+ /** A finger landed on a moving wheel and stopped it. */+ const caughtRef = useRef(false);++ // The latest props, for the motion's and the gesture listeners' callbacks,+ // which are attached once and outlive a render.+ const latestRef = useRef({options, value, onChange, layout});+ useIsomorphicLayoutEffect(() => {+ latestRef.current = {options, value, onChange, layout};+ });++ // The row under the band is marked as the scrolling column marks it. At rest+ // that is the committed row, styled in render. While a finger drags the+ // wheel, the row reaching the band is painted directly, so marking it never+ // re-renders. A motion unmarks every row as it starts and marks the row it+ // stops or ends on. The compositor then plays it with no layout or paint per+ // frame, and no mark rides away from the band.+ const paintedRef = useRef<Set<HTMLElement>>(new Set());+ const paintRow = useCallback((position: number | null) => {+ const container = rowsRef.current;+ if (container == null || container.children.length === 0) {+ return;+ }+ const rows = container.children;+ const {options: currentOptions, value: currentValue} = latestRef.current;+ const active =+ position == null+ ? null+ : ((rows[position] as HTMLElement | undefined) ?? null);+ const painted = paintedRef.current;+ for (const row of painted) {+ row.style.removeProperty('color');+ row.style.removeProperty('font-weight');+ }+ painted.clear();+ const selected = currentOptions.findIndex(+ option => option.value === currentValue,+ );+ if (rows[selected] != null && rows[selected] !== active) {+ // The committed row's own mark gives way while another row is under+ // the band.+ const row = rows[selected] as HTMLElement;+ row.style.color = currentOptions[selected]?.isDisabled+ ? colorVars['--color-text-disabled']+ : colorVars['--color-text-primary'];+ row.style.fontWeight = fontWeightVars['--font-weight-normal'];+ painted.add(row);+ }+ if (active == null || position == null) {+ return;+ }+ active.style.color = currentOptions[position]?.isDisabled+ ? colorVars['--color-text-disabled']+ : colorVars['--color-text-accent'];+ active.style.fontWeight = fontWeightVars['--font-weight-semibold'];+ painted.add(active);+ }, []);++ // Every motion the wheel starts. Under Reduce Motion a transition lands+ // without travel: the animator cross-fades the strip onto its row. The+ // momentum that continues a throw is not a transition, so it plays as is.+ const move = useCallback(+ (curve: WheelCurve, options: PlayOptions = {}) => {+ paintRow(null);+ // The mark comes back from the row the motion reports nearest when it+ // ends, even the row it began on.+ motion.forgetNearest();+ motion.play(curve, options);+ },+ [motion, paintRow],+ );++ // The wheel came to rest at `offset`: commit, or turn on to the row the+ // rest rule names first.+ const arrive = useCallback(+ (offset: number) => {+ const current = latestRef.current;+ const row = nearestIndex(offset, current.layout);+ const committed = current.options.findIndex(+ option => option.value === current.value,+ );+ // A rest on the committed row is not a stop to correct. A committed value+ // outside the bounds stays until a person moves the wheel off it, as in+ // the scrolling column.+ let step = 0;+ if (row !== committed) {+ step =+ nearestEnabledIndex(current.options, row, Math.max(0, committed)) -+ row;+ }+ if (step !== 0) {+ const target = row + step;+ move(turnCurve(columnRef.current, offset, target * ROW_HEIGHT), {+ onEnd: (outcome, end) => {+ if (outcome === 'arrived') {+ arrive(end);+ }+ },+ });+ return;+ }+ const option = current.options[row];+ if (+ option != null &&+ !option.isDisabled &&+ option.value !== current.value+ ) {+ current.onChange(option.value);+ }+ },+ [move],+ );++ const onEnd = useCallback(+ (outcome: 'arrived' | 'stopped', offset: number) => {+ if (outcome === 'arrived') {+ arrive(offset);+ }+ },+ [arrive],+ );++ // The animator holds the strip while it is attached, and lets it go as it+ // detaches or is replaced.+ const attachStrip = useCallback(+ (strip: HTMLDivElement) => {+ rowsRef.current = strip;+ motion.attach(strip);+ return () => {+ rowsRef.current = null;+ motion.attach(null);+ };+ },+ [motion],+ );++ // The motion's layout follows the rows.+ useIsomorphicLayoutEffect(() => {+ motion.setLayout(layout);+ }, [motion, layout]);++ // The band's mark follows the row the motion reports nearest the band.+ useIsomorphicLayoutEffect(() => {+ motion.onNearestChange(paintRow);+ return () => motion.onNearestChange(null);+ }, [motion, paintRow]);+ // At rest on the committed row, render's own mark takes over again.+ useIsomorphicLayoutEffect(() => {+ if (+ motion.isMoving() ||+ dragRef.current != null ||+ nearestIndex(motion.offset(), layout) !== selectedIndex+ ) {+ return;+ }+ for (const row of paintedRef.current) {+ row.style.removeProperty('color');+ row.style.removeProperty('font-weight');+ }+ paintedRef.current.clear();+ });++ // The motion's animations and timers end with the wheel.+ useEffect(() => () => motion.dispose(), [motion]);++ // Park the committed row under the band when the wheel is shown, at once. 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. A second change during that+ // turn turns on from where the wheel is drawn. Never while a finger or a+ // motion of its own owns the wheel.+ const parkedRef = useRef(false);+ const parkTurnRef = useRef<object | null>(null);+ useIsomorphicLayoutEffect(() => {+ if (!isActive) {+ parkedRef.current = false;+ return;+ }+ if (+ dragRef.current != null ||+ (motion.isMoving() && parkTurnRef.current == null)+ ) {+ return;+ }+ const target = selectedIndex * ROW_HEIGHT;+ const shown = motion.isMoving() ? motion.stop() : motion.offset();+ const isAway = Math.abs(shown - target) > 0.01;+ if (isAway && parkedRef.current) {+ // The turn's own end paints the band's row.+ const turn = {};+ parkTurnRef.current = turn;+ move(turnCurve(columnRef.current, shown, target), {+ onEnd: () => {+ if (parkTurnRef.current === turn) {+ parkTurnRef.current = null;+ }+ },+ });+ return;+ }+ if (isAway) {+ motion.setOffset(target);+ }+ parkedRef.current = true;+ }, [isActive, selectedIndex, motion, move]);++ // A hidden wheel keeps no motion running and holds no drag. Hiding it+ // mid-drag ends the pan without calling its listener, because the toggle's+ // owner owns that end. So the drag is dropped here, uncommitted. Shown again,+ // the wheel parks the committed row.+ useEffect(() => {+ if (!isActive) {+ dragRef.current = null;+ motion.stop();+ }+ }, [isActive, motion]);++ // A finger lands: a moving wheel stops where it is on screen.+ const onTouchDown = useCallback(+ (time: number) => {+ caughtRef.current = motion.isMoving();+ if (caughtRef.current) {+ motion.stop(time);+ }+ },+ [motion],+ );++ // The latest touch-down handler, for the gesture listener attached once.+ const onTouchDownRef = useRef(onTouchDown);+ useIsomorphicLayoutEffect(() => {+ onTouchDownRef.current = onTouchDown;+ });++ const release = useCallback(+ (velocity: number) => {+ registerWheelTables();+ const plan = planRelease(+ motion.offset(),+ velocity,+ latestRef.current.layout,+ resolveMotion(columnRef.current, scroll.bounce),+ );+ move(plan.curve, {+ ticks: true,+ onEnd,+ touchRelease: true,+ momentum: plan.kind === 'coast' || plan.kind === 'edge',+ });+ },+ [motion, move, onEnd],+ );++ const pan = useGestureRecognizer(+ columnRef,+ () =>+ new PanGestureRecognizer({+ name: 'wheel-pan',+ direction: 'vertical',+ // A trackpad's two-finger scroll drives the pan as a finger does. The+ // rows follow, coast on at the lift with the fingers' last speed, and+ // rest by the rest rule. A mouse wheel's notches never reach the pan.+ allowedScrollTypes: ['continuous'],+ // A held finger on the wheel never starts text selection or the+ // callout.+ selectionLock: lockSelection,+ shouldReceiveTouch: (_pan, touch) => {+ onTouchDownRef.current(touch.time);+ return true;+ },+ }),+ recognizer => {+ const {layout: currentLayout} = latestRef.current;+ switch (recognizer.state) {+ case 'began': {+ const shown = motion.isMoving() ? motion.stop() : motion.offset();+ dragRef.current = {start: fingerOffset(shown, currentLayout)};+ motion.resetDrag();+ motion.setOffset(+ dragOffset(+ dragRef.current.start - recognizer.translation().y,+ currentLayout,+ ),+ {ticks: true},+ );+ break;+ }+ case 'changed': {+ const drag = dragRef.current;+ if (drag == null) {+ break;+ }+ motion.setOffset(+ dragOffset(drag.start - recognizer.translation().y, currentLayout),+ {ticks: true},+ );+ break;+ }+ case 'ended': {+ const drag = dragRef.current;+ dragRef.current = null;+ // A scroll view's release velocity (the pan's last two, blended as+ // UIPickerView's); the rows move against the finger.+ release(drag == null ? 0 : -recognizer.scrollVelocity().y);+ break;+ }+ case 'cancelled': {+ dragRef.current = null;+ release(0);+ break;+ }+ case 'possible':+ case 'failed':+ break;+ }+ },+ {isEnabled: isActive},+ );++ // A touch that stopped a moving wheel and lifted without dragging: the+ // wheel eases onto the nearest row, as a release without velocity does.+ useEffect(+ () =>+ pan.addTransitionListener((_pan, _from, to) => {+ // The flag stays up until the next touch lands. The tap recognizer may+ // hear of this lift after the pan does, and must not read it as a tap+ // on a row.+ if (to === 'failed' && caughtRef.current && !motion.isMoving()) {+ release(0);+ }+ }),+ [pan, motion, release],+ );++ useGestureRecognizer(+ columnRef,+ () => new TapGestureRecognizer({name: 'wheel-tap'}),+ recognizer => {+ if (recognizer.state !== 'ended' || caughtRef.current) {+ return;+ }+ const column = columnRef.current;+ if (column == null) {+ return;+ }+ const box = column.getBoundingClientRect();+ const {y} = recognizer.location();+ const offset = motion.offset();+ const currentLayout = latestRef.current.layout;+ const target = rowAtPoint(+ y - (box.top + box.height / 2),+ offset,+ currentLayout,+ );+ if (target == null || target === nearestIndex(offset, currentLayout)) {+ return;+ }+ move(turnCurve(columnRef.current, offset, target * ROW_HEIGHT), {+ onEnd,+ });+ },+ {isEnabled: isActive},+ );++ // Keep the finger, and the pointer it lands with: inside a BottomSheet the+ // sheet would otherwise read a downward drag here as swipe-to-dismiss. This+ // wheel pans through the gesture system, which never cancels the pointer+ // the sheet armed on (see useOwnScrollGesture).+ useOwnScrollGesture(columnRef, 'all', {+ isEnabled: isActive,+ isPointerKept: true,+ });++ // A key commits the row at `position` at once and turns the wheel there+ // from `offset`.+ const turnToPosition = useCallback(+ (position: number, offset: number) => {+ const current = latestRef.current;+ const option = current.options[position];+ if (option.value !== current.value) {+ current.onChange(option.value);+ }+ move(turnCurve(columnRef.current, offset, position * ROW_HEIGHT));+ },+ [move],+ );++ const moveBy = useCallback(+ (delta: number) => {+ const current = latestRef.current;+ if (current.options.length === 0 || delta === 0) {+ return;+ }+ // Keys step from the row the wheel is heading to, not the one it is+ // passing: two quick presses move two rows. A key with nowhere to go+ // leaves a turn in flight to finish on its row.+ const row = steppedIndex(+ current.options,+ nearestIndex(motion.target(), current.layout),+ delta,+ );+ if (row == null) {+ return;+ }+ const offset = motion.isMoving() ? motion.stop() : motion.offset();+ turnToPosition(row, offset);+ },+ [motion, turnToPosition],+ );++ // A mouse wheel's notch turns the wheel one row, as an arrow key does, with+ // no coast. The gesture host leaves a notch to what is under the pointer,+ // which is this wheel. A wheel the pan took arrives here already prevented.+ // A ctrl-wheel stays the page's zoom, and a sideways scroll stays the+ // page's.+ useEffect(() => {+ const column = columnRef.current;+ if (column == null || !isActive) {+ return undefined;+ }+ const onWheel = (event: WheelEvent) => {+ if (+ event.defaultPrevented ||+ event.ctrlKey ||+ event.shiftKey ||+ event.deltaY === 0 ||+ Math.abs(event.deltaX) > Math.abs(event.deltaY) ||+ scrollTypeOf(event) !== 'discrete'+ ) {+ return;+ }+ event.preventDefault();+ moveBy(Math.sign(event.deltaY));+ };+ column.addEventListener('wheel', onWheel, {passive: false});+ return () => column.removeEventListener('wheel', onWheel);+ }, [isActive, moveBy]);++ // Home and End: the first and the last enabled row.+ const moveToEnd = useCallback(+ (end: 'first' | 'last') => {+ const row = endIndex(latestRef.current.options, end);+ if (row == null) {+ return;+ }+ const offset = motion.isMoving() ? motion.stop() : motion.offset();+ turnToPosition(row, offset);+ },+ [motion, turnToPosition],+ );++ // A click on a row commits it at once and turns the wheel there, as the arrow+ // keys do. The click comes from assistive technology, a keyboard, a test, or+ // a mouse the tap recognizer did not take. A finger's tap is the tap+ // recognizer's, and the click it would produce is swallowed by the gesture+ // system.+ const activateRow = useCallback(+ (row: number) => {+ const current = latestRef.current;+ const option = current.options[row];+ if (option == null || option.isDisabled) {+ return;+ }+ const offset = motion.isMoving() ? motion.stop() : motion.offset();+ if (option.value !== current.value) {+ current.onChange(option.value);+ }+ move(turnCurve(columnRef.current, offset, row * ROW_HEIGHT));+ },+ [motion, move],+ );++ const {listboxProps, optionProps} = useWheelListbox({+ label,+ options,+ value,+ // The committed row: a value set from outside shows in the same render.+ activeIndex: selectedIndex,+ stepBy: moveBy,+ toEnd: moveToEnd,+ activate: activateRow,+ });++ return (+ <div+ ref={columnRef}+ {...listboxProps}+ data-wheel=""+ {...stylex.props(styles.column, focusOutlineStyles.focusVisible)}>+ <div data-wheel-fade="" {...stylex.props(styles.fade)}>+ <div aria-hidden="true" {...stylex.props(styles.band)} />+ <div+ ref={attachStrip}+ data-wheel-strip=""+ {...stylex.props(styles.strip)}>+ {options.map((option, index) => (+ <div+ key={option.value}+ {...optionProps(option, index)}+ data-wheel-row=""+ data-label={option.label}+ {...stylex.props(+ styles.row,+ styles.rowAt(`${index * ROW_HEIGHT}px`),+ index === selectedIndex && styles.rowActive,+ option.isDisabled && styles.rowDisabled,+ )}>+ {option.label}+ </div>+ ))}+ </div>+ </div>+ </div>+ );+}++PickerWheel.displayName = 'PickerWheel';++/**+ * The row under a point `dy` px below the band's centre, or null past either+ * end of the list.+ */+function rowAtPoint(+ dy: number,+ offset: number,+ layout: WheelLayout,+): number | null {+ const position = Math.round((offset + dy) / layout.rowHeight);+ if (position < 0 || position >= layout.rowCount) {+ return null;+ }+ return position;+}++/**+ * The finger's offset for a shown one. Past an end, it is the travel that the+ * rubber band shows as `shown`. So a drag that starts in a bounce continues+ * without a jump.+ */+function fingerOffset(shown: number, layout: WheelLayout): number {+ const {min, max} = offsetBounds(layout);+ const dimension = RUBBER_BAND_DIMENSION;+ if (shown < min) {+ return min + rubberBandInverse(shown - min, dimension);+ }+ if (shown > max) {+ return max + rubberBandInverse(shown - max, dimension);+ }+ return shown;+}diff --git a/packages/core/src/DateInput/Wheel.test.tsx b/packages/core/src/DateInput/Wheel.test.tsxindex 130c9f0d36..e7fbb5a047 100644--- a/packages/core/src/DateInput/Wheel.test.tsx+++ b/packages/core/src/DateInput/Wheel.test.tsx@@ -2,17 +2,26 @@/*** @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+ * @input Uses Vitest, Testing Library, the Wheel column and a stubbed+ * matchMedia (and CSS.supports, to show the engine does not matter)+ * @output Proves where today's wheel rests when it stops on a row it cannot+ * commit, and which column (and which frame) each primary pointer draws+ * @position Unit coverage for Wheel.tsx: the switch and today's column+ * (PickerWheel.test.tsx covers the touch column); the wheels inside the* DateInput, DateTimeInput and TimeInput sheets are covered by their own* touch suites*/+import {useState} from 'react';import {act, fireEvent, render, screen} from '@testing-library/react';import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest';import {fakeAnimate} from '../motion/__tests__/fakeWebAnimation';-import {nearestEnabledIndex, Wheel, type WheelOption} from './Wheel';+import {+ nearestEnabledIndex,+ ScrollWheel,+ Wheel,+ type WheelOption,+} from './Wheel';import {SCROLL_QUIET_MS} from './useScrollSettle';const ROW = 28;@@ -68,7 +77,7 @@ describe('Wheel — where it comes to rest', () => {* the scroller's scrollTop and scrollTo, so a test can stop the wheel on any* row.*/- function renderWheel(value: number) {+ function renderWheel(value: number, Column: typeof ScrollWheel = Wheel) {Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {configurable: true,get(this: HTMLElement) {@@ -78,7 +87,7 @@ describe('Wheel — where it comes to rest', () => {const onChange = vi.fn();const scrollTo = vi.fn();const {rerender, unmount} = render(- <Wheel label="Hour" options={HOURS} value={value} onChange={onChange} />,+ <Column label="Hour" options={HOURS} value={value} onChange={onChange} />,);const scroller = screen.getByRole('listbox', {name: 'Hour'});let top = value * ROW;@@ -214,10 +223,13 @@ describe('Wheel — where it comes to rest', () => {);});- it('cross-fades onto it on a touch screen: opacity only, 200 ms', async () => {- stubReducedMotion('coarse');+ it('cross-fades onto it after a touch: opacity only, 200 ms', async () => {+ // A touch screen whose primary pointer is fine (a laptop's): today's+ // column, and a touch release fades (DR2).+ stubReducedMotion('fine');const {scrollTo, stopOn} = renderWheel(10);const scroller = screen.getByRole('listbox', {name: 'Hour'});+ fireEvent.pointerDown(scroller, {pointerType: 'touch'});const {animate, animations} = fakeAnimate();scroller.animate = animate;stopOn(7);@@ -253,10 +265,11 @@ describe('Wheel — where it comes to rest', () => {it('lands the rows only when the fade-out ends, however late its frame comes', async () => {// design:reduced-motion DR2: a timer at the dip's middle could fire// after the fade-in began, and the rows would move fully visible.- stubReducedMotion('coarse');+ stubReducedMotion('fine');vi.useFakeTimers();const {scrollTo, stopOn} = renderWheel(10);const scroller = screen.getByRole('listbox', {name: 'Hour'});+ fireEvent.pointerDown(scroller, {pointerType: 'touch'});const {animate, animations} = fakeAnimate();scroller.animate = animate;stopOn(7);@@ -294,9 +307,11 @@ describe('Wheel — where it comes to rest', () => {});}- it('lands an arrow key step on a touch screen under its cross-fade, not before', async () => {+ it('lands an arrow key step on a coarse pointer under its cross-fade, not before', async () => {+ // A finger gets the touch column (PickerWheel.test.tsx); today's+ // column keeps its dip for a coarse pointer wherever it is rendered.stubReducedMotion('coarse');- const {onChange, scrollTo, rerender} = renderWheel(10);+ const {onChange, scrollTo, rerender} = renderWheel(10, ScrollWheel);const scroller = screen.getByRole('listbox', {name: 'Hour'});const {animate, animations} = fakeAnimate();scroller.animate = animate;@@ -305,7 +320,12 @@ describe('Wheel — where it comes to rest', () => {// 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} />,+ <ScrollWheel+ label="Hour"+ options={HOURS}+ value={11}+ onChange={onChange}+ />,);expect(animations).toHaveLength(1);expect(scrollTo).not.toHaveBeenCalled();@@ -318,8 +338,10 @@ describe('Wheel — where it comes to rest', () => {it('starts a second step’s dip where the first one’s fade-in has the column', async () => {// 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.+ // A finger gets the touch column (PickerWheel.test.tsx); today's+ // column keeps its dip for a coarse pointer wherever it is rendered.stubReducedMotion('coarse');- renderWheel(10);+ renderWheel(10, ScrollWheel);const scroller = screen.getByRole('listbox', {name: 'Hour'});const {animate, animations} = fakeAnimate();scroller.animate = animate;@@ -339,9 +361,10 @@ describe('Wheel — where it comes to rest', () => {});it('lands nothing once unmounted within the fade-out', async () => {- stubReducedMotion('coarse');+ stubReducedMotion('fine');const {scrollTo, stopOn, unmount} = renderWheel(10);const scroller = screen.getByRole('listbox', {name: 'Hour'});+ fireEvent.pointerDown(scroller, {pointerType: 'touch'});const {animate, animations} = fakeAnimate();scroller.animate = animate;stopOn(7);@@ -506,3 +529,171 @@ describe('Wheel — where it comes to rest', () => {expect(onChange).not.toHaveBeenCalled();});});++describe('Wheel — keys under a mouse', () => {+ /** The scrolling column over `options`, whose owner commits each change. */+ function OwnedColumn({+ options,+ initial,+ onChange,+ }: {+ options: WheelOption[];+ initial: number;+ onChange: (value: number) => void;+ }) {+ const [value, setValue] = useState(initial);+ return (+ <ScrollWheel+ label="Hour"+ options={options}+ value={value}+ onChange={next => {+ onChange(next);+ setValue(next);+ }}+ />+ );+ }++ function renderColumn(options: WheelOption[], initial: number) {+ const onChange = vi.fn();+ render(+ <OwnedColumn options={options} initial={initial} onChange={onChange} />,+ );+ return {listbox: screen.getByRole('listbox', {name: 'Hour'}), onChange};+ }++ it('at a 12:00–17:00 bound, moves a key to the next enabled row and stops at the last one', () => {+ const bound = HOURS.map(option => ({+ ...option,+ isDisabled: option.value < 12 || option.value > 17,+ }));+ const {listbox, onChange} = renderColumn(bound, 17);+ // No enabled row lies below 17: these keys commit nothing.+ for (const key of ['ArrowDown', 'PageDown', 'End']) {+ fireEvent.keyDown(listbox, {key});+ }+ expect(onChange).not.toHaveBeenCalled();+ // PageUp's target, 7, is past the bound: the key stops at 12.+ fireEvent.keyDown(listbox, {key: 'PageUp'});+ expect(onChange).toHaveBeenLastCalledWith(12);+ fireEvent.keyDown(listbox, {key: 'ArrowUp'});+ fireEvent.keyDown(listbox, {key: 'Home'});+ expect(onChange).toHaveBeenCalledTimes(1);+ fireEvent.keyDown(listbox, {key: 'End'});+ expect(onChange).toHaveBeenLastCalledWith(17);+ });++ it('at a 12:00–17:00 bound on a 12-hour hour wheel, steps in time order: nothing after 5 PM, and 1 PM after 12 PM', () => {+ // The PM hours as the 12-hour wheel lists them, 1 to 12, each standing for+ // its full hour: 12 (noon) comes before 1. Noon to 5 PM are in the bound.+ const pmHours = Array.from({length: 12}, (_, index) => {+ const hour = index + 1;+ const hour24 = hour === 12 ? 12 : hour + 12;+ return {+ value: hour,+ label: String(hour),+ order: hour24,+ isDisabled: hour24 > 17,+ };+ });+ const {listbox, onChange} = renderColumn(pmHours, 5);+ for (const key of ['ArrowDown', 'PageDown', 'End']) {+ fireEvent.keyDown(listbox, {key});+ }+ expect(onChange).not.toHaveBeenCalled();+ fireEvent.keyDown(listbox, {key: 'Home'});+ expect(onChange).toHaveBeenLastCalledWith(12);+ fireEvent.keyDown(listbox, {key: 'ArrowDown'});+ expect(onChange).toHaveBeenLastCalledWith(1);+ fireEvent.keyDown(listbox, {key: 'ArrowUp'});+ expect(onChange).toHaveBeenLastCalledWith(12);+ });++ it('moves a key from a row outside the bounds onto the first enabled row in its direction', () => {+ const bound = HOURS.map(option => ({+ ...option,+ isDisabled: option.value < 12 || option.value > 17,+ }));+ const {listbox, onChange} = renderColumn(bound, 20);+ fireEvent.keyDown(listbox, {key: 'ArrowDown'});+ expect(onChange).not.toHaveBeenCalled();+ fireEvent.keyDown(listbox, {key: 'ArrowUp'});+ expect(onChange).toHaveBeenLastCalledWith(17);+ });+});++describe('Wheel — by pointer', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ /**+ * The pointer and the engine: `(pointer: coarse)` is a finger, and+ * `-webkit-touch-callout` exists only in WebKit on iOS, which must not+ * matter.+ */+ function stubDevice({ios, coarse}: {ios: boolean; coarse: boolean}) {+ vi.stubGlobal('CSS', {+ supports: (condition: string) =>+ ios && condition.includes('-webkit-touch-callout'),+ });+ vi.stubGlobal(+ 'matchMedia',+ vi.fn((query: string) => ({+ matches: query === '(pointer: coarse)' && coarse,+ media: query,+ addEventListener: () => {},+ removeEventListener: () => {},+ })),+ );+ }++ function renderPicker() {+ const onChange = vi.fn();+ const view = render(+ <Wheel label="Hour" options={HOURS} value={12} onChange={onChange} />,+ );+ return {...view, onChange};+ }++ it.each([+ ['iOS WebKit', true],+ ['Android Chrome', false],+ ])('draws the touch column under a finger, on %s', (_, ios) => {+ stubDevice({ios, coarse: true});+ const {container} = renderPicker();+ expect(container.querySelector('[data-wheel]')).not.toBeNull();+ // Each option is a drawn row, once.+ expect(container.querySelectorAll('[data-wheel-row]')).toHaveLength(+ HOURS.length,+ );+ });++ it.each([+ ['a mouse', false],+ ['iOS WebKit with a mouse', true],+ ])('keeps the scrolling column, with no frame, for %s', (_, ios) => {+ stubDevice({ios, coarse: false});+ const {container} = renderPicker();+ expect(container.querySelector('[data-wheel]')).toBeNull();+ // Today's column, straight in its container: no group frame around it.+ expect(+ screen.getByRole('listbox', {name: 'Hour'}).parentElement?.parentElement,+ ).toBe(container);+ });+});++describe('Wheel — markup', () => {+ // Written before the listbox wiring moved into useWheelListbox: the+ // snapshot holds today's column to its markup (attributes, classes, order).+ it('keeps today’s column’s markup', () => {+ const {container} = render(+ <Wheel label="Hour" options={HOURS} value={10} onChange={() => {}} />,+ );+ // React's generated ids depend on how many renders ran before.+ expect(+ container.innerHTML.replace(/_r_[0-9a-z]+_/g, '_r_id_'),+ ).toMatchSnapshot();+ });+});diff --git a/packages/core/src/DateInput/Wheel.tsx b/packages/core/src/DateInput/Wheel.tsxindex 5c8e6e62ce..29cb1e5848 100644--- a/packages/core/src/DateInput/Wheel.tsx+++ b/packages/core/src/DateInput/Wheel.tsx@@ -4,41 +4,30 @@/*** @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+ * @input Option list, selected value and change callback+ * @output Exports Wheel (one picker column), ScrollWheel (the scrolling+ * column) and the shared types of wheelOptions.ts+ * @position Internal component; consumed by MonthYearWheels.tsx,+ * TouchTimeField.tsx and TouchDateTimeField.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 and no finger or mouse drag still holds it.+ * Wheel picks its column by the primary pointer. Under a finger it is+ * PickerWheel.tsx, the touch layer, imported here alone. Under a fine pointer+ * it is the snap-scrolling column below.*- * 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.- *- * 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- * the scroll-driven decoration.+ * The scrolling column is a scroll container: momentum, rubber-banding and the+ * settle are the platform's. Its rows fade and tip on a CSS `view()` timeline,+ * behind `@supports`. Under Reduce Motion its own scrolls land without travel.** SYNC: When modified, update:+ * - /packages/core/src/DateInput/PickerWheel.tsx (the touch column)+ * - /packages/core/src/DateInput/wheelOptions.ts* - /packages/core/src/DateInput/TouchDateField.tsx* - /packages/core/src/DateTimeInput/TouchDateTimeField.tsx* - /packages/core/src/DateInput/DateInput.doc.mjs* - /packages/core/src/DateInput/DateInputTouch.test.tsx*/-import {useCallback, useEffect, useId, useRef, useState} from 'react';+import {useCallback, useEffect, useRef, useState} from 'react';import * as stylex from '@stylexjs/stylex';import {colorVars,@@ -54,10 +43,25 @@ import {reducedMotionFade,type ReducedMotionDip,} from '../motion/reducedMotion';+import {useTouchPresentation} from '../utils/touchPresentation';+import {PickerWheel} from './PickerWheel';import {dateInputTouchSizes, dateInputTouchGeometry} from './tokens.stylex';import {useOwnScrollGesture} from './useOwnScrollGesture';import {usePointerDragScroll} from './usePointerDragScroll';import {useScrollSettle} from './useScrollSettle';+import {useWheelListbox} from './useWheelListbox';+import {+ endIndex,+ nearestEnabledIndex,+ steppedIndex,+ type WheelProps,+} from './wheelOptions';++export {+ nearestEnabledIndex,+ type WheelOption,+ type WheelProps,+} from './wheelOptions';const ITEM_BLOCK_SIZE = dateInputTouchSizes.wheelItemSize;@@ -214,80 +218,35 @@ const styles = stylex.create({},});-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: a wheel that- * stops on one travels on to the nearest enabled row.- */- 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;-}-/**- * 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`.+ * One picker column: UIPickerView's motion with flat rows under a finger, the+ * snap-scrolling column under a fine pointer.** @example* ```- * // Hours 0-23 with 09:00-17:00 bounds: stopping on 7 rests on 9.- * nearestEnabledIndex(hourOptions, 7, 10); // 9+ * <Wheel+ * label="Month"+ * options={monthOptions}+ * value={month}+ * onChange={setMonth}+ * />* ```*/-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;+export function Wheel(props: WheelProps) {+ // One touch model on every touch device: a finger gets UIPickerView's motion+ // with flat rows, a fine pointer the scrolling column.+ const {isTouch} = useTouchPresentation();+ return isTouch ? <PickerWheel {...props} /> : <ScrollWheel {...props} />;}+Wheel.displayName = 'Wheel';+/**- * One snap-scrolling picker column.+ * One snap-scrolling picker column, under a fine pointer.** @example* ```- * <Wheel+ * <ScrollWheel* label="Month"* options={monthOptions}* value={month}@@ -295,14 +254,13 @@ export function nearestEnabledIndex(* />* ```*/-export function Wheel({+export function ScrollWheel({label,options,value,onChange,isActive = true,}: WheelProps) {- const id = useId();const scrollerRef = useRef<HTMLDivElement | null>(null);const selectedIndex = Math.max(0,@@ -535,69 +493,64 @@ export function Wheel({// there is no way to share — it takes every touch that lands on it.useOwnScrollGesture(scrollerRef, 'all', {isEnabled: 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) {+ // A key commits the row it moves to and scrolls the column there.+ const moveTo = useCallback(+ (row: number | null) => {+ const option = row == null ? undefined : options[row];+ if (row == null || option == null || option.isDisabled) {return;}- setActiveIndex(next);- scrollToIndex(next, 'smooth');+ setActiveIndex(row);+ scrollToIndex(row, 'smooth');if (option.value !== value) {onChange(option.value);}},- [activeIndex, options, scrollToIndex, value, onChange],+ [options, scrollToIndex, value, onChange],+ );++ const moveBy = useCallback(+ (delta: number) => moveTo(steppedIndex(options, activeIndex, delta)),+ [moveTo, options, activeIndex],);- 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;+ // Home and End: the first and the last enabled row.+ const toEnd = useCallback(+ (end: 'first' | 'last') => moveTo(endIndex(options, end)),+ [moveTo, options],+ );++ const activate = useCallback(+ (index: number) => {+ const option = options[index];+ if (option == null || option.isDisabled) {+ return;+ }+ setActiveIndex(index);+ scrollToIndex(index, 'smooth');+ if (option.value !== value) {+ onChange(option.value);}},- [moveBy, activeIndex, options.length],+ [options, scrollToIndex, value, onChange],);+ const {listboxProps, optionProps} = useWheelListbox({+ label,+ options,+ value,+ activeIndex,+ stepBy: moveBy,+ toEnd,+ activate,+ });+return (<div {...stylex.props(styles.column)}><div aria-hidden="true" {...stylex.props(styles.band)} /><divref={scrollerRef}- role="listbox"- aria-label={label}- aria-activedescendant={`${id}-${options[activeIndex]?.value}`}- tabIndex={0}- onKeyDown={handleKeyDown}+ {...listboxProps}// 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@@ -612,20 +565,7 @@ export function Wheel({{options.map((option, index) => (<divkey={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);- }- }}+ {...optionProps(option, index)}{...stylex.props(styles.item,index === activeIndex && styles.itemActive,@@ -639,4 +579,4 @@ export function Wheel({);}-Wheel.displayName = 'Wheel';+ScrollWheel.displayName = 'ScrollWheel';diff --git a/packages/core/src/DateInput/__snapshots__/PickerWheel.test.tsx.snap b/packages/core/src/DateInput/__snapshots__/PickerWheel.test.tsx.snapnew file mode 100644index 0000000000..37b06f0ab1--- /dev/null+++ b/packages/core/src/DateInput/__snapshots__/PickerWheel.test.tsx.snap@@ -0,0 +1,3 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`PickerWheel — markup > keeps the touch column’s markup 1`] = `"<div role="listbox" aria-label="Hour" aria-activedescendant="_r_id_-10" tabindex="0" data-wheel="" class="PickerWheel__styles.column x1n2onr6 x1cqoux5 xeuugli xm8gem xb3r6kr x1a2a7pz x1i10hfl focusOutline__focusOutlineStyles.focusVisible x1k57tk5 x1vidyx5 x1t137rt x1jhp3zv xx47ajj x1wfwxd8 x1vwwbsn" data-astryx-touch-action="pan-x pinch-zoom"><div data-wheel-fade="" class="PickerWheel__styles.fade x10l6tqk x10a8y8t x47corl xheapza"><div aria-hidden="true" class="PickerWheel__styles.band x10l6tqk x17y0mx6 x7rbydg x6hpsvf xh6dtrn x17x4s8c x47corl"></div><div data-wheel-strip="" class="PickerWheel__styles.strip x10l6tqk x17y0mx6 x7rbydg x47corl" style="translate: 0px -280px;"><div id="_r_id_-0" role="option" aria-selected="false" aria-disabled="true" data-wheel-row="" data-label="00" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowDisabled xnbbluu" style="--x-insetBlockStart: 0px;">00</div><div id="_r_id_-1" role="option" aria-selected="false" aria-disabled="true" data-wheel-row="" data-label="01" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowDisabled xnbbluu" style="--x-insetBlockStart: 28px;">01</div><div id="_r_id_-2" role="option" aria-selected="false" aria-disabled="true" data-wheel-row="" data-label="02" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowDisabled xnbbluu" style="--x-insetBlockStart: 56px;">02</div><div id="_r_id_-3" role="option" aria-selected="false" aria-disabled="true" data-wheel-row="" data-label="03" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowDisabled xnbbluu" style="--x-insetBlockStart: 84px;">03</div><div id="_r_id_-4" role="option" aria-selected="false" aria-disabled="true" data-wheel-row="" data-label="04" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowDisabled xnbbluu" style="--x-insetBlockStart: 112px;">04</div><div id="_r_id_-5" role="option" aria-selected="false" aria-disabled="true" data-wheel-row="" data-label="05" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowDisabled xnbbluu" style="--x-insetBlockStart: 140px;">05</div><div id="_r_id_-6" role="option" aria-selected="false" aria-disabled="true" data-wheel-row="" data-label="06" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowDisabled xnbbluu" style="--x-insetBlockStart: 168px;">06</div><div id="_r_id_-7" role="option" aria-selected="false" aria-disabled="true" data-wheel-row="" data-label="07" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowDisabled xnbbluu" style="--x-insetBlockStart: 196px;">07</div><div id="_r_id_-8" role="option" aria-selected="false" aria-disabled="true" data-wheel-row="" data-label="08" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowDisabled xnbbluu" style="--x-insetBlockStart: 224px;">08</div><div id="_r_id_-9" role="option" aria-selected="false" data-wheel-row="" data-label="09" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla x1tgivj0 xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7" style="--x-insetBlockStart: 252px;">09</div><div id="_r_id_-10" role="option" aria-selected="true" data-wheel-row="" data-label="10" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowActive xjse4m1 x2mo6ok" style="--x-insetBlockStart: 280px; color: var(--color-text-accent); font-weight: var(--font-weight-semibold);">10</div><div id="_r_id_-11" role="option" aria-selected="false" data-wheel-row="" data-label="11" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla x1tgivj0 xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7" style="--x-insetBlockStart: 308px;">11</div><div id="_r_id_-12" role="option" aria-selected="false" data-wheel-row="" data-label="12" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla x1tgivj0 xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7" style="--x-insetBlockStart: 336px;">12</div><div id="_r_id_-13" role="option" aria-selected="false" data-wheel-row="" data-label="13" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla x1tgivj0 xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7" style="--x-insetBlockStart: 364px;">13</div><div id="_r_id_-14" role="option" aria-selected="false" data-wheel-row="" data-label="14" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla x1tgivj0 xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7" style="--x-insetBlockStart: 392px;">14</div><div id="_r_id_-15" role="option" aria-selected="false" data-wheel-row="" data-label="15" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla x1tgivj0 xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7" style="--x-insetBlockStart: 420px;">15</div><div id="_r_id_-16" role="option" aria-selected="false" data-wheel-row="" data-label="16" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla x1tgivj0 xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7" style="--x-insetBlockStart: 448px;">16</div><div id="_r_id_-17" role="option" aria-selected="false" data-wheel-row="" data-label="17" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla x1tgivj0 xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7" style="--x-insetBlockStart: 476px;">17</div><div id="_r_id_-18" role="option" aria-selected="false" aria-disabled="true" data-wheel-row="" data-label="18" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowDisabled xnbbluu" style="--x-insetBlockStart: 504px;">18</div><div id="_r_id_-19" role="option" aria-selected="false" aria-disabled="true" data-wheel-row="" data-label="19" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowDisabled xnbbluu" style="--x-insetBlockStart: 532px;">19</div><div id="_r_id_-20" role="option" aria-selected="false" aria-disabled="true" data-wheel-row="" data-label="20" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowDisabled xnbbluu" style="--x-insetBlockStart: 560px;">20</div><div id="_r_id_-21" role="option" aria-selected="false" aria-disabled="true" data-wheel-row="" data-label="21" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowDisabled xnbbluu" style="--x-insetBlockStart: 588px;">21</div><div id="_r_id_-22" role="option" aria-selected="false" aria-disabled="true" data-wheel-row="" data-label="22" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowDisabled xnbbluu" style="--x-insetBlockStart: 616px;">22</div><div id="_r_id_-23" role="option" aria-selected="false" aria-disabled="true" data-wheel-row="" data-label="23" class="PickerWheel__styles.row x10l6tqk x17y0mx6 x6hpsvf x78zum5 x6s0dn4 xl56j7k xf314gf x9f619 x18juvz8 x1sodnla xuxw1ft xb3r6kr xlyipyv x87ps6o PickerWheel__styles.rowAt x5mnzd7 PickerWheel__styles.rowDisabled xnbbluu" style="--x-insetBlockStart: 644px;">23</div></div></div></div>"`;diff --git a/packages/core/src/DateInput/__snapshots__/Wheel.test.tsx.snap b/packages/core/src/DateInput/__snapshots__/Wheel.test.tsx.snapnew file mode 100644index 0000000000..7363fd6e39--- /dev/null+++ b/packages/core/src/DateInput/__snapshots__/Wheel.test.tsx.snap@@ -0,0 +1,3 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`Wheel — markup > keeps today’s column’s markup 1`] = `"<div class="Wheel__styles.column x1n2onr6 x1cqoux5 xeuugli"><div aria-hidden="true" class="Wheel__styles.band x10l6tqk x17y0mx6 x7rbydg x6hpsvf xh6dtrn x17x4s8c x47corl"></div><div role="listbox" aria-label="Hour" aria-activedescendant="_r_id_-10" tabindex="0" class="Wheel__styles.scroller xm8gem x9f619 x1odjw0f x6ikm8r x168l2et xish69e x1uameg1 x201tam x1oyok0e x1rohswg x1a2a7pz xge0x1e focusOutline__focusOutlineStyles.focusVisible x1k57tk5 x1vidyx5 x1t137rt x1jhp3zv xx47ajj x1wfwxd8 x1vwwbsn"><div id="_r_id_-0" role="option" aria-selected="false" aria-disabled="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla xuxw1ft x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemDisabled xnbbluu xt0e3qv"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">00</span></div><div id="_r_id_-1" role="option" aria-selected="false" aria-disabled="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla xuxw1ft x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemDisabled xnbbluu xt0e3qv"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">01</span></div><div id="_r_id_-2" role="option" aria-selected="false" aria-disabled="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla xuxw1ft x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemDisabled xnbbluu xt0e3qv"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">02</span></div><div id="_r_id_-3" role="option" aria-selected="false" aria-disabled="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla xuxw1ft x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemDisabled xnbbluu xt0e3qv"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">03</span></div><div id="_r_id_-4" role="option" aria-selected="false" aria-disabled="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla xuxw1ft x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemDisabled xnbbluu xt0e3qv"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">04</span></div><div id="_r_id_-5" role="option" aria-selected="false" aria-disabled="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla xuxw1ft x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemDisabled xnbbluu xt0e3qv"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">05</span></div><div id="_r_id_-6" role="option" aria-selected="false" aria-disabled="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla xuxw1ft x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemDisabled xnbbluu xt0e3qv"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">06</span></div><div id="_r_id_-7" role="option" aria-selected="false" aria-disabled="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla xuxw1ft x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemDisabled xnbbluu xt0e3qv"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">07</span></div><div id="_r_id_-8" role="option" aria-selected="false" aria-disabled="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla xuxw1ft x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemDisabled xnbbluu xt0e3qv"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">08</span></div><div id="_r_id_-9" role="option" aria-selected="false" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla x1tgivj0 xuxw1ft x1ypdohk x16khyan x87ps6o x1jbe559 xuedmi6"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">09</span></div><div id="_r_id_-10" role="option" aria-selected="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 xuxw1ft x1ypdohk x16khyan x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemActive xjse4m1 x2mo6ok"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">10</span></div><div id="_r_id_-11" role="option" aria-selected="false" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla x1tgivj0 xuxw1ft x1ypdohk x16khyan x87ps6o x1jbe559 xuedmi6"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">11</span></div><div id="_r_id_-12" role="option" aria-selected="false" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla x1tgivj0 xuxw1ft x1ypdohk x16khyan x87ps6o x1jbe559 xuedmi6"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">12</span></div><div id="_r_id_-13" role="option" aria-selected="false" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla x1tgivj0 xuxw1ft x1ypdohk x16khyan x87ps6o x1jbe559 xuedmi6"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">13</span></div><div id="_r_id_-14" role="option" aria-selected="false" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla x1tgivj0 xuxw1ft x1ypdohk x16khyan x87ps6o x1jbe559 xuedmi6"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">14</span></div><div id="_r_id_-15" role="option" aria-selected="false" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla x1tgivj0 xuxw1ft x1ypdohk x16khyan x87ps6o x1jbe559 xuedmi6"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">15</span></div><div id="_r_id_-16" role="option" aria-selected="false" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla x1tgivj0 xuxw1ft x1ypdohk x16khyan x87ps6o x1jbe559 xuedmi6"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">16</span></div><div id="_r_id_-17" role="option" aria-selected="false" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla x1tgivj0 xuxw1ft x1ypdohk x16khyan x87ps6o x1jbe559 xuedmi6"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">17</span></div><div id="_r_id_-18" role="option" aria-selected="false" aria-disabled="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla xuxw1ft x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemDisabled xnbbluu xt0e3qv"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">18</span></div><div id="_r_id_-19" role="option" aria-selected="false" aria-disabled="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla xuxw1ft x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemDisabled xnbbluu xt0e3qv"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">19</span></div><div id="_r_id_-20" role="option" aria-selected="false" aria-disabled="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla xuxw1ft x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemDisabled xnbbluu xt0e3qv"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">20</span></div><div id="_r_id_-21" role="option" aria-selected="false" aria-disabled="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla xuxw1ft x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemDisabled xnbbluu xt0e3qv"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">21</span></div><div id="_r_id_-22" role="option" aria-selected="false" aria-disabled="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla xuxw1ft x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemDisabled xnbbluu xt0e3qv"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">22</span></div><div id="_r_id_-23" role="option" aria-selected="false" aria-disabled="true" class="Wheel__styles.item x78zum5 x6s0dn4 xl56j7k x6hpsvf xf314gf x1hdbdi8 xc342km xng3xce xjbqb8w x18juvz8 x1sodnla xuxw1ft x87ps6o x1jbe559 xuedmi6 Wheel__styles.itemDisabled xnbbluu xt0e3qv"><span class="Wheel__styles.itemInner x78zum5 x6s0dn4 xl56j7k xh8yej3 x5yr21d xb3r6kr xlyipyv x1iu2jvn xk3h8ob x190lv1 xg8s4dl x1u6ievf xwms9i0 x1esw782 xlp1x4z">23</span></div></div></div>"`;diff --git a/packages/core/src/DateInput/__tests__/Wheel.interaction.browser.spec.ts b/packages/core/src/DateInput/__tests__/Wheel.interaction.browser.spec.tsnew file mode 100644index 0000000000..a809fb972f--- /dev/null+++ b/packages/core/src/DateInput/__tests__/Wheel.interaction.browser.spec.ts@@ -0,0 +1,1184 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Wheel.interaction.browser.spec.ts+ * @input The built "Core/Wheel" stories, real touch input, the interaction+ * harness, and the Wheel's own physics as the oracle of UIKit's picker+ * @output Interaction and animation proofs for the touch picker wheel: the+ * coast's curve, its frames through a blocked main thread, a finger's+ * catch, a storyboard, Reduce Motion, and a mouse drag on today's column+ * @position Browser proof for DateInput/PickerWheel.tsx and the Wheel switch,+ * run by `pnpm test:interaction`; wheelPhysics.test.ts holds the oracle to+ * the UIKit recordings+ */++import {expect, test, type Locator, type Page} from '@playwright/test';+import {+ animationStoryboard,+ blockMainThread,+ busyWindowProof,+ castStoryboard,+ CONTROL_RGB,+ compareCurve,+ countBetween,+ curveOf,+ flick,+ freezeTimers,+ holdAnimations,+ installTimerGate,+ markElement,+ openStory,+ releaseAnimations,+ releaseVelocity,+ sampleCurve,+ startBusyControl,+ startCompositorTrace,+ startScreencast,+ tap,+ thawTimers,+ timeline,+ touchDriver,+ touchStoryboard,+ toTouchEvents,+ traceRendering,+ trackMarker,+ waitForAnimation,+ waitForRest,+ retakeOnWheelPacing,+ webInputDriver,+ WHEEL_SKIP,+ withStorybook,+ writeEvidence,+ type TouchDriver,+} from '@astryxdesign/interaction-harness';+import {UIKIT_GESTURES} from '../../motion/uikit';+import {WHEEL_ROW_HEIGHT} from '../wheelOptions';+import {planRelease, type WheelLayout} from '../wheelPhysics';+import {VelocityTracker} from '../../gestures/VelocityTracker';++const storybook = withStorybook(test);++const ROW = WHEEL_ROW_HEIGHT;+const MINUTES: WheelLayout = {rowHeight: ROW, rowCount: 60};+const HYSTERESIS = UIKIT_GESTURES.pan.hysteresis.value;+/** A flick up the minute wheel: the rows run on towards higher minutes. */+const FLICK_VELOCITY = 900;+/** The busy-main-thread proof's block: spec:AST-094 FR5's verification. */+const BLOCK_MS = 1000;+/**+ * The rows the busy proof's strip markers sit on, three rows apart in three+ * colours. Two markers of one colour are nine rows apart, never both in sight.+ * Neighbours' reaches overlap by over three rows.+ */+const STRIP_MARKER_ROWS = Array.from({length: 20}, (_, i) => 2 + 3 * i);+const STRIP_MARKER_RGB = [+ [255, 0, 255],+ [255, 255, 0],+ [255, 140, 0],+] as const;+/** How far from the band a strip marker is judged, px: inside the column. */+const STRIP_MARKER_REACH = 92;+/** The shortest stretch of the block one marker is judged over, ms. */+const MIN_REACH_MS = 150;++interface OpenWheel {+ driver: TouchDriver;+ field: Locator;+ minutes: Locator;+ strip: Locator;+ /** Where a finger lands to flick: low on the minute column. */+ start: {x: number; y: number};+}++async function openWheel(page: Page): Promise<OpenWheel> {+ await openStory(page, storybook(), 'core-wheel--minutes');+ const driver = await touchDriver(page);+ const field = page.getByRole('textbox', {name: 'Committed minute'});+ await expect(field).toHaveValue('00');+ const minutes = page.getByRole('listbox', {name: 'Minute'});+ await expect(minutes).toBeVisible();+ await page.waitForTimeout(600);+ // The touch column: a finger gets it on every engine.+ await expect(page.locator('[data-wheel]')).toHaveCount(1);+ // The column fades its rows toward its edges with a mask, which washes out+ // the colour a proof tracks. So the proofs read it unmasked. The mask is+ // static, and the motion is the same either way.+ await minutes.locator('[data-wheel-fade]').evaluate(element => {+ element.style.setProperty('mask-image', 'none');+ element.style.setProperty('-webkit-mask-image', 'none');+ });+ const column = await minutes.boundingBox();+ if (column == null) {+ throw new Error('no minute column');+ }+ await expectRowsPainted(minutes, column);+ return {+ driver,+ field,+ minutes,+ strip: minutes.locator('[data-wheel-strip]'),+ start: {+ x: Math.round(column.x + column.width / 2),+ y: Math.round(column.y + column.height * 0.8),+ },+ };+}++/**+ * Presence first: what a proof tracks is on screen before it acts. The strip+ * and its 60 rows are there, each row a painted box one row tall. The strip is+ * opaque, and the committed row is drawn inside the column. A proof that would+ * pass with nothing painted proves nothing.+ */+async function expectRowsPainted(+ minutes: Locator,+ column: {y: number; height: number},+) {+ const strip = minutes.locator('[data-wheel-strip]');+ await expect(strip).toHaveCount(1);+ await expect(strip).toHaveCSS('opacity', '1');+ await expect(strip).toHaveCSS('visibility', 'visible');+ const rows = minutes.locator('[data-wheel-row]');+ await expect(rows).toHaveCount(MINUTES.rowCount);+ const sizes = await rows.evaluateAll(elements =>+ elements.map(element => {+ const box = element.getBoundingClientRect();+ return {width: box.width, height: box.height};+ }),+ );+ expect(+ sizes.filter(+ ({width, height}) => width > 0 && Math.abs(height - ROW) < 0.5,+ ),+ 'every row is a painted row',+ ).toHaveLength(MINUTES.rowCount);+ const committed = minutes.getByRole('option', {selected: true});+ await expect(committed).toBeVisible();+ const box = await committed.boundingBox();+ if (box == null) {+ throw new Error('the committed row has no box');+ }+ expect(+ box.y,+ 'the committed row is drawn in the column',+ ).toBeGreaterThanOrEqual(column.y);+ expect(box.y + box.height).toBeLessThanOrEqual(column.y + column.height);+}++/**+ * The flick's script, and the offset the rows show at its lift.+ *+ * WebKit's injected touches carry only real dispatch time (README: engine+ * limits). So the release velocity the page reads from them is only as good as+ * the machine's pace. Under podman `--cpus=3` with 16 workers, the 120 Hz+ * script's moves arrive in bursts and stalls, with `LP_NUM_THREADS=3` too. An+ * A/B in one hour on Oct 31 failed 3 and 6 of 18 runs with it, and 7 and 7+ * without. The median gaps are 1 to 2 ms with stalls up to 73 ms, where the+ * script has 8.3 ms. A failing flick coasts on to the end of the list: 1,687+ * px, where UIKit's plan rests at 719. The proofs that read the coast a flick+ * starts fail there: the UIKit curve, a finger catching the coast and the+ * storyboard. The reduced-motion momentum fails too, without the flag. This is+ * an engine limit of WebKit's real-time input, not a pass. Under the CI WebKit+ * lane's own profile (`--cpus=4`, `LP_NUM_THREADS=4`, `CI=1`, 1 worker, ×10),+ * the moves arrive every 8 ms, at most 11. All 60 runs pass.+ */+function flickUp(start: {x: number; y: number}) {+ const script = flick(start, {+ velocity: {x: 0, y: -FLICK_VELOCITY},+ durationMs: 100,+ hz: 120,+ });+ const events = toTouchEvents(script);+ const moves = events.filter(e => e.type === 'touchMove');+ const last = moves[moves.length - 1];+ const travel = start.y - (last?.fingers[0]?.y ?? start.y);+ // Minute 00 is under the band; the pan begins past its hysteresis, which+ // the rows never show.+ return {script, offsetAtLift: travel - HYSTERESIS};+}++/**+ * The busy-main-thread proof needs a coast as long as the script's release+ * makes it. Where the page sees real dispatch times (WebKit here), the release+ * velocity is the engine's own and can fall under the velocity floor. The+ * screencast's cadence also varies with load. For Mobile Safari there is an iOS+ * simulator capture of a coast through a 530 ms block. There is no real device,+ * and no 1 s block there.+ */+// WebKit's busy-thread run is skipped: lifted under the CI WebKit lane's own+// profile (Oct 31, podman `--cpus=4`, `LP_NUM_THREADS=4`, `CI=1`, ×10), 7 of 10+// runs failed. In 3, WebKit's real-time release was too slow for a coast that+// outlasts the 1 s block. In 4, the coast moved on 94 to 97% of the frames the+// control moved. Its tail moved 1.3 to 2 px a frame, against WebKit's 2 px+// screencast steps. So it runs through the block, finer than the cast shows.+const SCRIPTED_RELEASE_SKIP =+ 'the coast needs the scripted release velocity, which only an engine replaying the script timestamps gives, and its tail moves under WebKit\u2019s 2 px screencast step (README: engine limits); Mobile Safari has an iOS simulator capture through a 530 ms block instead';++/** The y of a strip keyframe: the animator plays the strip's `translate`. */+function stripYOf(frame: Record<string, unknown> | undefined): number {+ const translate = frame?.translate;+ if (translate === 'none') {+ return 0;+ }+ if (typeof translate !== 'string') {+ throw new Error(`not a translate keyframe: ${JSON.stringify(frame)}`);+ }+ const [, y = '0px'] = translate.trim().split(/\s+/);+ return Number.parseFloat(y);+}++type WheelAnimation = Awaited<ReturnType<typeof waitForAnimation>>[number];++/**+ * The strip's own animation among those under it: the one whose keyframes+ * are all translations (the rows are flat and never animate).+ */+function stripAnimationOf(animations: WheelAnimation[]): WheelAnimation {+ const strip = animations.find(+ animation =>+ (animation.keyframes ?? []).length > 0 &&+ (animation.keyframes ?? []).every(+ frame => frame.opacity == null && typeof frame.translate === 'string',+ ),+ );+ if (strip == null) {+ throw new Error('no strip animation');+ }+ return strip;+}++/** The strip's translation is minus the wheel's offset. */+/** The strip's running coast, from and to on the page clock, read without+ * its keyframes. */+async function stripCoastTiming(+ strip: Locator,+): Promise<{from: number; to: number}> {+ await expect+ .poll(+ async () =>+ strip.evaluate(element =>+ element+ .getAnimations()+ .some(a => a.playState === 'running' && a.startTime != null),+ ),+ {timeout: 5_000},+ )+ .toBe(true);+ return strip.evaluate(element => {+ const animation = element+ .getAnimations()+ .find(a => a.playState === 'running' && a.startTime != null);+ const effect = animation?.effect as KeyframeEffect | null | undefined;+ const timing = effect?.getComputedTiming();+ const start = performance.timeOrigin + Number(animation?.startTime ?? 0);+ const delay = timing?.delay ?? 0;+ const active = Number(timing?.activeDuration ?? 0);+ // The curve's end, as the harness reads it: the first of the frames+ // that hold the strip's last position (the arrival commits there).+ const frames = effect?.getKeyframes() ?? [];+ let first = frames.length - 1;+ while (+ first > 0 &&+ String(frames[first - 1].translate) === String(frames[first].translate)+ ) {+ first -= 1;+ }+ const linear = (effect?.getTiming().easing ?? 'linear') === 'linear';+ const end = linear ? (frames[first]?.computedOffset ?? 1) * active : active;+ return {from: start + delay, to: start + delay + end};+ });+}++const stripOffset = async (strip: Locator) =>+ strip.evaluate(element => {+ const translate = getComputedStyle(element).translate;+ const [, y = '0px'] =+ translate === 'none' ? [] : translate.trim().split(/\s+/);+ return -Number.parseFloat(y);+ });++/** An input the page received: its type, timestamp (ms) and position. */+type InputSeen = [type: string, time: number, x: number, y: number];++/**+ * Record the inputs a finger's pan reads, before the gesture system sees them.+ * A finger begins with its touchstart and lifts with its touchend. Its moves+ * are its touch `pointermove`s, one sample per event, as the pan takes them.+ * Each time is on the page's clock, as the gesture host reads it.+ */+async function recordFingerInputs(page: Page): Promise<void> {+ await page.evaluate(() => {+ const seen: [string, number, number, number][] = [];+ (window as unknown as {__inputsSeen: typeof seen}).__inputsSeen = seen;+ const timeOf = (event: Event) =>+ event.timeStamp > 1e12+ ? event.timeStamp - performance.timeOrigin+ : event.timeStamp;+ for (const type of ['touchstart', 'touchend']) {+ window.addEventListener(+ type,+ event => {+ const touch = (event as TouchEvent).changedTouches[0];+ if (touch != null) {+ seen.push([type, timeOf(event), touch.clientX, touch.clientY]);+ }+ },+ {capture: true, passive: true},+ );+ }+ window.addEventListener(+ 'pointermove',+ event => {+ if (event.pointerType === 'touch' && seen.length > 0) {+ seen.push([+ 'pointermove',+ timeOf(event),+ event.clientX,+ event.clientY,+ ]);+ }+ },+ {capture: true, passive: true},+ );+ });+}++async function fingerInputsSeen(page: Page): Promise<InputSeen[]> {+ return page.evaluate(+ () => (window as unknown as {__inputsSeen: InputSeen[]}).__inputsSeen,+ );+}++/**+ * The release velocity (px/s, positive when the rows move up) that the pan's+ * tracker reads from `inputs`, as the wheel's release does. The gesture+ * arena never lets time go backwards, so each time is held at the latest.+ */+function releaseVelocityOf(inputs: ReadonlyArray<InputSeen>): number {+ const tracker = new VelocityTracker();+ let latest = -Infinity;+ for (const [type, time, x, y] of inputs) {+ latest = Math.max(time, latest);+ if (type === 'touchend') {+ return -tracker.scrollVelocity(latest).y;+ }+ tracker.add(x, y, latest);+ }+ throw new Error(`no lift among the inputs: ${JSON.stringify(inputs)}`);+}++test('a flick coasts on UIKit’s curve onto the row it projects, and commits it on arrival', async ({+ page,+ browserName,+}, testInfo) => {+ const {driver, field, strip, start} = await openWheel(page);+ const {script, offsetAtLift} = flickUp(start);+ expect(releaseVelocity(script).y).toBeCloseTo(-FLICK_VELOCITY, -1);+ await recordFingerInputs(page);+ await driver.play(script);+ const coast = stripAnimationOf(await waitForAnimation(strip));+ const held = await holdAnimations(page, strip);+ const motion = held.find(animation => animation.kind === 'Animation');+ if (motion == null) {+ throw new Error(`no coast held: ${JSON.stringify(held)}`);+ }+ const samples = curveOf(+ await sampleCurve(strip, timeline(motion.curveEndMs)),+ 'translateY',+ ).map(sample => ({t: sample.t, value: -sample.value}));+ await releaseAnimations(page);++ const from = samples[0].value;+ const rest = samples[samples.length - 1].value;+ // The page reads the release velocity from the timestamps of the inputs it+ // receives. WebKit stamps each input as it dispatches it, so under load its+ // velocity can differ from the scripted one. The pan's own tracker reads the+ // inputs the page saw. The whole release is UIKit's plan for that velocity:+ // the row projected, and the coast's rate re-solved to stop there.+ const inputs = await fingerInputsSeen(page);+ const pageVelocity = releaseVelocityOf(inputs);+ const plan = planRelease(from, pageVelocity, MINUTES);+ const expected = (t: number) => plan.curve.value(t / 1000);+ const result = compareCurve(samples, expected, 0.75);+ await writeEvidence(+ 'curves/wheel-coast',+ {+ [`${testInfo.project.name}.json`]: JSON.stringify(+ {+ coast,+ motion,+ offsetAtLift,+ from,+ rest,+ plan: {+ kind: plan.kind,+ index: plan.index,+ duration: plan.curve.duration,+ },+ pageVelocity,+ inputs,+ comparison: result,+ },+ null,+ 2,+ ),+ },+ testInfo,+ );+ expect(result.maxError, JSON.stringify(result.worst)).toBeLessThanOrEqual(+ 0.75,+ );+ // WebKit's input has integer CSS px and its own timing: within a few px.+ expect(Math.abs(from - offsetAtLift)).toBeLessThan(+ browserName === 'chromium' ? 2 : 24,+ );+ if (browserName === 'chromium') {+ // Chromium replays the script's timestamps, so the page measures the+ // scripted velocity.+ expect(+ Math.abs(pageVelocity - FLICK_VELOCITY) / FLICK_VELOCITY,+ ).toBeLessThan(0.05);+ }+ // The last sample is half a millisecond before the end.+ expect(Math.abs(rest - plan.index * ROW)).toBeLessThan(0.5);+ if (browserName === 'chromium') {+ // UIKit's coast takes about 2.2 s from 900 pt/s.+ expect(motion.curveEndMs).toBeGreaterThan(1800);+ expect(motion.curveEndMs).toBeLessThan(2700);+ }+ // Committed on arrival, not before.+ await waitForRest(strip);+ await expect(field).toHaveValue(+ String(Math.round(rest / ROW)).padStart(2, '0'),+ );+});++test('the coast keeps advancing every frame while the main thread is blocked', async ({+ page,+}, testInfo) => {+ const {driver, minutes, strip, start} = await openWheel(page);+ test.skip(!driver.scriptedTimestamps, SCRIPTED_RELEASE_SKIP);+ // Markers riding the strip itself, every few rows in three colours. They move+ // with the coast and never turn or fade as the rows do, so their steps are+ // the coast's own. They are placed before the flick, so the block meets them+ // already on screen.+ await strip.evaluate(+ (element, {rows, rowHeight, colours}) => {+ rows.forEach((row, i) => {+ const marker = document.createElement('div');+ marker.dataset.busyMarker = String(row);+ const [r, g, b] = colours[i % colours.length];+ Object.assign(marker.style, {+ position: 'absolute',+ insetInlineStart: '8px',+ insetBlockStart: `${row * rowHeight + (rowHeight - 16) / 2}px`,+ inlineSize: '16px',+ blockSize: '16px',+ backgroundColor: `rgb(${r}, ${g}, ${b})`,+ zIndex: '2147483647',+ pointerEvents: 'none',+ });+ element.append(marker);+ });+ },+ {rows: STRIP_MARKER_ROWS, rowHeight: ROW, colours: STRIP_MARKER_RGB},+ );+ // Presence first: the markers ride the strip, and those in the column are+ // painted there before the flick.+ const markers = strip.locator('[data-busy-marker]');+ await expect(markers).toHaveCount(STRIP_MARKER_ROWS.length);+ const columnBox = await minutes.boundingBox();+ if (columnBox == null) {+ throw new Error('no minute column');+ }+ expect(+ await markers.evaluateAll(+ (elements, column) =>+ elements.filter(element => {+ const box = element.getBoundingClientRect();+ return (+ box.width > 0 &&+ box.height > 0 &&+ box.top >= column.y &&+ box.bottom <= column.y + column.height+ );+ }).length,+ columnBox,+ ),+ 'a marker is painted in the column',+ ).toBeGreaterThan(0);+ // A compositor-only control in the page's top edge, recorded in the same+ // frames: the coast is judged against what this machine presented.+ const control = await startBusyControl(page);+ const {script} = flickUp(start);+ const cast = await startScreencast(page);+ // The compositor's own record of the frames it presents: a frame the+ // screencast skips under load is not a stall (busyWindowProof).+ const compositor = await startCompositorTrace(page);+ await driver.play(script);+ const coast = stripAnimationOf(+ await waitForAnimation(strip, {minProgressMs: 16}),+ );+ // Read the coast the page is playing, from its keyframes: where the strip is+ // at each moment. WebKit's real-time input gives the page its own release+ // velocity.+ const points = (coast.keyframes ?? []).map(frame => ({+ t: Number(frame.computedOffset ?? frame.offset) * coast.durationMs,+ offset: -stripYOf(frame),+ }));+ const rest = points[points.length - 1].offset;+ const when = (distance: number) =>+ points.find(point => rest - point.offset <= distance)?.t ??+ coast.durationMs;+ // A 1 s block, as spec:AST-094 FR5's proof names, ending while the coast is+ // still over a row from rest.+ const blockTo = when(1.25 * ROW);+ const blockFrom = blockTo - BLOCK_MS;+ expect(blockFrom, 'the coast runs the whole block').toBeGreaterThan(0);+ await page.waitForTimeout(Math.max(0, coast.from + blockFrom - Date.now()));+ const block = await blockMainThread(page, BLOCK_MS);+ await page.waitForTimeout(150);+ const presented = await compositor.stop();+ const castFrames = await cast.stop();+ const tracks: Awaited<ReturnType<typeof trackMarker>>[] = [];+ for (const rgb of STRIP_MARKER_RGB) {+ tracks.push(await trackMarker(page, castFrames, {rgb}));+ }+ const controlFrames = await trackMarker(page, castFrames, {+ rgb: CONTROL_RGB,+ });+ await control.remove();+ // Every marker colour, and the control, is in the recorded frames.+ tracks.forEach((track, i) =>+ expect(+ track.some(frame => frame.box != null),+ `marker colour ${i} is in the frames`,+ ).toBe(true),+ );+ expect(+ controlFrames.some(frame => frame.box != null),+ 'the control is in the frames',+ ).toBe(true);+ // Each marker is judged while it is within reach of the band, inside the+ // column. Neighbours' reaches overlap. So a marker in sight for only a sliver+ // of the block is left out where its neighbour covers that time.+ const end = Math.min(block.to, coast.to);+ const at = (offset: number) =>+ coast.from ++ (points.find(point => point.offset >= offset)?.t ?? coast.durationMs);+ const reaches = STRIP_MARKER_ROWS.map((row, i) => ({+ row,+ track: i % STRIP_MARKER_RGB.length,+ from: Math.max(block.from, at(row * ROW - STRIP_MARKER_REACH)),+ to: Math.min(end, at(row * ROW + STRIP_MARKER_REACH)),+ })).filter(reach => reach.to - reach.from >= MIN_REACH_MS);+ // Together the judged reaches cover the whole block.+ let covered = block.from;+ for (const reach of reaches) {+ expect(reach.from, 'the markers cover the block').toBeLessThanOrEqual(+ covered,+ );+ covered = Math.max(covered, reach.to);+ }+ expect(covered, 'the markers cover the block').toBeGreaterThanOrEqual(end);+ const proofs = reaches.map(({track, from, to}) =>+ busyWindowProof(+ tracks[track],+ {from, to},+ {presented, control: controlFrames},+ ),+ );+ await writeEvidence(+ 'busy-main-thread/wheel-coast',+ {+ [`${testInfo.project.name}.json`]: JSON.stringify(+ {+ block,+ coast,+ reaches,+ proofs,+ frames: tracks[0].map((f, i) => ({+ t: +(f.t - block.from).toFixed(1),+ y: tracks.map(track => track[i]?.box?.y ?? null),+ })),+ },+ null,+ 1,+ ),+ },+ testInfo,+ );+ const film = await castStoryboard(page, castFrames, {+ name: 'wheel-coast-busy-main-thread',+ zero: block.from,+ from: block.from - 40,+ to: end + 40,+ columns: 8,+ cellScale: 0.35,+ data: t =>+ Object.fromEntries(+ tracks.map((track, i) => [+ `y${i}`,+ track.find(f => f.t === t)?.box?.y ?? -1,+ ]),+ ),+ });+ await film.write(testInfo, {block, coast});+ // Judged against the control: the coast moved on every frame the control+ // moved, and its longest stall is no longer than the control's. On the+ // coast's slowing tail it moves under one cast step a frame. So a run of+ // unchanged frames that a single step ends counts as moved there. A frozen+ // coast ends its run in a catch-up of many steps, or never moves while the+ // control does.+ for (const proof of proofs) {+ expect(proof.verdict.failures, proof.summary).toEqual([]);+ expect(proof.control?.moved).toBeGreaterThanOrEqual(4);+ expect(proof.monotonic).toBe(true);+ }+});++test('the coast does no Layout or Paint per frame', async ({+ page,+ browserName,+}) => {+ test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only');+ const {driver, strip, start} = await openWheel(page);+ const {script} = flickUp(start);+ let coast = {from: 0, to: 0};+ const trace = await traceRendering(page, async () => {+ await driver.play(script);+ // The strip's own timing only. Describing every row's baked keyframes+ // (waitForAnimation) is itself a DevTools task of nearly 50 ms on the+ // page's main thread. The long-task check would count it.+ coast = await stripCoastTiming(strip);+ await waitForRest(strip);+ });+ // Presence first: the window is a real coast, which ran and moved the rows.+ expect(coast.to - coast.from, 'the coast ran').toBeGreaterThan(500);+ expect(await stripOffset(strip), 'the rows travelled').toBeGreaterThanOrEqual(+ 3 * ROW,+ );+ const during = countBetween(trace, coast.from + 50, coast.to - 50);+ expect(during.Layout ?? 0, JSON.stringify(during)).toBe(0);+ expect(during.Paint ?? 0, JSON.stringify(during)).toBe(0);+ expect(trace.longTasks).toEqual([]);+});++test('a finger landing on the coasting wheel stops it where it is, then it eases onto the nearest row', async ({+ page,+}) => {+ const {driver, field, strip, start} = await openWheel(page);+ const before = await stripOffset(strip);+ await driver.play(flickUp(start).script);+ const coast = stripAnimationOf(+ await waitForAnimation(strip, {minProgressMs: 16}),+ );+ const coastEnd = -stripYOf(coast.keyframes?.at(-1));+ await page.waitForTimeout(300);+ // Land and hold still: the wheel stops at once, between rows.+ const hold = tap(start, {holdMs: 300});+ let caught = NaN;+ let held = NaN;+ let step = 0;+ await driver.play(hold, {+ onEvent: async () => {+ if (step++ === 0) {+ await page.waitForTimeout(50);+ caught = await stripOffset(strip);+ await page.waitForTimeout(150);+ held = await stripOffset(strip);+ }+ },+ });+ // Presence first: the wheel was moving when the finger landed.+ expect(caught, 'it moved before the catch').toBeGreaterThan(before + ROW);+ expect(held).toBeCloseTo(caught, 0);+ // It was caught mid-run, short of where the coast was heading.+ expect(caught).toBeLessThan(coastEnd - ROW / 2);+ // Lifted without moving: no tap on the touched row, a snap to the nearest.+ await waitForRest(strip);+ const rested = await stripOffset(strip);+ expect(rested % ROW).toBe(0);+ expect(Math.abs(rested - caught)).toBeLessThanOrEqual(ROW / 2);+ await expect(field).toHaveValue(String(rested / ROW).padStart(2, '0'));+});++test(+ 'storyboard: a flick and its coast onto a row',+ {tag: '@storyboard'},+ async ({page}, testInfo) => {+ const {driver, minutes, strip, start} = await openWheel(page);+ const box = await minutes.boundingBox();+ if (box == null) {+ throw new Error('no minute column');+ }+ const clip = {+ x: Math.max(0, box.x - 160),+ y: box.y - 20,+ width: Math.min(402, box.width + 320),+ height: box.height + 40,+ };+ const measure = async () => ({offset: await stripOffset(strip)});+ const {script} = flickUp(start);+ // The wheel ends a motion from a timer; gate the page's timers so the+ // held coast is not finished behind the filmstrip's back.+ await installTimerGate(page);+ const flickBoard = await touchStoryboard(page, driver, script, {+ name: 'wheel-flick',+ clip,+ measure,+ columns: 6,+ cellScale: 0.5,+ });+ await waitForAnimation(strip);+ await freezeTimers(page);+ const {storyboard: coastBoard} = await animationStoryboard(page, {+ name: 'wheel-coast',+ clip,+ scope: strip,+ measure,+ columns: 8,+ cellScale: 0.5,+ });+ await releaseAnimations(page, {finish: true});+ await thawTimers(page);+ await flickBoard.write(testInfo);+ await coastBoard.write(testInfo);+ // The trace is the assertion; the sheets are the evidence.+ const offsets = coastBoard.frames.map(f => f.data.offset as number);+ expect(offsets.every((o, i) => i === 0 || o >= offsets[i - 1] - 0.5)).toBe(+ true,+ );+ const last = offsets.at(-1) ?? NaN;+ expect(Math.abs(last - Math.round(last / ROW) * ROW)).toBeLessThan(0.5);+ // It decelerates: each frame covers no more than the one before.+ const steps = offsets.slice(1).map((o, i) => o - offsets[i]);+ expect(steps.every((s, i) => i === 0 || s <= steps[i - 1] + 0.5)).toBe(+ true,+ );+ },+);++/**+ * Records every animation under `column`, every frame: its animated+ * properties, length, translations, opacities and keyframe offsets. It also+ * records whether it animates a row, and when it started (epoch ms, once its+ * start time resolves).+ */+async function recordAnimations(column: Locator) {+ await column.evaluate(element => {+ const seen = new Map<+ Animation,+ {+ props: string[];+ duration: number;+ translates: string[];+ opacities: number[];+ offsets: number[];+ isRow: boolean;+ startedAt: number | null;+ }+ >();+ (window as unknown as {wheelAnimations: typeof seen}).wheelAnimations =+ seen;+ const startOf = (animation: Animation) =>+ animation.startTime == null+ ? null+ : performance.timeOrigin + Number(animation.startTime);+ const sample = () => {+ for (const animation of document.getAnimations()) {+ const effect = animation.effect;+ if (!(effect instanceof KeyframeEffect)) {+ continue;+ }+ const target = effect.target;+ if (target == null || !element.contains(target)) {+ continue;+ }+ const known = seen.get(animation);+ if (known != null) {+ known.startedAt ??= startOf(animation);+ continue;+ }+ const props = new Set<string>();+ const translates: string[] = [];+ const opacities: number[] = [];+ const offsets: number[] = [];+ for (const frame of effect.getKeyframes()) {+ offsets.push(frame.computedOffset);+ for (const key of Object.keys(frame)) {+ if (+ !['offset', 'computedOffset', 'easing', 'composite'].includes(key)+ ) {+ props.add(key);+ }+ }+ if (frame.translate != null) {+ translates.push(String(frame.translate));+ }+ if (frame.opacity != null) {+ opacities.push(Number(frame.opacity));+ }+ }+ seen.set(animation, {+ props: [...props],+ duration: Number(effect.getTiming().duration),+ translates,+ opacities,+ offsets,+ isRow:+ target instanceof Element && target.matches('[data-wheel-row]'),+ startedAt: startOf(animation),+ });+ }+ requestAnimationFrame(sample);+ };+ requestAnimationFrame(sample);+ });+ return async () =>+ column.page().evaluate(() => [+ ...(+ window as unknown as {+ wheelAnimations: Map<+ unknown,+ {+ props: string[];+ duration: number;+ translates: string[];+ opacities: number[];+ offsets: number[];+ isRow: boolean;+ startedAt: number | null;+ }+ >;+ }+ ).wheelAnimations.values(),+ ]);+}++test('under reduced motion, a flick still coasts as momentum, its rows flat', async ({+ page,+}) => {+ // design:reduced-motion DR2: the momentum that continues a throw is direct+ // movement, not a transition, so it coasts as scrolling does.+ await page.emulateMedia({reducedMotion: 'reduce'});+ const {driver, field, minutes, start} = await openWheel(page);+ const read = await recordAnimations(minutes);+ await driver.play(flickUp(start).script);+ await expect(field).not.toHaveValue('00', {timeout: 4000});+ const seen = await read();+ // The strip coasts: a translation longer than any cross-fade.+ const coasts = seen.filter(animation =>+ animation.props.includes('translate'),+ );+ expect(coasts.length).toBeGreaterThan(0);+ expect(+ Math.max(...coasts.map(animation => animation.duration)),+ ).toBeGreaterThan(200);+ // Nothing fades, and the rows stay flat: no animation reaches a row.+ for (const animation of seen) {+ expect(animation.props).not.toContain('opacity');+ expect(animation.isRow).toBe(false);+ }+});++test('under reduced motion, a tap cross-fades onto its row: nothing travels, in 200 ms or less', async ({+ page,+}) => {+ // design:reduced-motion DR2: a transition the wheel starts, here a tap's+ // turn, is the animator's cross-fade. The strip's opacity dips out and back+ // in, 200 ms in all. Its rows land on their row while it is faded out, as a+ // style write with no animation. So nothing is seen to travel.+ await page.emulateMedia({reducedMotion: 'reduce'});+ const {driver, field, minutes} = await openWheel(page);+ const read = await recordAnimations(minutes);+ const box = await minutes.boundingBox();+ if (box == null) {+ throw new Error('no minute column');+ }+ // Two rows below the band: minute 02.+ await driver.tap({+ x: Math.round(box.x + box.width / 2),+ y: Math.round(box.y + box.height / 2 + 2 * ROW),+ });+ await expect(field).toHaveValue('02', {timeout: 3000});+ const seen = await read();+ expect(seen.length).toBeGreaterThan(0);+ // No travel: every animation is an opacity fade.+ for (const animation of seen) {+ expect(animation.props).toEqual(['opacity']);+ }+ // Each half of the dip changes over 100 ms or less; the rest of each+ // animation holds its last value.+ for (const {opacities, offsets, duration} of seen) {+ let held = opacities.length - 1;+ while (held > 0 && opacities[held - 1] === opacities[held]) {+ held -= 1;+ }+ expect(offsets[held] * duration).toBeLessThanOrEqual(100 + 1);+ }+ expect(+ seen.some(({opacities}) => opacities.includes(0)),+ 'the strip faded out',+ ).toBe(true);+});++test('under reduced motion, a tap’s cross-fade never shows the old row again while the main thread is blocked', async ({+ page,+ browserName,+}) => {+ // design:reduced-motion DR2 with spec:AST-094 FR5: the strip fades out on the+ // compositor. It holds faded out through a main-thread block across the+ // fade's midpoint, so no frame brings the old row back. The animator lands+ // the row as the main thread runs again, and the strip fades back in on it.+ test.skip(+ browserName !== 'chromium',+ 'the screencast proof runs on Chromium; WebKit runs the landing case above',+ );+ await page.emulateMedia({reducedMotion: 'reduce'});+ const {driver, field, minutes, strip} = await openWheel(page);+ const box = await minutes.boundingBox();+ if (box == null) {+ throw new Error('no minute column');+ }+ const target = minutes.getByRole('option', {name: '01'});+ await markElement(target);+ const chip = page.locator('[data-harness-marker-chip]');+ const from = await chip.boundingBox();+ const cast = await startScreencast(page);+ // The fade lasts 200 ms, less than a busy machine's round trip from the test.+ // The animator also cancels each half once it has retired it. So the page+ // records the strip's animations from before the tap. It starts the block+ // itself once the cross-fade has run a frame on the compositor+ // (blockMainThread's `during`). The block then covers the fade's midpoint and+ // its end, however late the test reads them.+ const read = await recordAnimations(minutes);+ const blocking = blockMainThread(page, 700, {during: strip});+ // The row below the band, minute 01, in sight before and after (today’s+ // rows fade toward the edges).+ await driver.tap({+ x: Math.round(box.x + box.width / 2),+ y: Math.round(box.y + box.height / 2 + ROW),+ });+ const block = await blocking;+ // The fade out: the opacity animation the tap started, falling to 0.+ const fade = (await read()).find(+ animation => animation.opacities.includes(0) && animation.startedAt != null,+ );+ if (fade?.startedAt == null) {+ throw new Error('no cross-fade');+ }+ const fadeMs = 200;+ const midpoint = fade.startedAt + fadeMs / 2;+ // Presence first: the block spans the fade's midpoint, where the animator+ // lands the row.+ expect(+ block.from,+ 'the block starts before the fade’s midpoint',+ ).toBeLessThan(midpoint);+ expect(block.to, 'the block ends after the fade’s midpoint').toBeGreaterThan(+ midpoint,+ );+ await page.waitForTimeout(150);+ const frames = await cast.stop();+ await expect(field).toHaveValue('01', {timeout: 3000});+ const to = await chip.boundingBox();+ if (from == null || to == null) {+ throw new Error('no marker');+ }+ expect(Math.abs(to.y - from.y), 'the row moved to the band').toBeGreaterThan(+ ROW / 2,+ );+ // Every frame with the row in sight after the fade's midpoint has the row at+ // the band, through the block and after it. The old row never comes back.+ const tracked = await trackMarker(page, frames);+ const afterMidpoint = tracked.filter(+ frame => frame.box != null && frame.t >= midpoint + 10,+ );+ const timeline = tracked+ .map(+ frame =>+ `+${Math.round(frame.t - block.from)}:${frame.box == null ? '-' : Math.round(frame.box.y)}`,+ )+ .join(' ');+ expect(+ afterMidpoint.length,+ `frames with the row in sight (${timeline})`,+ ).toBeGreaterThan(0);+ for (const frame of afterMidpoint) {+ expect(+ Math.abs((frame.box?.y ?? Infinity) - to.y),+ `the row at +${Math.round(frame.t - block.from)} ms, at rest y ${Math.round(to.y)} (${timeline})`,+ ).toBeLessThan(3);+ }+});++test.describe('a mouse wheel and a trackpad (component:DateInput FR15)', () => {+ test('one mouse-wheel notch turns the touch column one row, as an arrow key does; three turn it three', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ "a mouse wheel's notch is Chromium's driver's wheel; WebKit's sends a trackpad's precise deltas, from a desktop context only",+ );+ const {field, minutes} = await openWheel(page);+ const input = await webInputDriver(page);+ test.skip(!input.wheels, WHEEL_SKIP);+ const box = await minutes.boundingBox();+ if (box == null) {+ throw new Error('no minute column');+ }+ const at = {x: box.x + box.width / 2, y: box.y + box.height / 2};+ await input.wheel({...at, dy: 100});+ // As an arrow key: the next row commits at once, with no coast.+ await expect(field).toHaveValue('01');+ await input.wheel({...at, dy: 100});+ await input.wheel({...at, dy: 100});+ await expect(field).toHaveValue('03');+ await page.waitForTimeout(600);+ await expect(field).toHaveValue('03');+ // A ctrl-wheel is the page's zoom: the wheel keeps its row.+ await input.wheel({...at, dy: 100, ctrl: true});+ await page.waitForTimeout(600);+ await expect(field).toHaveValue('03');+ });++ test.describe('a trackpad', () => {+ // WebKit's driver sends a trackpad's precise deltas from a desktop+ // context; the touch column is opened alone there.+ test.use({hasTouch: false, isMobile: false});++ async function openTouchColumn(page: Page) {+ await openStory(page, storybook(), 'core-wheel--touch-minutes');+ const field = page.getByRole('textbox', {name: 'Committed minute'});+ await expect(field).toHaveValue('00');+ const minutes = page.getByRole('listbox', {name: 'Minute'});+ await expect(minutes).toBeVisible();+ await expect(page.locator('[data-wheel]')).toHaveCount(1);+ await page.waitForTimeout(600);+ const box = await minutes.boundingBox();+ if (box == null) {+ throw new Error('no minute column');+ }+ return {+ field,+ at: {x: box.x + box.width / 2, y: box.y + box.height / 2},+ };+ }++ test('a trackpad flick drives the touch column as a finger does: it follows, coasts on at the lift, and commits the row it rests on', async ({+ page,+ browserName,+ }, testInfo) => {+ test.skip(+ browserName !== 'webkit',+ "Chromium's driver sends each wheel as a mouse wheel's notch; only WebKit's sends a trackpad's precise deltas",+ );+ await retakeOnWheelPacing(testInfo, async () => {+ const {field, at} = await openTouchColumn(page);+ const input = await webInputDriver(page);+ test.skip(!input.wheels, WHEEL_SKIP);+ // The fingers: 12 px a frame for 12 frames (144 px, five rows and a+ // bit), then the platform's momentum, a shrinking run.+ const fingers = Array.from({length: 12}, () => ({dy: 12}));+ const momentum = [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1].map(dy => ({dy}));+ await input.wheelBurst({+ ...at,+ steps: [...fingers, ...momentum],+ maxGapMs: 100,+ });+ // It coasts on at UIKit's deceleration, well past the fingers'+ // travel and the momentum's (66 px), and commits where it rests.+ await expect+ .poll(async () => Number(await field.inputValue()), {timeout: 8000})+ .toBeGreaterThanOrEqual(10);+ const rested = await field.inputValue();+ await page.waitForTimeout(1000);+ await expect(field).toHaveValue(rested);+ });+ });++ test('a slow trackpad drag that stops rests on the nearest row, without coasting', async ({+ page,+ browserName,+ }, testInfo) => {+ test.skip(+ browserName !== 'webkit',+ "Chromium's driver sends each wheel as a mouse wheel's notch; only WebKit's sends a trackpad's precise deltas",+ );+ await retakeOnWheelPacing(testInfo, async () => {+ const {field, at} = await openTouchColumn(page);+ const input = await webInputDriver(page);+ test.skip(!input.wheels, WHEEL_SKIP);+ // 2 px a frame for 20 frames: 40 px, a row and a half less a bit.+ await input.wheelBurst({+ ...at,+ steps: Array.from({length: 20}, () => ({dy: 2})),+ maxGapMs: 100,+ });+ await expect(field).toHaveValue('01', {timeout: 5000});+ await page.waitForTimeout(1000);+ await expect(field).toHaveValue('01');+ });+ });+ });+});++test.describe('under a mouse', () => {+ // A desktop: today's column.+ test.use({hasTouch: false, isMobile: false});++ test('a drag scrolls today’s column onto a row and commits it', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'one engine is enough for the fine-pointer path, which is main’s column',+ );+ await openStory(page, storybook(), 'core-wheel--minutes');+ // A mouse case runs under a fine primary pointer: the page agrees.+ expect(+ await page.evaluate(() => window.matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ const field = page.getByRole('textbox', {name: 'Committed minute'});+ await expect(field).toHaveValue('00');+ const minutes = page.getByRole('listbox', {name: 'Minute'});+ await expect(minutes).toBeVisible();+ // Today's column, not the touch one.+ await expect(page.locator('[data-wheel]')).toHaveCount(0);+ await page.waitForTimeout(600);+ const row = await minutes+ .locator('[role="option"]')+ .first()+ .evaluate(el => el.getBoundingClientRect().height);+ const box = await minutes.boundingBox();+ if (box == null) {+ throw new Error('no minute column');+ }+ const x = box.x + box.width / 2;+ const y = box.y + box.height / 2;+ // Up three rows and a little: the content follows the hand.+ await page.mouse.move(x, y);+ await page.mouse.down();+ for (let i = 1; i <= 30; i++) {+ await page.waitForTimeout(16);+ await page.mouse.move(x, y - ((3 * row + 8) * i) / 30);+ }+ await page.waitForTimeout(200);+ await page.mouse.up();+ // The column snaps onto a row and commits it.+ await expect(field).not.toHaveValue('00', {timeout: 5000});+ await expect+ .poll(+ async () =>+ minutes.evaluate((el, pitch) => {+ const rows = el.scrollTop / pitch;+ return Math.abs(rows - Math.round(rows));+ }, row),+ {timeout: 5000},+ )+ .toBeLessThan(0.05);+ });+});diff --git a/packages/core/src/DateInput/__tests__/WheelActivation.interaction.browser.spec.ts b/packages/core/src/DateInput/__tests__/WheelActivation.interaction.browser.spec.tsnew file mode 100644index 0000000000..0d71f50f23--- /dev/null+++ b/packages/core/src/DateInput/__tests__/WheelActivation.interaction.browser.spec.ts@@ -0,0 +1,189 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file WheelActivation.interaction.browser.spec.ts+ * @input The built DateInput stories "BottomSheetWideRange" (200 years) and+ * "BottomSheetNarrowRange" (2 years), real touch input+ * @output Proof that showing a touch wheel (a finger gets it on every engine)+ * costs no more per year than today's column: opening the month and year+ * wheels writes no element per year, and each year is drawn once, as its+ * own flat row. Under a mouse the year wheel is today's column, every year+ * listed natively.+ * @position Browser proof for DateInput/PickerWheel.tsx's rows, run by+ * playwright.interaction.config.ts. It counts the elements an opening+ * writes rather than timing it: the load on the machine running it moves+ * a frame clock, never that count.+ */++import {expect, test, type Page} from '@playwright/test';+import {+ openStory,+ touchDriver,+ waitForRest,+ withStorybook,+} from '@astryxdesign/interaction-harness';+import {WHEEL_ROW_HEIGHT} from '../wheelOptions';++const storybook = withStorybook(test);++interface Activation {+ /** Year options listed, and the year rows drawn (each option is one). */+ yearOptions: number;+ yearRowsDrawn: number;+ /** Year rows painted: a box one row tall. */+ yearRowsPainted: number;+ /**+ * The year wheel's elements the opening wrote (any attribute) or added,+ * from the tap that shows the wheels until the year wheel rests.+ */+ yearElementsWritten: number;+}++async function openMonthYearWheels(+ page: Page,+ storyId: string,+): Promise<Activation> {+ await openStory(page, storybook(), storyId);+ const driver = await touchDriver(page);+ const field = page.getByRole('combobox', {name: 'Date of birth'});+ const fieldBox = await field.boundingBox();+ if (fieldBox == null) {+ throw new Error('no field');+ }+ await driver.tap({+ x: fieldBox.x + fieldBox.width / 2,+ y: fieldBox.y + fieldBox.height / 2,+ });+ const title = page.locator('[data-title="month-year"]');+ await expect(title).toBeVisible();+ await waitForRest(page.locator('.astryx-bottom-sheet').first());+ const titleBox = await title.boundingBox();+ if (titleBox == null) {+ throw new Error('no month and year title');+ }+ // Every element of the year wheel the opening writes or adds, recorded as+ // it happens.+ await page.evaluate(() => {+ const written = new Set<Element>();+ (window as unknown as {__yearWritten: Set<Element>}).__yearWritten =+ written;+ const inYear = (node: Node): node is Element =>+ node instanceof Element &&+ node.closest('[role="listbox"][aria-label="Year"]') != null;+ new MutationObserver(records => {+ for (const record of records) {+ if (record.type === 'attributes' && inYear(record.target)) {+ written.add(record.target);+ }+ for (const node of record.addedNodes) {+ if (node instanceof Element) {+ for (const element of [node, ...node.querySelectorAll('*')]) {+ if (inYear(element)) {+ written.add(element);+ }+ }+ }+ }+ }+ }).observe(document.body, {+ subtree: true,+ attributes: true,+ childList: true,+ });+ });+ await driver.tap({+ x: titleBox.x + titleBox.width / 2,+ y: titleBox.y + titleBox.height / 2,+ });+ const years = page.getByRole('listbox', {name: 'Year'});+ await expect(years).toBeVisible();+ await waitForRest(years.locator('[data-wheel-strip]'));+ // The committed year is drawn where the wheel shows it.+ await expect(years.getByRole('option', {selected: true})).toBeVisible();+ return {+ yearOptions: await years.getByRole('option').count(),+ // Every row the wheel draws: each option is its own row, and nothing+ // else draws a year.+ yearRowsDrawn: await years.evaluate(+ list => list.querySelectorAll('[data-wheel-row]').length,+ ),+ yearRowsPainted: await years.evaluate(+ (list, rowHeight) =>+ Array.from(list.querySelectorAll('[data-wheel-row]')).filter(row => {+ const box = row.getBoundingClientRect();+ return box.width > 0 && Math.abs(box.height - rowHeight) < 0.5;+ }).length,+ WHEEL_ROW_HEIGHT,+ ),+ yearElementsWritten: await page.evaluate(+ () =>+ (window as unknown as {__yearWritten: Set<Element>}).__yearWritten.size,+ ),+ };+}++test('the month and year wheels draw each year once, and opening them writes no element per year', async ({+ page,+}, testInfo) => {+ const narrow = await openMonthYearWheels(+ page,+ 'core-dateinput--bottom-sheet-narrow-range',+ );+ const wide = await openMonthYearWheels(+ page,+ 'core-dateinput--bottom-sheet-wide-range',+ );+ testInfo.annotations.push({+ type: 'activation',+ description: JSON.stringify({narrow, wide}),+ });+ expect(narrow.yearOptions).toBe(2);+ expect(wide.yearOptions).toBe(200);+ // The touch column.+ await expect(page.locator('[data-wheel]')).toHaveCount(2);+ // Each year is drawn once, as its own row.+ expect(narrow.yearRowsDrawn).toBe(2);+ expect(wide.yearRowsDrawn).toBe(200);+ // And painted: each one a box one row tall.+ expect(narrow.yearRowsPainted).toBe(2);+ expect(wide.yearRowsPainted).toBe(200);+ // What opening costs, counted: the year wheel parks its strip on its year+ // and marks the band's row, beside what the two-year wheel writes. A cost+ // per year (every row written as the wheel opens) shows here as 200 or+ // more.+ expect(wide.yearElementsWritten).toBeLessThanOrEqual(+ narrow.yearElementsWritten + 2,+ );+});++test.describe('under a mouse', () => {+ // A desktop: today's column, in the sheet the story asks for.+ test.use({hasTouch: false, isMobile: false});++ test('the year wheel is the scrolling column with every year', async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'chromium',+ 'one engine is enough for the fine-pointer path, which is main’s column',+ );+ await openStory(+ page,+ storybook(),+ 'core-dateinput--bottom-sheet-wide-range',+ );+ // A mouse case runs under a fine primary pointer: the page agrees.+ expect(+ await page.evaluate(() => window.matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ await page.getByRole('combobox', {name: 'Date of birth'}).click();+ const title = page.locator('[data-title="month-year"]');+ await expect(title).toBeVisible();+ await title.click();+ const years = page.getByRole('listbox', {name: 'Year'});+ await expect(years).toBeVisible();+ await expect(page.locator('[data-wheel]')).toHaveCount(0);+ expect(await years.getByRole('option').count()).toBe(200);+ });+});diff --git a/packages/core/src/DateInput/__tests__/WheelPinchZoom.a11y.chromium.spec.ts b/packages/core/src/DateInput/__tests__/WheelPinchZoom.a11y.chromium.spec.tsindex 4f4b7241a5..1d6cb11eaa 100644--- a/packages/core/src/DateInput/__tests__/WheelPinchZoom.a11y.chromium.spec.ts+++ b/packages/core/src/DateInput/__tests__/WheelPinchZoom.a11y.chromium.spec.ts@@ -3,12 +3,14 @@/*** @file WheelPinchZoom.a11y.chromium.spec.ts- * @input The built TimeInput bottom-sheet story and real Chromium touch input- * (CDP) on a phone profile+ * @input The built TimeInput bottom-sheet stories and real Chromium touch+ * input (CDP) on a phone profile* @output Browser evidence that a two-finger pinch over an open picker wheel- * zooms the page (WCAG 1.4.4) and changes no value- * @position Real-engine proof for the wheel's `touch-action`; jsdom computes- * no touch-action. The menus and listboxes have the same proof in+ * zooms the page (WCAG 1.4.4) and changes no value, and that one finger+ * still turns the wheel and leaves the page at scale 1: the touch column,+ * which a finger gets on every engine+ * @position Real-engine proof for each wheel's `touch-action`; jsdom+ * computes no touch-action. The menus and listboxes have the same proof in* MenuPinchZoom.a11y.chromium.spec.ts.*/@@ -103,9 +105,8 @@ async function pinch(cdp: CDPSession, at: Point) {await sleep(600);}-test('a pinch over an open picker wheel zooms the page and changes no value', async ({- page,-}) => {+/** The pinch over the open Minute wheel. */+async function pinchOverWheel(page: Page) {await page.goto(`${storybook.origin}/iframe.html?id=core-timeinput--styling-parts&viewMode=story`,);@@ -125,20 +126,29 @@ test('a pinch over an open picker wheel zooms the page and changes no value', asexpect(await pageScale(page)).toBeGreaterThan(1.2);await expect(wheel).toBeVisible();expect(await field.inputValue()).toBe(valueBefore);+}++test('a pinch over an open picker wheel zooms the page and changes no value', async ({+ page,+}) => {+ await pinchOverWheel(page);+ // The touch column: a finger gets it on every engine.+ await expect(page.locator('[data-wheel]').first()).toBeVisible();});-test('one finger dragged up a wheel still scrolls it and leaves the page at scale 1', async ({+test('one finger dragged up a wheel still turns it and leaves the page at scale 1', async ({page,}) => {+ // A field whose owner keeps its value, so the turn commits and shows.await page.goto(- `${storybook.origin}/iframe.html?id=core-timeinput--styling-parts&viewMode=story`,+ `${storybook.origin}/iframe.html?id=core-timeinput--bottom-sheet-with-min-max&viewMode=story`,);- const field = page.locator('[data-parts-row="control-bottom-sheet"] input');+ const field = page.getByRole('combobox', {name: 'Appointment time'});+ await expect(field).toHaveValue('10:00 AM');await field.tap();const wheel = page.getByRole('listbox', {name: 'Minute'});await expect(wheel).toBeVisible();await sleep(800);- const scrollTopBefore = await wheel.evaluate(el => el.scrollTop);const cdp = await page.context().newCDPSession(page);const at = await centerOf(wheel);@@ -157,15 +167,9 @@ test('one finger dragged up a wheel still scrolls it and leaves the page at scaltype: 'touchEnd',touchPoints: [],});- // From :30 the drag has rows to go. The column snaps to its rows: this asks- // that one finger scrolled it by at least one row, and left the page at- // scale 1.- const row = await wheel- .locator('[role="option"]')- .first()- .evaluate(el => el.getBoundingClientRect().height);- await expect- .poll(async () => wheel.evaluate(el => el.scrollTop), {timeout: 5000})- .toBeGreaterThanOrEqual(scrollTopBefore + row);++ // 120 px is more than three rows: whether or not the release coasts, the+ // wheel rests on a later minute and commits it.+ await expect(field).not.toHaveValue('10:00 AM', {timeout: 5000});expect(await pageScale(page)).toBe(1);});diff --git a/packages/core/src/DateInput/__tests__/WheelRest.a11y.chromium.spec.ts b/packages/core/src/DateInput/__tests__/WheelRest.a11y.chromium.spec.tsindex 688da07a7a..8f2b96dda4 100644--- a/packages/core/src/DateInput/__tests__/WheelRest.a11y.chromium.spec.ts+++ b/packages/core/src/DateInput/__tests__/WheelRest.a11y.chromium.spec.ts@@ -3,13 +3,17 @@/*** @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+ * @input The built TimeInput bottom-sheet story with bounds; real Chromium+ * touch input (CDP) on a phone profile, and a mouse on a desktop one* @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.+ * comes to rest on the nearest row inside them and commits it, on the touch+ * column under a finger and on today's column under a mouse; that a+ * downward drag on the touch column leaves the sheet where it is; and that+ * today's column under Reduce Motion fades its rows without tipping them+ * @position Real-engine proof for the rest rule: on the touch column, real+ * touch input through the gesture system; on today's column, native+ * scrolling, CSS snapping and the browser's own end-of-scroll signal. None+ * of it is in jsdom. Wheel.test.tsx and PickerWheel.test.tsx hold the rule.*/import {expect, test, type Locator, type Page} from '@playwright/test';@@ -18,6 +22,8 @@ import {serveStorybook,type StaticServer,} from '@astryxdesign/a11y-spec/storybook';+import {UIKIT_GESTURES} from '../../motion/uikit';+import {WHEEL_ROW_HEIGHT} from '../wheelOptions';let storybook: StaticServer;test.beforeAll(async () => {@@ -53,8 +59,15 @@ async function openHourWheel(page: Page) {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) {+/** A slow one-finger drag: no fling, so the wheel rests where it is let go. */+/** A mouse case runs under a fine primary pointer: the page agrees. */+async function expectFinePointer(page: Page) {+ expect(+ await page.evaluate(() => window.matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+}++async function drag(page: Page, wheel: Locator, dy: number, steps = 30) {const box = await wheel.boundingBox();if (box == null) {throw new Error('no rendered bounds');@@ -66,7 +79,6 @@ async function drag(page: Page, wheel: Locator, dy: number) {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', {@@ -127,23 +139,57 @@ interface RowFrame {const selectedHour = (hours: Locator) =>hours.locator('[role="option"][aria-selected="true"]');+/** The touch column's row pitch: today's row. */+const ROW = WHEEL_ROW_HEIGHT;/**- * 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.+ * A drag begins only once the finger has travelled the pan's hysteresis, which+ * the rows never show. So each drag adds that and a little more, and the wheel+ * rests on the intended row.*/-const SCROLL_SLOP_ALLOWANCE = 16;+const SLOP_ALLOWANCE = UIKIT_GESTURES.pan.hysteresis.value + 6;+// Slow (well under the release velocity floor), so the wheel rests on the+// row it is let go on rather than coasting.+const SLOW_STEPS = 60;++test('a downward drag on a wheel moves its rows and leaves the sheet where it is', async ({+ page,+}) => {+ const {hours} = await openHourWheel(page);+ const sheet = page.locator('.astryx-bottom-sheet').first();+ // The sheet's top on screen, every frame through the drag.+ await sheet.evaluate(element => {+ const tops: number[] = [];+ (window as unknown as {sheetTops: number[]}).sheetTops = tops;+ const sample = () => {+ tops.push(element.getBoundingClientRect().top);+ if (tops.length < 240) {+ requestAnimationFrame(sample);+ }+ };+ requestAnimationFrame(sample);+ });+ const restingBefore = await hours.getAttribute('aria-activedescendant');+ // Down: the rows move toward the earlier hours.+ await drag(page, hours, 2 * ROW + SLOP_ALLOWANCE, SLOW_STEPS);+ const tops = await page.evaluate(+ () => (window as unknown as {sheetTops: number[]}).sheetTops,+ );+ expect(tops.length).toBeGreaterThan(30);+ expect(Math.max(...tops) - Math.min(...tops)).toBeLessThan(1);+ await expect(hours).not.toHaveAttribute(+ 'aria-activedescendant',+ restingBefore ?? '',+ );+});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);+ // The touch column: a finger gets it on every engine.+ await expect(page.locator('[data-wheel]').first()).toBeVisible();// 10 → 7: three rows down, past 9 AM.- await drag(page, hours, 3 * row + SCROLL_SLOP_ALLOWANCE);+ await drag(page, hours, 3 * ROW + SLOP_ALLOWANCE, SLOW_STEPS);await expect(selectedHour(hours)).toHaveText('9', {timeout: 3000});await expect(field).toHaveValue('9:00 AM');@@ -153,12 +199,8 @@ 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 drag(page, hours, -(ROW + SLOP_ALLOWANCE), SLOW_STEPS);await expect(selectedHour(hours)).toHaveText('11', {timeout: 3000});await expect(field).toHaveValue('11:00 AM');@@ -171,20 +213,20 @@ test('under reduced motion an arrow key step lands under its cross-fade, never aconst {field, hours} = await openHourWheel(page);await hours.focus();// Record every frame the page draws, from before the key until the column- // is at rest again. 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.+ // is at rest again. Each frame holds where the committed row (10) is drawn+ // and how opaque its rows are. The rows are the scroller's or the touch+ // column's strip, whichever holds the options.await hours.evaluate(column => {const recorder = {seen: [] as RowFrame[], isDone: false};(window as unknown as {stepFrames: typeof recorder}).stepFrames = recorder;+ const row = column.querySelector<HTMLElement>(+ '[role="option"][aria-selected="true"]',+ );+ const faded = row?.parentElement ?? column;const sample = () => {- const strip = column.querySelector<HTMLElement>('[data-wheel-strip]');- const rows =- strip ?? column.querySelector<HTMLElement>('[role="option"]');- const faded = strip?.parentElement ?? column;recorder.seen.push({at: Math.round(- (rows?.getBoundingClientRect().top ?? 0) -+ (row?.getBoundingClientRect().top ?? 0) -column.getBoundingClientRect().top,),opacity: Number(getComputedStyle(faded).opacity),@@ -227,33 +269,67 @@ test('under reduced motion an arrow key step lands under its cross-fade, never aexpect(moved?.opacity, JSON.stringify(seen)).toBeLessThan(1);});+test('a focused wheel under a finger shows its whole focus ring, and its rows still fade', async ({+ page,+}) => {+ const {hours} = await openHourWheel(page);+ // A key makes the focus visible, as a keyboard user's would.+ await hours.focus();+ await page.keyboard.press('ArrowDown');+ const column = await hours.evaluate(element => {+ const style = getComputedStyle(element);+ return {+ focusVisible: element.matches(':focus-visible'),+ outlineStyle: style.outlineStyle,+ mask: style.maskImage,+ };+ });+ expect(column.focusVisible).toBe(true);+ expect(column.outlineStyle).not.toBe('none');+ // A mask on the column would clip the ring it draws outside its box.+ expect(column.mask).toBe('none');+ const fade = await hours+ .locator('[data-wheel-fade]')+ .evaluate(element => getComputedStyle(element).maskImage);+ expect(fade).toContain('linear-gradient');+});+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 the page draws, from- // before the tap until the wheel is at rest.- await hours.evaluate(scroller => {+ // The touch column draws its rows on a strip it translates. The animator+ // writes `translate`, which `transform` does not report. Record its drawn top+ // on every frame from before the tap until the wheel is at rest.+ const strip = hours.locator('[data-wheel-strip]');+ await expect(strip).toHaveCount(1);+ // The strip has no size of its own: its rows are placed on it. A drawn row+ // shows that the sheet is laid out before the sampling starts.+ await expect(strip.locator(':scope > *').first()).toBeVisible();+ const from = await strip.evaluate(+ element => element.getBoundingClientRect().top,+ );+ // 10 onto 5: five rows down the strip.+ const to = from + 5 * ROW;+ await strip.evaluate(element => {const recorder = {frames: [] as DrawnFrame[], isDone: false};(window as unknown as {hourTurn: typeof recorder}).hourTurn = recorder;const sample = (at: number) => {- recorder.frames.push({at, y: scroller.scrollTop});+ recorder.frames.push({at, y: element.getBoundingClientRect().top});if (!recorder.isDone) {requestAnimationFrame(sample);}};requestAnimationFrame(sample);});- // 10 PM is past the 5 PM maximum: the field clamps to it.- await meridiem.getByRole('option', {name: 'PM'}).tap();+ // 10 PM is past the 5 PM maximum: the field clamps to it. A finger taps the+ // PM row, one below the band. The options lie under the drawn rows, so the+ // tap goes to the column's own recognizer, as a finger's does.+ const pm = await meridiem+ .getByRole('option', {name: 'PM'})+ .evaluate(el => el.getBoundingClientRect().toJSON() as DOMRect);+ await page.touchscreen.tap(pm.x + pm.width / 2, pm.y + pm.height / 2);await expect(field).toHaveValue('5:00 PM', {timeout: 3000});// The record ends once a drawn frame shows the wheel at rest on 5.await expect@@ -275,7 +351,169 @@ test('a meridiem change past the maximum turns the hour wheel onto it, frame byrecorder.isDone = true;return recorder.frames;});+ await expect(selectedHour(hours)).toHaveText('5');// From 10 onto 5 through the rows between, as UIDatePicker turns onto its// maximum, never a jump, and only ever one way.expectAnimatedTurn(frames, from, to);});++test('on a starved main thread, a meridiem change past the maximum still comes to rest on it (component:DateInput FR13, FR14)', async ({+ page,+}) => {+ const {field, hours} = await openHourWheel(page);+ const meridiem = page.getByRole('listbox', {name: 'AM/PM'});+ const pm = await meridiem+ .getByRole('option', {name: 'PM'})+ .evaluate(el => el.getBoundingClientRect().toJSON() as DOMRect);+ // Frames come late and few, as on a slow phone.+ const cdp = await page.context().newCDPSession(page);+ await cdp.send('Emulation.setCPUThrottlingRate', {rate: 8});+ try {+ await page.touchscreen.tap(pm.x + pm.width / 2, pm.y + pm.height / 2);+ // The wheels are at rest when two reads in a row find the same value,+ // rows and positions, and no timed animation runs.+ let previous = '';+ await expect+ .poll(+ async () => {+ const now = await page.evaluate(() => {+ const field = document.querySelector<HTMLInputElement>(+ 'input[role="combobox"]',+ );+ const boxes = [...document.querySelectorAll('[role="listbox"]')];+ return JSON.stringify({+ value: field?.value,+ rows: boxes.map(+ box => box.querySelector('[aria-selected="true"]')?.textContent,+ ),+ tops: [...document.querySelectorAll('[data-wheel-strip]')].map(+ strip => Math.round(strip.getBoundingClientRect().top),+ ),+ scrolls: boxes.map(box => Math.round(box.scrollTop)),+ // Scroll-driven row effects run for as long as the rows show;+ // only the clock's animations move the wheels on their own.+ running: document+ .getAnimations()+ .filter(+ animation =>+ animation.playState === 'running' &&+ animation.timeline === document.timeline,+ ).length,+ });+ });+ const isAtRest = now === previous && now.endsWith('"running":0}');+ previous = now;+ return isAtRest;+ },+ {timeout: 30_000, intervals: [500]},+ )+ .toBe(true);+ } finally {+ await cdp.send('Emulation.setCPUThrottlingRate', {rate: 1});+ }+ // 10 PM clamps to the 5 PM maximum, and no late frame moves it on.+ await expect(field).toHaveValue('5:00 PM');+ await expect(selectedHour(hours)).toHaveText('5');+});++test.describe('under a mouse', () => {+ // A desktop: today's column, in the sheet the story asks for.+ test.use({+ hasTouch: false,+ isMobile: false,+ viewport: {width: 1280, height: 800},+ deviceScaleFactor: 1,+ });++ /**+ * A slow mouse drag. The drag starts past its slop, and the release carries+ * no velocity, so the column snaps to the row it is let go on.+ */+ async function mouseDrag(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 steps = 30;+ await page.mouse.move(x, y);+ await page.mouse.down();+ for (let i = 1; i <= steps; i++) {+ await sleep(16);+ await page.mouse.move(x, y + (dy * i) / steps);+ }+ await sleep(200);+ await page.mouse.up();+ }++ /** Today's row height, and the mouse's slop with room to spare. */+ async function rowOf(hours: Locator) {+ return hours+ .locator('[role="option"]')+ .first()+ .evaluate(el => el.getBoundingClientRect().height);+ }+ const MOUSE_SLOP_ALLOWANCE = 8;++ async function openHourWheelWithMouse(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.click();+ const hours = page.getByRole('listbox', {name: 'Hour'});+ await expect(hours).toBeVisible();+ // Today's column, not the touch one.+ await expect(page.locator('[data-wheel]')).toHaveCount(0);+ await sleep(800);+ return {field, hours};+ }++ test('a wheel dragged below the minimum comes to rest on the minimum', async ({+ page,+ }) => {+ const {field, hours} = await openHourWheelWithMouse(page);+ // 10 → 7: the content follows the hand, three rows down, past 9 AM.+ await mouseDrag(+ page,+ hours,+ 3 * (await rowOf(hours)) + MOUSE_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 openHourWheelWithMouse(page);+ // 10 → 11: one row up, still inside the bounds.+ await mouseDrag(+ page,+ hours,+ -((await rowOf(hours)) + MOUSE_SLOP_ALLOWANCE),+ );++ await expect(selectedHour(hours)).toHaveText('11', {timeout: 3000});+ await expect(field).toHaveValue('11:00 AM');+ });++ test('under Reduce Motion, the rows fade toward the edges without tipping', async ({+ page,+ }) => {+ await page.emulateMedia({reducedMotion: 'reduce'});+ const {hours} = await openHourWheelWithMouse(page);+ await expectFinePointer(page);+ // Two rows above the band (8 AM): dimmed, and flat.+ const label = hours.locator('[role="option"]').nth(8).locator('span');+ const {opacity, transform} = await label.evaluate(el => {+ const style = getComputedStyle(el);+ return {opacity: Number(style.opacity), transform: style.transform};+ });+ expect(opacity).toBeLessThan(0.95);+ expect(transform).toBe('none');+ });+});diff --git a/packages/core/src/DateInput/useOwnScrollGesture.ts b/packages/core/src/DateInput/useOwnScrollGesture.tsindex c25870dbb7..536423f67b 100644--- a/packages/core/src/DateInput/useOwnScrollGesture.ts+++ b/packages/core/src/DateInput/useOwnScrollGesture.ts@@ -6,7 +6,8 @@* @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+ * @position Internal behavior hook; consumed by Wheel.tsx, PickerWheel.tsx and+ * MonthScroller.tsx** Lets a nested scroller keep the finger that lands on it.*@@ -114,6 +115,16 @@ export type OwnScrollGestureOptions = {* so momentum and snapping are never second-guessed.*/onSwipe?: (direction: 1 | -1) => void;+ /**+ * Also keep the pointer a touch lands with, for an `'all'` scroller that pans+ * through the gesture system rather than natively. A sheet arms its pull-down+ * on its body's `pointerdown`, and counts on a native pan to cancel a touch+ * pointer. A pan of the gesture system never cancels it. Without this, the+ * sheet follows the first 8 px of a downward drag before the scroller's own+ * pan takes over. The gesture host and the shared modality tracker listen in+ * the capture phase, before this.+ */+ isPointerKept?: boolean;};/**@@ -130,7 +141,7 @@ export function useOwnScrollGesture(axis: OwnedAxis = 'all',options: OwnScrollGestureOptions = {},): void {- const {isEnabled = true, onSwipe} = options;+ const {isEnabled = true, onSwipe, isPointerKept = false} = options;// Read through a ref so a caller need not memoize the callback: re-running// this effect would tear the listeners off mid-gesture.@@ -215,15 +226,24 @@ export function useOwnScrollGesture(claimed = null;};+ const keepPointer = (event: PointerEvent) => event.stopPropagation();+ const isKeepingPointer = axis === 'all' && isPointerKept;+element.addEventListener('touchstart', onStart, {passive: true});element.addEventListener('touchmove', onMove, {passive: true});element.addEventListener('touchend', onEnd, {passive: true});element.addEventListener('touchcancel', onEnd, {passive: true});+ if (isKeepingPointer) {+ element.addEventListener('pointerdown', keepPointer);+ }return () => {element.removeEventListener('touchstart', onStart);element.removeEventListener('touchmove', onMove);element.removeEventListener('touchend', onEnd);element.removeEventListener('touchcancel', onEnd);+ if (isKeepingPointer) {+ element.removeEventListener('pointerdown', keepPointer);+ }};- }, [ref, axis, isEnabled]);+ }, [ref, axis, isEnabled, isPointerKept]);}diff --git a/packages/core/src/DateInput/useWheelListbox.ts b/packages/core/src/DateInput/useWheelListbox.tsnew file mode 100644index 0000000000..6b24d3cd8e--- /dev/null+++ b/packages/core/src/DateInput/useWheelListbox.ts@@ -0,0 +1,112 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useWheelListbox.ts+ * @input A wheel's label, options, committed value and active row, and its+ * presentation's three moves: a step, an end, a row+ * @output useWheelListbox: the listbox and option props both wheels share+ * @position Internal hook of ScrollWheel (Wheel.tsx) and PickerWheel.tsx+ *+ * A wheel is a listbox: one tab stop, with Arrow, Page, Home and End keys.+ * Each presentation decides what its keys and clicks do to its own column.+ *+ * SYNC: When modified, update Wheel.tsx and PickerWheel.tsx.+ */++import {useCallback, useId, type KeyboardEvent} from 'react';+import type {WheelOption} from './wheelOptions';++/** Rows a Page Up or Page Down key moves. */+const PAGE_ROWS = 10;++export interface WheelListboxProps {+ /** Accessible name for the column. */+ label: string;+ /** Rows, top to bottom. */+ options: ReadonlyArray<WheelOption>;+ /** Committed value. */+ value: number;+ /** The row `aria-activedescendant` names. */+ activeIndex: number;+ /** An Arrow or Page key: a step of `delta` rows. */+ stepBy: (delta: number) => void;+ /** Home or End. */+ toEnd: (end: 'first' | 'last') => void;+ /** A click on row `index`. */+ activate: (index: number) => void;+}++/**+ * The listbox and option props of one wheel column: ids, ARIA, the keys and+ * a click on a row. `aria-activedescendant` marks the active row, and a click+ * reaches every row. The scrolling column steps from the row under its band. The+ * touch column steps from the row it is heading to.+ *+ * @example+ * ```+ * const {listboxProps, optionProps} = useWheelListbox({label, options, value, activeIndex, stepBy, toEnd, activate});+ * <div {...listboxProps}>{options.map((option, index) => <div key={option.value} {...optionProps(option, index)} />)}</div>+ * ```+ */+export function useWheelListbox({+ label,+ options,+ value,+ activeIndex,+ stepBy,+ toEnd,+ activate,+}: WheelListboxProps) {+ const id = useId();+ const onKeyDown = useCallback(+ (event: KeyboardEvent) => {+ switch (event.key) {+ case 'ArrowDown':+ event.preventDefault();+ stepBy(1);+ break;+ case 'ArrowUp':+ event.preventDefault();+ stepBy(-1);+ break;+ case 'PageDown':+ event.preventDefault();+ stepBy(PAGE_ROWS);+ break;+ case 'PageUp':+ event.preventDefault();+ stepBy(-PAGE_ROWS);+ break;+ case 'Home':+ event.preventDefault();+ toEnd('first');+ break;+ case 'End':+ event.preventDefault();+ toEnd('last');+ break;+ default:+ break;+ }+ },+ [stepBy, toEnd],+ );+ return {+ listboxProps: {+ role: 'listbox' as const,+ 'aria-label': label,+ 'aria-activedescendant': `${id}-${options[activeIndex]?.value}`,+ tabIndex: 0,+ onKeyDown,+ },+ optionProps: (option: WheelOption, index: number) => ({+ id: `${id}-${option.value}`,+ role: 'option' as const,+ 'aria-selected': option.value === value,+ 'aria-disabled': option.isDisabled || undefined,+ onClick: () => activate(index),+ }),+ };+}diff --git a/packages/core/src/DateInput/wheelOptions.ts b/packages/core/src/DateInput/wheelOptions.tsnew file mode 100644index 0000000000..e77d93c47a--- /dev/null+++ b/packages/core/src/DateInput/wheelOptions.ts@@ -0,0 +1,155 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file wheelOptions.ts+ * @input Nothing; types, the row height and pure functions+ * @output WheelOption, WheelProps, WHEEL_ROW_HEIGHT, nearestEnabledIndex,+ * steppedIndex and endIndex: what both wheels share+ * @position Internal; read by Wheel.tsx (which re-exports all of it) and+ * PickerWheel.tsx+ *+ * SYNC: When modified, update:+ * - /packages/core/src/DateInput/Wheel.tsx+ * - /packages/core/src/DateInput/PickerWheel.tsx+ */++/**+ * The row height, px (`dateInputTouchSizes.wheelItemSize`): the pitch of both+ * columns' rows, and the unit of the touch wheel's offset.+ */+export const WHEEL_ROW_HEIGHT = 28;++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: a wheel that+ * stops on one travels on to the nearest enabled row.+ */+ isDisabled?: boolean;+ /**+ * Where the row falls when a key steps the wheel; without it, rows step in+ * list order. A 12-hour hour column sets the full hour, so 12 PM comes before+ * 1 PM.+ */+ order?: number;+}++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. The scrolling column then waits to listen+ * and scroll, because a hidden scroller's offsets mean nothing. The touch+ * wheel turns its gestures off, and shows a value set from outside without+ * motion.+ */+ 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;+}++/** The rows' indices in the order keys step them: by `order`, else list order. */+function inKeyOrder(options: ReadonlyArray<WheelOption>): number[] {+ const indices = options.map((_, index) => index);+ if (options.every(option => option.order == null)) {+ return indices;+ }+ return indices.sort(+ (a, b) => (options[a].order ?? a) - (options[b].order ?? b),+ );+}++/**+ * The row a key moves a wheel to from `from` by `delta` rows, in key order. It+ * is the next enabled row from the target in the key's direction. Past the+ * last enabled row, it is the last enabled row before the target. Null when no+ * enabled row lies in that direction, so the key commits nothing.+ */+export function steppedIndex(+ options: ReadonlyArray<WheelOption>,+ from: number,+ delta: number,+): number | null {+ const count = options.length;+ if (count === 0 || delta === 0) {+ return null;+ }+ const rows = inKeyOrder(options);+ const start = Math.max(0, rows.indexOf(from));+ const isEnabled = (position: number) => !options[rows[position]].isDisabled;+ const step = Math.sign(delta);+ const target = Math.min(count - 1, Math.max(0, start + delta));+ for (+ let position = target;+ position >= 0 && position < count;+ position += step+ ) {+ if (isEnabled(position)) {+ return position === start ? null : rows[position];+ }+ }+ for (let position = target; position !== start; position -= step) {+ if (isEnabled(position)) {+ return rows[position];+ }+ }+ return null;+}++/** The first or the last enabled row in key order: where Home or End moves a wheel. */+export function endIndex(+ options: ReadonlyArray<WheelOption>,+ end: 'first' | 'last',+): number | null {+ const enabled = inKeyOrder(options).filter(+ index => !options[index].isDisabled,+ );+ return (end === 'first' ? enabled[0] : enabled[enabled.length - 1]) ?? null;+}diff --git a/packages/core/src/DateInput/wheelPhysics.test.ts b/packages/core/src/DateInput/wheelPhysics.test.tsnew file mode 100644index 0000000000..256d003da5--- /dev/null+++ b/packages/core/src/DateInput/wheelPhysics.test.ts@@ -0,0 +1,409 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file wheelPhysics.test.ts+ * @input wheelPhysics.ts and per-frame offsets recorded from a UIPickerView,+ * with the release velocity UIKit handed its delegate+ * @output Proves the Wheel's curves reproduce UIKit's measured picker: the+ * projected target, the coast onto the row, the coast into an end, the+ * snap, the rubber band, the tap spin and the ticks+ * @position Unit coverage for DateInput/wheelPhysics.ts+ *+ * The recordings are of a 216 pt UIPickerView column of 60 rows, 32 pt each.+ * Real HID touches drove it on the iOS 26.2 simulator (iPhone 17 Pro), Oct 23+ * 2026. Offsets are converted to this file's convention (row k centred at k ×+ * 32): UIKit's contentOffset + 129.67. Frames are [ms after the lift, offset].+ */++import {describe, expect, it} from 'vitest';+import {picker} from '../motion/uikit/picker';+import {timing} from '../motion/uikit/timing';+import {+ MAX_PLAN_SECONDS,+ coastCurve,+ dragOffset,+ planRelease,+ projectRelease,+ reachesRow,+ snapCurve,+ spinCurve,+ tickTimes,+ type WheelLayout,+} from './wheelPhysics';++const MINUTES: WheelLayout = {rowHeight: 32, rowCount: 60};++interface Recording {+ /** Offset at the lift. */+ readonly offset: number;+ /** The velocity UIKit handed scrollViewWillEndDragging, px/s. */+ readonly velocity: number;+ /** Its projected target, and the row it snapped that to. */+ readonly targetIn: number;+ readonly targetOut: number;+ /** ms after the lift. */+ readonly didSelect: number;+ readonly frames: ReadonlyArray<readonly [number, number]>;+}++const SWIPE_200_IN_50MS: Recording = {+ offset: 1093.33,+ velocity: 933.4,+ targetIn: 1554.67,+ targetOut: 1568,+ didSelect: 2314,+ frames: [],+};++const SWIPE_200_IN_100MS: Recording = {+ offset: 1143.33,+ velocity: 2114,+ targetIn: 1888,+ targetOut: 1888,+ didSelect: 1220,+ frames: [],+};++const SWIPE_200_IN_200MS: Recording = {+ offset: 1110,+ velocity: 1016.2,+ targetIn: 1612.67,+ targetOut: 1600,+ didSelect: 2316,+ frames: [+ [15, 1126.67],+ [81.4, 1187.67],+ [149.2, 1241],+ [215.6, 1287.67],+ [282.2, 1328],+ [351.3, 1363.33],+ [415, 1394.33],+ [481.6, 1421],+ [550.8, 1444.67],+ [617.3, 1465],+ [681.5, 1482.67],+ [749, 1498.33],+ [815.9, 1512],+ [882.6, 1523.67],+ [949.1, 1534],+ [1015.5, 1543],+ [1084, 1551],+ [1149.7, 1557.67],+ [1214.9, 1563.67],+ [1282.1, 1569],+ [1351.5, 1573.33],+ [1415.2, 1577.33],+ [1481.7, 1581],+ [1549, 1584],+ [1614.7, 1586.33],+ [1684.1, 1588.67],+ [1748.1, 1590.67],+ [1815.2, 1592.33],+ [1883.9, 1594],+ [1948.2, 1595.33],+ [2014.9, 1596.33],+ [2081.6, 1597.33],+ [2149.5, 1598.33],+ [2216.3, 1599],+ [2282.4, 1599.67],+ [2315.2, 1600],+ ],+};++const FLICK_90: Recording = {+ offset: 1014,+ velocity: 543.6,+ targetIn: 1280.67,+ targetOut: 1280,+ didSelect: 2032,+ frames: [+ [19.4, 1023],+ [81.4, 1055.67],+ [151.9, 1084.33],+ [215.5, 1109.33],+ [281.4, 1131.33],+ [352.9, 1150.67],+ [415.1, 1167.33],+ [482, 1182],+ [548.2, 1195],+ [615.9, 1206],+ [682.6, 1216],+ [748.2, 1224.67],+ [816.8, 1232],+ [883.1, 1238.67],+ [949.1, 1244.33],+ [1016, 1249.33],+ [1081.5, 1254],+ [1149.7, 1257.67],+ [1214.8, 1261],+ [1281.9, 1264],+ [1350.8, 1266.67],+ [1415.7, 1269],+ [1483.9, 1271],+ [1548.4, 1272.67],+ [1616.4, 1274],+ [1682.3, 1275.33],+ [1750.6, 1276.67],+ [1815, 1277.67],+ [1882.9, 1278.67],+ [1949.6, 1279.33],+ [2015.2, 1280],+ [2031.5, 1280],+ ],+};++/** A slow drag up, held still 300 ms: no velocity, 6 px past row 31. */+const STILL_6PX_PAST: Recording = {+ offset: 998,+ velocity: 0,+ targetIn: 998,+ targetOut: 992,+ didSelect: 300,+ frames: [+ [16.1, 997],+ [34.2, 996],+ [50.7, 995.33],+ [66.2, 994.67],+ [82.9, 994.33],+ [102.3, 994],+ [116.3, 993.67],+ [133.2, 993.33],+ [152.4, 993.33],+ [166.2, 993],+ [184.1, 993],+ [199.5, 992.67],+ [216.1, 992.67],+ [232.8, 992.67],+ [249.5, 992.33],+ [267.3, 992.33],+ [283, 992],+ [299.7, 992],+ ],+};++/** RMS distance between a curve and recorded frames, in px. */+function rms(+ value: (t: number) => number,+ frames: Recording['frames'],+): number {+ let sum = 0;+ for (const [ms, offset] of frames) {+ sum += (value(ms / 1000) - offset) ** 2;+ }+ return Math.sqrt(sum / frames.length);+}++describe('the projected target', () => {+ it.each([+ ['200 pt in 50 ms', SWIPE_200_IN_50MS],+ ['200 pt in 200 ms', SWIPE_200_IN_200MS],+ ['a 90 pt flick', FLICK_90],+ ])('matches UIKit’s targetContentOffset for %s', (_name, recording) => {+ expect(+ Math.abs(+ projectRelease(recording.offset, recording.velocity) -+ recording.targetIn,+ ),+ ).toBeLessThan(0.3);+ });++ it('snaps to the row UIKit snapped to', () => {+ for (const recording of [SWIPE_200_IN_50MS, SWIPE_200_IN_200MS, FLICK_90]) {+ const plan = planRelease(recording.offset, recording.velocity, MINUTES);+ expect(plan.kind).toBe('coast');+ expect(plan.index * 32).toBe(recording.targetOut);+ }+ });+});++describe('the coast onto a row', () => {+ it.each([+ ['200 pt in 200 ms', SWIPE_200_IN_200MS, 0.8],+ ['a 90 pt flick', FLICK_90, 0.8],+ ])(+ 'follows UIKit’s frames for %s and stops on the row',+ (_name, recording, tolerance) => {+ const {curve} = planRelease(+ recording.offset,+ recording.velocity,+ MINUTES,+ );+ expect(rms(curve.value, recording.frames)).toBeLessThan(tolerance);+ expect(curve.value(curve.duration)).toBe(recording.targetOut);+ // didSelect lands in the frame of the last offset change.+ expect(+ Math.abs(curve.duration * 1000 - recording.didSelect),+ ).toBeLessThan(50);+ },+ );++ it('keeps the release velocity at the lift and ends at the stop speed', () => {+ const curve = coastCurve(1110, 1016.2, 1600);+ expect(curve.velocity(0)).toBeCloseTo(1016.2, 6);+ expect(curve.velocity(curve.duration - 1e-9)).toBeCloseTo(8.9, 3);+ expect(curve.velocity(curve.duration)).toBe(0);+ });++ it('is never re-solved backwards: a target behind the velocity snaps', () => {+ const curve = coastCurve(1010, 500, 992);+ expect(curve.value(curve.duration)).toBe(992);+ expect(curve.velocity(0)).toBeLessThan(0);+ });+});++describe('a coast into an end', () => {+ it('decays at the normal rate into the last row, then bounces back to it', () => {+ const plan = planRelease(+ SWIPE_200_IN_100MS.offset,+ SWIPE_200_IN_100MS.velocity,+ MINUTES,+ );+ expect(plan.kind).toBe('edge');+ expect(plan.index).toBe(59);+ const end = 59 * 32;+ // UIKit's frames pass the end about 600 ms after the lift. They overshoot+ // by 20.7 pt around 700 ms and are back on the row by about 1.2 s.+ let hit = 0;+ let peak = end;+ for (let t = 0; t < plan.curve.duration; t += 1 / 240) {+ const value = plan.curve.value(t);+ if (hit === 0 && value >= end) {+ hit = t;+ }+ peak = Math.max(peak, value);+ }+ expect(hit).toBeGreaterThan(0.55);+ expect(hit).toBeLessThan(0.65);+ expect(peak - end).toBeGreaterThan(10);+ expect(peak - end).toBeLessThan(30);+ expect(plan.curve.value(plan.curve.duration)).toBe(end);+ });+});++describe('a release without velocity', () => {+ it('eases onto the nearest row as UIKit does', () => {+ const plan = planRelease(STILL_6PX_PAST.offset, 0, MINUTES);+ expect(plan.kind).toBe('snap');+ expect(plan.index).toBe(31);+ expect(rms(plan.curve.value, STILL_6PX_PAST.frames)).toBeLessThan(0.4);+ expect(+ Math.abs(plan.curve.duration * 1000 - STILL_6PX_PAST.didSelect),+ ).toBeLessThan(60);+ });++ it('treats a release below the velocity floor as no velocity', () => {+ // 244.7 pt/s was zeroed by UIKit; 257.7 was handed on.+ expect(planRelease(1000, 240, MINUTES).kind).toBe('snap');+ expect(planRelease(1000, -240, MINUTES).kind).toBe('snap');+ expect(planRelease(1000, 260, MINUTES).kind).toBe('coast');+ });++ it('is already at rest on a row', () => {+ const curve = snapCurve(992, 992);+ expect(curve.duration).toBe(0);+ expect(curve.value(0)).toBe(992);+ });+});++describe('past an end', () => {+ it('rubber-bands a drag past the last row as UIPickerView does', () => {+ const end = 59 * 32;+ // 10, 50 and 110 px of finger travel past the end; UIKit showed 5.3, 25+ // and 50.+ expect(dragOffset(end + 10, MINUTES) - end).toBeCloseTo(5.4, 1);+ expect(dragOffset(end + 50, MINUTES) - end).toBeCloseTo(25.1, 1);+ expect(dragOffset(end + 110, MINUTES) - end).toBeCloseTo(50.1, 1);+ expect(dragOffset(-50, MINUTES)).toBeCloseTo(-25.1, 1);+ expect(dragOffset(500, MINUTES)).toBe(500);+ });++ it('returns to the end it was released past, keeping any velocity', () => {+ const plan = planRelease(-37.33, -147.8, MINUTES);+ expect(plan.kind).toBe('return');+ expect(plan.index).toBe(0);+ expect(plan.curve.velocity(0)).toBeCloseTo(-147.8, 6);+ expect(plan.curve.value(plan.curve.duration)).toBe(0);+ });+});++describe('the tap spin', () => {+ it('turns onto the row on Core Animation’s ease-in-ease-out in 0.3 s', () => {+ const curve = spinCurve(+ 0,+ 64,+ picker.tapSpin.durationMs / 1000,+ timing.curves.move,+ );+ expect(curve.duration).toBe(0.3);+ // UIKit, a tap two rows below the band: 6.8, 25.1, 50.2, 75.4 and 93.7 % of+ // the way at 50 ms steps. The recording starts a few ms early.+ const measured = [0.068, 0.251, 0.502, 0.754, 0.937];+ measured.forEach((fraction, i) => {+ expect(+ Math.abs(curve.value((i + 1) * 0.05) / 64 - fraction),+ ).toBeLessThan(0.025);+ });+ expect(curve.value(0.3)).toBe(64);+ expect(curve.velocity(0.15)).toBeGreaterThan(0);+ });+});++describe('the selection tick', () => {+ it('fires when a row’s centre reaches the band, not when it leaves it', () => {+ expect(reachesRow(31.9 * 32, 32 * 32, 32)).toBe(true);+ expect(reachesRow(32 * 32, 32.4 * 32, 32)).toBe(false);+ expect(reachesRow(32.1 * 32, 32 * 32, 32)).toBe(true);+ expect(reachesRow(32 * 32, 31.6 * 32, 32)).toBe(false);+ });++ it('ticks once per row on a coast, at most every 40 ms', () => {+ const {curve} = planRelease(1110, 1016.2, MINUTES);+ const ticks = tickTimes(curve, 32);+ // From row 34.7 to row 50: rows 35 to 50.+ expect(ticks.length).toBeLessThanOrEqual(16);+ expect(ticks.length).toBeGreaterThan(12);+ for (let i = 1; i < ticks.length; i++) {+ expect(ticks[i] - ticks[i - 1]).toBeGreaterThanOrEqual(0.04 - 1e-9);+ }+ });+});++describe('the bounce spring it is handed', () => {+ it('returns from past an end on the spring it is handed', () => {+ const layout: WheelLayout = {rowHeight: 32, rowCount: 60};+ const table = planRelease(-60, 0, layout);+ const stiff = planRelease(-60, 0, layout, {duration: 0.2, bounce: 0});+ expect(table.kind).toBe('return');+ expect(stiff.kind).toBe('return');+ expect(stiff.curve.to).toBe(0);+ expect(stiff.curve.duration).toBeLessThan(table.curve.duration);+ });++ // An undamped bounce spring (bounce 1, or a physical spring with no+ // damping) never settles, and a plan that never ends cannot be baked. It snaps onto its end at the animator's limit, as the+ // animator's own motion does.+ it('ends a plan whose bounce never settles at the animator limit', () => {+ const springs = [+ {duration: 0.5, bounce: 1},+ {stiffness: 300, damping: 0},+ {duration: 0.5, bounce: 0.999},+ ];+ for (const bounce of springs) {+ const back = planRelease(-60, 0, MINUTES, bounce);+ const into = planRelease(+ SWIPE_200_IN_100MS.offset,+ SWIPE_200_IN_100MS.velocity,+ MINUTES,+ bounce,+ );+ expect([back.kind, into.kind]).toEqual(['return', 'edge']);+ for (const {curve} of [back, into]) {+ expect(curve.duration, JSON.stringify(bounce)).toBeLessThanOrEqual(+ MAX_PLAN_SECONDS,+ );+ expect(curve.value(curve.duration)).toBe(curve.to);+ expect(curve.velocity(curve.duration)).toBe(0);+ }+ }+ });+});diff --git a/packages/core/src/DateInput/wheelPhysics.ts b/packages/core/src/DateInput/wheelPhysics.tsnew file mode 100644index 0000000000..849eb262e7--- /dev/null+++ b/packages/core/src/DateInput/wheelPhysics.ts@@ -0,0 +1,406 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file wheelPhysics.ts+ * @input A wheel's offset and release velocity, its rows, and the UIKit+ * picker constants (motion/uikit/picker.ts)+ * @output The curves a picker wheel moves on: the release plan, the tap spin,+ * the rubber band, and the row crossings that tick+ * @position Pure math of the touch picker wheel (PickerWheel.tsx)+ *+ * Positions are px, times seconds and velocities px/s. Row k is under the+ * band at an offset of k rows. UIKit's pt values scale by `scale`.+ *+ * SYNC: When modified, update wheelPhysics.test.ts and PickerWheel.tsx.+ */++import {cubicBezier} from '../motion/bezier';+import {projectDistance} from '../motion/projection';+import {solveDecay} from '../motion/decay';+import {rubberBand} from '../motion/rubberBand';+import {solveSpring, toSpring, type SpringDescription} from '../motion/spring';+import {picker} from '../motion/uikit/picker';+import {scroll} from '../motion/uikit/scroll';++/** A motion of the wheel's offset, from t = 0 to `duration` (seconds). */+export interface WheelCurve {+ /** Seconds until the wheel is at rest on `to`. */+ readonly duration: number;+ /** Where the motion ends. */+ readonly to: number;+ /** Offset at `t` seconds; `to` from `duration` on. */+ value(t: number): number;+ /** Velocity at `t` seconds, px/s; 0 from `duration` on. */+ velocity(t: number): number;+}++/** How a release moves the wheel. */+export type WheelPlanKind = 'coast' | 'snap' | 'edge' | 'return';++/** What a release does: the curve, and the row it ends on. */+export interface WheelPlan {+ readonly kind: WheelPlanKind;+ /** The row the wheel comes to rest on. */+ readonly index: number;+ readonly curve: WheelCurve;+}++/** The rows a wheel moves over. */+export interface WheelLayout {+ /** Row height, px. */+ readonly rowHeight: number;+ readonly rowCount: number;+}++/** UIKit's row height in pt: the unit the picker constants are measured in. */+const UIKIT_ROW_HEIGHT = picker.geometry.rowHeight;++/** Below half a device pixel at 3×, a motion is on its row. */+const AT_REST_PT = 1 / 6;++/**+ * The longest a plan runs, s: the animator's limit (`MAX_DURATION_MS` in+ * motion/animator.ts). A spring that has not settled by then (an undamped+ * one, which never does) snaps onto its end.+ */+export const MAX_PLAN_SECONDS = 30;++/** The constants' scale for a wheel whose rows are `rowHeight` px tall. */+export function scaleFor(rowHeight: number): number {+ return rowHeight / UIKIT_ROW_HEIGHT;+}++/** The wheel at rest on `offset`: a curve that does not move. */+export function restCurve(offset: number): WheelCurve {+ return {+ duration: 0,+ to: offset,+ value: () => offset,+ velocity: () => 0,+ };+}++/** The offsets of the first and last rows. */+export function offsetBounds({rowHeight, rowCount}: WheelLayout): {+ min: number;+ max: number;+} {+ return {min: 0, max: Math.max(0, rowCount - 1) * rowHeight};+}++/**+ * The offset a drag shows for the finger's `offset`: past the first or last+ * row it is rubber-banded, as a UIPickerView's table is.+ */+export function dragOffset(offset: number, layout: WheelLayout): number {+ const {min, max} = offsetBounds(layout);+ const dimension =+ picker.geometry.rubberBandDimension * scaleFor(layout.rowHeight);+ if (offset < min) {+ return min + rubberBand(offset - min, dimension);+ }+ if (offset > max) {+ return max + rubberBand(offset - max, dimension);+ }+ return offset;+}++/** The nearest row to `offset`, clamped to the rows. */+export function nearestIndex(offset: number, layout: WheelLayout): number {+ const index = Math.round(offset / layout.rowHeight);+ return Math.min(Math.max(index, 0), Math.max(0, layout.rowCount - 1));+}++/**+ * Ease from `from` onto `to` as UIKit does after a release without velocity.+ * The distance left falls as e^(−k t), and the ease ends within half a device+ * pixel.+ */+export function snapCurve(from: number, to: number, scale = 1): WheelCurve {+ const distance = from - to;+ const rate = picker.snapRate * 1000;+ const epsilon = AT_REST_PT * scale;+ if (Math.abs(distance) <= epsilon) {+ return {+ duration: 0,+ to,+ value: () => to,+ velocity: () => 0,+ };+ }+ const duration = Math.log(Math.abs(distance) / epsilon) / rate;+ return {+ duration,+ to,+ value: t => (t >= duration ? to : to + distance * Math.exp(-rate * t)),+ velocity: t => (t >= duration ? 0 : -rate * distance * Math.exp(-rate * t)),+ };+}++/**+ * A coast from `from` at `velocity` that keeps the velocity and ends on `to` at+ * the stop speed. The rate is re-solved, so the speed falls from |velocity| to+ * the stop speed over exactly `to − from`.+ */+export function coastCurve(+ from: number,+ velocity: number,+ to: number,+ scale = 1,+): WheelCurve {+ const stopSpeed = picker.release.stopSpeed * 1000 * scale;+ const distance = to - from;+ const speed = Math.abs(velocity);+ if (+ distance === 0 ||+ Math.sign(distance) !== Math.sign(velocity) ||+ speed <= stopSpeed+ ) {+ return snapCurve(from, to, scale);+ }+ const direction = Math.sign(distance);+ // Per second: the speed falls by λ × the distance covered.+ const lambda = (speed - stopSpeed) / Math.abs(distance);+ const duration = Math.log(speed / stopSpeed) / lambda;+ return {+ duration,+ to,+ value: t =>+ t >= duration+ ? to+ : from + (direction * speed * -Math.expm1(-lambda * t)) / lambda,+ velocity: t =>+ t >= duration ? 0 : direction * speed * Math.exp(-lambda * t),+ };+}++/**+ * The bounce spring, from `from` with `velocity`, onto `to`. `bounce` is+ * `scroll.bounce`'s spring as its caller resolves it.+ */+export function bounceCurve(+ from: number,+ velocity: number,+ to: number,+ scale = 1,+ bounce: SpringDescription = scroll.bounce,+): WheelCurve {+ const spring = solveSpring(toSpring(bounce), {+ from,+ to,+ velocity,+ });+ const duration = Math.min(+ MAX_PLAN_SECONDS,+ spring.settleTime(AT_REST_PT * scale),+ );+ return {+ duration,+ to,+ value: t => (t >= duration ? to : spring.value(t)),+ velocity: t => (t >= duration ? 0 : spring.velocity(t)),+ };+}++/**+ * A coast that runs into an end: the normal decay until the offset reaches+ * `edge`, then the bounce spring with the velocity it has there.+ */+export function edgeCurve(+ from: number,+ velocity: number,+ edge: number,+ scale = 1,+ bounceSpring: SpringDescription = scroll.bounce,+): WheelCurve {+ const decay = solveDecay({from, velocity});+ const hit = decay.timeToReach(edge);+ if (hit == null) {+ return bounceCurve(from, velocity, edge, scale, bounceSpring);+ }+ const bounce = bounceCurve(+ edge,+ decay.velocity(hit),+ edge,+ scale,+ bounceSpring,+ );+ const duration = Math.min(MAX_PLAN_SECONDS, hit + bounce.duration);+ return {+ duration,+ to: edge,+ value: t =>+ t >= duration ? edge : t < hit ? decay.value(t) : bounce.value(t - hit),+ velocity: t =>+ t >= duration+ ? 0+ : t < hit+ ? decay.velocity(t)+ : bounce.velocity(t - hit),+ };+}++/**+ * Where the scroll view projects a release. This is the coast's rest point at+ * the normal rate, short of the stop speed. UIScrollView sums it the same way+ * (`projectDistance`: r ÷ (1 − r) ms of the speed).+ */+export function projectRelease(+ offset: number,+ velocity: number,+ scale = 1,+): number {+ const stopSpeed = picker.release.stopSpeed * 1000 * scale;+ const speed = Math.abs(velocity);+ if (speed <= stopSpeed) {+ return offset;+ }+ return offset + Math.sign(velocity) * projectDistance(speed - stopSpeed);+}++/**+ * What the wheel does when the finger lifts at `offset` with `velocity`+ * (px/s, positive when the rows move up). `bounce` is `scroll.bounce`'s+ * spring as the wheel resolves it. The velocity is the pan's+ * `scrollVelocity()` at the lift. The plan follows UIKit, as measured:+ *+ * - Inside the rows, a release slower than `release.minimumSpeed` carries no+ * velocity. Past an end, the velocity is kept.+ * - The scroll view projects the coast (`projectRelease`), and the picker+ * snaps that to the nearest row. The coast keeps the release velocity and+ * stops exactly on that row.+ * - A projection past an end is not re-solved. The coast decays at the normal+ * rate into the end, and the bounce takes its velocity there.+ * - A release without velocity eases onto the nearest row at `snapRate`.+ * - A release past an end returns on the bounce spring.+ * - A spring that has not settled by the animator's limit snaps onto its end+ * there, as the animator's own motion does.+ *+ * @example+ * ```+ * const plan = planRelease(963.67, 933.4, {rowHeight: 32, rowCount: 60});+ * plan.index; // 45: the coast stops on row 45 after about 2.3 s+ * ```+ */+export function planRelease(+ offset: number,+ velocity: number,+ layout: WheelLayout,+ bounce: SpringDescription = scroll.bounce,+): WheelPlan {+ const scale = scaleFor(layout.rowHeight);+ const {min, max} = offsetBounds(layout);+ if (offset < min || offset > max) {+ const edge = offset < min ? min : max;+ return {+ kind: 'return',+ index: nearestIndex(edge, layout),+ curve: bounceCurve(offset, velocity, edge, scale, bounce),+ };+ }+ const minimumSpeed = picker.release.minimumSpeed * 1000 * scale;+ const speed = Math.abs(velocity) < minimumSpeed ? 0 : velocity;+ const projected = projectRelease(offset, speed, scale);+ if (projected < min || projected > max) {+ const edge = projected < min ? min : max;+ return {+ kind: 'edge',+ index: nearestIndex(edge, layout),+ curve: edgeCurve(offset, speed, edge, scale, bounce),+ };+ }+ const index = nearestIndex(projected, layout);+ const target = index * layout.rowHeight;+ if (speed === 0) {+ return {kind: 'snap', index, curve: snapCurve(offset, target, scale)};+ }+ const curve = coastCurve(offset, speed, target, scale);+ return {kind: curve.duration > 0 ? 'coast' : 'snap', index, curve};+}++/**+ * The tap spin onto a row: UIKit's animated setContentOffset, over+ * `duration` seconds on `curve`.+ */+export function spinCurve(+ from: number,+ to: number,+ duration: number,+ curve: readonly [number, number, number, number],+): WheelCurve {+ if (from === to || !(duration > 0)) {+ return restCurve(to);+ }+ const ease = cubicBezier(curve);+ const distance = to - from;+ // Velocity from the eased progress's slope, by a central difference.+ const step = 1e-4;+ return {+ duration,+ to,+ value: t => (t >= duration ? to : from + distance * ease(t / duration)),+ velocity: t => {+ if (t >= duration || t < 0) {+ return 0;+ }+ const a = ease(Math.max(0, t / duration - step));+ const b = ease(Math.min(1, t / duration + step));+ return (distance * (b - a)) / (2 * step * duration);+ },+ };+}++/**+ * The times (seconds, ascending) at which a row's centre reaches the band's+ * centre during `curve`, after `after` and up to `until`. They are thinned so+ * that two are never closer than the selection tick's minimum interval. `last`+ * is the time of the previous tick, if any. Leaving the row the wheel starts on+ * is not a tick; reaching the next one is.+ */+export function tickTimes(+ curve: WheelCurve,+ rowHeight: number,+ {+ after = 0,+ until = curve.duration,+ last = -Infinity,+ step = 1 / 240,+ }: {after?: number; until?: number; last?: number; step?: number} = {},+): number[] {+ const interval = picker.selectionTick.minimumIntervalMs / 1000;+ const times: number[] = [];+ let previous = curve.value(after);+ let lastTick = last;+ for (let t = after + step; t < until + step; t += step) {+ const time = Math.min(t, until);+ const value = curve.value(time);+ if (reachesRow(previous, value, rowHeight) && time - lastTick >= interval) {+ times.push(time);+ lastTick = time;+ }+ previous = value;+ if (time === until) {+ break;+ }+ }+ return times;+}++/**+ * Whether moving from offset `from` to `to` brings a row's centre onto the+ * band's. That is a multiple of `rowHeight` in (from, to] moving up, or in [to,+ * from) moving down.+ */+export function reachesRow(+ from: number,+ to: number,+ rowHeight: number,+): boolean {+ if (to > from) {+ return Math.floor(to / rowHeight) > Math.floor(from / rowHeight);+ }+ if (to < from) {+ return Math.ceil(to / rowHeight) < Math.ceil(from / rowHeight);+ }+ return false;+}diff --git a/packages/core/src/DateInput/wheelStrip.test.ts b/packages/core/src/DateInput/wheelStrip.test.tsnew file mode 100644index 0000000000..c44e706767--- /dev/null+++ b/packages/core/src/DateInput/wheelStrip.test.ts@@ -0,0 +1,199 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file wheelStrip.test.ts+ * @input Uses Vitest, a fake clock and the shared animator in jsdom+ * @output Proves the touch wheel's strip: a drag's frames and their ticks,+ * a curve played to its end or stopped where it is shown, the row reported+ * nearest the band, and Reduce Motion's cross-fade for a transition while+ * momentum keeps its motion+ * @position Unit coverage for wheelStrip.ts; PickerWheel.test.tsx covers the+ * wheel that drives it, and the browser specs the compositor+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {createWheelStrip} from './wheelStrip';+import {spinCurve, type WheelCurve, type WheelLayout} from './wheelPhysics';++const haptics = vi.hoisted(() => ({+ canVibrate: vi.fn(() => true),+ playHaptic: vi.fn(),+}));+vi.mock('../gestures/haptics', () => haptics);++const ROW = 28;+const LAYOUT: WheelLayout = {rowHeight: ROW, rowCount: 60};++/** A linear motion from `from` to `to` over `seconds`. */+function line(from: number, to: number, seconds: number): WheelCurve {+ return {+ duration: seconds,+ to,+ value: t => from + ((to - from) * Math.min(t, seconds)) / seconds,+ velocity: t => (t < seconds ? (to - from) / seconds : 0),+ };+}++function translateY(element: HTMLElement): number {+ const [, y = '0'] = element.style+ .getPropertyValue('translate')+ .trim()+ .split(/\s+/);+ return Number.parseFloat(y) || 0;+}++let reducedMotion = false;++beforeEach(() => {+ vi.useFakeTimers({+ toFake: ['setTimeout', 'clearTimeout', 'performance', 'Date'],+ });+ reducedMotion = false;+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches:+ query === '(pointer: coarse)' ||+ (reducedMotion && query === '(prefers-reduced-motion: reduce)'),+ media: query,+ addEventListener: () => {},+ removeEventListener: () => {},+ }));+ haptics.playHaptic.mockClear();+});++afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++function setup() {+ const element = document.createElement('div');+ const strip = createWheelStrip(LAYOUT);+ strip.attach(element);+ const nearest: number[] = [];+ strip.onNearestChange(position => nearest.push(position));+ return {element, strip, nearest};+}++describe('createWheelStrip', () => {+ it('shows a drag frame at once on the strip, and reports the row nearest the band', () => {+ const {element, strip, nearest} = setup();+ strip.setOffset(3.4 * ROW);+ expect(translateY(element)).toBeCloseTo(-3.4 * ROW, 3);+ expect(strip.offset()).toBeCloseTo(3.4 * ROW, 3);+ expect(nearest).toEqual([3]);+ strip.setOffset(3.6 * ROW);+ expect(nearest).toEqual([3, 4]);+ });++ it('plays a curve to its end, then reports its row and that it arrived', () => {+ const {strip, nearest} = setup();+ const onEnd = vi.fn();+ strip.play(line(0, 5 * ROW, 0.5), {onEnd});+ expect(strip.isMoving()).toBe(true);+ expect(strip.target()).toBe(5 * ROW);+ vi.advanceTimersByTime(250);+ expect(strip.offset()).toBeCloseTo(2.5 * ROW, 0);+ // A motion reports nothing until it ends.+ expect(nearest).toEqual([]);+ vi.advanceTimersByTime(250);+ expect(onEnd).toHaveBeenCalledExactlyOnceWith('arrived', 5 * ROW);+ expect(strip.isMoving()).toBe(false);+ expect(nearest).toEqual([5]);+ });++ it('stops a motion where it was shown at the given time', () => {+ const {element, strip} = setup();+ const onEnd = vi.fn();+ strip.play(line(0, 10 * ROW, 1), {onEnd});+ vi.advanceTimersByTime(400);+ const touchedAt = performance.now() - 100;+ const stopped = strip.stop(touchedAt);+ expect(stopped).toBeCloseTo(3 * ROW, 0);+ expect(onEnd).toHaveBeenCalledExactlyOnceWith('stopped', stopped);+ expect(translateY(element)).toBeCloseTo(-stopped, 3);+ vi.advanceTimersByTime(1000);+ expect(onEnd).toHaveBeenCalledTimes(1);+ expect(strip.offset()).toBeCloseTo(stopped, 3);+ });++ it('ends a motion as stopped when a drag frame takes the strip', () => {+ const {strip} = setup();+ const onEnd = vi.fn();+ strip.play(line(0, 10 * ROW, 1), {onEnd});+ vi.advanceTimersByTime(100);+ strip.setOffset(2 * ROW, {ticks: true});+ expect(onEnd).toHaveBeenCalledWith('stopped', expect.any(Number));+ expect(strip.isMoving()).toBe(false);+ });++ it('ticks each row a drag frame brings to the band', () => {+ const {strip} = setup();+ strip.resetDrag();+ strip.setOffset(0, {ticks: true});+ strip.setOffset(0.4 * ROW, {ticks: true});+ expect(haptics.playHaptic).not.toHaveBeenCalled();+ vi.advanceTimersByTime(50);+ strip.setOffset(1.1 * ROW, {ticks: true});+ expect(haptics.playHaptic).toHaveBeenCalledExactlyOnceWith('selection');+ });++ it('ticks the rows a released curve passes, at most one per 40 ms, and none for a spin', () => {+ const {strip} = setup();+ // 20 rows in 0.5 s: a row every 25 ms, faster than the tick allows.+ strip.play(line(0, 20 * ROW, 0.5), {ticks: true, momentum: true});+ vi.advanceTimersByTime(600);+ const ticks = haptics.playHaptic.mock.calls.length;+ expect(ticks).toBeGreaterThan(5);+ expect(ticks).toBeLessThanOrEqual(13);+ haptics.playHaptic.mockClear();+ strip.play(spinCurve(20 * ROW, 23 * ROW, 0.3, [0.42, 0, 0.58, 1]));+ vi.advanceTimersByTime(400);+ expect(haptics.playHaptic).not.toHaveBeenCalled();+ });++ it('lands a zero-length curve at once', () => {+ const {element, strip} = setup();+ const onEnd = vi.fn();+ strip.play(line(0, 7 * ROW, 0), {onEnd});+ expect(onEnd).toHaveBeenCalledExactlyOnceWith('arrived', 7 * ROW);+ expect(translateY(element)).toBeCloseTo(-7 * ROW, 3);+ });++ it('under Reduce Motion, cross-fades a transition and keeps a throw’s momentum', async () => {+ reducedMotion = true;+ const {strip, nearest} = setup();+ const onEnd = vi.fn();+ // A tap's turn: the animator's cross-fade, which lands at its midpoint.+ strip.play(line(0, 4 * ROW, 0.3), {onEnd, ticks: true});+ await vi.advanceTimersByTimeAsync(100);+ expect(nearest).toEqual([4]);+ expect(onEnd).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(100);+ expect(onEnd).toHaveBeenCalledExactlyOnceWith('arrived', 4 * ROW);+ expect(haptics.playHaptic).not.toHaveBeenCalled();+ // A coast plays as is, for its whole length.+ const coastEnd = vi.fn();+ strip.play(line(4 * ROW, 24 * ROW, 0.8), {+ onEnd: coastEnd,+ momentum: true,+ touchRelease: true,+ });+ await vi.advanceTimersByTimeAsync(400);+ expect(coastEnd).not.toHaveBeenCalled();+ expect(strip.offset()).toBeCloseTo(14 * ROW, 0);+ await vi.advanceTimersByTimeAsync(400);+ expect(coastEnd).toHaveBeenCalledExactlyOnceWith('arrived', 24 * ROW);+ });++ it('ends a motion still running as stopped when it is disposed', () => {+ const {strip} = setup();+ const onEnd = vi.fn();+ strip.play(line(0, 10 * ROW, 1), {onEnd});+ vi.advanceTimersByTime(300);+ strip.dispose();+ expect(onEnd).toHaveBeenCalledExactlyOnceWith(+ 'stopped',+ expect.any(Number),+ );+ });+});diff --git a/packages/core/src/DateInput/wheelStrip.ts b/packages/core/src/DateInput/wheelStrip.tsnew file mode 100644index 0000000000..8feef24354--- /dev/null+++ b/packages/core/src/DateInput/wheelStrip.ts@@ -0,0 +1,341 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file wheelStrip.ts+ * @input The touch wheel's strip (its flat rows in one element), its layout,+ * and curves from wheelPhysics.ts+ * @output createWheelStrip: the one owner of a wheel's offset. It writes a+ * drag's frames, plays and stops curves, ticks, and reports the nearest row+ * @position Glue of the touch picker wheel (PickerWheel.tsx) over the shared+ * animator (motion/animator.ts)+ *+ * The strip is the one element that moves, on `translate`, so a motion plays+ * on the compositor with no layout or paint per frame.+ *+ * SYNC: When modified, update wheelStrip.test.ts and PickerWheel.tsx.+ */++import {canVibrate, playHaptic} from '../gestures/haptics';+import {createMotionAnimator, type MotionCurve} from '../motion/animator';+import {reducedMotionFade} from '../motion/reducedMotion';+import {picker} from '../motion/uikit/picker';+import {+ nearestIndex,+ reachesRow,+ tickTimes,+ type WheelCurve,+ type WheelLayout,+} from './wheelPhysics';++/** How a motion ended: arrived on its row, or stopped before. */+export type WheelMotionOutcome = 'arrived' | 'stopped';++/** Options for one motion. */+export interface PlayOptions {+ /** Tick as rows reach the band (a drag's release); a tap's spin does not. */+ ticks?: boolean;+ /** Called once when the motion ends, either way. */+ onEnd?: (outcome: WheelMotionOutcome, offset: number) => void;+ /** Started by a touch drag's release, which cross-fades under Reduce Motion. */+ touchRelease?: boolean;+ /**+ * The momentum that continues a throw: a coast, and its bounce at an end.+ * It is direct movement, so it plays under Reduce Motion too, as scrolling+ * keeps decelerating under iOS Reduce Motion.+ */+ momentum?: boolean;+}++/** One picker column's offset and everything that moves it. */+export interface WheelStrip {+ /** The strip the offset moves (null detaches it). */+ attach(strip: HTMLElement | null): void;+ /** Update the rows (a new option list); keeps the offset. */+ setLayout(layout: WheelLayout): void;+ /**+ * Tell `listener` the position of the row nearest the band whenever it+ * changes. That is on a drag frame, where a motion stops or ends, and at+ * rest. A cross-fade's landing counts as an end. A motion itself reports+ * nothing until it ends, so the compositor plays it without the main thread+ * painting a mark per row.+ */+ onNearestChange(listener: ((position: number) => void) | null): void;+ /** Whether a motion is playing. */+ isMoving(): boolean;+ /**+ * The offset on screen at `time` (ms, the document timeline's clock; default+ * now). It is the animator's presentation value. So a motion that has not+ * started on screen yet shows its start.+ */+ offset(time?: number): number;+ /** Where the wheel will be at rest: the motion's end, or the offset now. */+ target(): number;+ /**+ * Show `offset` at once, stopping any motion: a drag frame or a park. A drag+ * frame passes `ticks`, which also keeps the strip on its own compositing+ * layer for the frames that follow.+ */+ setOffset(offset: number, options?: {ticks?: boolean}): void;+ /** Forget the previous drag frame (a new gesture starts). */+ resetDrag(): void;+ /**+ * Stop the motion where it was on screen at `time` (a finger landing on a+ * spinning wheel: its touch-down time). Returns that offset.+ */+ stop(time?: number): number;+ /** Play `curve` from the current offset; the strip ends at `curve.to`. */+ play(curve: WheelCurve, options?: PlayOptions): void;+ /**+ * Forget the row last reported nearest the band, so the next report names it+ * again even unchanged. A caller that clears its mark as a motion starts then+ * gets it back. That happens when the motion ends on the row it began on.+ */+ forgetNearest(): void;+ /** Stop everything; a motion still running ends as stopped. */+ dispose(): void;+}++interface Running {+ readonly curve: WheelCurve;+ readonly onEnd?: (outcome: WheelMotionOutcome, offset: number) => void;+ readonly timers: ReturnType<typeof setTimeout>[];+}++function now(): number {+ const time =+ typeof document !== 'undefined'+ ? (document.timeline?.currentTime as number | null | undefined)+ : null;+ return typeof time === 'number' ? time : performance.now();+}++/**+ * Creates a wheel's strip on a fresh animator. It uses the internal animator+ * for three jobs the public handle lacks:+ *+ * - It plays a closed-form curve on the compositor: a coast onto a row, a+ * snap, a spin.+ * - It times haptic ticks on that curve's clock.+ * - It substitutes Reduce Motion's cross-fade for a move.+ *+ * A release's coast and its bounce at an end are momentum (`decay`), so they+ * keep their motion under Reduce Motion. Every other curve is a transition+ * (`play`). Under Reduce Motion the animator cross-fades it after a touch or+ * on a coarse pointer. Otherwise it lands at once.+ *+ * @example+ * ```+ * const strip = createWheelStrip({rowHeight: 28, rowCount: 60});+ * strip.attach(element);+ * strip.setOffset(30 * 28);+ * strip.play(planRelease(strip.offset(), 900, layout).curve, {ticks: true, momentum: true});+ * ```+ */+export function createWheelStrip(initialLayout: WheelLayout): WheelStrip {+ const animator = createMotionAnimator(null);+ let layout = initialLayout;+ let running: Running | null = null;+ let nearestListener: ((position: number) => void) | null = null;+ let lastNearest: number | null = null;+ let lastTick = -Infinity;+ /** Last offset a drag frame showed, for its ticks. */+ let dragPrevious: number | null = null;++ const shown = (time?: number): number =>+ // The strip's top sits on the band's row: offset `o` is `translate` −o.+ -animator.get('y', time);++ const reportNearest = (offset: number): void => {+ const position = nearestIndex(offset, layout);+ if (position === lastNearest) {+ return;+ }+ lastNearest = position;+ nearestListener?.(position);+ };++ const tick = (time: number): void => {+ if (time - lastTick < picker.selectionTick.minimumIntervalMs) {+ return;+ }+ lastTick = time;+ playHaptic('selection');+ };++ const clear = (motion: Running): void => {+ for (const timer of motion.timers) {+ clearTimeout(timer);+ }+ motion.timers.length = 0;+ if (running === motion) {+ running = null;+ }+ };++ /**+ * The motion's timers, from `origin` (when it started on screen): its+ * ticks, a cross-fade's landing, and its end.+ */+ const schedule = (+ motion: Running,+ origin: number,+ {+ endMs,+ ticks,+ landingMs,+ }: {endMs: number; ticks: boolean; landingMs: number | null},+ ): void => {+ for (const timer of motion.timers) {+ clearTimeout(timer);+ }+ motion.timers.length = 0;+ const elapsed = now() - origin;+ if (ticks) {+ for (const t of tickTimes(motion.curve, layout.rowHeight)) {+ motion.timers.push(+ setTimeout(+ () => {+ if (running === motion) {+ tick(now());+ }+ },+ Math.max(0, t * 1000 - elapsed),+ ),+ );+ }+ }+ if (landingMs != null) {+ motion.timers.push(+ setTimeout(+ () => {+ if (running === motion) {+ reportNearest(motion.curve.to);+ }+ },+ Math.max(0, landingMs - elapsed),+ ),+ );+ }+ motion.timers.push(+ setTimeout(+ () => {+ if (running !== motion) {+ return;+ }+ clear(motion);+ reportNearest(motion.curve.to);+ motion.onEnd?.('arrived', motion.curve.to);+ },+ Math.max(0, endMs - elapsed),+ ),+ );+ };++ const stop = (time?: number): number => {+ const motion = running;+ if (motion == null) {+ return shown();+ }+ const offset = shown(time);+ clear(motion);+ // `set` ends the strip's animation and puts it where it was shown.+ animator.set({y: -offset});+ reportNearest(offset);+ motion.onEnd?.('stopped', offset);+ return offset;+ };++ return {+ attach(strip) {+ animator.attach(strip);+ },+ setLayout(next) {+ layout = next;+ },+ onNearestChange(listener) {+ nearestListener = listener;+ lastNearest = null;+ },+ isMoving() {+ return running != null;+ },+ offset(time) {+ return shown(time);+ },+ target() {+ return running?.curve.to ?? shown();+ },+ setOffset(offset, {ticks = false} = {}) {+ if (running != null) {+ stop();+ }+ if (+ ticks &&+ dragPrevious != null &&+ canVibrate() &&+ reachesRow(dragPrevious, offset, layout.rowHeight)+ ) {+ tick(now());+ }+ dragPrevious = offset;+ // A park is a one-off write: no layer for a strip at rest.+ animator.set({y: -offset}, {promote: ticks});+ reportNearest(offset);+ },+ resetDrag() {+ dragPrevious = null;+ },+ stop,+ play(+ curve,+ {ticks = false, onEnd, touchRelease = false, momentum = false} = {},+ ) {+ stop();+ dragPrevious = null;+ const element = animator.element;+ // What Reduce Motion makes of a transition: null while motion plays.+ // Momentum is never substituted.+ const fade = momentum ? null : reducedMotionFade(element, {touchRelease});+ const endMs = fade == null ? curve.duration * 1000 : fade.duration;+ if (!(endMs > 0)) {+ animator.set({y: -curve.to});+ reportNearest(curve.to);+ onEnd?.('arrived', curve.to);+ return;+ }+ const motionCurve: MotionCurve = {+ duration: curve.duration,+ at: t => -curve.value(t),+ velocity: t => -curve.velocity(t),+ };+ const handle = momentum+ ? animator.decay({y: motionCurve}, {touchRelease})+ : animator.play({y: motionCurve}, {touchRelease});+ const motion: Running = {curve, onEnd, timers: []};+ running = motion;+ const plan = {+ endMs,+ // A cross-fade has no travel to tick through.+ ticks: ticks && fade == null && canVibrate(),+ // A cross-fade lands its rows at its midpoint, faded out.+ landingMs: fade == null ? null : endMs / 2,+ };+ schedule(motion, now(), plan);+ // A busy main thread can hold a motion's first frame: its timers then+ // follow the start the browser gives it. The animator's start promise+ // only resolves, so nothing here waits on a rejection.+ void handle.started.then(start => {+ if (running === motion) {+ schedule(motion, start, plan);+ }+ });+ },+ forgetNearest() {+ lastNearest = null;+ },+ dispose() {+ stop();+ animator.dispose();+ },+ };+}diff --git a/packages/core/src/DateTimeInput/TouchDateTimeField.tsx b/packages/core/src/DateTimeInput/TouchDateTimeField.tsxindex 00c8248bb2..1348e65c73 100644--- a/packages/core/src/DateTimeInput/TouchDateTimeField.tsx+++ b/packages/core/src/DateTimeInput/TouchDateTimeField.tsx@@ -881,6 +881,8 @@ export function TouchDateTimeField({return {value: hour,label: String(hour),+ // Keys step in time order: 12 PM comes before 1 PM.+ order: hour24,isDisabled: !rangeOverlaps(hour24 * 3600,hour24 * 3600 + 3599,diff --git a/packages/core/src/TimeInput/Presentation.test.tsx b/packages/core/src/TimeInput/Presentation.test.tsxindex c4e5628ead..fdf8fb449a 100644--- a/packages/core/src/TimeInput/Presentation.test.tsx+++ b/packages/core/src/TimeInput/Presentation.test.tsx@@ -8,7 +8,7 @@*/import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest';-import {fireEvent, render, screen} from '@testing-library/react';+import {act, fireEvent, render, screen} from '@testing-library/react';import {TimeInput} from './TimeInput';import {InternationalizationProvider} from '../i18n';import type {ISOTimeString} from '../utils';@@ -190,3 +190,57 @@ describe('TimeInput presentation', () => {expect(document.querySelector('input[type="time"]')).toBeNull();});});++// A 12-hour sheet wheel bounded 12:00–17:00: its rows are 1 … 12, and 6 to 11+// are disabled. Keys follow the full time, so 12 PM comes before 1 PM.+describe('sheet wheel keys at a 12:00–17:00 bound (component:DateInput FR17)', () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ function openHourWheel(value: string) {+ const onChange = vi.fn();+ const view = render(+ <TimeInput+ label="Start"+ presentation="bottom-sheet"+ hourFormat="12h"+ min={'12:00' as ISOTimeString}+ max={'17:00' as ISOTimeString}+ value={value as ISOTimeString}+ onChange={onChange}+ />,+ );+ fireEvent.click(screen.getByRole('combobox', {name: 'Start'}));+ act(() => {+ vi.advanceTimersByTime(600);+ });+ return {hour: screen.getByRole('listbox', {name: 'Hour'}), onChange, view};+ }++ for (const pointer of ['finger', 'mouse'] as const) {+ it(`at a 12:00–17:00 bound, ArrowDown from 5 PM commits nothing and ArrowDown from 12 PM commits 1 PM, under a ${pointer}`, () => {+ vi.useFakeTimers();+ stubPointer(pointer === 'finger');+ // No enabled hour comes after 5 PM: ArrowDown and End commit nothing.+ const late = openHourWheel('17:00');+ fireEvent.keyDown(late.hour, {key: 'ArrowDown'});+ fireEvent.keyDown(late.hour, {key: 'End'});+ expect(late.onChange).not.toHaveBeenCalled();+ late.view.unmount();+ // 1 PM is the hour after 12 PM.+ const noon = openHourWheel('12:00');+ fireEvent.keyDown(noon.hour, {key: 'ArrowDown'});+ expect(noon.onChange).toHaveBeenLastCalledWith('13:00');+ noon.view.unmount();+ // 12 PM is the hour before 1 PM, and the first enabled one.+ const early = openHourWheel('13:00');+ fireEvent.keyDown(early.hour, {key: 'ArrowUp'});+ expect(early.onChange).toHaveBeenLastCalledWith('12:00');+ early.view.unmount();+ const first = openHourWheel('13:00');+ fireEvent.keyDown(first.hour, {key: 'Home'});+ expect(first.onChange).toHaveBeenLastCalledWith('12:00');+ });+ }+});diff --git a/packages/core/src/TimeInput/TouchTimeField.tsx b/packages/core/src/TimeInput/TouchTimeField.tsxindex ea6e970a0b..75ed25806b 100644--- a/packages/core/src/TimeInput/TouchTimeField.tsx+++ b/packages/core/src/TimeInput/TouchTimeField.tsx@@ -378,6 +378,8 @@ export function TouchTimeField({return {value: hour,label: String(hour),+ // Keys step in time order: 12 PM comes before 1 PM.+ order: hour24,isDisabled: !rangeOverlaps(hour24 * 3600,hour24 * 3600 + 3599,diff --git a/packages/core/src/gestures/GestureHost.ts b/packages/core/src/gestures/GestureHost.tsindex 536218d189..712119d4d5 100644--- a/packages/core/src/gestures/GestureHost.ts+++ b/packages/core/src/gestures/GestureHost.ts@@ -590,7 +590,7 @@ function wheelPixels(* A trackpad's precise deltas, a third of their legacy `wheelDelta` in* Chromium and WebKit, read as a trackpad's.*/-function scrollTypeOf(wheel: WheelEvent): ScrollType {+export function scrollTypeOf(wheel: WheelEvent): ScrollType {if (wheel.deltaMode !== 0 || wheel.shiftKey) {return 'discrete';}diff --git a/packages/core/src/motion/MEASUREMENTS.md b/packages/core/src/motion/MEASUREMENTS.mdindex e5306b7539..bc49b27849 100644--- a/packages/core/src/motion/MEASUREMENTS.md+++ b/packages/core/src/motion/MEASUREMENTS.md@@ -286,3 +286,21 @@ fades in, with Prefer Cross-Fade Transitions on or off.| M-CM4 | Reduce Motion press feedback | Probe app with Reduce Motion on: long press, then dismiss | press feedback, lift and dismiss animations under Reduce Motion | A, B || M-CM5 | Commit haptic stand-in | An Android device: `navigator.vibrate` patterns against the platform's HapticFeedbackConstants for the context-click moment | the pattern that matches; not a UIKit parity value (as M-G18) | H || M-CM6 | Press thresholds | Probe app: repeated long presses at random vsync phases | from touch receipt and from the HID timestamp, the tick before and the tick at the press observer's began and at the click commit; the intersection pins the 150 ms and 400 ms thresholds | C |++## Picker (UIPickerView)++Values the Wheel reads from its own table (`uikit/picker.ts`).++The recordings are of a 402 × 216 pt UIPickerView with two columns of 24 and+60 rows. It runs in an instrumented host app on the iOS 26.2 simulator+(iPhone 17 Pro), driven by real HID touches. They hold per-frame offsets, the+table views' and cells' layers, the delegate calls and the haptics.++Done (UIKit lab, iOS 26.2 simulator, Oct 23 2026; in the picker's table): the+row pitch, the picker's height, the rubber band's dimension, the coast's stop+speed, the velocity floor, the snap at rest, the tap spin and the selection+tick. Measured and kept by the gesture system instead: the+scroll view coasts with 0.25 × the pan's velocity plus 0.75 × its value one+event earlier (four HID releases; `velocity.scrollReleaseWeight`, which a+pan's `scrollVelocity()` reads). On UIKit, Reduce Motion with Prefer Cross-Fade changes+nothing on a picker; the Wheel follows design:reduced-motion instead.diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.mdindex 19ef169b0e..b935f744a8 100644--- a/packages/core/src/motion/README.md+++ b/packages/core/src/motion/README.md@@ -23,6 +23,7 @@ roles through `resolveMotion`.| `uikit/navigation.ts` | UINavigationController: push velocity, parallax, dimming, transition clock, interactive pop finish rule. || `uikit/progressBar.ts` | UIProgressView's fill: the whole-track duration and curve, its minimum length and empty alpha; the reduced-motion pulse (three roles). || `uikit/gestures.ts` | Gesture recognizer thresholds, the velocity filter and haptic stand-ins, as `{value, unit}` entries (sources in JSDoc). |+| `uikit/picker.ts` | UIPickerView: row pitch, height and rubber band, velocity floor, the coast's stop speed, snap at rest, tap spin, tick. || `uikit/segmented.ts` | UISegmentedControl: the selection indicator's spring; under Reduce Motion the animator's cross-fade replaces it. || `uikit/switch.ts` | UISwitch on iOS 26.2: geometry, the lift, settle, travel and tracking springs, the flip distance, the track colour. || `roles.ts` | The internal motion roles: the springs, durations and curves `spec:AST-094` FR4 names, registered by the shared tables, and a role's CSS form read back. |diff --git a/packages/core/src/motion/uikit/index.ts b/packages/core/src/motion/uikit/index.tsindex ab92f5038e..de0bee40f0 100644--- a/packages/core/src/motion/uikit/index.ts+++ b/packages/core/src/motion/uikit/index.ts@@ -4,9 +4,9 @@* @file index.ts* @input The domain files of the UIKit constants table* @output Re-exports `springs` and one constant per spring (`SHEET_PRESENT_SPRING`,- * …), `scroll`, `timing`, `navigation`, `progressBar`, `segmentedControl`,- * the `slider` and switch (`switchControl`) domains, and the gesture- * thresholds (one `UIKIT_*` group per recognizer, their union+ * …), `scroll`, `timing`, `navigation`, `picker`, `progressBar`,+ * `segmentedControl`, the `slider` and switch (`switchControl`) domains, and+ * the gesture thresholds (one `UIKIT_*` group per recognizer, their union* `UIKIT_GESTURES`, and the haptic tables)* @position Entry of the UIKit constants table (motion/uikit). Internal to* core: not exported from the package entry point@@ -40,6 +40,7 @@ export {type HapticFeedbackKind,} from './gestures';export {navigation, registerNavigationTable} from './navigation';+export {picker} from './picker';export {progressBar, registerProgressBarTable} from './progressBar';export {registerScrollTable, scroll} from './scroll';export {segmentedControl} from './segmented';diff --git a/packages/core/src/motion/uikit/picker.ts b/packages/core/src/motion/uikit/picker.tsnew file mode 100644index 0000000000..e9c7015349--- /dev/null+++ b/packages/core/src/motion/uikit/picker.ts@@ -0,0 +1,116 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file picker.ts+ * @input Nothing; data only+ * @output `picker`, UIPickerView's measured constants, and+ * `registerPickerTable`, which makes the tap spin's duration a motion role+ * @position The picker domain of the UIKit table (motion/uikit); read by+ * DateInput's wheelPhysics.ts, wheelStrip.ts and PickerWheel.tsx+ *+ * Lengths are pt at UIKit's scale, times ms and velocities pt/ms. Every leaf+ * carries one `@source`, as uikit.test.ts enforces.+ *+ * SYNC: When modified, update motion/MEASUREMENTS.md and PickerWheel.tsx.+ */++import {registerMotionTable} from '../roles';++export const picker = {+ geometry: {+ /**+ * Row pitch: rows sit at k × 32 pt in each column's table.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, UIPickerView table offsets and cell frames, Oct 23 2026+ */+ rowHeight: 32,+ /**+ * The picker's height (its intrinsic content size).+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, UIPickerView frame, Oct 23 2026+ */+ height: 216,+ /**+ * d of the rubber band past the first or last row. The column's table view+ * is 291 pt tall in a 216 pt picker. With c = 0.55, scroll.rubberBand's+ * formula puts 10, 50 and 110 pt of finger travel past the end at 5.4, 25.1+ * and 50.1 pt. The measured values are 5.3, 25 and 50.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, UIPickerTableView frame and offsets during drags+ * 20, 60 and 120 pt past the last row, Oct 23 2026+ */+ rubberBandDimension: 291,+ },+ release: {+ /**+ * The speed at which a coast ends. The scroll view projects the target at+ * offset + (v − this) × r ÷ (1 − r), with r = scroll.decelerationRate+ * .normal. That gives 461.33, 502.67 and 266.67 pt for v = 0.9334, 1.0162+ * and 0.5436, all three to 0.3 pt. The coast onto the row it snaps to keeps+ * the release velocity. It re-solves the rate so that the speed reaches+ * this exactly at that row, where it stops. Two coasts fit it to 0.4 and+ * 0.3 pt RMS, ending within 30 ms of the measured end.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, scrollViewWillEndDragging targets and per-frame+ * offsets to rest, Oct 23 2026+ */+ stopSpeed: 0.0089,+ /**+ * Below this release speed (pt/ms, a scroll view's release velocity), a+ * release inside the rows carries no velocity. The wheel then snaps to the+ * nearest row instead of coasting. Past the first or last row the velocity+ * is kept, however small (0.0816 kept). A pause before the lift does not+ * zero it: the velocity changes only when the finger moves.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, steady 100 pt drags mid-list lifted while moving: zeroed+ * at 100 to 250 pt/s both ways, passed from 260 pt/s (0.2577 the+ * smallest velocity handed on); a 300 pt/s drag held still 300 ms+ * still coasted, Oct 23 2026+ */+ minimumSpeed: 0.25,+ },+ /**+ * A release without velocity, or a coast already on a row, eases onto the+ * nearest row exponentially. Each millisecond it covers this fraction of the+ * distance left: e^(−0.011 t), done in about 0.3 s. Snaps of 4, 6 and 8 pt+ * fit 0.0099, 0.0107 and 0.0123.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, per-frame offsets after three slow releases between+ * rows, Oct 23 2026+ */+ snapRate: 0.011,+ tapSpin: {+ /**+ * A tap on a row turns the wheel onto it in this long (setContentOffset+ * animated), on Core Animation's ease-in-ease-out (timing.curves.move). The+ * row is selected on arrival. A tap on the band's row does nothing.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, per-frame offsets after a tap two rows below the band+ * (6.8, 25.1, 50.2, 75.4, 93.7 % at 50 ms steps, arriving at 300 ms;+ * the same with Reduce Motion and Prefer Cross-Fade on), Oct 23 2026+ */+ durationMs: 300,+ },+ selectionTick: {+ /**+ * One selection haptic per row whose centre reaches the band's centre,+ * at most one per this interval. Not during a tap's spin.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, selectionChangedAtLocation: and the feedback+ * generator's minimum interval (0.040 s) logged during drags and+ * coasts, Oct 23 2026+ */+ minimumIntervalMs: 40,+ },+} as const;++/**+ * Registers the tap spin's duration as an internal motion role,+ * `picker.tapSpin.durationMs`. Every other value stays an internal measured+ * constant. The tap spin's curve is the shared role `timing.curves.move`, and+ * the bounce at an end is `scroll.bounce`. Nothing registers on import, and+ * registering again does nothing.+ */+export function registerPickerTable(): void {+ registerMotionTable('picker', picker, {roles: ['tapSpin.durationMs']});+}diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjsindex 01a04f3919..af25cc6328 100644--- a/scripts/touch-support-bundle.test.mjs+++ b/scripts/touch-support-bundle.test.mjs@@ -141,7 +141,8 @@ const GESTURE_USERS = new Set([// AlertDialog: its actions' press, tracked across both for every pointer.'AlertDialog',// Through AlertDialog: Tokenizer's bottom sheet confirms with an alert, and- // PowerSearch and Table's filtering render a Tokenizer.+ // PowerSearch and Table's filtering render a Tokenizer. Both also reach+ // TimeInput's wheels: PowerSearch's edit popover and Table's filtering.'PowerSearch','Table','Tokenizer',@@ -153,7 +154,9 @@ const GESTURE_USERS = new Set(['SegmentedControl',// DateTimeInput: through the SegmentedControl its touch field renders.'DateTimeInput',- // useScrollLock's page hold, and the imports that reach it.+ // useScrollLock's page hold, and the imports that reach it. The sheet+ // wheels of DateInput, TimeInput and DateTimeInput also drag and tap+ // through the gesture system's pan and tap (DateInput/PickerWheel.tsx).'hooks: useScrollLock','AppShell','BottomSheet',