Skip to content

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

TypeScript

fix(DateInput): a Reduce Motion step lands under its cross-fade, on the fade's own timeline (#9734)

Christopher Chedeau273ec43565da
diff --git a/.changeset/reduce-motion-step-lands-on-dip.md b/.changeset/reduce-motion-step-lands-on-dip.md
new file mode 100644
index 0000000000..a9834563fa
--- /dev/null
+++ b/.changeset/reduce-motion-step-lands-on-dip.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Under Reduce Motion on a touch screen, a step on a DateInput, TimeInput or DateTimeInput wheel, and a month step in the touch calendar, change under their cross-fade even on a busy page. Before, the change landed on a timer at the fade's middle, and a busy page could fire it after the fade had ended, so the rows or the month moved fully visible. Now the change lands when the fade-out ends, on the fade's own timeline, and the fade-in starts only after it, so it never shows at full opacity. The month's dip now eases each half, as the wheels' does.
+
+@vjeux
diff --git a/packages/core/src/DateInput/MonthScroller.test.tsx b/packages/core/src/DateInput/MonthScroller.test.tsx
index 581f01be53..0eba41d572 100644
--- a/packages/core/src/DateInput/MonthScroller.test.tsx
+++ b/packages/core/src/DateInput/MonthScroller.test.tsx
@@ -3,6 +3,10 @@
import {act, render} from '@testing-library/react';
import {createRef} from 'react';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {
+ fakeAnimate,
+ type FakeAnimation,
+} from '../motion/__tests__/fakeWebAnimation';
import {MonthScroller, type MonthScrollerHandle} from './MonthScroller';
/**
@@ -35,6 +39,12 @@ class FakeResizeObserver {
describe('MonthScroller under Reduced Motion on a touch screen', () => {
const scrollTo = vi.fn();
+ // The dips' animations, in order. A fade-out ends only when a test ends it.
+ let animations: FakeAnimation[] = [];
+ /** The newest dip's fade-out ends: its step lands. */
+ async function endFadeOut() {
+ await act(async () => animations[animations.length - 1].finish());
+ }
beforeEach(() => {
vi.useFakeTimers();
stubReducedMotionTouch();
@@ -42,10 +52,11 @@ describe('MonthScroller under Reduced Motion on a touch screen', () => {
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();
+ const fake = fakeAnimate();
+ Element.prototype.animate = fake.animate;
+ animations = fake.animations;
+ // mockReset, not mockClear: a test's implementation must not outlive it.
+ scrollTo.mockReset();
});
afterEach(() => {
vi.useRealTimers();
@@ -75,51 +86,78 @@ describe('MonthScroller under Reduced Motion on a touch screen', () => {
return {handleRef, ...view};
}
- it('lets a second step within the dip replace the first: only its scroll lands', () => {
+ it('lets a second step within the dip replace the first: only its scroll lands', async () => {
const {handleRef} = renderScroller();
act(() => handleRef.current?.scrollToMonth(10));
- act(() => {
- vi.advanceTimersByTime(40);
- });
+ const first = animations[0];
act(() => handleRef.current?.scrollToMonth(11));
- act(() => {
- vi.advanceTimersByTime(400);
- });
+ expect(first.cancel).toHaveBeenCalled();
+ // The replaced dip's fade-out ending lands nothing.
+ await act(async () => first.finish());
+ expect(scrollTo).not.toHaveBeenCalled();
+ await endFadeOut();
expect(scrollTo).toHaveBeenCalledTimes(1);
});
- it('keeps a jump to a distant month made within the dip: the dip does not land after it', () => {
+ it('lands a step to another month before its fade-in starts', async () => {
+ // The fade-in starts as soon as the landing returns. A month that only
+ // scheduled its scroll then would change fully visible on a busy page.
+ const {handleRef} = renderScroller();
+ const order: string[] = [];
+ scrollTo.mockImplementation(() => {
+ order.push('scroll');
+ });
+ const fake = fakeAnimate();
+ Element.prototype.animate = function (
+ this: Element,
+ ...args: Parameters<Element['animate']>
+ ) {
+ order.push('animate');
+ return fake.animate.apply(this, args);
+ };
+ act(() => handleRef.current?.scrollToMonth(10));
+ expect(order).toEqual(['animate']);
+ await act(async () => fake.animations[0].finish());
+ expect(order).toEqual(['animate', 'scroll', 'animate']);
+ });
+
+ it('lands a step only when its 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 month would change fully visible.
const {handleRef} = renderScroller();
act(() => handleRef.current?.scrollToMonth(10));
act(() => {
- vi.advanceTimersByTime(40);
+ vi.advanceTimersByTime(10_000);
});
+ expect(scrollTo).not.toHaveBeenCalled();
+ await endFadeOut();
+ expect(scrollTo).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps a jump to a distant month made within the dip: the dip does not land after it', async () => {
+ const {handleRef} = renderScroller();
+ act(() => handleRef.current?.scrollToMonth(10));
+ const dip = animations[0];
// Eleven months on: beyond the mounted window, so it jumps at once.
act(() => handleRef.current?.scrollToMonth(20));
- act(() => {
- vi.advanceTimersByTime(400);
- });
+ await act(async () => dip.finish());
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', () => {
+ it('keeps a step at once made within the dip: the dip does not land after it', async () => {
const {handleRef} = renderScroller();
act(() => handleRef.current?.scrollToMonth(10));
- act(() => {
- vi.advanceTimersByTime(40);
- });
+ const dip = animations[0];
act(() => handleRef.current?.scrollToMonth(8, 'auto'));
- act(() => {
- vi.advanceTimersByTime(400);
- });
+ await act(async () => dip.finish());
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', () => {
+ it('reports a trackpad scroll after a step lands, even with an earlier steer that never arrived', async () => {
const onVisibleMonthChange = vi.fn();
const {handleRef, container} = renderScroller({onVisibleMonthChange});
const scroller = container.querySelector<HTMLElement>(
@@ -133,9 +171,7 @@ describe('MonthScroller under Reduced Motion on a touch screen', () => {
act(() => handleRef.current?.scrollToMonth(9, 'auto'));
// A step lands at its dip's middle.
act(() => handleRef.current?.scrollToMonth(10));
- act(() => {
- vi.advanceTimersByTime(400);
- });
+ await endFadeOut();
// A trackpad scroll on to the next month: no touch ends the steer.
act(() => {
scroller.scrollLeft = 11 * 300;
@@ -145,13 +181,12 @@ describe('MonthScroller under Reduced Motion on a touch screen', () => {
expect(onVisibleMonthChange).toHaveBeenLastCalledWith(11);
});
- it('scrolls nothing once unmounted within the dip', () => {
+ it('scrolls nothing once unmounted within the dip', async () => {
const {handleRef, unmount} = renderScroller();
act(() => handleRef.current?.scrollToMonth(10));
unmount();
- act(() => {
- vi.advanceTimersByTime(400);
- });
+ expect(animations[0].cancel).toHaveBeenCalled();
+ await endFadeOut();
expect(scrollTo).not.toHaveBeenCalled();
});
});
diff --git a/packages/core/src/DateInput/MonthScroller.tsx b/packages/core/src/DateInput/MonthScroller.tsx
index 95c10802de..38b086ff71 100644
--- a/packages/core/src/DateInput/MonthScroller.tsx
+++ b/packages/core/src/DateInput/MonthScroller.tsx
@@ -38,6 +38,7 @@ import {
useRef,
useState,
} from 'react';
+import {flushSync} from 'react-dom';
import * as stylex from '@stylexjs/stylex';
import {useCalendarDays} from '../Calendar';
import {useDirection, useLocale} from '../i18n';
@@ -62,7 +63,11 @@ import {
plainDateToISO,
DATE_FORMAT_WITH_WEEKDAY,
} from '../utils';
-import {reducedMotionFade} from '../motion/reducedMotion';
+import {
+ playReducedMotionDip,
+ reducedMotionFade,
+ type ReducedMotionDip,
+} from '../motion/reducedMotion';
import {dateInputTouchSizes, dateInputTouchGeometry} from './tokens.stylex';
import {useOwnScrollGesture} from './useOwnScrollGesture';
import {useScrollSettle} from './useScrollSettle';
@@ -434,17 +439,12 @@ export function MonthScroller({
// 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 dipRef = useRef<ReducedMotionDip | null>(null);
const stopDip = useCallback(() => {
- const dip = dipRef.current;
- if (dip != null) {
- window.clearTimeout(dip.timer);
- dip.animation.cancel();
- dipRef.current = null;
- }
+ dipRef.current?.cancel();
+ dipRef.current = null;
}, []);
- // Synchronizes with the dip's timer and animation: neither outlives the
- // scroller.
+ // Synchronizes with the dip's animations: they do not outlive the scroller.
useEffect(() => stopDip, [stopDip]);
const scrollToMonth = useCallback(
@@ -505,18 +505,14 @@ export function MonthScroller({
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),
- };
+ // A newer step replaces this one: only its scroll lands.
+ dipRef.current = playReducedMotionDip(scroller, fade, () => {
+ dipRef.current = null;
+ // The fade-in starts as soon as this returns. So render now: the
+ // scroll lands in the layout effect, before the fade-in.
+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the month must change before the dip's fade-in starts
+ flushSync(land);
+ });
return;
}
steeredRowRef.current = row;
diff --git a/packages/core/src/DateInput/Wheel.test.tsx b/packages/core/src/DateInput/Wheel.test.tsx
index ba75cac259..130c9f0d36 100644
--- a/packages/core/src/DateInput/Wheel.test.tsx
+++ b/packages/core/src/DateInput/Wheel.test.tsx
@@ -11,6 +11,7 @@
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 {SCROLL_QUIET_MS} from './useScrollSettle';
@@ -76,7 +77,7 @@ describe('Wheel — where it comes to rest', () => {
});
const onChange = vi.fn();
const scrollTo = vi.fn();
- const {rerender} = render(
+ const {rerender, unmount} = render(
<Wheel label="Hour" options={HOURS} value={value} onChange={onChange} />,
);
const scroller = screen.getByRole('listbox', {name: 'Hour'});
@@ -106,7 +107,7 @@ describe('Wheel — where it comes to rest', () => {
scroller.dispatchEvent(new Event('scrollend'));
});
};
- return {onChange, scrollTo, moveTo, stopOn, rerender};
+ return {onChange, scrollTo, moveTo, stopOn, rerender, unmount};
}
it('commits an enabled row it stops on', () => {
@@ -213,34 +214,59 @@ describe('Wheel — where it comes to rest', () => {
);
});
- it('cross-fades onto it on a touch screen: opacity only, 200 ms', () => {
+ it('cross-fades onto it on a touch screen: opacity only, 200 ms', async () => {
stubReducedMotion('coarse');
- vi.useFakeTimers();
const {scrollTo, stopOn} = renderWheel(10);
const scroller = screen.getByRole('listbox', {name: 'Hour'});
- const animate = vi.fn();
- scroller.animate = animate as HTMLElement['animate'];
+ const {animate, animations} = fakeAnimate();
+ scroller.animate = animate;
stopOn(7);
- expect(animate).toHaveBeenCalledTimes(1);
- const [keyframes, timing] = animate.mock.calls[0];
- // Out and back in, opacity alone.
- expect((keyframes as Keyframe[]).map(frame => frame.opacity)).toEqual([
- 1, 0, 1,
+ // Out, then back in after the rows land: opacity alone.
+ expect(animations).toHaveLength(1);
+ expect(animations[0].keyframes.map(frame => frame.opacity)).toEqual([
+ 1, 0,
]);
- for (const frame of keyframes as Keyframe[]) {
- expect(
- Object.keys(frame).filter(
- key => key !== 'offset' && key !== 'easing',
- ),
- ).toEqual(['opacity']);
- }
- expect(timing.duration).toBeLessThanOrEqual(200);
- // The rows land at the dip's midpoint, with no travel.
expect(scrollTo).not.toHaveBeenCalled();
+ await act(async () => animations[0].finish());
+ // The rows land at the dip's midpoint, with no travel.
+ expect(scrollTo).toHaveBeenCalledWith({top: 9 * ROW, behavior: 'auto'});
+ expect(animations).toHaveLength(2);
+ expect(animations[1].keyframes.map(frame => frame.opacity)).toEqual([
+ 0, 1,
+ ]);
+ for (const {keyframes} of animations) {
+ for (const frame of keyframes) {
+ expect(
+ Object.keys(frame).filter(
+ key => key !== 'offset' && key !== 'easing',
+ ),
+ ).toEqual(['opacity']);
+ }
+ }
+ const total = animations.reduce(
+ (sum, {options}) => sum + Number(options.duration),
+ 0,
+ );
+ expect(total).toBeLessThanOrEqual(200);
+ });
+
+ 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');
+ vi.useFakeTimers();
+ const {scrollTo, stopOn} = renderWheel(10);
+ const scroller = screen.getByRole('listbox', {name: 'Hour'});
+ const {animate, animations} = fakeAnimate();
+ scroller.animate = animate;
+ stopOn(7);
act(() => {
- vi.advanceTimersByTime(timing.duration / 2);
+ vi.advanceTimersByTime(10_000);
});
- expect(scrollTo).toHaveBeenCalledWith({top: 9 * ROW, behavior: 'auto'});
+ expect(scrollTo).not.toHaveBeenCalled();
+ expect(animations).toHaveLength(1);
+ await act(async () => animations[0].finish());
+ expect(scrollTo.mock.calls).toEqual([[{top: 9 * ROW, behavior: 'auto'}]]);
});
it('steps with the arrow keys at once with a keyboard', () => {
@@ -268,13 +294,12 @@ describe('Wheel — where it comes to rest', () => {
});
}
- it('lands an arrow key step on a touch screen under its cross-fade, not before', () => {
+ it('lands an arrow key step on a touch screen under its cross-fade, not before', async () => {
stubReducedMotion('coarse');
- vi.useFakeTimers();
const {onChange, scrollTo, rerender} = renderWheel(10);
const scroller = screen.getByRole('listbox', {name: 'Hour'});
- const animate = vi.fn();
- scroller.animate = animate as HTMLElement['animate'];
+ const {animate, animations} = fakeAnimate();
+ scroller.animate = animate;
pressArrowDown();
expect(onChange).toHaveBeenCalledWith(11);
// The parent takes the step. The new value must not move the rows
@@ -282,42 +307,50 @@ describe('Wheel — where it comes to rest', () => {
rerender(
<Wheel label="Hour" options={HOURS} value={11} onChange={onChange} />,
);
- expect(animate).toHaveBeenCalledTimes(1);
+ expect(animations).toHaveLength(1);
expect(scrollTo).not.toHaveBeenCalled();
- const [, timing] = animate.mock.calls[0];
- act(() => {
- vi.advanceTimersByTime(timing.duration / 2);
- });
+ await act(async () => animations[0].finish());
expect(scrollTo.mock.calls).toEqual([
[{top: 11 * ROW, behavior: 'auto'}],
]);
});
- it('starts a second step’s dip where the first one’s fade-in has the column', () => {
+ 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.
stubReducedMotion('coarse');
- vi.useFakeTimers();
renderWheel(10);
const scroller = screen.getByRole('listbox', {name: 'Hour'});
- const animate = vi.fn();
- scroller.animate = animate as HTMLElement['animate'];
+ const {animate, animations} = fakeAnimate();
+ scroller.animate = animate;
pressArrowDown();
- const [first, timing] = animate.mock.calls[0];
- expect((first as Keyframe[])[0].opacity).toBe(1);
- // Past the midpoint: the rows have landed and the column fades back in.
- act(() => {
- vi.advanceTimersByTime(timing.duration / 2 + 40);
- });
+ expect(animations[0].keyframes[0].opacity).toBe(1);
+ // The rows have landed, and the column fades back in.
+ await act(async () => animations[0].finish());
+ expect(animations).toHaveLength(2);
scroller.style.opacity = '0.5';
pressArrowDown();
- expect(animate).toHaveBeenCalledTimes(2);
- const [second] = animate.mock.calls[1];
- expect((second as Keyframe[]).map(frame => frame.opacity)).toEqual([
- 0.5, 0, 1,
+ expect(animations).toHaveLength(3);
+ // The fade-in stops, and the next fade-out starts where it was.
+ expect(animations[1].cancel).toHaveBeenCalled();
+ expect(animations[2].keyframes.map(frame => frame.opacity)).toEqual([
+ 0.5, 0,
]);
});
+ it('lands nothing once unmounted within the fade-out', async () => {
+ stubReducedMotion('coarse');
+ const {scrollTo, stopOn, unmount} = renderWheel(10);
+ const scroller = screen.getByRole('listbox', {name: 'Hour'});
+ const {animate, animations} = fakeAnimate();
+ scroller.animate = animate;
+ stopOn(7);
+ unmount();
+ expect(animations[0].cancel).toHaveBeenCalled();
+ await act(async () => animations[0].finish());
+ expect(scrollTo).not.toHaveBeenCalled();
+ });
+
it('changes at once after an earlier touch on a fine pointer, for a key or a tap', () => {
// This is a laptop's touch screen: its primary pointer is fine. Only a
// touch drag's release fades. A key step or a row tap lands at once.
@@ -341,20 +374,17 @@ describe('Wheel — where it comes to rest', () => {
expect(animate).not.toHaveBeenCalled();
});
- it('cross-fades the travel after a touch drag on a fine pointer', () => {
+ it('cross-fades the travel after a touch drag on a fine pointer', async () => {
stubReducedMotion('fine');
- vi.useFakeTimers();
const {scrollTo, stopOn} = renderWheel(10);
const scroller = screen.getByRole('listbox', {name: 'Hour'});
- const animate = vi.fn();
- scroller.animate = animate as HTMLElement['animate'];
+ const {animate, animations} = fakeAnimate();
+ scroller.animate = animate;
fireEvent.pointerDown(scroller, {pointerType: 'touch'});
stopOn(7);
- expect(animate).toHaveBeenCalledTimes(1);
+ expect(animations).toHaveLength(1);
expect(scrollTo).not.toHaveBeenCalled();
- act(() => {
- vi.advanceTimersByTime(animate.mock.calls[0][1].duration / 2);
- });
+ await act(async () => animations[0].finish());
expect(scrollTo).toHaveBeenCalledWith({top: 9 * ROW, behavior: 'auto'});
});
diff --git a/packages/core/src/DateInput/Wheel.tsx b/packages/core/src/DateInput/Wheel.tsx
index ee99b403c6..2fafc9ba63 100644
--- a/packages/core/src/DateInput/Wheel.tsx
+++ b/packages/core/src/DateInput/Wheel.tsx
@@ -49,7 +49,11 @@ import {
durationVars,
} from '../theme/tokens.stylex';
import {focusOutlineStyles} from '../utils';
-import {reducedMotionFade} from '../motion/reducedMotion';
+import {
+ playReducedMotionDip,
+ reducedMotionFade,
+ type ReducedMotionDip,
+} from '../motion/reducedMotion';
import {dateInputTouchSizes, dateInputTouchGeometry} from './tokens.stylex';
import {useOwnScrollGesture} from './useOwnScrollGesture';
import {usePointerDragScroll} from './usePointerDragScroll';
@@ -331,19 +335,19 @@ export function Wheel({
// once on a fine one.
const lastPointerRef = useRef<string | null>(null);
- // A reduced-motion dip whose rows have not landed yet: its timer and the
- // row it lands on. While one is pending the rows stay put for it, so they
- // never move at full opacity, and a further step retargets it.
- const pendingFadeRef = useRef<{timer: number; top: 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.
+ const pendingFadeRef = useRef<{top: number} | null>(null);
// The running dip, so a step during its fade-in starts the next one where
// the column is.
- const dipRef = useRef<Animation | null>(null);
+ const dipRef = useRef<ReducedMotionDip | null>(null);
+ // Synchronizes with the dip's animations: an unmounted wheel lands nothing.
useEffect(
() => () => {
- if (pendingFadeRef.current != null) {
- window.clearTimeout(pendingFadeRef.current.timer);
- pendingFadeRef.current = null;
- }
+ pendingFadeRef.current = null;
+ dipRef.current?.cancel();
+ dipRef.current = null;
},
[],
);
@@ -368,19 +372,15 @@ export function Wheel({
? reducedMotionFade(scroller, {touchRelease})
: null;
const pending = pendingFadeRef.current;
+ // A change that lands now replaces a pending landing. Its dip goes on
+ // and fades back in.
if (fadeTiming == null) {
- if (pending != null) {
- window.clearTimeout(pending.timer);
- pendingFadeRef.current = null;
- }
+ pendingFadeRef.current = null;
scroller.scrollTo({top, behavior});
return;
}
if (fadeTiming.duration === 0 || typeof scroller.animate !== 'function') {
- if (pending != null) {
- window.clearTimeout(pending.timer);
- pendingFadeRef.current = null;
- }
+ pendingFadeRef.current = null;
scroller.scrollTo({top, behavior: 'auto'});
return;
}
@@ -389,26 +389,24 @@ export function Wheel({
pending.top = top;
return;
}
- const {duration, easing} = fadeTiming;
// A step during the last dip's fade-in starts the new dip at the
// column's current opacity, not at full opacity. A leaving element fades
// out from where it is.
const shown = Number.parseFloat(getComputedStyle(scroller).opacity);
dipRef.current?.cancel();
- dipRef.current = scroller.animate(
- [
- {opacity: Number.isFinite(shown) ? shown : 1, easing},
- {opacity: 0, easing},
- {opacity: 1},
- ],
- {duration, easing: 'linear'},
- );
- const landing = {top, timer: 0};
- landing.timer = window.setTimeout(() => {
- pendingFadeRef.current = null;
- scroller.scrollTo({top: landing.top, behavior: 'auto'});
- }, duration / 2);
+ const landing = {top};
pendingFadeRef.current = landing;
+ dipRef.current = playReducedMotionDip(
+ scroller,
+ fadeTiming,
+ () => {
+ if (pendingFadeRef.current === landing) {
+ pendingFadeRef.current = null;
+ scroller.scrollTo({top: landing.top, behavior: 'auto'});
+ }
+ },
+ Number.isFinite(shown) ? shown : 1,
+ );
},
[itemBlockSize],
);
diff --git a/packages/core/src/DateInput/__tests__/MonthScroller.interaction.browser.spec.ts b/packages/core/src/DateInput/__tests__/MonthScroller.interaction.browser.spec.ts
index ad4dd70f7f..1e4c39b4e7 100644
--- a/packages/core/src/DateInput/__tests__/MonthScroller.interaction.browser.spec.ts
+++ b/packages/core/src/DateInput/__tests__/MonthScroller.interaction.browser.spec.ts
@@ -229,17 +229,18 @@ test('on a touch screen, under Reduced Motion an arrow dips the calendar and cha
)
.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.
+ // at its end, in at most the cross-fade's 200 ms. It plays as two halves,
+ // so the month changes between them.
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);
+ expect(runs).toHaveLength(2);
+ const [fadeOut, fadeIn] = runs;
+ expect(fadeOut.properties).toEqual(['opacity']);
+ expect(fadeIn.properties).toEqual(['opacity']);
+ expect(fadeOut.opacities).toEqual([1, 0]);
+ expect(fadeIn.opacities).toEqual([0, 1]);
+ expect(fadeOut.duration + fadeIn.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);
diff --git a/packages/core/src/DateInput/__tests__/WheelRest.a11y.chromium.spec.ts b/packages/core/src/DateInput/__tests__/WheelRest.a11y.chromium.spec.ts
index eeb9110d74..688da07a7a 100644
--- a/packages/core/src/DateInput/__tests__/WheelRest.a11y.chromium.spec.ts
+++ b/packages/core/src/DateInput/__tests__/WheelRest.a11y.chromium.spec.ts
@@ -118,6 +118,12 @@ function expectAnimatedTurn(
expect(between.length, record).toBeGreaterThan(0);
}
+/** A frame the page drew: where the rows sit in the column, and its opacity. */
+interface RowFrame {
+ at: number;
+ opacity: number;
+}
+
const selectedHour = (hours: Locator) =>
hours.locator('[role="option"][aria-selected="true"]');
@@ -164,38 +170,54 @@ test('under reduced motion an arrow key step lands under its cross-fade, never a
await page.emulateMedia({reducedMotion: 'reduce'});
const {field, hours} = await openHourWheel(page);
await hours.focus();
- // Record every frame from before the key until well after the 200 ms dip.
- // 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.
- const frames = hours.evaluate(
- async column =>
- new Promise<{at: number; opacity: number}[]>(resolve => {
- const seen: {at: number; opacity: number}[] = [];
- const sample = () => {
- const strip = column.querySelector<HTMLElement>('[data-wheel-strip]');
- const rows =
- strip ?? column.querySelector<HTMLElement>('[role="option"]');
- const faded = strip?.parentElement ?? column;
- seen.push({
- at: Math.round(
- (rows?.getBoundingClientRect().top ?? 0) -
- column.getBoundingClientRect().top,
- ),
- opacity: Number(getComputedStyle(faded).opacity),
- });
- if (seen.length < 45) {
- requestAnimationFrame(sample);
- } else {
- resolve(seen);
- }
- };
+ // 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.
+ await hours.evaluate(column => {
+ const recorder = {seen: [] as RowFrame[], isDone: false};
+ (window as unknown as {stepFrames: typeof recorder}).stepFrames = recorder;
+ 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) -
+ column.getBoundingClientRect().top,
+ ),
+ opacity: Number(getComputedStyle(faded).opacity),
+ });
+ if (!recorder.isDone) {
requestAnimationFrame(sample);
- }),
- );
+ }
+ };
+ requestAnimationFrame(sample);
+ });
await sleep(50);
await page.keyboard.press('ArrowDown');
- const seen = await frames;
+ await expect(selectedHour(hours)).toHaveText('11');
+ await expect(field).toHaveValue('11:00 AM');
+ // The record ends on a drawn frame with the rows moved and the column fully
+ // visible again. A loaded page may draw only a few frames before it.
+ await expect
+ .poll(async () =>
+ page.evaluate(() => {
+ const {seen} = (window as unknown as {stepFrames: {seen: RowFrame[]}})
+ .stepFrames;
+ const last = seen.at(-1);
+ return last != null && last.at !== seen[0].at && last.opacity === 1;
+ }),
+ )
+ .toBe(true);
+ const seen = await page.evaluate(() => {
+ const recorder = (
+ window as unknown as {stepFrames: {seen: RowFrame[]; isDone: boolean}}
+ ).stepFrames;
+ recorder.isDone = true;
+ return recorder.seen;
+ });
// The rows never move while they are fully visible: they land under the
// dip (design:reduced-motion DR2), then fade back in on 11.
@@ -203,9 +225,6 @@ test('under reduced motion an arrow key step lands under its cross-fade, never a
const moved = seen.find(frame => frame.at !== start);
expect(moved, JSON.stringify(seen)).toBeDefined();
expect(moved?.opacity, JSON.stringify(seen)).toBeLessThan(1);
- expect(seen.at(-1)?.opacity).toBe(1);
- await expect(selectedHour(hours)).toHaveText('11');
- await expect(field).toHaveValue('11:00 AM');
});
test('a meridiem change past the maximum turns the hour wheel onto it, frame by frame (component:DateInput FR14)', async ({
diff --git a/packages/core/src/motion/__tests__/fakeWebAnimation.ts b/packages/core/src/motion/__tests__/fakeWebAnimation.ts
new file mode 100644
index 0000000000..94a8376d9f
--- /dev/null
+++ b/packages/core/src/motion/__tests__/fakeWebAnimation.ts
@@ -0,0 +1,78 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file fakeWebAnimation.ts
+ * @input Nothing; a test utility
+ * @output fakeAnimate: an `Element.animate` stand-in whose animations finish
+ * only when a test finishes them
+ * @position Test helper for motion code that waits on an animation's
+ * `finished` (reducedMotion.ts' dip, and the wheels and month scroller that
+ * play it). jsdom has no Web Animations.
+ */
+
+import {vi} from 'vitest';
+
+/** One animation the stand-in started. */
+export interface FakeAnimation {
+ readonly keyframes: ReadonlyArray<Keyframe>;
+ readonly options: KeyframeAnimationOptions;
+ /** Settles `finished`, as the animation's own timeline would at its end. */
+ finish(): void;
+ readonly cancel: ReturnType<typeof vi.fn>;
+ /** The animation itself: its start time (ms), which a test or the code sets. */
+ readonly animation: {startTime: number | null};
+}
+
+/**
+ * An `Element.animate` stand-in. Each call records its keyframes and timing.
+ * Its `finished` settles only on `finish()`, and `cancel()` rejects it, as a
+ * browser does. No timer finishes it, so a test can hold an animation past
+ * any number of frames.
+ *
+ * @example
+ * ```
+ * const {animate, animations} = fakeAnimate();
+ * scroller.animate = animate;
+ * // …start a dip…
+ * await act(async () => animations[0].finish());
+ * ```
+ */
+export function fakeAnimate(): {
+ animate: Element['animate'];
+ animations: FakeAnimation[];
+} {
+ const animations: FakeAnimation[] = [];
+ const animate = vi.fn(
+ (
+ keyframes: Keyframe[] | PropertyIndexedKeyframes | null,
+ options?: number | KeyframeAnimationOptions,
+ ) => {
+ let resolve = () => {};
+ let reject = (_reason: unknown) => {};
+ const finished = new Promise<void>((onResolve, onReject) => {
+ resolve = onResolve;
+ reject = onReject;
+ });
+ // A cancelled animation's rejection is expected: keep it unreported.
+ finished.catch(() => {});
+ const cancel = vi.fn(() => {
+ reject(new DOMException('The animation was cancelled.', 'AbortError'));
+ });
+ const animation = {
+ finished,
+ cancel,
+ startTime: null as number | null,
+ };
+ animations.push({
+ keyframes: (keyframes ?? []) as Keyframe[],
+ options:
+ typeof options === 'number' ? {duration: options} : (options ?? {}),
+ finish: () => resolve(),
+ cancel,
+ animation,
+ });
+ return animation as unknown as Animation;
+ },
+ );
+ return {animate, animations};
+}
diff --git a/packages/core/src/motion/reducedMotion.test.ts b/packages/core/src/motion/reducedMotion.test.ts
index 465b8b9f41..b0dbb9a3ba 100644
--- a/packages/core/src/motion/reducedMotion.test.ts
+++ b/packages/core/src/motion/reducedMotion.test.ts
@@ -4,19 +4,21 @@
* @file reducedMotion.test.ts
* @input reducedMotion.ts, reducedMotion.stylex.ts, the timing table, and
* every StyleX source file in core
- * @output Proof that the Reduced Motion policy for code beside the animator
- * fades 200 ms at most on a coarse pointer or a touch release and completes
- * at once elsewhere, that its CSS constants match the table, and that every
- * StyleX key splitting Reduce Motion by pointer spells the two queries
+ * @output Proof of the Reduced Motion policy beside the animator. Its fade is
+ * 200 ms at most on a coarse pointer or touch release, else at once. Its dip
+ * lands a change on its own timeline. Its CSS constants match the table, and
+ * every StyleX key splitting Reduce Motion by pointer spells the two queries.
* @position Testing for /packages/core/src/motion/reducedMotion.ts
*/
import {readdirSync, readFileSync} from 'node:fs';
import {join, resolve} from 'node:path';
import {afterEach, describe, expect, it, vi} from 'vitest';
+import {fakeAnimate} from './__tests__/fakeWebAnimation';
import {
REDUCED_MOTION_FADE_QUERY,
REDUCED_MOTION_INSTANT_QUERY,
+ playReducedMotionDip,
reducedMotionFade,
} from './reducedMotion';
import {
@@ -67,6 +69,117 @@ describe('reducedMotionFade', () => {
});
});
+describe('playReducedMotionDip', () => {
+ const fade = {duration: 200, easing: 'cubic-bezier(0.42, 0, 0.58, 1)'};
+
+ function startDip(from?: number) {
+ const element = document.createElement('div');
+ const {animate, animations} = fakeAnimate();
+ element.animate = animate;
+ const land = vi.fn();
+ const dip = playReducedMotionDip(element, fade, land, from);
+ return {animations, land, dip};
+ }
+
+ it('fades out over half the fade, and holds at 0 until the change lands', () => {
+ const {animations} = startDip();
+ expect(animations).toHaveLength(1);
+ const [fadeOut] = animations;
+ expect(fadeOut.keyframes.map(frame => frame.opacity)).toEqual([1, 0]);
+ expect(fadeOut.keyframes[0].easing).toBe(fade.easing);
+ expect(fadeOut.options).toMatchObject({duration: 100, fill: 'forwards'});
+ });
+
+ it('lands the change when the fade-out ends, however late, and never on a timer', async () => {
+ vi.useFakeTimers();
+ try {
+ const {animations, land} = startDip();
+ // A main thread held far past the middle: no timer lands the change.
+ vi.advanceTimersByTime(10_000);
+ expect(land).not.toHaveBeenCalled();
+ animations[0].finish();
+ await Promise.resolve();
+ expect(land).toHaveBeenCalledOnce();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('fades back in only after the change, from 0, over the other half', async () => {
+ const {animations, land} = startDip();
+ land.mockImplementation(() => {
+ // The fade-in has not started while the change lands.
+ expect(animations).toHaveLength(1);
+ });
+ animations[0].finish();
+ await Promise.resolve();
+ expect(land).toHaveBeenCalledOnce();
+ expect(animations).toHaveLength(2);
+ const fadeIn = animations[1];
+ expect(fadeIn.keyframes.map(frame => frame.opacity)).toEqual([0, 1]);
+ expect(fadeIn.keyframes[0].easing).toBe(fade.easing);
+ expect(fadeIn.options).toMatchObject({duration: 100});
+ // The fade-in holds the opacity now, so the held 0 goes.
+ expect(animations[0].cancel).toHaveBeenCalled();
+ });
+
+ /** A dip whose fade-out started at 1000 ms, and the clock its landing reads. */
+ async function landAt(clockAfterLanding: number) {
+ const clock = vi.spyOn(performance, 'now').mockReturnValue(1100);
+ const element = document.createElement('div');
+ const {animate, animations} = fakeAnimate();
+ element.animate = animate;
+ // The landing's own work moves the clock.
+ playReducedMotionDip(element, fade, () => {
+ clock.mockReturnValue(clockAfterLanding);
+ });
+ animations[0].animation.startTime = 1000;
+ animations[0].finish();
+ await Promise.resolve();
+ clock.mockRestore();
+ return animations;
+ }
+
+ it('starts the fade-in where the fade-out ended, counting the landing', async () => {
+ // Due at 1100 ms; the landing ran until 1140 ms. The fade-in is 40 ms in.
+ const animations = await landAt(1140);
+ expect(animations[1].animation.startTime).toBe(1100);
+ });
+
+ it('starts an on-time fade-in on time, and after a long stall still plays half of it', async () => {
+ expect((await landAt(1100))[1].animation.startTime).toBe(1100);
+ const stalled = await landAt(1500);
+ expect(stalled[1].animation.startTime).toBe(1450);
+ // That start is after the frame that runs the landing: until then, the
+ // fade-in holds 0, so the change does not show.
+ expect(stalled[1].options).toMatchObject({fill: 'backwards'});
+ });
+
+ it('leaves a fade-in to start on its own when the fade-out has no start time', async () => {
+ const {animations} = startDip();
+ animations[0].finish();
+ await Promise.resolve();
+ expect(animations[1].animation.startTime).toBeNull();
+ });
+
+ it('starts the fade-out where the element is (DR2)', () => {
+ const {animations} = startDip(0.5);
+ expect(animations[0].keyframes.map(frame => frame.opacity)).toEqual([
+ 0.5, 0,
+ ]);
+ });
+
+ it('lands nothing once cancelled, and stops both fades', async () => {
+ const {animations, land, dip} = startDip();
+ dip.cancel();
+ expect(animations[0].cancel).toHaveBeenCalled();
+ animations[0].finish();
+ await Promise.resolve();
+ expect(land).not.toHaveBeenCalled();
+ expect(animations).toHaveLength(1);
+ });
+});
+
describe('the CSS side of the policy', () => {
it('holds the same fade as the table', () => {
expect(reducedMotionFadeConsts.duration).toBe(
diff --git a/packages/core/src/motion/reducedMotion.ts b/packages/core/src/motion/reducedMotion.ts
index 5c6dbdee90..32450a3281 100644
--- a/packages/core/src/motion/reducedMotion.ts
+++ b/packages/core/src/motion/reducedMotion.ts
@@ -4,7 +4,7 @@
* @file reducedMotion.ts
* @input The Reduced Motion preference, the primary pointer, the motion tables
* @output reducedMotionFade (the fade the animator would play, for motion it
- * does not drive) and the two media queries a StyleX transition spells
+ * does not drive), playReducedMotionDip, and the queries a transition spells
* @position The one Reduced Motion policy (design:reduced-motion) for code
* beside the animator: a raw Web Animations fade, a CSS transition
*
@@ -102,3 +102,81 @@ export function reducedMotionFade(
easing: `cubic-bezier(${curve.join(', ')})`,
};
}
+
+/** A running Reduced Motion dip. */
+export interface ReducedMotionDip {
+ /** Stops the dip. A change that has not landed yet never lands. */
+ cancel(): void;
+}
+
+/**
+ * Plays `fade` on `element` as a dip, and runs `land` at its middle: the
+ * fade-out, the change, then the fade-in. The fade-out holds at 0 until `land`
+ * has run, and the fade-in starts only after it. So the change never shows at
+ * full opacity, however late the main thread runs. A timer at the middle can
+ * fire after the fade-in has begun.
+ *
+ * `land` must apply the change before it returns: the fade-in starts right
+ * after it. `from` is the opacity the fade-out starts at: a leaving element
+ * fades out from where it is.
+ *
+ * @example
+ * ```
+ * const dip = playReducedMotionDip(scroller, fade, () => scroller.scrollTo({top}));
+ * // A newer change replaces it:
+ * dip.cancel();
+ * ```
+ */
+export function playReducedMotionDip(
+ element: Element,
+ fade: ReducedMotionFade,
+ land: () => void,
+ from = 1,
+): ReducedMotionDip {
+ const half = fade.duration / 2;
+ let isCancelled = false;
+ let fadeIn: Animation | null = null;
+ const fadeOut = element.animate(
+ [{opacity: from, easing: fade.easing}, {opacity: 0}],
+ {duration: half, fill: 'forwards'},
+ );
+ fadeOut.finished.then(
+ () => {
+ if (isCancelled) {
+ return;
+ }
+ land();
+ // The fade-in holds 0 until it starts: after a long stall, its start can
+ // come after the frame that runs this.
+ fadeIn = element.animate(
+ [{opacity: 0, easing: fade.easing}, {opacity: 1}],
+ {duration: half, fill: 'backwards'},
+ );
+ // The fade-in keeps the dip's own schedule: it starts where the fade-out
+ // ended, so the dip keeps its length. The clock is read after the
+ // landing, because a frame's timestamp does not count the landing's own
+ // work. After a long stall, half of the fade-in still plays.
+ const fadeOutEnd = endTime(fadeOut, half);
+ if (fadeOutEnd != null) {
+ fadeIn.startTime = Math.max(fadeOutEnd, performance.now() - half / 2);
+ }
+ // The fade-in now holds the opacity, so the held 0 can go.
+ fadeOut.cancel();
+ },
+ // A cancelled fade-out rejects `finished`: nothing lands.
+ () => {},
+ );
+ return {
+ cancel() {
+ isCancelled = true;
+ fadeOut.cancel();
+ fadeIn?.cancel();
+ },
+ };
+}
+
+/** When `animation` was due to end, on its timeline (ms), if it has started. */
+function endTime(animation: Animation, duration: number): number | null {
+ const start = animation.startTime;
+ return typeof start === 'number' ? start + duration : null;
+}