Skip to content

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

TypeScript

fix(DateInput, DateTimeInput): after a month arrow, Safari's calendar rests on the month the title names (#8513)

Christopher Chedeau16a7494046c3
diff --git a/.changeset/month-scroller-late-step.md b/.changeset/month-scroller-late-step.md
new file mode 100644
index 0000000000..548a4bfa6c
--- /dev/null
+++ b/.changeset/month-scroller-late-step.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] In the DateInput and DateTimeInput bottom-sheet calendars, a month arrow clicked or tapped as the previous arrow's scroll is ending now brings the calendar to the month its title names in Safari, instead of back to the previous arrow's month.
+
+@vjeux
diff --git a/.changeset/month-scroller-stalled-frame.md b/.changeset/month-scroller-stalled-frame.md
new file mode 100644
index 0000000000..af67c54092
--- /dev/null
+++ b/.changeset/month-scroller-stalled-frame.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] In the DateInput and DateTimeInput bottom-sheet calendars, a month arrow no longer sets the calendar paging on by itself in Safari when the page stalls for a moment right after the tap; the calendar moves one month and stays there.
+
+@vjeux
diff --git a/packages/core/package.json b/packages/core/package.json
index 3375b3a134..e6c8651750 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -864,6 +864,7 @@
"devDependencies": {
"@astryxdesign/a11y-spec": "workspace:*",
"@astryxdesign/cli": "workspace:*",
+ "@astryxdesign/interaction-harness": "workspace:*",
"@babel/cli": "catalog:",
"@babel/core": "catalog:",
"@babel/preset-react": "catalog:",
diff --git a/packages/core/src/DateInput/MonthScroller.tsx b/packages/core/src/DateInput/MonthScroller.tsx
index 63c8da6012..dbf2b8e129 100644
--- a/packages/core/src/DateInput/MonthScroller.tsx
+++ b/packages/core/src/DateInput/MonthScroller.tsx
@@ -85,6 +85,14 @@ const DAY_SIZE = dateInputTouchSizes.daySize;
*/
const OVERSCAN = 3;
+/** Input on the scroller that ends a steer: the user's from here. */
+const USER_INPUT_EVENTS = [
+ 'touchstart',
+ 'wheel',
+ 'pointerdown',
+ 'keydown',
+] as const;
+
const styles = stylex.create({
scroller: {
position: 'relative',
@@ -326,13 +334,59 @@ export function MonthScroller({
// updater — React runs updaters during render, where another component's
// setState is illegal.
const centerRowRef = useRef(centerRow);
+
+ /**
+ * Scroll snapping is off from a re-center until the frame after its
+ * commit. WebKit keeps the position it snapped to as an index into the
+ * container's snap offsets, and re-snaps to that index after a layout: a
+ * re-center that unmounts panes before the snapped one shifts the index,
+ * so the re-snap lands a month further on, and the scroll that makes
+ * re-centers again. One stalled frame right after an arrow (300 ms,
+ * measured) was enough to set the calendar paging on by itself, a month
+ * every few frames. With snapping off across the commit nothing re-snaps,
+ * and switching it back on a frame later snaps to the pane in place.
+ *
+ * Each pause counts itself, so a batch of re-centers that ends on the
+ * center it began from, which commits no new center, still restores
+ * snapping.
+ *
+ * Not while a finger drives the scroll, from its touch until the scroll it
+ * started comes to rest: iOS tracks a snap target for the gesture, and
+ * turning snapping off drops it, so the swipe coasted past the month for
+ * about two seconds and was corrected late (iOS 26.2 simulator, where the
+ * same swipe snaps in about 0.6 s with snapping left on).
+ */
+ const [snapPauses, setSnapPauses] = useState(0);
+ const isFingerScrollRef = useRef(false);
+ const recenter = useCallback((scroller: HTMLElement, row: number) => {
+ if (!isFingerScrollRef.current) {
+ scroller.style.scrollSnapType = 'none';
+ setSnapPauses(count => count + 1);
+ }
+ setCenterRow(row);
+ }, []);
+ // Synchronizes the scroller's snapping with the browser's frame loop: it
+ // comes back on in the frame after the pause's commit, and a restore still
+ // pending at the next pause or at unmount is dropped.
+ useLayoutEffect(() => {
+ const scroller = scrollerRef.current;
+ if (snapPauses === 0 || scroller == null) {
+ return undefined;
+ }
+ const frame = requestAnimationFrame(() => {
+ scroller.style.scrollSnapType = '';
+ });
+ return () => cancelAnimationFrame(frame);
+ }, [snapPauses]);
// A row to scroll to once its pane is mounted; see scrollToMonth.
const pendingScrollRef = useRef<number | null>(null);
/**
* The row a programmatic scroll is heading for, so its own scroll events
- * are not reported back as if the user had gone there. Null once a finger
- * touches the scroller, or once the steered scroll has arrived.
+ * 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.
*/
const steeredRowRef = useRef<number | null>(null);
@@ -401,7 +455,12 @@ export function MonthScroller({
// below); a jump that far is never worth animating either.
pendingScrollRef.current = row;
centerRowRef.current = row;
- setCenterRow(row);
+ // The jump is a steer too. Recording it replaces a steer left behind
+ // 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;
+ recenter(scroller, row);
return;
}
steeredRowRef.current = row;
@@ -410,7 +469,7 @@ export function MonthScroller({
behavior,
});
},
- [paneSize, minMonthIndex, rowCount, isRTL],
+ [paneSize, minMonthIndex, rowCount, isRTL, recenter],
);
// Deliberately un-keyed: it runs after every render, costs a null check, and
@@ -476,8 +535,11 @@ export function MonthScroller({
* 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.
+ * After the user's own scroll the correction goes to the nearest boundary,
+ * at most half a pane away. After a steer it goes on to the steered month,
+ * however early the browser cut the steer short. Either way its own scroll
+ * settles onto the boundary it aimed at, where a steer counts as arrived, so
+ * it cannot oscillate.
*/
const settleFrameRef = useRef<number | undefined>(undefined);
useEffect(
@@ -490,6 +552,8 @@ export function MonthScroller({
);
useScrollSettle(scrollerRef, scroller => {
+ // At rest, momentum included: the finger no longer drives the scroll.
+ isFingerScrollRef.current = false;
if (paneSize === 0) {
return;
}
@@ -505,15 +569,22 @@ export function MonthScroller({
if (Math.abs(scroller.scrollLeft - offsetBefore) >= 0.5) {
return;
}
- const row = rowAtScrollOffset(
- scroller.scrollLeft,
- paneSize,
- rowCount,
- isRTL,
- );
+ // A steer the browser cut short is finished, not rounded back. WebKit
+ // ends a smooth scroll that a second one retargeted once the first
+ // one's time is up, firing `scrollend` part-way: an arrow tapped late
+ // 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 row =
+ steered ??
+ 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) {
+ // At rest on its target, a steer has arrived even if no scroll
+ // crossed into its month.
+ steeredRowRef.current = null;
return;
}
scroller.scrollTo({left: target, behavior: 'smooth'});
@@ -554,11 +625,20 @@ export function MonthScroller({
if (scroller == null || paneSize === 0) {
return;
}
- // A finger on the scroller ends any steering: from here the months it
- // passes are the user's doing and every one of them is worth reporting.
- const onTouchStart = () => {
+ // 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 = () => {
+ isFingerScrollRef.current = true;
+ };
const onScroll = () => {
if (frameRef.current != null) {
@@ -576,7 +656,7 @@ export function MonthScroller({
return;
}
centerRowRef.current = row;
- setCenterRow(row);
+ recenter(scroller, row);
// Report nothing while a steer is in flight. `scrollToMonth` is only
// ever called by something that already knows the month — a wheel
// commit, a header arrow, the re-assert when the wheels close — so
@@ -590,9 +670,9 @@ 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 a touch below — once a finger is on the
- // scroller the user owns it, and every month it passes is worth
- // reporting.
+ // 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;
@@ -603,16 +683,22 @@ export function MonthScroller({
});
};
scroller.addEventListener('scroll', onScroll, {passive: true});
+ for (const type of USER_INPUT_EVENTS) {
+ scroller.addEventListener(type, endSteer, {passive: true});
+ }
scroller.addEventListener('touchstart', onTouchStart, {passive: true});
return () => {
scroller.removeEventListener('scroll', onScroll);
+ for (const type of USER_INPUT_EVENTS) {
+ scroller.removeEventListener(type, endSteer);
+ }
scroller.removeEventListener('touchstart', onTouchStart);
if (frameRef.current != null) {
cancelAnimationFrame(frameRef.current);
frameRef.current = undefined;
}
};
- }, [paneSize, rowCount, minMonthIndex, isRTL]);
+ }, [paneSize, rowCount, minMonthIndex, isRTL, recenter]);
// 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.tsx
new file mode 100644
index 0000000000..368bebedb2
--- /dev/null
+++ b/packages/core/src/DateInput/MonthScrollerSettle.test.tsx
@@ -0,0 +1,165 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {act, render} from '@testing-library/react';
+import {createRef} from 'react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {MonthScroller, type MonthScrollerHandle} from './MonthScroller';
+import {SCROLL_QUIET_MS} from './useScrollSettle';
+
+class FakeResizeObserver {
+ constructor(private callback: ResizeObserverCallback) {}
+ observe() {
+ this.callback([], this);
+ }
+ unobserve() {}
+ disconnect() {}
+}
+
+const PANE = 300;
+
+/**
+ * The month scroller's settle, with the browser's scrolling played by hand:
+ * `scrollTo` is recorded, and the offset is whatever the test sets.
+ */
+describe('MonthScroller settle', () => {
+ const scrollTo = vi.fn();
+ beforeEach(() => {
+ vi.useFakeTimers({
+ toFake: [
+ 'setTimeout',
+ 'clearTimeout',
+ 'requestAnimationFrame',
+ 'cancelAnimationFrame',
+ 'Date',
+ 'performance',
+ ],
+ });
+ vi.stubGlobal('ResizeObserver', FakeResizeObserver);
+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(PANE);
+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(
+ PANE,
+ );
+ Element.prototype.scrollTo = scrollTo;
+ scrollTo.mockClear();
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ function renderScroller() {
+ const handleRef = createRef<MonthScrollerHandle>();
+ const view = render(
+ <MonthScroller
+ handleRef={handleRef}
+ minMonthIndex={0}
+ maxMonthIndex={23}
+ initialMonthIndex={9}
+ onVisibleMonthChange={() => {}}
+ selectedDate={null}
+ today={{year: 2026, month: 10, day: 15}}
+ isDateDisabled={() => false}
+ weekStartsOn={0}
+ onSelect={() => {}}
+ />,
+ );
+ const scroller = view.container.querySelector<HTMLElement>(
+ '[data-scroller="months"]',
+ );
+ if (scroller == null) {
+ throw new Error('no month scroller');
+ }
+ scrollTo.mockClear();
+ return {handleRef, scroller};
+ }
+
+ /** The browser moving the scroller to `left`, as a scroll event reports. */
+ /**
+ * A touch event carrying the lists a real one always has: jsdom has no
+ * constructible TouchEvent, and the gesture hook reads `touches[0]`.
+ */
+ function touchEvent(type: 'touchstart' | 'touchend') {
+ 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;
+ }
+
+ function scrollBy(scroller: HTMLElement, left: number) {
+ scroller.scrollLeft = left;
+ scroller.dispatchEvent(new Event('scroll'));
+ }
+
+ it('turns scroll snapping back on after re-centers that end on the month they began on', () => {
+ const {handleRef, scroller} = renderScroller();
+ // Two far jumps in one batch, out and back: each re-centers the mounted
+ // months, pausing scroll snapping, and the second puts the center back
+ // where it was, so the render that follows changes no center.
+ act(() => {
+ handleRef.current?.scrollToMonth(20);
+ handleRef.current?.scrollToMonth(9);
+ });
+ act(() => {
+ vi.advanceTimersByTime(50);
+ });
+ expect(scroller.style.scrollSnapType).toBe('');
+ });
+
+ it('leaves snapping on for a re-center while a finger drives the scroll', () => {
+ const {scroller} = renderScroller();
+ // A finger drags the next month in: the scroller crosses the middle of
+ // October's pane and re-centers its months with the finger still down.
+ act(() => {
+ scroller.dispatchEvent(touchEvent('touchstart'));
+ });
+ act(() => scrollBy(scroller, 9 * PANE + 0.6 * PANE));
+ act(() => {
+ vi.advanceTimersByTime(16);
+ });
+ // Snapping stays on: iOS tracks a snap target for the gesture.
+ expect(scroller.style.scrollSnapType).toBe('');
+ });
+
+ it('pauses snapping for a re-center again once the finger’s scroll has come to rest', () => {
+ const {handleRef, scroller} = renderScroller();
+ act(() => {
+ scroller.dispatchEvent(touchEvent('touchstart'));
+ scroller.dispatchEvent(touchEvent('touchend'));
+ });
+ act(() => {
+ vi.advanceTimersByTime(SCROLL_QUIET_MS + 50);
+ });
+ // An arrow's far jump after the swipe re-centers with snapping paused.
+ act(() => handleRef.current?.scrollToMonth(20));
+ expect(scroller.style.scrollSnapType).toBe('none');
+ act(() => {
+ vi.advanceTimersByTime(50);
+ });
+ expect(scroller.style.scrollSnapType).toBe('');
+ });
+
+ it('finishes a steer the browser cut short instead of rounding it back', () => {
+ const {handleRef, scroller} = renderScroller();
+ // An arrow toward month 10, its scroll 95 % of the way there.
+ act(() => handleRef.current?.scrollToMonth(10));
+ act(() => scrollBy(scroller, 9 * PANE + 0.95 * PANE));
+ // The other arrow, late in that scroll: back toward month 9.
+ act(() => handleRef.current?.scrollToMonth(9));
+ scrollTo.mockClear();
+ // WebKit ends the retargeted scroll where the first one's time ran out,
+ // near month 10, and the scroller goes quiet there.
+ act(() => scrollBy(scroller, 9 * PANE + 0.95 * PANE));
+ act(() => {
+ vi.advanceTimersByTime(SCROLL_QUIET_MS + 50);
+ });
+ // The settle finishes the steer onto month 9, not the nearest pane (10).
+ expect(
+ scrollTo.mock.calls.map(([options]) => (options as ScrollToOptions).left),
+ ).toEqual([9 * PANE]);
+ });
+});
diff --git a/packages/core/src/DateInput/__tests__/MonthScrollerSteps.interaction.browser.spec.ts b/packages/core/src/DateInput/__tests__/MonthScrollerSteps.interaction.browser.spec.ts
new file mode 100644
index 0000000000..e4ed51e4f0
--- /dev/null
+++ b/packages/core/src/DateInput/__tests__/MonthScrollerSteps.interaction.browser.spec.ts
@@ -0,0 +1,312 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file MonthScrollerSteps.interaction.browser.spec.ts
+ * @input The built "Default" DateInput story, shown in a bottom sheet, the
+ * arrows clicked from the page, real mouse and trackpad input and the
+ * interaction harness
+ * @output Interaction proofs for the month scroller's steps: after the month
+ * and year wheels close, a trackpad scroll still pages to the next month and
+ * Reset from four months on still rests on today's month; an arrow step
+ * through a stalled frame moves exactly one month; under a finger, a swipe
+ * that crosses the middle of a month as it lifts keeps scroll snapping on
+ * and rests on the next month.
+ * (A second arrow step late in the first one's scroll, which WebKit cuts
+ * short, is proven in MonthScrollerSettle.test.tsx: a loaded page's frames
+ * are too far apart to aim a click at a share of a 300 ms scroll.)
+ * @position Interaction tests of MonthScroller.tsx
+ * (`*.interaction.browser.spec.ts`, run by `pnpm test:interaction`)
+ */
+
+import {expect, test, type Locator, type Page} from '@playwright/test';
+import {
+ blockMainThread,
+ drag,
+ openStory,
+ touchDriver,
+ withStorybook,
+} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+const STORY = 'core-dateinput--default';
+const ARGS = {presentation: 'bottom-sheet'};
+
+/** Waits until the scroller's offset has not moved for ten frames. */
+async function waitForRest(viewport: Locator): Promise<number> {
+ return viewport.evaluate(
+ async element =>
+ new Promise<number>(resolve => {
+ let last = element.scrollLeft;
+ let still = 0;
+ const check = () => {
+ const now = element.scrollLeft;
+ still = now === last ? still + 1 : 0;
+ last = now;
+ if (still >= 10) {
+ resolve(now);
+ } else {
+ requestAnimationFrame(check);
+ }
+ };
+ requestAnimationFrame(check);
+ }),
+ );
+}
+
+/** The month the scroller rests on, as the pane's own grid names it. */
+/**
+ * Waits until a month's grid sits flush with the scroller's edge, the offset
+ * unchanged, for ten frames: the end of the scroller's own settle
+ * correction, however long the page takes to run it. (The panes' width can
+ * be fractional, so the grid's own box is the measure, not the offset.)
+ */
+async function waitForRestOnMonth(viewport: Locator): Promise<number> {
+ return viewport.evaluate(
+ async element =>
+ new Promise<number>(resolve => {
+ let last = element.scrollLeft;
+ let still = 0;
+ const flush = () => {
+ const edge = element.getBoundingClientRect().left;
+ return [
+ ...element.querySelectorAll<HTMLElement>('[role="grid"]'),
+ ].some(
+ grid => Math.abs(grid.getBoundingClientRect().left - edge) < 1,
+ );
+ };
+ const check = () => {
+ const now = element.scrollLeft;
+ still = now === last && flush() ? still + 1 : 0;
+ last = now;
+ if (still >= 10) {
+ resolve(now);
+ } else {
+ requestAnimationFrame(check);
+ }
+ };
+ requestAnimationFrame(check);
+ }),
+ );
+}
+
+async function monthAtRest(viewport: Locator): Promise<string> {
+ return viewport.evaluate(element => {
+ const box = element.getBoundingClientRect();
+ const middle = box.left + box.width / 2;
+ for (const grid of element.querySelectorAll<HTMLElement>('[role="grid"]')) {
+ const r = grid.getBoundingClientRect();
+ if (r.left <= middle && r.right >= middle) {
+ return grid.getAttribute('aria-label') ?? '';
+ }
+ }
+ return '';
+ });
+}
+
+async function openCalendar(page: Page) {
+ await openStory(page, storybook(), STORY, ARGS);
+ await page
+ .getByRole('button', {name: /calendar/i})
+ .first()
+ .click();
+ const viewport = page.locator('[data-scroller="months"]');
+ await expect(viewport).toBeVisible();
+ await waitForRest(viewport);
+ return viewport;
+}
+
+test.use({hasTouch: false, isMobile: false});
+
+/**
+ * Waits until the scroller comes to rest, or until it has gone more than
+ * `limit` past `from`: a scroller that runs on by itself never rests, and
+ * the proof should fail where it ran, not at the test's timeout.
+ */
+async function waitForRestOrRun(
+ viewport: Locator,
+ from: number,
+ limit: number,
+): Promise<number> {
+ return viewport.evaluate(
+ async (element, {from, limit}) =>
+ new Promise<number>(resolve => {
+ let last = element.scrollLeft;
+ let still = 0;
+ const check = () => {
+ const now = element.scrollLeft;
+ still = now === last ? still + 1 : 0;
+ last = now;
+ if (still >= 10 || Math.abs(now - from) > limit) {
+ resolve(now);
+ } else {
+ requestAnimationFrame(check);
+ }
+ };
+ requestAnimationFrame(check);
+ }),
+ {from, limit},
+ );
+}
+
+/**
+ * A stalled frame right after an arrow (a 300 ms block of the main thread)
+ * let the re-center that follows the step land after the scroll had ended,
+ * and WebKit's re-snap after it then paged on by itself, a month every few
+ * frames. The step moves exactly one month.
+ */
+test('an arrow step through a stalled frame moves exactly one month', async ({
+ page,
+}) => {
+ const viewport = await openCalendar(page);
+ const title = page.getByRole('button', {name: /Choose month and year/});
+ const from = await viewport.evaluate(element => element.scrollLeft);
+ const width = await viewport.evaluate(element => element.clientWidth);
+ const box = await page
+ .getByRole('button', {name: 'Next month'})
+ .boundingBox();
+ if (box == null) {
+ throw new Error('no Next month button');
+ }
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
+ await blockMainThread(page, 300);
+ const at = await waitForRestOrRun(viewport, from, 2 * width);
+ expect(Math.round((at - from) / width)).toBe(1);
+ await waitForRestOnMonth(viewport);
+ expect(
+ Math.round(((await viewport.evaluate(e => e.scrollLeft)) - from) / width),
+ ).toBe(1);
+ await expect(title).toHaveAccessibleName(
+ new RegExp(await monthAtRest(viewport)),
+ );
+});
+
+/**
+ * Closing the month and year wheels re-asserts the month shown, a steer that
+ * moves nothing. A trackpad scroll after it is the user's: it pages to the
+ * next month and stays there, the title following.
+ */
+test('after the month and year wheels close, a trackpad scroll to the next month stays there', async ({
+ page,
+}) => {
+ const viewport = await openCalendar(page);
+ const toggle = page.getByRole('button', {name: /Choose month and year/});
+ const start = await monthAtRest(viewport);
+ expect(start).not.toBe('');
+ const toggleBox = await toggle.boundingBox();
+ if (toggleBox == null) {
+ throw new Error('no month and year toggle');
+ }
+ const clickToggle = async () =>
+ page.mouse.click(
+ toggleBox.x + toggleBox.width / 2,
+ toggleBox.y + toggleBox.height / 2,
+ );
+ await clickToggle();
+ await expect(toggle).toHaveAttribute('aria-expanded', 'true');
+ await clickToggle();
+ await expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ await waitForRest(viewport);
+
+ const box = await viewport.boundingBox();
+ if (box == null) {
+ throw new Error('no month scroller');
+ }
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ // A horizontal trackpad scroll of 70 % of a month, as one wheel event: a
+ // burst of small ones reaches a loaded page far enough apart to count as
+ // separate gestures, each snapping back on its own.
+ await page.mouse.wheel(box.width * 0.7, 0);
+ // Past the scroller's own settle correction too, which ends on a month's
+ // boundary.
+ await waitForRestOnMonth(viewport);
+ const next = await monthAtRest(viewport);
+ expect(next).not.toBe(start);
+ await expect(toggle).toHaveAccessibleName(new RegExp(next));
+});
+
+/**
+ * Reset from four months on is a far jump, mounting today's month before the
+ * scroller moves. After the month and year wheels close, whose re-assert is a
+ * steer that moved nothing, the jump still rests on today's month, the title
+ * with it.
+ */
+test('after the month and year wheels close, Reset from four months on rests on today’s month', async ({
+ page,
+}) => {
+ const viewport = await openCalendar(page);
+ const toggle = page.getByRole('button', {name: /Choose month and year/});
+ const today = await monthAtRest(viewport);
+ expect(today).not.toBe('');
+ const clickCentre = async (name: string | RegExp) => {
+ const box = await page.getByRole('button', {name}).boundingBox();
+ if (box == null) {
+ throw new Error(`no ${String(name)} button`);
+ }
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
+ };
+ for (let step = 0; step < 4; step++) {
+ await clickCentre('Next month');
+ await waitForRest(viewport);
+ }
+ expect(await monthAtRest(viewport)).not.toBe(today);
+ await clickCentre(/Choose month and year/);
+ await expect(toggle).toHaveAttribute('aria-expanded', 'true');
+ await clickCentre(/Choose month and year/);
+ await expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ await waitForRest(viewport);
+
+ await clickCentre('Reset');
+ // Past the scroller's own settle correction too, which ends on a month's
+ // boundary.
+ await waitForRestOnMonth(viewport);
+ expect(await monthAtRest(viewport)).toBe(today);
+ await expect(toggle).toHaveAccessibleName(new RegExp(today));
+});
+
+test.describe('under a finger', () => {
+ test.use({hasTouch: true, isMobile: true});
+
+ /**
+ * A swipe whose last move crosses the middle of the month makes the
+ * scroller re-center as the finger lifts. The finger drives that scroll, so
+ * the re-center leaves scroll snapping on (turning it off drops the snap
+ * target iOS tracks for the gesture, and the swipe coasted past the month),
+ * and the swipe comes to rest on the next month.
+ */
+ test('a swipe that crosses the middle of a month as it lifts keeps snapping on and rests on the next month', async ({
+ page,
+ }) => {
+ const viewport = await openCalendar(page);
+ const start = await monthAtRest(viewport);
+ const box = await viewport.boundingBox();
+ if (box == null) {
+ throw new Error('no month scroller');
+ }
+ // Every change of the scroller's inline scroll-snap-type from here on.
+ await viewport.evaluate(element => {
+ const changes: string[] = [];
+ (window as unknown as {snapChanges: string[]}).snapChanges = changes;
+ new MutationObserver(() => {
+ changes.push((element as HTMLElement).style.scrollSnapType || 'on');
+ }).observe(element, {attributes: true, attributeFilter: ['style']});
+ });
+ const driver = await touchDriver(page);
+ const y = box.y + box.height / 2;
+ const from = {x: box.x + box.width * 0.8, y};
+ // 55 % of a month toward the next one, the middle crossed by the last
+ // move, lifting a quarter frame after it.
+ await driver.play(
+ drag(from, {x: from.x - box.width * 0.55, y}, {durationMs: 300}),
+ );
+ await waitForRestOnMonth(viewport);
+ const rest = await monthAtRest(viewport);
+ expect(rest).not.toBe('');
+ expect(rest).not.toBe(start);
+ // Snapping was never turned off while the finger drove the scroll.
+ expect(
+ await page.evaluate(
+ () => (window as unknown as {snapChanges: string[]}).snapChanges,
+ ),
+ ).not.toContain('none');
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c93bc6ef38..ad5e966730 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -882,6 +882,9 @@ importers:
'@astryxdesign/cli':
specifier: workspace:*
version: link:../cli
+ '@astryxdesign/interaction-harness':
+ specifier: workspace:*
+ version: link:../../internal/interaction-harness
'@babel/cli':
specifier: 'catalog:'
version: 7.29.7(@babel/[email protected])