An open source design system that's fully customizable and agent ready
TypeScript
fix(DateInput): a wheel's key step rests on the row it steps to (#10610)
Christopher Chedeau7cc934044b85
diff --git a/.changeset/wheel-step-rests-on-its-row.md b/.changeset/wheel-step-rests-on-its-row.mdnew file mode 100644index 0000000000..d72df4b69a--- /dev/null+++ b/.changeset/wheel-step-rests-on-its-row.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] With a mouse or trackpad, a date or time sheet's wheel no longer turns back to the row a key step is leaving. A key step commits its row at once and then scrolls there. On a busy page or a slow device the scroll could draw no frame for longer than the wheel's quiet period, or the browser could end it part-way, and the wheel took that pause for rest: it committed the row under the band and turned back there. A rest before the step's row is reached now finishes the scroll instead. A scroll a person makes still rests where it stops.++@vjeuxdiff --git a/packages/core/src/DateInput/MonthScroller.tsx b/packages/core/src/DateInput/MonthScroller.tsxindex 5bf595f1e4..c0e685e424 100644--- a/packages/core/src/DateInput/MonthScroller.tsx+++ b/packages/core/src/DateInput/MonthScroller.tsx@@ -76,7 +76,7 @@ import {} from '../utils/calendarSystem';import {dateInputTouchSizes, dateInputTouchGeometry} from './tokens.stylex';import {useOwnScrollGesture} from './useOwnScrollGesture';-import {useScrollSettle} from './useScrollSettle';+import {useScrollSettle, useScrollSteer} from './useScrollSettle';import {type MonthModel,paneWindow,@@ -394,13 +394,13 @@ export function MonthScroller({const pendingScrollRef = useRef<number | null>(null);/**- * The row a programmatic scroll is heading for, so its own scroll events- * are not reported back as if the user had gone there, and so the settle- * correction finishes the steer instead of rounding it back. Null once the- * user's own input reaches the scroller (a finger, a wheel or trackpad, a- * press, a key), or once the steered scroll has arrived.+ * The row a programmatic scroll is heading for. Its own scroll events are+ * not reported back as if the user had gone there. The settle correction+ * finishes the steer instead of rounding it back. The steer ends once its+ * scroll has arrived, or once the user's own input reaches the scroller+ * (useScrollSettle).*/- const steeredRowRef = useRef<number | null>(null);+ const steer = useScrollSteer();// Keyboard focus moves by date, not by cell index, so it crosses month// boundaries the way a calendar should. Null until the user takes the grid@@ -484,7 +484,7 @@ export function MonthScroller({// by a scroll that moved nothing (the re-assert when the month and// year wheels close), which the settle would otherwise finish,// pulling the scroller back off the jump's month.- steeredRowRef.current = row;+ steer.start(row);recenter(scroller, row);return;}@@ -503,7 +503,7 @@ export function MonthScroller({// never arrived would otherwise hide every scroll after it, a// trackpad's included. Closing the wheels makes such a steer: it// re-asserts the month already in view.- steeredRowRef.current = null;+ steer.end();if (row === centerRowRef.current) {scroller.scrollTo({left, behavior: 'auto'});return;@@ -526,10 +526,10 @@ export function MonthScroller({});return;}- steeredRowRef.current = row;+ steer.start(row);scroller.scrollTo({left, behavior});},- [paneSize, minMonthIndex, rowCount, isRTL, recenter, stopDip],+ [paneSize, minMonthIndex, rowCount, isRTL, recenter, stopDip, steer],);// Deliberately un-keyed: it runs after every render, costs a null check, and@@ -612,7 +612,7 @@ export function MonthScroller({[],);- useScrollSettle(scrollerRef, scroller => {+ const settleOnRest = (scroller: HTMLElement) => {// At rest, momentum included: the finger no longer drives the scroll.isFingerScrollRef.current = false;if (paneSize === 0) {@@ -636,7 +636,7 @@ export function MonthScroller({// in the previous arrow's scroll stopped near that month, and rounding// to the nearest pane put the scroller back on it while the title named// the new one.- const steered = steeredRowRef.current;+ const steered = steer.current();const row =steered ??rowAtScrollOffset(scroller.scrollLeft, paneSize, rowCount, isRTL);@@ -645,12 +645,13 @@ export function MonthScroller({if (Math.abs(scroller.scrollLeft - target) < 1) {// At rest on its target, a steer has arrived even if no scroll// crossed into its month.- steeredRowRef.current = null;+ steer.end();return;}scroller.scrollTo({left: target, behavior: 'smooth'});});- });+ };+ useScrollSettle(scrollerRef, settleOnRest, true, undefined, steer);// Claim horizontal gestures, leave vertical ones to the sheet.//@@ -675,7 +676,7 @@ export function MonthScroller({// rAF-throttled: a touch scroll fires far more scroll events than frames,// and all this does is move a label and widen a window.const frameRef = useRef<number | undefined>(undefined);- // Syncs scroll, touch and wheel listeners on the scroller with its measured+ // Syncs scroll and touch listeners on the scroller with its measured// height.useEffect(() => {const scroller = scrollerRef.current;@@ -688,15 +689,6 @@ export function MonthScroller({if (scroller == null || paneSize === 0) {return;}- // A finger, a wheel or trackpad, a press or a key on the scroller ends any- // steering: from here the months it passes are the user's doing, every- // one of them is worth reporting, and the settle rounds to the nearest- // month instead of finishing a steer. A steer that moved nothing (the- // re-assert when the month and year wheels close on the month shown)- // would otherwise pull the user's next scroll back to its month.- const endSteer = () => {- steeredRowRef.current = null;- };// From a touch until its scroll comes to rest (the settle above), the// finger drives the scroll and a re-center leaves snapping on.const onTouchStart = () => {@@ -733,12 +725,13 @@ export function MonthScroller({// the exact moment reports start being trusted again. The month drifted// on the way back to the calendar.//- // Cleared on arrival, or by the user's input below (a finger, a wheel- // or trackpad, a press, a key) — from then the user owns the scroller,- // and every month it passes is worth reporting.- if (steeredRowRef.current != null) {- if (steeredRowRef.current === row) {- steeredRowRef.current = null;+ // Ended on arrival, or by the user's input (useScrollSettle). From then+ // the user owns the scroller, and every month it passes is worth+ // reporting.+ const steered = steer.current();+ if (steered != null) {+ if (steered === row) {+ steer.end();}return;}@@ -746,25 +739,16 @@ export function MonthScroller({});};scroller.addEventListener('scroll', onScroll, PASSIVE);- // The user's input on the scroller ends a steer: from here, it's theirs.- scroller.addEventListener('touchstart', endSteer, PASSIVE);- scroller.addEventListener('wheel', endSteer, PASSIVE);- scroller.addEventListener('pointerdown', endSteer, PASSIVE);- scroller.addEventListener('keydown', endSteer, PASSIVE);scroller.addEventListener('touchstart', onTouchStart, PASSIVE);return () => {scroller.removeEventListener('scroll', onScroll, PASSIVE);- scroller.removeEventListener('touchstart', endSteer, PASSIVE);- scroller.removeEventListener('wheel', endSteer, PASSIVE);- scroller.removeEventListener('pointerdown', endSteer, PASSIVE);- scroller.removeEventListener('keydown', endSteer, PASSIVE);scroller.removeEventListener('touchstart', onTouchStart, PASSIVE);if (frameRef.current != null) {cancelAnimationFrame(frameRef.current);frameRef.current = undefined;}};- }, [paneSize, rowCount, minMonthIndex, isRTL, recenter]);+ }, [paneSize, rowCount, minMonthIndex, isRTL, recenter, steer]);// Move the keyboard focus by whole days and let the scroller follow. Paging// by month is PageUp/PageDown; everything else is the APG grid vocabulary.diff --git a/packages/core/src/DateInput/MonthScrollerSettle.test.tsx b/packages/core/src/DateInput/MonthScrollerSettle.test.tsxindex 3e55268020..522be1253c 100644--- a/packages/core/src/DateInput/MonthScrollerSettle.test.tsx+++ b/packages/core/src/DateInput/MonthScrollerSettle.test.tsx@@ -6,6 +6,7 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';import {MonthScroller, type MonthScrollerHandle} from './MonthScroller';import {SCROLL_QUIET_MS} from './useScrollSettle';import {createMonthModel} from './monthGeometry';+import type {PlainDate} from '../utils/dateTypes';class FakeResizeObserver {constructor(private callback: ResizeObserverCallback) {}@@ -49,23 +50,24 @@ describe('MonthScroller settle', () => {vi.restoreAllMocks();});- function renderScroller() {+ function renderScroller(onVisibleMonthChange = () => {}) {const handleRef = createRef<MonthScrollerHandle>();- const view = render(+ const scrollerFor = (selectedDate: PlainDate | null) => (<MonthScrollermonthModel={createMonthModel('gregory')}handleRef={handleRef}minMonthIndex={0}maxMonthIndex={23}initialMonthIndex={9}- onVisibleMonthChange={() => {}}- selectedDate={null}+ onVisibleMonthChange={onVisibleMonthChange}+ selectedDate={selectedDate}today={{year: 2026, month: 10, day: 15}}isDateDisabled={() => false}weekStartsOn={0}onSelect={() => {}}- />,+ />);+ const view = render(scrollerFor(null));const scroller = view.container.querySelector<HTMLElement>('[data-scroller="months"]',);@@ -73,7 +75,11 @@ describe('MonthScroller settle', () => {throw new Error('no month scroller');}scrollTo.mockClear();- return {handleRef, scroller};+ /** The owner renders the scroller again with a new selection. */+ const select = (date: PlainDate) => {+ view.rerender(scrollerFor(date));+ };+ return {handleRef, scroller, select};}/** The browser moving the scroller to `left`, as a scroll event reports. */@@ -164,4 +170,65 @@ describe('MonthScroller settle', () => {scrollTo.mock.calls.map(([options]) => (options as ScrollToOptions).left),).toEqual([9 * PANE]);});++ it('rests a step that arrives on scrollend once: no correction and no report, and a scroll after it reports', () => {+ const onVisibleMonthChange = vi.fn();+ const {handleRef, scroller} = renderScroller(onVisibleMonthChange);+ act(() => handleRef.current?.scrollToMonth(10));+ scrollTo.mockClear();+ // The step's scroll arrives on month 10, and the browser ends it.+ act(() => scrollBy(scroller, 10 * PANE));+ act(() => {+ vi.advanceTimersByTime(16);+ scroller.dispatchEvent(new Event('scrollend'));+ vi.advanceTimersByTime(16);+ });+ act(() => {+ vi.advanceTimersByTime(SCROLL_QUIET_MS + 50);+ });+ expect(scrollTo).not.toHaveBeenCalled();+ expect(onVisibleMonthChange).not.toHaveBeenCalled();+ // The steer ended where it arrived: a trackpad scroll on to month 11 is+ // the user's, and it reports.+ act(() => scrollBy(scroller, 11 * PANE));+ act(() => {+ vi.advanceTimersByTime(16);+ });+ expect(onVisibleMonthChange.mock.calls).toEqual([[11]]);+ });++ it('keeps a steer through a render: the settle still finishes it', () => {+ const {handleRef, scroller, select} = renderScroller();+ act(() => handleRef.current?.scrollToMonth(10));+ act(() => scrollBy(scroller, 9 * PANE + 0.3 * PANE));+ // The owner renders the scroller again mid-scroll: the settle stays+ // attached, so the steer stays.+ act(() => select({year: 2026, month: 11, day: 3}));+ scrollTo.mockClear();+ act(() => {+ vi.advanceTimersByTime(SCROLL_QUIET_MS + 50);+ });+ // On to the steered month 10, not the nearest pane (9).+ expect(+ scrollTo.mock.calls.map(([options]) => (options as ScrollToOptions).left),+ ).toEqual([10 * PANE]);+ });++ it('ends a steer on a person’s input, so the settle rounds their scroll to the nearest month', () => {+ const {handleRef, scroller} = renderScroller();+ act(() => handleRef.current?.scrollToMonth(10));+ act(() => scrollBy(scroller, 9 * PANE + 0.3 * PANE));+ // A trackpad takes the scroller part-way and stops nearer month 9.+ act(() => {+ scroller.dispatchEvent(new Event('wheel'));+ });+ scrollTo.mockClear();+ act(() => scrollBy(scroller, 9 * PANE + 0.2 * PANE));+ act(() => {+ vi.advanceTimersByTime(SCROLL_QUIET_MS + 50);+ });+ expect(+ scrollTo.mock.calls.map(([options]) => (options as ScrollToOptions).left),+ ).toEqual([9 * PANE]);+ });});diff --git a/packages/core/src/DateInput/Wheel.test.tsx b/packages/core/src/DateInput/Wheel.test.tsxindex b86a6ec2ab..4310e350f7 100644--- a/packages/core/src/DateInput/Wheel.test.tsx+++ b/packages/core/src/DateInput/Wheel.test.tsx@@ -624,6 +624,290 @@ describe('Wheel — keys under a mouse', () => {});});+describe('Wheel — a key step on a page starved of frames', () => {+ afterEach(() => {+ vi.useRealTimers();+ // @ts-expect-error - deleting the shadow restores Element's own getter+ delete HTMLElement.prototype.offsetHeight;+ });++ /** Each row gets a height: jsdom has no layout. */+ function giveRowsHeight() {+ Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {+ configurable: true,+ get(this: HTMLElement) {+ return this.getAttribute('role') === 'option' ? ROW : 0;+ },+ });+ }++ /**+ * Plays the browser for the scrolling column `listbox`, resting on hour+ * `initial`. `frame` draws one frame of a scroll at the `scrollTop` it+ * gives, and `wait` moves the clock. A starved page waits without drawing.+ * `scrollTo` records each scroll the wheel starts, and `land` plays the+ * browser ending the last one where it aimed, with `scrollend`.+ */+ function playBrowser(listbox: HTMLElement, initial: number) {+ let top = initial * ROW;+ Object.defineProperty(listbox, 'scrollTop', {+ configurable: true,+ get: () => top,+ set: (next: number) => {+ top = next;+ },+ });+ const frame = (at: number) => {+ act(() => {+ top = at;+ listbox.dispatchEvent(new Event('scroll'));+ });+ };+ const wait = (ms: number) => {+ act(() => {+ vi.advanceTimersByTime(ms);+ });+ };+ const scrollTo = vi.fn();+ listbox.scrollTo = ((options: ScrollToOptions) => {+ scrollTo(options);+ }) as HTMLElement['scrollTo'];+ const land = () => {+ const last = scrollTo.mock.lastCall?.[0] as ScrollToOptions | undefined;+ if (last?.top == null) {+ throw new Error('no scroll to land');+ }+ frame(last.top);+ act(() => {+ listbox.dispatchEvent(new Event('scrollend'));+ });+ };+ /** The column rests on `row`: the row the value names is the row shown. */+ const expectRestOn = (row: number) => {+ expect(Math.abs(listbox.scrollTop - row * ROW)).toBeLessThanOrEqual(0.5);+ };+ return {frame, wait, scrollTo, land, expectRestOn};+ }++ /** The scrolling column on hour `initial`, whose owner commits each change. */+ function renderStepped(initial: number) {+ giveRowsHeight();+ const onChange = vi.fn();+ function Owned() {+ const [value, setValue] = useState(initial);+ return (+ <ScrollWheel+ label="Hour"+ options={HOURS}+ value={value}+ onChange={next => {+ onChange(next);+ setValue(next);+ }}+ />+ );+ }+ render(<Owned />);+ const listbox = screen.getByRole('listbox', {name: 'Hour'});+ return {listbox, onChange, ...playBrowser(listbox, initial)};+ }++ /**+ * The scrolling column on hour `initial`, shown. `show` sets its value and+ * whether it is shown, as DateInput's sheet does when the wheels close and+ * the calendar moves.+ */+ function renderShown(initial: number) {+ giveRowsHeight();+ const onChange = vi.fn();+ const column = (value: number, isActive: boolean) => (+ <ScrollWheel+ label="Hour"+ options={HOURS}+ value={value}+ onChange={onChange}+ isActive={isActive}+ />+ );+ const {rerender} = render(column(initial, true));+ const listbox = screen.getByRole('listbox', {name: 'Hour'});+ const show = (value: number, isActive: boolean) => {+ rerender(column(value, isActive));+ };+ return {listbox, onChange, show, ...playBrowser(listbox, initial)};+ }++ it('rests on the row a key steps to when its frames stop for longer than the quiet period', () => {+ vi.useFakeTimers();+ const {listbox, onChange, frame, wait, scrollTo, expectRestOn} =+ renderStepped(10);+ fireEvent.keyDown(listbox, {key: 'ArrowDown'});+ expect(onChange.mock.calls).toEqual([[11]]);+ scrollTo.mockClear();+ // The step's first frame, a fifth of a row along. Then no frame comes for+ // longer than the quiet period, as on a busy page or a slow device.+ frame(10 * ROW + 6);+ wait(SCROLL_QUIET_MS + 80);+ // The row the step is leaving is not a rest: the step re-aims at 11, once.+ expect(onChange.mock.calls).toEqual([[11]]);+ expect(scrollTo.mock.calls).toEqual([+ [{top: 11 * ROW, behavior: 'smooth'}],+ ]);+ scrollTo.mockClear();+ frame(11 * ROW);+ act(() => {+ listbox.dispatchEvent(new Event('scrollend'));+ });+ expect(onChange.mock.calls).toEqual([[11]]);+ expectRestOn(11);+ expect(scrollTo).not.toHaveBeenCalled();+ });++ it('keeps the row a key steps to when the quiet period of a scroll before the key ends first', () => {+ vi.useFakeTimers();+ const {listbox, onChange, frame, wait, scrollTo, land, expectRestOn} =+ renderStepped(10);+ // A glide that ends on 10 just before the key: its quiet period runs on.+ frame(10 * ROW - 5);+ frame(10 * ROW);+ fireEvent.keyDown(listbox, {key: 'ArrowDown'});+ scrollTo.mockClear();+ // That quiet period ends before the step draws its first frame.+ wait(SCROLL_QUIET_MS);+ expect(onChange.mock.calls).toEqual([[11]]);+ expect(scrollTo.mock.calls).toEqual([+ [{top: 11 * ROW, behavior: 'smooth'}],+ ]);+ land();+ expect(onChange.mock.calls).toEqual([[11]]);+ expectRestOn(11);+ expect(scrollTo).toHaveBeenCalledTimes(1);+ });++ it('finishes a key step that stops short of its row instead of rounding it back, without scrollend', () => {+ vi.useFakeTimers();+ const {listbox, onChange, frame, wait, scrollTo, land, expectRestOn} =+ renderStepped(10);+ fireEvent.keyDown(listbox, {key: 'ArrowDown'});+ // The step stops 30 px short of row 11, back on row 10, as when a layout+ // change moves the snap points mid-step. No person touches the wheel.+ frame(11 * ROW - 30);+ scrollTo.mockClear();+ wait(SCROLL_QUIET_MS + 10);+ expect(onChange.mock.calls).toEqual([[11]]);+ expect(scrollTo.mock.calls).toEqual([+ [{top: 11 * ROW, behavior: 'smooth'}],+ ]);+ land();+ expect(onChange.mock.calls).toEqual([[11]]);+ expectRestOn(11);+ expect(scrollTo).toHaveBeenCalledTimes(1);+ });++ it('commits the row the column shows when a key step rests short of its row again, with no progress', () => {+ vi.useFakeTimers();+ const {listbox, onChange, frame, wait, scrollTo, expectRestOn} =+ renderStepped(10);+ fireEvent.keyDown(listbox, {key: 'ArrowDown'});+ // The step's scroll snaps back onto row 10, and so does the re-aim.+ frame(10 * ROW + 6);+ frame(10 * ROW);+ scrollTo.mockClear();+ wait(SCROLL_QUIET_MS + 10);+ frame(10 * ROW + 6);+ frame(10 * ROW);+ wait(SCROLL_QUIET_MS + 10);+ // It re-aims once, then the value follows the row the column shows.+ expect(scrollTo).toHaveBeenCalledTimes(1);+ expect(onChange.mock.calls).toEqual([[11], [10]]);+ expectRestOn(10);+ });++ it('finishes a second key step that the browser ends part-way instead of rounding it back', () => {+ vi.useFakeTimers();+ const {listbox, onChange, frame, scrollTo, land, expectRestOn} =+ renderStepped(10);+ fireEvent.keyDown(listbox, {key: 'ArrowDown'});+ fireEvent.keyDown(listbox, {key: 'ArrowDown'});+ expect(onChange.mock.calls).toEqual([[11], [12]]);+ scrollTo.mockClear();+ // WebKit ends a smooth scroll that a second one retargeted once the+ // first one's time is up, with `scrollend` near row 11.+ frame(11 * ROW + 3);+ act(() => {+ listbox.dispatchEvent(new Event('scrollend'));+ });+ expect(onChange.mock.calls).toEqual([[11], [12]]);+ expect(scrollTo.mock.calls).toEqual([+ [{top: 12 * ROW, behavior: 'smooth'}],+ ]);+ land();+ expect(onChange.mock.calls).toEqual([[11], [12]]);+ expectRestOn(12);+ expect(scrollTo).toHaveBeenCalledTimes(1);+ });++ it('parks on the value it is shown with after a hide, though a scroll of its own never moved', () => {+ vi.useFakeTimers();+ const {onChange, show, scrollTo, land, expectRestOn} = renderShown(10);+ // A click on the row already under the band: its scroll moves nothing,+ // so it never comes to rest.+ fireEvent.click(screen.getByRole('option', {name: '10'}));+ expect(onChange).not.toHaveBeenCalled();+ // The wheels close, the calendar moves on, and the wheels open again.+ show(10, false);+ show(11, false);+ scrollTo.mockClear();+ show(11, true);+ // The wheel parks on 11 and rests there. Nothing turns it back to 10.+ land();+ expect(onChange).not.toHaveBeenCalled();+ expectRestOn(11);+ expect(scrollTo).toHaveBeenCalledTimes(1);+ });++ it('rests on the row a key steps to a quiet period after the frame that reaches it, without scrollend', () => {+ vi.useFakeTimers();+ const {listbox, onChange, frame, wait} = renderStepped(10);+ fireEvent.keyDown(listbox, {key: 'ArrowDown'});+ frame(10 * ROW + 6);+ frame(11 * ROW);+ wait(SCROLL_QUIET_MS + 10);+ expect(onChange.mock.calls).toEqual([[11]]);+ // At rest, a key steps on from 11.+ fireEvent.keyDown(listbox, {key: 'ArrowDown'});+ expect(onChange).toHaveBeenLastCalledWith(12);+ });++ it.each([+ [+ 'a trackpad',+ (listbox: HTMLElement) => fireEvent.wheel(listbox, {deltaY: 60}),+ () => {},+ ],+ [+ 'a finger',+ (listbox: HTMLElement) => fireEvent.touchStart(listbox),+ (listbox: HTMLElement) => fireEvent.touchEnd(listbox),+ ],+ ])(+ 'commits the row %s leaves it on when it takes the wheel during a key step',+ (_name, take, leave) => {+ vi.useFakeTimers();+ const {listbox, onChange, frame, wait} = renderStepped(10);+ fireEvent.keyDown(listbox, {key: 'ArrowDown'});+ frame(10 * ROW + 6);+ take(listbox);+ frame(12 * ROW);+ frame(13 * ROW);+ leave(listbox);+ // A person's scroll still rests after the quiet period.+ wait(SCROLL_QUIET_MS + 10);+ expect(onChange).toHaveBeenLastCalledWith(13);+ },+ );+});+describe('Wheel — by pointer', () => {afterEach(() => {vi.unstubAllGlobals();diff --git a/packages/core/src/DateInput/Wheel.tsx b/packages/core/src/DateInput/Wheel.tsxindex 53e713e0d1..2da7701c24 100644--- a/packages/core/src/DateInput/Wheel.tsx+++ b/packages/core/src/DateInput/Wheel.tsx@@ -55,7 +55,7 @@ import {PickerWheel} from './PickerWheel';import {dateInputTouchSizes, dateInputTouchGeometry} from './tokens.stylex';import {useOwnScrollGesture} from './useOwnScrollGesture';import {usePointerDragScroll} from './usePointerDragScroll';-import {useScrollSettle} from './useScrollSettle';+import {useScrollSettle, useScrollSteer} from './useScrollSettle';import {useWheelListbox} from './useWheelListbox';import {canSpinTo,@@ -289,6 +289,12 @@ export function Wheel(props: WheelProps) {Wheel.displayName = 'Wheel';+/**+ * A steer that never reaches its row still rests. The wheel re-aims at it at+ * most this many times.+ */+const MAX_RE_AIMS = 3;+/*** One snap-scrolling picker column, under a fine pointer.*@@ -360,6 +366,15 @@ export function ScrollWheel({// once on a fine one.const lastPointerRef = useRef<string | null>(null);+ // The row the wheel's own scroll heads for. A step commits its row at once.+ // So a rest on the way finishes the scroll and commits nothing. A busy page+ // can draw no frame of a step for longer than the quiet period.+ const steer = useScrollSteer();+ // Where the wheel last re-aimed at its steered row, and how often. A rest+ // short of the row again, with no progress since, ends the steer. Then the+ // settle commits the row the column shows, so the two always agree.+ const reAimRef = useRef<{top: number; count: number} | null>(null);+// A reduced-motion dip whose rows have not landed yet: the row they land// on. While one is pending the rows stay put for it, so they never move at// full opacity, and a further step retargets it.@@ -381,7 +396,10 @@ export function ScrollWheel({(index: number,behavior: ScrollBehavior,- {touchRelease = false}: {touchRelease?: boolean} = {},+ {+ touchRelease = false,+ isReAim = false,+ }: {touchRelease?: boolean; isReAim?: boolean} = {},) => {const scroller = scrollerRef.current;const size = itemBlockSize();@@ -389,6 +407,10 @@ export function ScrollWheel({return;}const top = index * size;+ steer.start(index);+ if (!isReAim) {+ reAimRef.current = null;+ }// Under Reduce Motion the wheel's own scroll lands without travel. It// dips on a touch screen or for a touch drag's release. Otherwise it// lands at once.@@ -433,7 +455,7 @@ export function ScrollWheel({Number.isFinite(shown) ? shown : 1,);},- [itemBlockSize],+ [itemBlockSize, steer],);// Commit on rest. A wheel that stops on a disabled row travels on to the@@ -451,6 +473,22 @@ export function ScrollWheel({if (size === 0) {return;}+ const steered = steer.current();+ if (steered != null) {+ const top = scroller.scrollTop;+ const last = reAimRef.current;+ const isShort = Math.abs(top - steered * size) >= 1;+ const isStuck =+ last != null &&+ (Math.abs(top - last.top) < 1 || last.count >= MAX_RE_AIMS);+ if (isShort && !isStuck) {+ reAimRef.current = {top, count: (last?.count ?? 0) + 1};+ scrollToIndex(steered, 'smooth', {isReAim: true});+ return;+ }+ steer.end();+ reAimRef.current = null;+ }const index = Math.min(options.length - 1,Math.max(0, Math.round(scroller.scrollTop / size)),@@ -472,6 +510,7 @@ export function ScrollWheel({},isActive,isDraggingRef,+ steer,);// Park the committed row under the band at once whenever the wheel isdiff --git a/packages/core/src/DateInput/useScrollSettle.ts b/packages/core/src/DateInput/useScrollSettle.tsindex e5ff8642de..7fb5954dab 100644--- a/packages/core/src/DateInput/useScrollSettle.ts+++ b/packages/core/src/DateInput/useScrollSettle.ts@@ -5,8 +5,10 @@/*** @file useScrollSettle.ts* @input A scroll container ref, a settle callback, and optionally whether a- * mouse drag holds it (usePointerDragScroll's `isDraggingRef`)- * @output Calls back once, after scrolling (including momentum) stops+ * mouse drag holds it (usePointerDragScroll's `isDraggingRef`) and the+ * caller's steer (useScrollSteer)+ * @output Calls back once, after scrolling (including momentum) stops;+ * useScrollSteer, which tracks the caller's own scroll toward a row* @position Internal behavior hook; consumed by Wheel.tsx and MonthScroller.tsx** A snap scroller commits its value when it comes to rest, so it needs a@@ -51,10 +53,12 @@* the scroller is at rest, so a caller can refuse to reposition one that is* still moving.*+ * A person's input on the scroller ends the caller's steer (useScrollSteer).+ ** SYNC: When modified, update DateInputTouch.test.tsx.*/-import {useEffect, useRef} from 'react';+import {useEffect, useMemo, useRef} from 'react';/*** How long the scroller must be quiet before a settle is assumed. Long enough@@ -64,6 +68,47 @@ import {useEffect, useRef} from 'react';*/export const SCROLL_QUIET_MS = 220;+/**+ * The caller's own scroll toward a row it names (a `scrollTo` it makes), so+ * its settle can finish that scroll rather than round it back. The steer ends+ * when the scroll arrives, by the caller's measure, when a person's input+ * reaches the scroller, or when the settle detaches ({@link useScrollSettle}).+ */+export interface ScrollSteer {+ /** Records the row the caller's own scroll heads for. */+ start: (row: number) => void;+ /** The row of the caller's scroll still under way, or null. */+ current: () => number | null;+ /** Ends the steer. */+ end: () => void;+}++/**+ * One steer for one scroller: pass it to {@link useScrollSettle}, start it+ * before each `scrollTo` the caller makes, and read it in the settle.+ *+ * @example+ * ```+ * const steer = useScrollSteer();+ * useScrollSettle(ref, element => finishOrRound(element, steer.current()), true, undefined, steer);+ * ```+ */+export function useScrollSteer(): ScrollSteer {+ const rowRef = useRef<number | null>(null);+ return useMemo(+ () => ({+ start: row => {+ rowRef.current = row;+ },+ current: () => rowRef.current,+ end: () => {+ rowRef.current = null;+ },+ }),+ [],+ );+}+/** What {@link useScrollSettle} reports back about the scroller's state. */export type ScrollSettleState = {/**@@ -83,12 +128,16 @@ export type ScrollSettleState = {* @param isEnabled - skip attaching while false (e.g. a hidden panel)* @param isHeldRef - true while a mouse drag holds the scroller* (usePointerDragScroll's `isDraggingRef`): not rest, however quiet+ * @param steer - the caller's own scroll (useScrollSteer). A finger, a wheel+ * or trackpad, a press or a key on the scroller ends it: from there the+ * scroll is the person's. Detaching ends it too.*/export function useScrollSettle(ref: React.RefObject<HTMLElement | null>,onSettle: (element: HTMLElement) => void,isEnabled: boolean = true,isHeldRef?: React.RefObject<boolean>,+ steer?: ScrollSteer,): ScrollSettleState {// The callback closes over render-fresh values (the option list, the current// value); keeping it in a ref means the listeners attach once instead of@@ -98,8 +147,8 @@ export function useScrollSettle(const isAtRestRef = useRef(true);- // Syncs scroll, touch and pointer listeners with `isEnabled`. They find when- // scrolling stops.+ // Syncs scroll, touch, pointer and key listeners with `isEnabled`. They find+ // when scrolling stops, and end the caller's steer on a person's input.useEffect(() => {const element = ref.current;if (element == null || !isEnabled) {@@ -163,6 +212,10 @@ export function useScrollSettle(arm();};+ const endSteer = () => {+ steer?.end();+ };+const onPointerEnd = () => {// The drag's release: its glide to the nearest row re-arms this on its// own, and the timer covers a release already on a row, which scrolls@@ -180,9 +233,16 @@ export function useScrollSettle(element.addEventListener('touchcancel', onTouchEnd, {passive: true});element.addEventListener('pointerup', onPointerEnd);element.addEventListener('pointercancel', onPointerEnd);+ element.addEventListener('touchstart', endSteer, {passive: true});+ element.addEventListener('wheel', endSteer, {passive: true});+ element.addEventListener('pointerdown', endSteer, {passive: true});+ element.addEventListener('keydown', endSteer, {passive: true});return () => {clearTimeout(timer);+ // A steer whose scroll never came to rest ends here too. Shown again,+ // the scroller is parked afresh, not pulled back to an old row.+ steer?.end();element.removeEventListener('scroll', onScroll);element.removeEventListener('scrollend', settle);element.removeEventListener('touchstart', onTouchStart);@@ -190,8 +250,12 @@ export function useScrollSettle(element.removeEventListener('touchcancel', onTouchEnd);element.removeEventListener('pointerup', onPointerEnd);element.removeEventListener('pointercancel', onPointerEnd);+ element.removeEventListener('touchstart', endSteer);+ element.removeEventListener('wheel', endSteer);+ element.removeEventListener('pointerdown', endSteer);+ element.removeEventListener('keydown', endSteer);};- }, [ref, isEnabled, isHeldRef]);+ }, [ref, isEnabled, isHeldRef, steer]);return {isAtRestRef};}