An open source design system that's fully customizable and agent ready
TypeScript
fix(core): the touch calendar no longer rests between two months (#5319)
Xinzi Zhoua46266b816be
diff --git a/.changeset/date-input-touch-snap-correction.md b/.changeset/date-input-touch-snap-correction.mdnew file mode 100644index 0000000000..fcf6d5248d--- /dev/null+++ b/.changeset/date-input-touch-snap-correction.md@@ -0,0 +1,35 @@+---+'@astryxdesign/core': patch+---++[fix] DateInput's touch calendar no longer rests between two months++Swiping the month calendar on iOS could leave it parked a couple of columns+into a pane: the left of March and the right of April on screen at once, under+one square Sun-to-Sat header, with the title still naming March. The grid was+never skewed — the scrollport was simply at rest where no month begins.++`scroll-snap-type: mandatory` is supposed to make that impossible, and on a+static list it does. This list is virtualized: seven panes exist out of twelve+hundred, and the panes ARE the snap areas, so every month the finger crosses+mounts one and unmounts another while the fling is still running. iOS scrolls+off the main thread — it picks a landing place from the snap points it knows+about at that moment, and a React re-render that lands after the decision+moves them. The scroller stops where a snap point used to be and nothing+re-snaps it. Chrome never showed it because it snaps again after the mutation.++The rest position is now corrected rather than trusted: once the gesture is+genuinely over — touch released, the scroller quiet, AND its offset confirmed+unchanged across a frame — a scroller that is off a pane boundary is moved to+the nearest one. A scroller the browser snapped for itself is left alone, so+nothing extra happens on Chrome, and sub-pixel drift on a fractional viewport+is ignored.++That last condition is what keeps the fix from becoming a worse bug than the+one it fixes. A quiet period is not proof of rest: iOS runs its own snap+animation for a few hundred milliseconds after the finger lifts and fires+scroll events irregularly while it does, so a correction that trusts quiet+alone can land mid-animation, round an offset still travelling toward next+month back to the month it came from, and reverse the swipe.++@imdreamrunnerdiff --git a/packages/core/src/DateInput/DateInputTouch.test.tsx b/packages/core/src/DateInput/DateInputTouch.test.tsxindex e8136135bd..ce5543ff83 100644--- a/packages/core/src/DateInput/DateInputTouch.test.tsx+++ b/packages/core/src/DateInput/DateInputTouch.test.tsx@@ -56,6 +56,7 @@ import {} from './monthGeometry';import {SWIPE_DISTANCE} from './useOwnScrollGesture';import {DRAG_SLOP} from './usePointerDragScroll';+import {SCROLL_QUIET_MS} from './useScrollSettle';// ---------------------------------------------------------------------------// jsdom scaffolding@@ -998,6 +999,194 @@ describe('DateInput — calendar surface', () => {});});+// ---------------------------------------------------------------------------+// Resting between two months — the iOS snap failure+// ---------------------------------------------------------------------------++/**+ * `scroll-snap-type: mandatory` is supposed to make all of this unnecessary,+ * and on a static list it does. This list is virtualized: seven panes exist+ * out of twelve hundred, and THE PANES ARE THE SNAP AREAS — so every month+ * the finger crosses mounts one and unmounts another, mid-fling.+ *+ * iOS scrolls off the main thread. It picks a landing place from the snap+ * points it knows about at the time, and a React re-render that lands after+ * that decision moves them; the scroller comes to rest where no snap point+ * exists any more and nothing re-snaps it. Reported from a device as the+ * calendar sitting between two months with the weekday header still square —+ * which is exactly the shape of it: the grid is not skewed, the scrollport is+ * parked a couple of columns into a pane, so the left of March and the right+ * of April are on screen under one Sun-to-Sat header.+ *+ * Chrome never shows it, because it snaps again after the mutation. jsdom+ * implements no snapping at all, which makes it a fine place to test the+ * correction: the scroller can simply be PUT at a bad offset, exactly as iOS+ * leaves it, and the settle has to fix it.+ */+describe('DateInput — a rest position between two months', () => {+ /** The row March 2026 occupies in a range that opens in January 2024. */+ const MARCH_2026_ROW = 26;+ const FIVE_YEARS = {min: '2024-01-01', max: '2028-12-31'} as const;++ /** A touchstart carrying the list a real one always has. */+ const touchEvent = (type: string) => {+ const event = new Event(type, {bubbles: true});+ const point = {identifier: 1, clientX: 100, clientY: 100};+ Object.defineProperties(event, {+ touches: {value: type === 'touchend' ? [] : [point]},+ targetTouches: {value: type === 'touchend' ? [] : [point]},+ changedTouches: {value: [point]},+ });+ return event;+ };++ /** Drag, release, and let the quiet period elapse. */+ const swipeTo = async (scroller: HTMLElement, offset: number) => {+ scroller.dispatchEvent(touchEvent('touchstart'));+ scroller.scrollLeft = offset;+ fireEvent.scroll(scroller);+ scroller.dispatchEvent(touchEvent('touchend'));+ };++ const openCalendar = () => {+ render(<Controlled initial="2026-03-21" {...FIVE_YEARS} />);+ fireEvent.click(screen.getByLabelText('Event date'));+ const scroller = document.querySelector<HTMLElement>(+ '[data-scroller="months"]',+ )!;+ const scrollTo = vi.mocked(Element.prototype.scrollTo);+ scrollTo.mockClear();+ return {scroller, scrollTo};+ };++ it('puts the calendar back on a pane once the swipe is over', async () => {+ await withLayout(async () => {+ const {scroller, scrollTo} = openCalendar();+ // Two columns in — what the device screenshot showed.+ const stray = Math.round((SCROLLPORT_WIDTH * 2) / 7);+ await swipeTo(scroller, MARCH_2026_ROW * SCROLLPORT_WIDTH + stray);++ await waitFor(() =>+ expect(scrollTo).toHaveBeenCalledWith(+ expect.objectContaining({left: MARCH_2026_ROW * SCROLLPORT_WIDTH}),+ ),+ );+ });+ });++ it('goes to the nearer pane, not back the way it came', async () => {+ await withLayout(async () => {+ const {scroller, scrollTo} = openCalendar();+ // Three quarters of the way to April: April is the honest answer, and a+ // correction that always rounded down would drag the user backwards.+ await swipeTo(+ scroller,+ MARCH_2026_ROW * SCROLLPORT_WIDTH + SCROLLPORT_WIDTH * 0.75,+ );++ await waitFor(() =>+ expect(scrollTo).toHaveBeenCalledWith(+ expect.objectContaining({+ left: (MARCH_2026_ROW + 1) * SCROLLPORT_WIDTH,+ }),+ ),+ );+ });+ });++ /**+ * A scroller the browser snapped for itself must be left alone. Correcting+ * it anyway would mean every swipe on Chrome — where snapping works — ended+ * with a second, pointless scroll.+ */+ it('leaves a scroller that snapped properly alone', async () => {+ await withLayout(async () => {+ const {scroller, scrollTo} = openCalendar();+ await swipeTo(scroller, (MARCH_2026_ROW + 2) * SCROLLPORT_WIDTH);++ // Long enough that the settle has certainly run.+ await new Promise(resolve => setTimeout(resolve, SCROLL_QUIET_MS * 2));+ expect(scrollTo).not.toHaveBeenCalled();+ });+ });++ /**+ * Sub-pixel drift is the browser's own rounding on a fractional viewport,+ * not a failed snap. Correcting it would fire a scroll after every gesture+ * on any device whose width is not a whole number of pixels.+ */+ it('ignores sub-pixel drift', async () => {+ await withLayout(async () => {+ const {scroller, scrollTo} = openCalendar();+ await swipeTo(scroller, MARCH_2026_ROW * SCROLLPORT_WIDTH + 0.4);++ await new Promise(resolve => setTimeout(resolve, SCROLL_QUIET_MS * 2));+ expect(scrollTo).not.toHaveBeenCalled();+ });+ });++ /**+ * The correction waits for the finger. Firing it mid-drag would fight the+ * hand that is still moving the scroller — the same mistake that made the+ * wheels climb a month at a time on iOS, and the reason `useScrollSettle`+ * waits for a release rather than for quiet alone.+ */+ it('does not correct while the finger is still down', async () => {+ await withLayout(async () => {+ const {scroller, scrollTo} = openCalendar();+ scroller.dispatchEvent(touchEvent('touchstart'));+ scroller.scrollLeft = MARCH_2026_ROW * SCROLLPORT_WIDTH + 120;+ fireEvent.scroll(scroller);++ await new Promise(resolve => setTimeout(resolve, SCROLL_QUIET_MS * 2));+ expect(scrollTo).not.toHaveBeenCalled();++ // And on release it does the correction it was holding back.+ scroller.dispatchEvent(touchEvent('touchend'));+ await waitFor(() => expect(scrollTo).toHaveBeenCalled());+ });+ });++ /**+ * The one that actually reverses a swipe, and the reason the correction+ * re-checks stillness rather than trusting the quiet period.+ *+ * iOS runs its own snap animation for ~150-300ms after the finger lifts,+ * and fires scroll events irregularly while it does — a gap longer than the+ * quiet period is routine in the slow tail. The settle lands mid-animation,+ * reads an offset still travelling toward April, rounds THAT to the nearest+ * pane (still March, since the animation is not yet halfway), and drags the+ * calendar back where it came from. Swipe forward, get pulled backward.+ *+ * Simulated by moving the scroller between the two samples, which is what+ * an animation in flight looks like from here.+ */+ it('does not correct a scroller that is still travelling', async () => {+ await withLayout(async () => {+ const {scroller, scrollTo} = openCalendar();+ // A quarter of the way to April, and still going.+ let offset = MARCH_2026_ROW * SCROLLPORT_WIDTH + SCROLLPORT_WIDTH * 0.25;+ Object.defineProperty(scroller, 'scrollLeft', {+ configurable: true,+ get: () => {+ // Every read advances it, the way an in-flight animation does.+ offset += 8;+ return offset;+ },+ set: (value: number) => {+ offset = value;+ },+ });++ await swipeTo(scroller, offset);+ await new Promise(resolve => setTimeout(resolve, SCROLL_QUIET_MS * 3));+ // Nothing. Correcting here would have sent it back to March, undoing a+ // swipe the browser was already completing.+ expect(scrollTo).not.toHaveBeenCalled();+ });+ });+});+// ---------------------------------------------------------------------------// Month / year wheels// ---------------------------------------------------------------------------diff --git a/packages/core/src/DateInput/MonthScroller.tsx b/packages/core/src/DateInput/MonthScroller.tsxindex fe293e73c1..ccdd8ffcc6 100644--- a/packages/core/src/DateInput/MonthScroller.tsx+++ b/packages/core/src/DateInput/MonthScroller.tsx@@ -63,6 +63,7 @@ import {} from '../utils';import {dateInputTouchSizes, dateInputTouchGeometry} from './tokens.stylex';import {useOwnScrollGesture} from './useOwnScrollGesture';+import {useScrollSettle} from './useScrollSettle';import {fromMonthIndex,monthIndexOf,@@ -425,6 +426,96 @@ export function MonthScroller({useImperativeHandle(handleRef, () => ({scrollToMonth}), [scrollToMonth]);+ /**+ * Put the scroller back on a pane boundary once the gesture is over.+ *+ * `scroll-snap-type: mandatory` is supposed to make this unnecessary, and+ * on a static list it does. This list is virtualized: seven panes exist out+ * of twelve hundred, and the panes ARE the snap areas — so every month the+ * finger crosses mounts one and unmounts another, mid-fling.+ *+ * iOS scrolls off the main thread. It picks a landing place from the snap+ * points it knows about at the time, and a React re-render that lands after+ * that decision moves them; the scroller then comes to rest where no snap+ * point exists any more, and nothing re-snaps it. That is the calendar+ * sitting between two months with the weekday header still square — the+ * grid is not skewed, the scrollport is simply parked a couple of columns+ * into a pane. Chrome hides it by snapping again after the mutation.+ *+ * So the rest position is corrected here rather than trusted. It waits for+ * a true settle — touch released AND quiet, since iOS below 26 has no+ * `scrollend` and its momentum outlasts any naive timer (see+ * useScrollSettle) — and only moves when the offset is genuinely off, so a+ * scroller the browser snapped for itself is left alone.+ *+ * ## Why it re-checks that the scroller is still+ *+ * A quiet period is not proof of rest, and getting that wrong here does not+ * merely fail to fix the bug — it REVERSES the user's swipe. iOS runs its+ * own snap animation for ~150-300ms after the finger lifts, and the scroll+ * events it fires during that animation arrive irregularly; a gap longer+ * than the quiet period is routine in the slow tail. The settle then lands+ * mid-animation, reads a scrollLeft still travelling toward April, rounds+ * THAT to the nearest pane — which is still March, because the animation is+ * not yet halfway — and drags the calendar back where it came from. Swipe+ * forward, get pulled backward, which is what this looked like on a device.+ *+ * Two samples a frame apart settle it: if the offset moved, the scroller is+ * still going somewhere and its destination is not ours to guess. Skipping+ * costs nothing, because the animation's own scroll events re-arm the+ * settle, and the last of them gets a quiet period that ends at true rest.+ *+ * The threshold is a subpixel rather than exact equality. A scroller at rest+ * on a fractional-density viewport can report an offset that wobbles in the+ * last decimal place, and exact equality would read that as travel and never+ * correct at all — the failure mode being silent, which is the worst kind.+ * A tail crawling slower than half a pixel a frame has effectively arrived,+ * so treating it as arrived is right anyway.+ *+ * The correction is at most half a pane by construction, and its own scroll+ * settles onto the boundary it just aimed at, so it cannot oscillate.+ */+ const settleFrameRef = useRef<number | undefined>(undefined);+ useEffect(+ () => () => {+ if (settleFrameRef.current != null) {+ cancelAnimationFrame(settleFrameRef.current);+ }+ },+ [],+ );++ useScrollSettle(scrollerRef, scroller => {+ if (paneSize === 0) {+ return;+ }+ const offsetBefore = scroller.scrollLeft;+ if (settleFrameRef.current != null) {+ cancelAnimationFrame(settleFrameRef.current);+ }+ settleFrameRef.current = requestAnimationFrame(() => {+ settleFrameRef.current = undefined;+ // Still travelling — including a snap animation iOS has not finished.+ // Correcting toward the nearest pane from a position mid-flight would+ // undo the swipe rather than complete it.+ if (Math.abs(scroller.scrollLeft - offsetBefore) >= 0.5) {+ return;+ }+ const row = rowAtScrollOffset(+ scroller.scrollLeft,+ paneSize,+ rowCount,+ isRTL,+ );+ const target = scrollOffsetForRow(row, paneSize, isRTL);+ // Sub-pixel drift is the browser's own rounding, not a failed snap.+ if (Math.abs(scroller.scrollLeft - target) < 1) {+ return;+ }+ scroller.scrollTo({left: target, behavior: 'smooth'});+ });+ });+// Claim horizontal gestures, leave vertical ones to the sheet.//// `touch-action: pan-x` alone is NOT enough: it governs what the browser