An open source design system that's fully customizable and agent ready
TypeScript
fix(DateInput, DateTimeInput): the month scroller's steps follow design:reduced-motion (#8496)
Christopher Chedeauaa864876069b
diff --git a/.changeset/month-scroller-reduced-motion.md b/.changeset/month-scroller-reduced-motion.mdnew file mode 100644index 0000000000..ff22cbf0b9--- /dev/null+++ b/.changeset/month-scroller-reduced-motion.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] With Reduce Motion on (`design:reduced-motion`), the month arrows in the DateInput and DateTimeInput bottom-sheet calendars, Reset, and a keyboard move into another month no longer scroll the months: on a computer with a mouse or trackpad the month changes at once, and on a touch screen it changes through a short opacity dip. A second step during the dip replaces the first, and unmounting the calendar during the dip scrolls nothing.++@vjeuxdiff --git a/packages/core/src/DateInput/MonthScroller.test.tsx b/packages/core/src/DateInput/MonthScroller.test.tsxnew file mode 100644index 0000000000..581f01be53--- /dev/null+++ b/packages/core/src/DateInput/MonthScroller.test.tsx@@ -0,0 +1,157 @@+// 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';++/**+ * A touch screen with Reduced Motion on: the policy's combined query+ * (motion/reducedMotion.ts) and the coarse pointer both match.+ */+function stubReducedMotionTouch(): void {+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches:+ query.includes('prefers-reduced-motion: reduce') ||+ /pointer:\s*coarse/.test(query),+ media: query,+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ dispatchEvent: () => false,+ }));+}++class FakeResizeObserver {+ constructor(private callback: ResizeObserverCallback) {}+ observe() {+ this.callback([], this);+ }+ unobserve() {}+ disconnect() {}+}++describe('MonthScroller under Reduced Motion on a touch screen', () => {+ const scrollTo = vi.fn();+ beforeEach(() => {+ vi.useFakeTimers();+ stubReducedMotionTouch();+ vi.stubGlobal('ResizeObserver', FakeResizeObserver);+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(300);+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(300);+ Element.prototype.scrollTo = scrollTo;+ Element.prototype.animate = vi.fn(() => ({+ cancel: vi.fn(),+ })) as unknown as typeof Element.prototype.animate;+ scrollTo.mockClear();+ });+ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ function renderScroller({+ onVisibleMonthChange = () => {},+ }: {onVisibleMonthChange?: (monthIndex: number) => void} = {}) {+ const handleRef = createRef<MonthScrollerHandle>();+ const view = render(+ <MonthScroller+ handleRef={handleRef}+ minMonthIndex={0}+ maxMonthIndex={23}+ initialMonthIndex={9}+ onVisibleMonthChange={onVisibleMonthChange}+ selectedDate={null}+ today={{year: 2026, month: 10, day: 15}}+ isDateDisabled={() => false}+ weekStartsOn={0}+ onSelect={() => {}}+ />,+ );+ scrollTo.mockClear();+ return {handleRef, ...view};+ }++ it('lets a second step within the dip replace the first: only its scroll lands', () => {+ const {handleRef} = renderScroller();+ act(() => handleRef.current?.scrollToMonth(10));+ act(() => {+ vi.advanceTimersByTime(40);+ });+ act(() => handleRef.current?.scrollToMonth(11));+ act(() => {+ vi.advanceTimersByTime(400);+ });+ expect(scrollTo).toHaveBeenCalledTimes(1);+ });++ it('keeps a jump to a distant month made within the dip: the dip does not land after it', () => {+ const {handleRef} = renderScroller();+ act(() => handleRef.current?.scrollToMonth(10));+ act(() => {+ vi.advanceTimersByTime(40);+ });+ // Eleven months on: beyond the mounted window, so it jumps at once.+ act(() => handleRef.current?.scrollToMonth(20));+ act(() => {+ vi.advanceTimersByTime(400);+ });+ expect(+ scrollTo.mock.calls.map(([options]) => (options as ScrollToOptions).left),+ ).toEqual([20 * 300]);+ });++ it('keeps a step at once made within the dip: the dip does not land after it', () => {+ const {handleRef} = renderScroller();+ act(() => handleRef.current?.scrollToMonth(10));+ act(() => {+ vi.advanceTimersByTime(40);+ });+ act(() => handleRef.current?.scrollToMonth(8, 'auto'));+ act(() => {+ vi.advanceTimersByTime(400);+ });+ expect(+ scrollTo.mock.calls.map(([options]) => (options as ScrollToOptions).left),+ ).toEqual([8 * 300]);+ });++ it('reports a trackpad scroll after a step lands, even with an earlier steer that never arrived', () => {+ const onVisibleMonthChange = vi.fn();+ const {handleRef, container} = renderScroller({onVisibleMonthChange});+ const scroller = container.querySelector<HTMLElement>(+ '[data-scroller="months"]',+ );+ if (scroller == null) {+ throw new Error('no scroller');+ }+ // The re-assert when the wheels close: a steer to the month already in+ // view, whose scroll never arrives.+ act(() => handleRef.current?.scrollToMonth(9, 'auto'));+ // A step lands at its dip's middle.+ act(() => handleRef.current?.scrollToMonth(10));+ act(() => {+ vi.advanceTimersByTime(400);+ });+ // A trackpad scroll on to the next month: no touch ends the steer.+ act(() => {+ scroller.scrollLeft = 11 * 300;+ scroller.dispatchEvent(new Event('scroll'));+ vi.advanceTimersByTime(50);+ });+ expect(onVisibleMonthChange).toHaveBeenLastCalledWith(11);+ });++ it('scrolls nothing once unmounted within the dip', () => {+ const {handleRef, unmount} = renderScroller();+ act(() => handleRef.current?.scrollToMonth(10));+ unmount();+ act(() => {+ vi.advanceTimersByTime(400);+ });+ expect(scrollTo).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/DateInput/MonthScroller.tsx b/packages/core/src/DateInput/MonthScroller.tsxindex 0ccac41f73..95c10802de 100644--- a/packages/core/src/DateInput/MonthScroller.tsx+++ b/packages/core/src/DateInput/MonthScroller.tsx@@ -62,6 +62,7 @@ import {plainDateToISO,DATE_FORMAT_WITH_WEEKDAY,} from '../utils';+import {reducedMotionFade} from '../motion/reducedMotion';import {dateInputTouchSizes, dateInputTouchGeometry} from './tokens.stylex';import {useOwnScrollGesture} from './useOwnScrollGesture';import {useScrollSettle} from './useScrollSettle';@@ -431,8 +432,26 @@ export function MonthScroller({);}, [paneSize, initialMonthIndex, minMonthIndex, isRTL]);+ // The Reduced Motion dip of a step on a touch screen, owned here so a+ // second step or the unmount clears it.+ const dipRef = useRef<{animation: Animation; timer: number} | null>(null);+ const stopDip = useCallback(() => {+ const dip = dipRef.current;+ if (dip != null) {+ window.clearTimeout(dip.timer);+ dip.animation.cancel();+ dipRef.current = null;+ }+ }, []);+ // Synchronizes with the dip's timer and animation: neither outlives the+ // scroller.+ useEffect(() => stopDip, [stopDip]);+const scrollToMonth = useCallback((monthIndex: number, behavior: ScrollBehavior = 'smooth') => {+ // Every step replaces a running dip, whichever way it moves. Otherwise+ // the dip's landing would undo a jump or an immediate step made after it.+ stopDip();const scroller = scrollerRef.current;if (scroller == null || paneSize === 0) {return;@@ -458,13 +477,52 @@ export function MonthScroller({recenter(scroller, row);return;}+ const left = scrollOffsetForRow(row, paneSize, isRTL);+ // Under reduced motion the month changes without travel: at once on a fine+ // primary pointer, under an opacity dip on a coarse one (reducedMotionFade).+ const fade = behavior === 'smooth' ? reducedMotionFade(scroller) : null;+ if (fade != null) {+ // The window mounts around the target first, and the scroll lands in+ // the layout effect below, as a far jump does. So nothing moves the+ // window after the jump. If the window followed the jump, WebKit would+ // re-snap it one pane further on every frame. A scroll that lands on+ // the centre row reports nothing.+ const land = () => {+ // The landing is the newest steer. An earlier steer whose scroll+ // 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;+ if (row === centerRowRef.current) {+ scroller.scrollTo({left, behavior: 'auto'});+ return;+ }+ pendingScrollRef.current = row;+ centerRowRef.current = row;+ setCenterRow(row);+ };+ if (fade.duration === 0) {+ land();+ return;+ }+ // A second step within the dip has replaced the first (above): only+ // its scroll lands, at its own dip's middle.+ dipRef.current = {+ animation: scroller.animate(+ [{opacity: 1}, {opacity: 0}, {opacity: 1}],+ {duration: fade.duration, easing: fade.easing},+ ),+ timer: window.setTimeout(() => {+ dipRef.current = null;+ land();+ }, fade.duration / 2),+ };+ return;+ }steeredRowRef.current = row;- scroller.scrollTo({- left: scrollOffsetForRow(row, paneSize, isRTL),- behavior,- });+ scroller.scrollTo({left, behavior});},- [paneSize, minMonthIndex, rowCount, isRTL, recenter],+ [paneSize, minMonthIndex, rowCount, isRTL, recenter, stopDip],);// Deliberately un-keyed: it runs after every render, costs a null check, anddiff --git a/packages/core/src/DateInput/__tests__/MonthScroller.interaction.browser.spec.ts b/packages/core/src/DateInput/__tests__/MonthScroller.interaction.browser.spec.tsnew file mode 100644index 0000000000..ad4dd70f7f--- /dev/null+++ b/packages/core/src/DateInput/__tests__/MonthScroller.interaction.browser.spec.ts@@ -0,0 +1,261 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file MonthScroller.interaction.browser.spec.ts+ * @input The built "Default" DateInput story, shown in a bottom sheet,+ * real touch and mouse input and the interaction harness+ * @output Interaction proofs for the month scroller's arrows under Reduced+ * Motion (`design:reduced-motion`): with a mouse the month changes at once,+ * with no animated property; on a touch screen through a short opacity+ * dip, the scroll landing at its middle with no travel+ * @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 {+ openStory,+ touchDriver,+ withStorybook,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);+const STORY = 'core-dateinput--default';+const ARGS = {presentation: 'bottom-sheet'};++/** Opens the sheet's calendar and waits for its scroller to come to rest. */+async function openCalendar(+ page: Page,+ input: 'mouse' | 'touch',+ reducedMotion: 'reduce' | 'no-preference' = 'reduce',+) {+ await page.emulateMedia({reducedMotion});+ await openStory(page, storybook(), STORY, ARGS);+ const opener = page.getByRole('button', {name: /calendar/i}).first();+ if (input === 'mouse') {+ await opener.click();+ } else {+ const box = await opener.boundingBox();+ if (box == null) {+ throw new Error('no opener');+ }+ const driver = await touchDriver(page);+ await driver.tap({x: box.x + box.width / 2, y: box.y + box.height / 2});+ }+ const viewport = page.locator('[data-scroller="months"]');+ await expect(viewport).toBeVisible();+ // The sheet's own entrance, and the scroller's first snap, settle first.+ await viewport.evaluate(+ async element =>+ new Promise<void>(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();+ } else {+ requestAnimationFrame(check);+ }+ };+ requestAnimationFrame(check);+ }),+ );+ return viewport;+}++test.describe('with a mouse', () => {+ test.use({hasTouch: false, isMobile: false});++ test('without Reduced Motion an arrow still scrolls the month', async ({+ page,+ }) => {+ const viewport = await openCalendar(page, 'mouse', 'no-preference');+ const before = await viewport.evaluate(element => element.scrollLeft);+ const offsets = await viewport.evaluate(+ async element =>+ new Promise<number[]>(resolve => {+ const seen: number[] = [];+ const t0 = performance.now();+ const tick = () => {+ seen.push(element.scrollLeft);+ if (performance.now() - t0 < 800) {+ requestAnimationFrame(tick);+ } else {+ resolve(seen);+ }+ };+ requestAnimationFrame(tick);+ (+ document.querySelector(+ 'button[aria-label="Next month"]',+ ) as HTMLButtonElement+ ).click();+ }),+ );+ // Today's smooth scroll travels: at least one frame shows the scroller+ // between the two months. This counts positions, not frames. In WebKit's CI+ // container each frame of this scroll takes 67 to 83 ms. So its 220 to 258+ // ms show two or three frames in between, and a slower frame leaves two.+ const end = offsets[offsets.length - 1];+ expect(end).not.toBe(before);+ expect(+ offsets.filter(+ left => Math.min(before, end) < left && left < Math.max(before, end),+ ),+ `the offsets each frame showed: ${offsets.join(', ')}`,+ ).not.toHaveLength(0);+ });++ test('under Reduced Motion an arrow changes the month at once', async ({+ page,+ }) => {+ const viewport = await openCalendar(page, 'mouse');+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ const before = await viewport.evaluate(element => element.scrollLeft);+ await page.getByRole('button', {name: 'Next month'}).click();+ // design:reduced-motion DR3: immediate, no animated property.+ const after = await viewport.evaluate(element => element.scrollLeft);+ expect(after).not.toBe(before);+ expect(+ await viewport.evaluate(element => element.getAnimations().length),+ ).toBe(0);+ // And it stays: the scroller does not move on by itself afterwards.+ const offsets = await viewport.evaluate(+ async element =>+ new Promise<number[]>(resolve => {+ const seen: number[] = [];+ const t0 = performance.now();+ const tick = () => {+ seen.push(element.scrollLeft);+ if (performance.now() - t0 < 500) {+ requestAnimationFrame(tick);+ } else {+ resolve(seen);+ }+ };+ requestAnimationFrame(tick);+ }),+ );+ expect(new Set(offsets)).toEqual(new Set([after]));+ });+});++/**+ * Records, as each is created, the animations made on `target`: what each+ * animates, its keyframes' opacity, and its duration in ms. Read at creation, a+ * dip is read on a loaded machine too. There, frames come too far apart to show+ * a 200 ms dip's darkest frame.+ */+async function recordCreatedRuns(target: Locator): Promise<void> {+ await target.evaluate(element => {+ const runs: CreatedRun[] = [];+ (window as unknown as {createdRuns: CreatedRun[]}).createdRuns = runs;+ const original = Element.prototype.animate;+ Element.prototype.animate = function (+ this: Element,+ ...args: Parameters<Element['animate']>+ ) {+ const animation = original.apply(this, args);+ if (this === element) {+ const effect = animation.effect as KeyframeEffect;+ const frames = effect.getKeyframes();+ runs.push({+ properties: [+ ...new Set(+ frames.flatMap(frame =>+ Object.keys(frame).filter(+ key =>+ ![+ 'offset',+ 'easing',+ 'composite',+ 'computedOffset',+ ].includes(key),+ ),+ ),+ ),+ ],+ opacities: frames.map(frame => Number(frame.opacity)),+ duration: Number(effect.getTiming().duration),+ });+ }+ return animation;+ };+ });+}++type CreatedRun = {properties: string[]; opacities: number[]; duration: number};++test('on a touch screen, under Reduced Motion an arrow dips the calendar and changes the month without travel', async ({+ page,+}) => {+ const viewport = await openCalendar(page, 'touch');+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(true);+ // The dip is read as it is created; the page's frames record where the+ // scroller stands, from the tap until the dip is over.+ await recordCreatedRuns(viewport);+ await viewport.evaluate(element => {+ const w = window as unknown as {offsets: number[]; offsetsDone?: boolean};+ w.offsets = [];+ const tick = () => {+ w.offsets.push(element.scrollLeft);+ if (w.offsetsDone !== true) {+ requestAnimationFrame(tick);+ }+ };+ requestAnimationFrame(tick);+ });+ const before = await viewport.evaluate(element => element.scrollLeft);+ await page.getByRole('button', {name: 'Next month'}).tap();+ await expect+ .poll(async () =>+ page.evaluate(+ () =>+ (window as unknown as {createdRuns: CreatedRun[]}).createdRuns.length,+ ),+ )+ .toBeGreaterThan(0);+ // The dip is over, however long a loaded machine takes to end it.+ await expect+ .poll(async () =>+ viewport.evaluate(element => element.getAnimations().length),+ )+ .toBe(0);+ // design:reduced-motion DR2: one opacity dip, dark at its middle and back+ // at its end, in at most the cross-fade's 200 ms.+ const runs = await page.evaluate(+ () => (window as unknown as {createdRuns: CreatedRun[]}).createdRuns,+ );+ expect(runs).toHaveLength(1);+ const [dip] = runs;+ expect(dip.properties).toEqual(['opacity']);+ expect(dip.opacities[0]).toBe(1);+ expect(dip.opacities[dip.opacities.length - 1]).toBe(1);+ expect(Math.min(...dip.opacities)).toBeLessThan(0.5);+ expect(dip.duration).toBeLessThanOrEqual(200);+ // The month changes with no travel: one jump from the old offset to the+ // new one, and the scroller stays there.+ const after = await viewport.evaluate(element => element.scrollLeft);+ expect(after).not.toBe(before);+ const offsets = await page.evaluate(() => {+ const w = window as unknown as {offsets: number[]; offsetsDone?: boolean};+ w.offsetsDone = true;+ return w.offsets;+ });+ expect(+ offsets.every(left => left === before || left === after),+ `the offsets each frame showed: ${offsets.join(', ')}`,+ ).toBe(true);+ expect(+ await viewport.evaluate(element =>+ Number(getComputedStyle(element).opacity),+ ),+ ).toBe(1);+});