diff --git a/.changeset/refresh-control-reduced-motion-cross-fade.md b/.changeset/refresh-control-reduced-motion-cross-fade.md new file mode 100644 index 0000000000000..0e394ad58052a --- /dev/null +++ b/.changeset/refresh-control-reduced-motion-cross-fade.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] With Reduce Motion on a phone, Lab's RefreshControl cross-fades its list through a copy when a pull's release or a refresh's end moves it, instead of dipping it through blank. The copy covers content of up to 1,500 elements, the indicator band included, whose canvases all read back pixels; other content keeps the dip. The copy loads no media, so a row's video or iframe fades in, as do rows that scroll into view. The cross-fade comes from a new export of `internal/touch`; apps import nothing new. + +@vjeux diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json index 298c140942694..2db68db43d3ee 100644 --- a/apps/sandbox/scripts/next-export-routes.json +++ b/apps/sandbox/scripts/next-export-routes.json @@ -57,6 +57,7 @@ "/pages/perf-scenes/", "/pages/polymorphic-link/", "/pages/powersearch-phone/", + "/pages/refresh-control/", "/pages/scroll-edge-taps/", "/pages/shell-lab/", "/pages/showcase-components/", diff --git a/apps/sandbox/src/app/(raw)/pages/refresh-control/page.tsx b/apps/sandbox/src/app/(raw)/pages/refresh-control/page.tsx new file mode 100644 index 0000000000000..287aa95b0bae2 --- /dev/null +++ b/apps/sandbox/src/app/(raw)/pages/refresh-control/page.tsx @@ -0,0 +1,118 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file page.tsx + * @input Nothing + * @output A bare page with a RefreshControl list in a fixed-height card, + * above rows that make the document scroll. A pull past the trigger + * refreshes for 1.5 s: the list settles below the spinner, then returns to + * the top. + * @position A raw page, with no sandbox chrome, for checking a pull to refresh + * on a phone, with motion and under Reduce Motion. The page scrolls with + * the document. + */ + +import {useCallback, useState} from 'react'; +import * as stylex from '@stylexjs/stylex'; +import {REFRESH_REVEAL_VAR, useRefreshControl} from '@astryxdesign/lab'; +import {Card} from '@astryxdesign/core/Card'; +import {VStack} from '@astryxdesign/core/Layout'; +import {List, ListItem} from '@astryxdesign/core/List'; +import {Spinner} from '@astryxdesign/core/Spinner'; +import {Heading, Text} from '@astryxdesign/core/Text'; + +const REFRESH_MS = 1500; + +const LIST_ROWS = Array.from( + {length: 30}, + (_, index) => `Message ${index + 1}`, +); +const PAGE_ROWS = Array.from({length: 30}, (_, index) => `Row ${index + 1}`); + +const styles = stylex.create({ + scroller: {height: '100%', overflowY: 'auto'}, + content: {position: 'relative'}, + // The indicator's band sits above the content, inside a box that clips it. + band: { + position: 'absolute', + insetInline: 0, + bottom: '100%', + height: '100lvh', + overflow: 'hidden', + pointerEvents: 'none', + }, + indicator: { + position: 'absolute', + insetInline: 0, + bottom: 0, + height: 60, + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + }, + revealed: (opacity: string) => ({opacity}), +}); + +export default function RefreshControlPage() { + const [count, setCount] = useState(0); + const onRefresh = useCallback(async () => { + await new Promise(resolve => { + setTimeout(resolve, REFRESH_MS); + }); + setCount(value => value + 1); + }, []); + const control = useRefreshControl({onRefresh, announce: 'Refreshing'}); + return ( + + + Refresh control + + With the messages at the top, pull them down past the spinner and let + go. They wait below the spinner while the refresh runs, then go back + to the top. + + + {`Refreshed ${count} times`} + +
+
+ + {LIST_ROWS.map(row => ( + + ))} + +
+
+ + + +
+
+
+
+
+ + {PAGE_ROWS.map(row => ( + + {row} + + ))} + +
+ ); +} diff --git a/apps/sandbox/src/app/sandboxPages.ts b/apps/sandbox/src/app/sandboxPages.ts index 15319d2b6952c..01430589aba4f 100644 --- a/apps/sandbox/src/app/sandboxPages.ts +++ b/apps/sandbox/src/app/sandboxPages.ts @@ -111,6 +111,12 @@ export const categories: SandboxCategory[] = [ description: 'A DropdownMenu in a fixed top bar that opens as a finger presses it, and one in the content, on a page that scrolls with the document', }, + { + name: 'Refresh Control', + href: '/pages/refresh-control/', + description: + 'A RefreshControl list in a card on a page that scrolls with the document, to check a pull to refresh on a phone, also under Reduce Motion', + }, { name: 'BottomSheet Pull', href: '/pages/bottom-sheet-pull/', diff --git a/apps/storybook/stories/PullToRefresh.stories.tsx b/apps/storybook/stories/PullToRefresh.stories.tsx index 5ff4ed634a8fe..783c6a6da6363 100644 --- a/apps/storybook/stories/PullToRefresh.stories.tsx +++ b/apps/storybook/stories/PullToRefresh.stories.tsx @@ -1,6 +1,6 @@ // Copyright (c) Meta Platforms, Inc. and affiliates. -import {useCallback, useState, type ReactNode} from 'react'; +import {useCallback, useEffect, useState, type ReactNode} from 'react'; import type {Meta, StoryObj} from '@storybook/react'; import {REFRESH_REVEAL_VAR, useRefreshControl} from '@astryxdesign/lab'; import {Button} from '@astryxdesign/core/Button'; @@ -163,19 +163,31 @@ function useInbox(refreshMs: number) { /** * A list in the app's own scroll container. Pull it down past the top on a * touch screen, or with a trackpad's two-finger scroll. Past the trigger, the - * refresh starts with the finger down. + * refresh starts with the finger down. The page can dispatch + * `refreshcontrol-story-unmount` on `window` to unmount the list, so a test + * can unmount it in the middle of a change. */ export const InAScrollContainer: Story = { render: function InAScrollContainerStory({refreshMs, rows}) { const {count, onRefresh} = useInbox(refreshMs); + const [isMounted, setIsMounted] = useState(true); + useEffect(() => { + // Effect: subscribes to the page's window event that unmounts the list. + const unmount = () => setIsMounted(false); + window.addEventListener('refreshcontrol-story-unmount', unmount); + return () => + window.removeEventListener('refreshcontrol-story-unmount', unmount); + }, []); return (
- - - + {isMounted && ( + + + + )}
); }, diff --git a/docs/architecture/component-style-authoring.md b/docs/architecture/component-style-authoring.md index 829a55ba01a18..125c529ff86a6 100644 --- a/docs/architecture/component-style-authoring.md +++ b/docs/architecture/component-style-authoring.md @@ -147,8 +147,12 @@ not evidence of conformance or violation. handoff between sheets, such as the cross-fade `design:reduced-motion` DR2 requires; AppShell's old content wrap during a side nav collapse or expand (`component:AppShell` FR17); the SideNav rail's - old state during a collapse or expand (`component:SideNav` FR6); or one moving preview while a - reorderable item is dragged (`design:ordered-collection-reordering`); it is + old state during a collapse or expand (`component:SideNav` FR6); the old + place of content that a Reduce Motion cross-fade moves, fading out as the + content fades in at its new place, such as RefreshControl's list at a + release or a refresh's end (`design:reduced-motion` DR2); or one moving + preview while a reorderable item is dragged + (`design:ordered-collection-reordering`); it is made by one Core mechanism for its kind, rather than by each component, and is removed within 1 second of the transition ending. Until that shared mechanism exists, a layer's own exit, presentation-switch, or handoff copy, or a reorderable diff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.md index 8fe0703ecacda..f4d4a757c0d1d 100644 --- a/docs/architecture/react-component-runtime.md +++ b/docs/architecture/react-component-runtime.md @@ -380,7 +380,10 @@ those contracts, and one user-facing rule that no component owns: how a subpath too: it marks a group's member so press feedback leaves its press to the group's tracker. `prepareFocusReturnOnRemoval` is on that subpath too: it returns focus when - a removal loses it. + a removal loses it. `playReducedMotionCrossFade` is on that subpath too: + under Reduce Motion, it cross-fades an element through an inert copy, so the + element's area never goes blank. The animator and `motion/reducedMotion.ts` + give only a dip, which blanks the area between the old state and the new one. - **INV15 — The animator animates a number.** The animator has a value mode: it plays a number, such as a count or a chart value, on the same timing as its property channels: theme motion tokens for a program-started change, and measured springs only where `spec:AST-094` FR45 keeps them, and hands the value to an `onUpdate` callback each frame for the component to format and write. The component owns diff --git a/packages/core/src/internal/touch.test.ts b/packages/core/src/internal/touch.test.ts index db9de291e8e12..596bcdf9a554c 100644 --- a/packages/core/src/internal/touch.test.ts +++ b/packages/core/src/internal/touch.test.ts @@ -210,6 +210,16 @@ describe('internal/touch', () => { ); }); + it("re-exports by name the cross-fade Lab's RefreshControl plays", async () => { + const entry: Record = await import('./touch'); + const crossFade = await import('../motion/reducedMotionCrossFade'); + // Identity alone passes when both sides are undefined. + expect(typeof entry.playReducedMotionCrossFade).toBe('function'); + expect(entry.playReducedMotionCrossFade).toBe( + crossFade.playReducedMotionCrossFade, + ); + }); + it("re-exports by name the focus hand-off Lab's Comments reads", async () => { const entry: Record = await import('./touch'); const swap = await import('../utils/useFocusAcrossSwap'); diff --git a/packages/core/src/internal/touch.ts b/packages/core/src/internal/touch.ts index 8eddcc799869f..662de27e376e5 100644 --- a/packages/core/src/internal/touch.ts +++ b/packages/core/src/internal/touch.ts @@ -128,6 +128,11 @@ export type {ActionGroupTrackingOptions} from '../hooks/useActionGroupTracking'; // Lab's TabBar finds a panel's scroll area with Core's scroll test. export {measureLogicalScrollAxis} from '../hooks/scrollGeometry'; +// Lab's RefreshControl cross-fades its list through a copy under Reduce +// Motion, so the list shows on every frame. +export {playReducedMotionCrossFade} from '../motion/reducedMotionCrossFade'; +export type {ReducedMotionCrossFade} from '../motion/reducedMotionCrossFade'; + // Lab's Comments carries focus to the control that replaces a pressed one, // Mark as resolved and Reopen, with the same focus hand-off as Core. export {useFocusAcrossSwap} from '../utils/useFocusAcrossSwap'; diff --git a/packages/core/src/motion/animatedLayout.boundary.test.ts b/packages/core/src/motion/animatedLayout.boundary.test.ts index 4df883db29f5e..c8047a4f8a181 100644 --- a/packages/core/src/motion/animatedLayout.boundary.test.ts +++ b/packages/core/src/motion/animatedLayout.boundary.test.ts @@ -136,7 +136,7 @@ describe('architecture:react-component-runtime INV12 source boundary', () => { } }); - it("keeps the copy mechanism to the swap and the layer's exit copy", () => { + it("keeps the copy mechanism to the swap, the layer's exit copy and the Reduce Motion cross-fade", () => { const users = sourceFiles(coreSrc) .filter(path => /from '[./]+(motion\/)?transientCopy'/.test(readFileSync(path, 'utf8')), @@ -146,6 +146,7 @@ describe('architecture:react-component-runtime INV12 source boundary', () => { expect(users).toEqual([ 'Layer/layerExitCopy.ts', 'motion/animatedLayout.ts', + 'motion/reducedMotionCrossFade.ts', ]); }); diff --git a/packages/core/src/motion/reducedMotionCrossFade.test.ts b/packages/core/src/motion/reducedMotionCrossFade.test.ts new file mode 100644 index 0000000000000..7b50461b1d9d8 --- /dev/null +++ b/packages/core/src/motion/reducedMotionCrossFade.test.ts @@ -0,0 +1,240 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file reducedMotionCrossFade.test.ts + * @input reducedMotionCrossFade.ts, with fakeAnimate for Web Animations + * @output Proof of the cross-fade through a copy: the copy fades out where + * the element showed while the element lands and fades in, on one easing. + * The copy sits next to the clipping box and is clipped to its visible box, + * past the copy's own edges, with no layout read once the copy is laid. It + * goes once both fades end or on cancel. An element that cannot be copied + * gets null. + * @position Testing for /packages/core/src/motion/reducedMotionCrossFade.ts + */ + +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {fakeAnimate, type FakeAnimation} from './__tests__/fakeWebAnimation'; +import {ENTRANCE_OPACITY_FLOOR} from './opacityFloor'; +import {playReducedMotionCrossFade} from './reducedMotionCrossFade'; + +const fade = {duration: 200, easing: 'cubic-bezier(0.42, 0, 0.58, 1)'}; + +/** A DOMRect-like box: jsdom lays nothing out. */ +function box(left: number, top: number, width: number, height: number) { + return { + x: left, + y: top, + left, + top, + width, + height, + right: left + width, + bottom: top + height, + toJSON: () => ({}), + } as DOMRect; +} + +let animations: FakeAnimation[] = []; +const nativeAnimate = Element.prototype.animate; +/** The scroller's layout reads and the copy's placement, when a case logs them. */ +let layoutLog: string[] | null = null; + +beforeEach(() => { + const fake = fakeAnimate(); + animations = fake.animations; + // The copy is a clone: it reaches `animate` through the prototype. + Element.prototype.animate = fake.animate; +}); + +afterEach(() => { + Element.prototype.animate = nativeAnimate; + layoutLog = null; + document.body.replaceChildren(); +}); + +/** A scroller in a wrapper, holding a list moved 167 px down. */ +function list() { + const wrapper = document.createElement('div'); + const scroller = document.createElement('div'); + const content = document.createElement('div'); + content.textContent = 'Message 1'; + content.style.setProperty('translate', '0px 167px'); + scroller.append(content); + wrapper.append(scroller); + document.body.append(wrapper); + content.getBoundingClientRect = () => box(0, 167, 400, 900); + scroller.getBoundingClientRect = () => { + layoutLog?.push('read the scroller'); + return box(0, 0, 400, 600); + }; + for (const [name, value] of [ + ['clientTop', 0], + ['clientLeft', 0], + ['clientWidth', 400], + ['clientHeight', 600], + ] as const) { + Object.defineProperty(scroller, name, { + get: () => { + layoutLog?.push('read the scroller'); + return value; + }, + }); + } + return {wrapper, scroller, content}; +} + +/** The copy the cross-fade laid, if any. */ +const copyIn = (wrapper: Element) => + [...wrapper.children].find(child => child.hasAttribute('inert')) as + HTMLElement | undefined; + +describe('playReducedMotionCrossFade', () => { + it('lays a copy where the list shows, then lands the list and fades both on one easing', () => { + const {wrapper, scroller, content} = list(); + const land = vi.fn(() => { + // The copy already shows the old state when the change lands. + expect(copyIn(wrapper)).toBeDefined(); + content.style.setProperty('translate', '0px 60px'); + }); + const played = playReducedMotionCrossFade(content, fade, land, scroller); + expect(played).not.toBeNull(); + expect(land).toHaveBeenCalledOnce(); + const copy = copyIn(wrapper); + expect(copy?.textContent).toBe('Message 1'); + // Next to the scroller, never inside it: a scroll moves nothing of it. + expect(scroller.nextElementSibling).toBe(copy); + // Its rect places it, so no transform moves it a second time. + expect(copy?.style.getPropertyValue('translate')).toBe('none'); + expect(copy?.style.getPropertyValue('pointer-events')).toBe('none'); + expect(animations).toHaveLength(2); + const [fadeIn, fadeOut] = animations; + expect(fadeIn.keyframes.map(frame => frame.opacity)).toEqual([ + ENTRANCE_OPACITY_FLOOR, + 1, + ]); + expect(fadeIn.options).toMatchObject({duration: 200, fill: 'backwards'}); + expect(fadeOut.keyframes.map(frame => frame.opacity)).toEqual([1, 0]); + expect(fadeOut.options).toMatchObject({duration: 200, fill: 'forwards'}); + expect(fadeIn.keyframes[0].easing).toBe(fade.easing); + expect(fadeOut.keyframes[0].easing).toBe(fade.easing); + }); + + it("clips the copy to the visible box of the scroller it is laid outside of, past the copy's own edges", () => { + const {wrapper, scroller, content} = list(); + // The copy's own box once laid: where the list showed, 900 px tall. + const nativeBox = Element.prototype.getBoundingClientRect; + Element.prototype.getBoundingClientRect = function (this: Element) { + return this.hasAttribute('inert') + ? box(0, 167, 400, 900) + : nativeBox.call(this); + }; + try { + playReducedMotionCrossFade(content, fade, () => {}, scroller); + } finally { + Element.prototype.getBoundingClientRect = nativeBox; + } + // The scroller shows 600 px: the copy's last 467 px are cut. Its top + // edge is 167 px below the scroller's: what the copy holds above its own + // box, such as an indicator band above a list, shows there as it did. + expect(copyIn(wrapper)?.style.getPropertyValue('clip-path')).toBe( + 'inset(-167px 0px 467px 0px)', + ); + }); + + it('reads the scroller before it lays the copy: once the copy is laid, nothing reads layout', () => { + const {wrapper, scroller, content} = list(); + const log: string[] = []; + layoutLog = log; + const insert = wrapper.insertBefore.bind(wrapper); + wrapper.insertBefore = (node: T, child: Node | null) => { + log.push('lay the copy'); + return insert(node, child); + }; + const nativeBox = Element.prototype.getBoundingClientRect; + Element.prototype.getBoundingClientRect = function (this: Element) { + if (this.hasAttribute('inert')) { + log.push('read the copy'); + return box(0, 167, 400, 900); + } + return nativeBox.call(this); + }; + try { + playReducedMotionCrossFade(content, fade, () => {}, scroller); + } finally { + Element.prototype.getBoundingClientRect = nativeBox; + } + expect(log).toContain('read the scroller'); + // Laying the copy reads its box once, to place it. A read after its last + // write would lay the page out a second time. + expect(log.slice(log.indexOf('lay the copy'))).toEqual([ + 'lay the copy', + 'read the copy', + ]); + }); + + it('removes the copy once both fades end, and reports it finished', async () => { + const {wrapper, scroller, content} = list(); + const played = playReducedMotionCrossFade( + content, + fade, + () => {}, + scroller, + ); + for (const animation of animations) { + animation.finish(); + } + await expect(played?.finished).resolves.toBe(true); + expect(copyIn(wrapper)).toBeUndefined(); + }); + + it('keeps the copy while one fade still runs', async () => { + const {wrapper, scroller, content} = list(); + playReducedMotionCrossFade(content, fade, () => {}, scroller); + animations[0].finish(); + await Promise.resolve(); + await Promise.resolve(); + expect(copyIn(wrapper)).toBeDefined(); + }); + + it('on cancel removes the copy, cancels both fades and reports it unfinished', async () => { + const {wrapper, scroller, content} = list(); + const played = playReducedMotionCrossFade( + content, + fade, + () => {}, + scroller, + ); + played?.cancel(); + expect( + animations.map(animation => animation.cancel.mock.calls.length), + ).toEqual([1, 1]); + expect(copyIn(wrapper)).toBeUndefined(); + await expect(played?.finished).resolves.toBe(false); + }); + + it('lands at once with no copy when the fade is instant', async () => { + const {wrapper, scroller, content} = list(); + const land = vi.fn(); + const played = playReducedMotionCrossFade( + content, + {...fade, duration: 0}, + land, + scroller, + ); + expect(land).toHaveBeenCalledOnce(); + expect(animations).toHaveLength(0); + expect(copyIn(wrapper)).toBeUndefined(); + await expect(played?.finished).resolves.toBe(true); + }); + + it('gives null and lands nothing for an element with no box', () => { + const {scroller, content} = list(); + content.getBoundingClientRect = () => box(0, 0, 0, 0); + const land = vi.fn(); + expect( + playReducedMotionCrossFade(content, fade, land, scroller), + ).toBeNull(); + expect(land).not.toHaveBeenCalled(); + expect(animations).toHaveLength(0); + }); +}); diff --git a/packages/core/src/motion/reducedMotionCrossFade.ts b/packages/core/src/motion/reducedMotionCrossFade.ts new file mode 100644 index 0000000000000..fce23003c3e6f --- /dev/null +++ b/packages/core/src/motion/reducedMotionCrossFade.ts @@ -0,0 +1,167 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file reducedMotionCrossFade.ts + * @input An element, a Reduced Motion fade (reducedMotion.ts), the change + * that moves the element, and the box that clips it + * @output playReducedMotionCrossFade and its handle + * @position Motion foundation, beside reducedMotion.ts's dip, for a change + * that a component cross-fades itself instead of through the animator. Lab + * reaches it through internal/touch.ts. + */ + +import {ENTRANCE_OPACITY_FLOOR} from './opacityFloor'; +import type {ReducedMotionFade} from './reducedMotion'; +import {inertCopy, isCopyable, placeOver} from './transientCopy'; + +export interface ReducedMotionCrossFade { + /** Ends the cross-fade at once: the copy goes, and the element shows. */ + cancel(): void; + /** Resolves true once both fades end, or false when cancelled. */ + readonly finished: Promise; +} + +/** + * The properties that place an element. The copy's rect already includes + * them. + */ +const PLACING_PROPERTIES = ['translate', 'transform', 'scale', 'rotate']; + +/** + * Plays `fade` as a cross-fade of `element`, with `land` as the change. `clip` + * is the box that clips the element, such as its scroll container, or null + * when only the viewport clips it. Returns null when the element cannot be + * copied (too large, or not laid out): the caller then plays its own form, + * such as a dip. + * + * A copy of the element as it shows now fades out where it is, and the + * element changes at once and fades in. The two fades run together, so the + * element's area shows the old state, the new one or both on every frame. A + * dip fades out, lands and fades back in, so the area goes blank between the + * two. The copy is inert and hidden from assistive technology + * (transientCopy.ts). It is laid next to the box that clips the element, + * never inside a scroll container. So a scroll that the change makes does not + * move it. It is clipped to that box's visible part, past its own edges. So + * the copy shows what the element draws outside its box, such as an indicator + * band above a list. + */ +export function playReducedMotionCrossFade( + element: HTMLElement, + fade: ReducedMotionFade, + land: () => void, + clip: HTMLElement | null = null, +): ReducedMotionCrossFade | null { + const anchor = clip ?? element; + const host = anchor.parentElement; + if (fade.duration <= 0) { + land(); + return {cancel() {}, finished: Promise.resolve(true)}; + } + const rect = element.getBoundingClientRect(); + if (host == null || rect.width === 0 || rect.height === 0) { + return null; + } + // Read with the element's box, before any write: laying the copy writes + // layout, and a read after it would lay the page out again. + const visible = clip == null ? null : visibleBox(clip); + const copy = isCopyable(element) ? inertCopy(element) : null; + if (copy == null) { + return null; + } + const shown = Number.parseFloat(getComputedStyle(element).opacity); + const opacity = Number.isFinite(shown) ? shown : 1; + // The copy's rect already places it: a transform it copied would move it + // a second time. + for (const property of PLACING_PROPERTIES) { + copy.style.setProperty(property, 'none'); + } + copy.style.setProperty('pointer-events', 'none'); + const scale = placeOver(copy, host, rect, anchor.nextSibling); + if (visible != null) { + clipTo(copy, rect, visible, scale); + } + land(); + // Both fades start in this task with one easing. So the content shows at + // 0.75 or more on every frame. + const fadeIn = element.animate( + [{opacity: ENTRANCE_OPACITY_FLOOR, easing: fade.easing}, {opacity}], + {duration: fade.duration, fill: 'backwards'}, + ); + const fadeOut = copy.animate([{opacity, easing: fade.easing}, {opacity: 0}], { + duration: fade.duration, + fill: 'forwards', + }); + let isDone = false; + let settle: (done: boolean) => void = () => {}; + const finished = new Promise(resolve => { + settle = resolve; + }); + const end = (done: boolean) => { + if (isDone) { + return; + } + isDone = true; + copy.remove(); + settle(done); + }; + Promise.all([fadeIn.finished, fadeOut.finished]).then( + () => end(true), + // A cancelled fade rejects `finished`; `cancel` has ended it. + () => {}, + ); + return { + cancel() { + if (isDone) { + return; + } + fadeIn.cancel(); + fadeOut.cancel(); + end(false); + }, + finished, + }; +} + +interface Edges { + top: number; + right: number; + bottom: number; + left: number; +} + +/** + * `clip`'s visible box in viewport pixels: its padding box, inside the + * borders and scroll bars. + */ +function visibleBox(clip: HTMLElement): Edges { + const box = clip.getBoundingClientRect(); + const top = box.top + clip.clientTop; + const left = box.left + clip.clientLeft; + return { + top, + left, + bottom: top + clip.clientHeight, + right: left + clip.clientWidth, + }; +} + +/** + * Clips `copy`, laid over `rect`, to `visible`: the visible box of the box it + * is laid outside of, which no longer clips it. An inset is negative where + * that box shows past the copy's own edge. + */ +function clipTo( + copy: HTMLElement, + rect: DOMRect, + visible: Edges, + scale: {x: number; y: number}, +): void { + // The inset is in the copy's own pixels: a scaled host draws them larger. + const inset = [ + (visible.top - rect.top) / scale.y, + (rect.right - visible.right) / scale.x, + (rect.bottom - visible.bottom) / scale.y, + (visible.left - rect.left) / scale.x, + ].map(value => `${value}px`); + copy.style.setProperty('clip-path', `inset(${inset.join(' ')})`); +} diff --git a/packages/core/src/motion/transientCopy.ts b/packages/core/src/motion/transientCopy.ts index b1afe45462b44..847c476368e99 100644 --- a/packages/core/src/motion/transientCopy.ts +++ b/packages/core/src/motion/transientCopy.ts @@ -9,8 +9,9 @@ * @position Motion foundation, internal to core; the copy mechanism the * in-place swap uses (`spec:AST-105` FR8, * `architecture:component-style-authoring` INV7). It also makes the - * layer's exit copy. motion/animatedLayout.ts and Layer/layerExitCopy.ts - * import it. + * layer's exit copy and the Reduce Motion cross-fade's copy. + * motion/animatedLayout.ts, Layer/layerExitCopy.ts and + * motion/reducedMotionCrossFade.ts import it. * * A copy takes no part in the page: it is inert and hidden from assistive * technology, carries no ids or test ids, joins no form or radio group (a @@ -32,6 +33,7 @@ * SYNC: When modified, update: * - /packages/core/src/motion/animatedLayout.ts * - /packages/core/src/Layer/layerExitCopy.ts + * - /packages/core/src/motion/reducedMotionCrossFade.ts */ import { @@ -213,14 +215,16 @@ export function keepInherited(copy: HTMLElement, host: Element): void { * Lay `element` over `rect` (viewport coordinates), absolutely, as a child of * `host` (before `beforeNode`, else last), wherever its containing block is: * no ancestor's position changes. A copy's scrolled descendants then restore their offsets, and the - * CSS animations and transitions its element ran carry on in it. + * CSS animations and transitions its element ran carry on in it. Returns the + * host's scale on each axis, so a caller converts viewport pixels to the + * element's own without reading its box again. */ export function placeOver( element: HTMLElement, host: Element, rect: DOMRect, beforeNode: Node | null = null, -): void { +): {x: number; y: number} { Object.assign(element.style, { position: 'absolute', boxSizing: 'border-box', @@ -265,6 +269,7 @@ export function placeOver( node => carried.copyOf.get(node) ?? null, ); } + return {x: scaleX, y: scaleY}; } /** diff --git a/packages/lab/src/RefreshControl/__tests__/RefreshControl.interaction.browser.spec.ts b/packages/lab/src/RefreshControl/__tests__/RefreshControl.interaction.browser.spec.ts index cdf3039663fce..2a5ba87652066 100644 --- a/packages/lab/src/RefreshControl/__tests__/RefreshControl.interaction.browser.spec.ts +++ b/packages/lab/src/RefreshControl/__tests__/RefreshControl.interaction.browser.spec.ts @@ -916,6 +916,646 @@ function reducedMotionFailures(log: readonly RecordedAnimation[]) { ); } +/** + * Records how much of a row the list shows on each frame. Every element that + * draws the row's label counts: the content's own and any copy of it. The + * share shown is 1 − Π(1 − opacity), each opacity taken up the tree. + */ +async function recordRowShown(page: Page, label: string) { + await page.evaluate(text => { + const record = window as unknown as { + __rowShown: {t: number; shown: number}[]; + __rowShownStop: boolean; + }; + record.__rowShown = []; + record.__rowShownStop = false; + const frame = () => { + let hidden = 1; + const texts = document.createTreeWalker( + document.body, + NodeFilter.SHOW_TEXT, + ); + for (let node = texts.nextNode(); node != null; node = texts.nextNode()) { + if (node.nodeValue?.trim() !== text) { + continue; + } + let opacity = 1; + for ( + let element = node.parentElement; + element != null; + element = element.parentElement + ) { + opacity *= Number(getComputedStyle(element).opacity); + } + hidden *= 1 - opacity; + } + record.__rowShown.push({t: performance.now(), shown: 1 - hidden}); + if (!record.__rowShownStop) { + requestAnimationFrame(frame); + } + }; + requestAnimationFrame(frame); + }, label); +} + +const stopRowShown = (page: Page) => + page.evaluate(() => { + const record = window as unknown as { + __rowShown: {t: number; shown: number}[]; + __rowShownStop: boolean; + }; + record.__rowShownStop = true; + return record.__rowShown; + }); + +interface IndicatorFrame { + t: number; + /** How much of the indicator shows, 0 to 1. */ + shown: number; + /** The content's copies on screen: a cross-fade is playing. */ + copies: number; + /** The highest opacity of those copies. */ + copyOpacity: number; +} + +/** + * Records how much of the refresh indicator shows on each frame, and the + * content's copies while a cross-fade lays one. Every element that draws the + * indicator counts: the content's own and any copy's. Each shows the part of + * its box that its clipping ancestors leave (a clip path, or a box that hides + * overflow), times its opacity up the tree. The shares combine as + * 1 − Π(1 − share). + */ +async function recordIndicatorShown(page: Page) { + await page.evaluate(() => { + type Box = {left: number; top: number; right: number; bottom: number}; + const record = window as unknown as { + __indicatorShown: IndicatorFrame[]; + __indicatorShownStop: boolean; + }; + record.__indicatorShown = []; + record.__indicatorShownStop = false; + const meet = (a: Box, b: Box): Box => ({ + left: Math.max(a.left, b.left), + top: Math.max(a.top, b.top), + right: Math.min(a.right, b.right), + bottom: Math.min(a.bottom, b.bottom), + }); + // The box `element` clips to: its clip path's inset box, and, for a + // descendant, its padding box when it hides overflow. + const clipOf = (element: Element, isAncestor: boolean): Box | null => { + const style = getComputedStyle(element); + const rect = element.getBoundingClientRect(); + let clip: Box | null = null; + if ( + isAncestor && + (style.overflowX !== 'visible' || style.overflowY !== 'visible') + ) { + const left = rect.left + element.clientLeft; + const top = rect.top + element.clientTop; + clip = { + left, + top, + right: left + element.clientWidth, + bottom: top + element.clientHeight, + }; + } + if (style.clipPath.startsWith('inset(')) { + const [top, right = top, bottom = top, left = right] = style.clipPath + .slice('inset('.length, -1) + .split(' round ')[0] + .trim() + .split(/\s+/) + .map(value => Number.parseFloat(value)); + const width = (element as HTMLElement).offsetWidth; + const scale = width > 0 ? rect.width / width : 1; + const inset = { + left: rect.left + left * scale, + top: rect.top + top * scale, + right: rect.right - right * scale, + bottom: rect.bottom - bottom * scale, + }; + clip = clip == null ? inset : meet(clip, inset); + } + return clip; + }; + const shareOf = (element: Element) => { + const rect = element.getBoundingClientRect(); + const area = rect.width * rect.height; + if (area === 0) { + return 0; + } + let visible: Box = { + left: rect.left, + top: rect.top, + right: rect.right, + bottom: rect.bottom, + }; + let opacity = 1; + for ( + let node: Element | null = element; + node != null; + node = node.parentElement + ) { + const clip = clipOf(node, node !== element); + if (clip != null) { + visible = meet(visible, clip); + } + opacity *= Number(getComputedStyle(node).opacity); + } + const width = Math.max(0, visible.right - visible.left); + const height = Math.max(0, visible.bottom - visible.top); + return ((width * height) / area) * opacity; + }; + const frame = () => { + let hidden = 1; + for (const element of document.querySelectorAll( + '[data-refresh-content] [role="progressbar"]', + )) { + hidden *= 1 - shareOf(element); + } + const copies = [ + ...document.querySelectorAll('[data-refresh-content][inert]'), + ]; + record.__indicatorShown.push({ + t: performance.now(), + shown: 1 - hidden, + copies: copies.length, + copyOpacity: Math.max( + 0, + ...copies.map(copy => Number(getComputedStyle(copy).opacity)), + ), + }); + if (!record.__indicatorShownStop) { + requestAnimationFrame(frame); + } + }; + requestAnimationFrame(frame); + }); +} + +const stopIndicatorShown = (page: Page) => + page.evaluate(() => { + const record = window as unknown as { + __indicatorShown: IndicatorFrame[]; + __indicatorShownStop: boolean; + }; + record.__indicatorShownStop = true; + return record.__indicatorShown; + }); + +/** Each cross-fade: a run of frames with a copy of the content on screen. */ +function crossFades(frames: readonly IndicatorFrame[]): IndicatorFrame[][] { + const runs: IndicatorFrame[][] = []; + let run: IndicatorFrame[] | null = null; + for (const frame of frames) { + if (frame.copies === 0) { + run = null; + } else if (run == null) { + run = [frame]; + runs.push(run); + } else { + run.push(frame); + } + } + return runs; +} + +test('under Reduce Motion the list and its indicator show on every frame: the release and the end cross-fade rather than dip', async ({ + page, +}) => { + // A cross-fade connects the two states: the list where it was fades out as + // the list in its new place fades in. A dip fades out, lands and fades back + // in, so the list area goes blank between the two. + await page.emulateMedia({reducedMotion: 'reduce'}); + await primaryPointer(page, 'coarse'); + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '-1', + }); + await recordRowShown(page, 'Message 2'); + await recordIndicatorShown(page); + await driver.play(slowPull(start, 300, 200)); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 1); + await endRefresh(page); + await expect.poll(() => isBusy(content), {timeout: 8000}).toBe(false); + // The end starts two frames after the busy state clears. + await expect + .poll(() => shownPull(content), {timeout: 8000}) + .toBeCloseTo(0, 1); + await waitForContentRest(content); + const frames = await stopRowShown(page); + const least = Math.min(...frames.map(frame => frame.shown)); + const emptiest = frames + .filter(frame => frame.shown < 0.5) + .map(frame => frame.shown.toFixed(3)) + .join(' '); + // Two equal fades crossing show the row at 0.75 or more. Half is the floor. + expect( + least, + `the row showed at ${least.toFixed(3)} on its emptiest frame; the list blanked (frames under half: ${emptiest})`, + ).toBeGreaterThanOrEqual(0.5); + // The indicator band sits above the content's box. The copy shows it as + // the content did, so it fades with the copy and never ahead of it: at the + // end it fades out, and at the release it stays in view as the rows do. + const indicator = await stopIndicatorShown(page); + const runs = crossFades(indicator); + const detail = JSON.stringify( + runs.map(run => + run.map(frame => [frame.shown.toFixed(3), frame.copyOpacity.toFixed(3)]), + ), + ); + expect( + runs.length, + `the release's and the end's cross-fades: ${detail}`, + ).toBe(2); + for (const [index, run] of runs.entries()) { + const behind = Math.min( + ...run.map(frame => frame.shown - frame.copyOpacity), + ); + expect( + behind, + `cross-fade ${index + 1}: the indicator showed ${(-behind).toFixed(3)} less than its copy's opacity; the copy hid it (shown, copy opacity per frame: ${detail})`, + ).toBeGreaterThanOrEqual(-0.1); + } + const releaseLeast = Math.min(...runs[0].map(frame => frame.shown)); + expect( + releaseLeast, + `the indicator showed at ${releaseLeast.toFixed(3)} during the release's cross-fade: it blinked (${detail})`, + ).toBeGreaterThanOrEqual(0.5); +}); + +test('under Reduce Motion an end scrolled into the inset reads no layout between laying its copy and starting its fade, and takes the scroll back once it ends', async ({ + page, +}) => { + // The end of a refresh scrolled 30 px into the 60 px inset cross-fades onto + // where its slide would end. It takes the 30 px of scroll back only once the + // cross-fade ends, as the slide does. A scroll read in the task that lays + // the copy would lay the page out a second time before the fade starts. + await page.emulateMedia({reducedMotion: 'reduce'}); + await primaryPointer(page, 'coarse'); + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '-1', + }); + await driver.play(slowPull(start, 300, 200)); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 1); + const scroller = page.locator('[data-refresh-scroller]').first(); + const scrollTop = () => scroller.evaluate(el => el.scrollTop); + await scroller.evaluate(el => { + el.scrollTop = 30; + }); + await expect.poll(scrollTop).toBe(30); + // Logs each layout read outside the content's copy, the copy's laying and + // its fade's start. + await page.evaluate(() => { + const log: string[] = []; + (window as unknown as {__endLog: string[]}).__endLog = log; + const isCopy = (node: unknown) => + node instanceof Element && + node.hasAttribute('data-refresh-content') && + node.hasAttribute('inert'); + const inCopy = (node: Element) => + node.closest('[data-refresh-content][inert]') != null; + const scroll = Object.getOwnPropertyDescriptor( + Element.prototype, + 'scrollTop', + ); + Object.defineProperty(Element.prototype, 'scrollTop', { + configurable: true, + get(this: Element) { + if (!inCopy(this)) { + log.push('read the scroll'); + } + return scroll?.get?.call(this); + }, + set(this: Element, value: number) { + scroll?.set?.call(this, value); + }, + }); + const rect = Element.prototype.getBoundingClientRect; + Element.prototype.getBoundingClientRect = function (this: Element) { + if (!inCopy(this)) { + log.push('read a box'); + } + return rect.call(this); + }; + const insert = Node.prototype.insertBefore; + Node.prototype.insertBefore = function ( + this: Node, + node: T, + child: Node | null, + ): T { + if (isCopy(node)) { + log.push('lay the copy'); + } + return insert.call(this, node, child) as T; + }; + const animate = Element.prototype.animate; + Element.prototype.animate = function ( + this: Element, + ...args: Parameters + ) { + if (isCopy(this)) { + log.push('fade the copy'); + } + return animate.apply(this, args); + }; + }); + const endLog = () => + page.evaluate(() => (window as unknown as {__endLog: string[]}).__endLog); + await endRefresh(page); + await expect + .poll(async () => (await endLog()).includes('fade the copy'), { + timeout: 8000, + }) + .toBe(true); + const log = await endLog(); + const laid = log.indexOf('lay the copy'); + const faded = log.indexOf('fade the copy'); + expect(laid, 'the end laid no copy').toBeGreaterThanOrEqual(0); + expect(log.slice(laid, faded + 1)).toEqual(['lay the copy', 'fade the copy']); + // Once the cross-fade ends, the list rests at the top with the scroll + // taken back, as after the slide. + await expect + .poll(() => shownPull(content), {timeout: 8000}) + .toBeCloseTo(0, 1); + await waitForContentRest(content); + expect(await scrollTop()).toBe(0); + expect(await shownPull(content)).toBeCloseTo(0, 1); +}); + +test('under Reduce Motion a refresh that begins during the end’s cross-fade keeps its inset: the list does not jump over the spinner', async ({ + page, +}) => { + // The controlled story's Refresh button starts a refresh with no finger. + // Pressed while the end cross-fades, it puts the list back on the inset. + // The end's own finish must not run after that and drop the inset. + await page.emulateMedia({reducedMotion: 'reduce'}); + await primaryPointer(page, 'coarse'); + const {driver, content, start} = await openRefresh( + page, + 'lab-pull-to-refresh--controlled', + {refreshMs: '-1'}, + ); + await driver.play(slowPull(start, 300, 200)); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 1); + // Presses Refresh 60 ms into the end's cross-fade, and notes whether the + // copy was still on screen then. + await page.evaluate(() => { + const record = window as unknown as { + __pressScheduled: boolean; + __pressedMidFade: boolean | null; + }; + record.__pressScheduled = false; + record.__pressedMidFade = null; + const animate = Element.prototype.animate; + Element.prototype.animate = function ( + this: Element, + ...args: Parameters + ) { + if ( + !record.__pressScheduled && + this.hasAttribute('data-refresh-content') && + this.hasAttribute('inert') + ) { + record.__pressScheduled = true; + setTimeout(() => { + record.__pressedMidFade = + document.querySelector('[data-refresh-content][inert]') != null; + const button = [...document.querySelectorAll('button')].find( + element => element.textContent?.trim() === 'Refresh', + ); + button?.click(); + }, 60); + } + return animate.apply(this, args); + }; + }); + const pressedMidFade = () => + page.evaluate( + () => + (window as unknown as {__pressedMidFade: boolean | null}) + .__pressedMidFade, + ); + await endRefresh(page); + await expect.poll(pressedMidFade, {timeout: 8000}).not.toBeNull(); + expect(await pressedMidFade(), 'the press landed after the cross-fade').toBe( + true, + ); + await expect.poll(() => isBusy(content)).toBe(true); + // Past the end's cross-fade, the new refresh still holds the inset. + await expect(page.locator('[data-refresh-content][inert]')).toHaveCount(0); + await frames(page, 3); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 1); +}); + +test('under Reduce Motion a pull pushed back past its start lays no copy: the release moves nothing, so nothing fades', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'native scrolling from injected touches is Chromium-only (WebKit: the iOS simulator rig)', + ); + await page.emulateMedia({reducedMotion: 'reduce'}); + await primaryPointer(page, 'coarse'); + const {driver, content, start} = await openRefresh(page); + // Notes any copy of the content laid in the page. + await page.evaluate(() => { + const record = window as unknown as {__copyLaid: boolean}; + record.__copyLaid = false; + new MutationObserver(records => { + for (const {addedNodes} of records) { + for (const node of addedNodes) { + if ( + node instanceof Element && + node.matches('[data-refresh-content][inert]') + ) { + record.__copyLaid = true; + } + } + } + }).observe(document.body, {childList: true, subtree: true}); + }); + // Down 50 px, then up 250 px, in one touch: the list is back at its start + // when the finger lifts. + const at = (progress: number) => + progress < 0.25 + ? {x: start.x, y: start.y + 50 * (progress / 0.25)} + : {x: start.x, y: start.y + 50 - 250 * ((progress - 0.25) / 0.75)}; + await driver.play(path(at, {durationMs: 900, hz: 60, restMs: 150})); + await waitForContentRest(content); + await frames(page, 3); + expect(await shownPull(content)).toBeCloseTo(0, 1); + expect(await isBusy(content)).toBe(false); + expect( + await page.evaluate( + () => (window as unknown as {__copyLaid: boolean}).__copyLaid, + ), + 'a copy faded over a list that did not move', + ).toBe(false); +}); + +test('under Reduce Motion a pull during a refresh that returns to the inset lays no copy', async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + 'native scrolling from injected touches is Chromium-only (WebKit: the iOS simulator rig)', + ); + await page.emulateMedia({reducedMotion: 'reduce'}); + await primaryPointer(page, 'coarse'); + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '-1', + }); + await driver.play(slowPull(start, 300, 200)); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 1); + // Notes any copy of the content laid from now on. + await page.evaluate(() => { + const record = window as unknown as {__copyLaid: boolean}; + record.__copyLaid = false; + new MutationObserver(records => { + for (const {addedNodes} of records) { + for (const node of addedNodes) { + if ( + node instanceof Element && + node.matches('[data-refresh-content][inert]') + ) { + record.__copyLaid = true; + } + } + } + }).observe(document.body, {childList: true, subtree: true}); + }); + // During the refresh, down 50 px, then up 250 px, in one touch: the list + // is back on the inset when the finger lifts. + const at = (progress: number) => + progress < 0.25 + ? {x: start.x, y: start.y + 50 * (progress / 0.25)} + : {x: start.x, y: start.y + 50 - 250 * ((progress - 0.25) / 0.75)}; + await driver.play(path(at, {durationMs: 900, hz: 60, restMs: 150})); + await waitForContentRest(content); + await frames(page, 3); + expect(await isBusy(content)).toBe(true); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 1); + expect( + await page.evaluate( + () => (window as unknown as {__copyLaid: boolean}).__copyLaid, + ), + 'a copy faded over a list that did not move', + ).toBe(false); +}); + +test('under Reduce Motion an unmount during the end’s cross-fade takes its copy along and scrolls nothing after', async ({ + page, +}) => { + // The end of a refresh scrolled 30 px into the inset cross-fades, and takes + // the scroll back once the cross-fade ends. The list unmounts 60 ms into the + // cross-fade: its copy is gone before the next frame, and no finish runs. + await page.emulateMedia({reducedMotion: 'reduce'}); + await primaryPointer(page, 'coarse'); + const {driver, content, start} = await openRefresh(page, undefined, { + refreshMs: '-1', + }); + await driver.play(slowPull(start, 300, 200)); + await waitForContentRest(content); + expect(await shownPull(content)).toBeCloseTo(HEIGHT, 1); + const scroller = page.locator('[data-refresh-scroller]').first(); + await scroller.evaluate(el => { + el.scrollTop = 30; + }); + await expect.poll(() => scroller.evaluate(el => el.scrollTop)).toBe(30); + // 60 ms into the copy's fade, unmounts the list. Notes whether a copy is + // still in the page at the first frame after the list is gone, and every + // scroll write after it is gone. + await page.evaluate(() => { + const record = window as unknown as { + __unmount: { + scheduled: boolean; + copyLeft: boolean | null; + scrollWrites: number; + }; + }; + const state = { + scheduled: false, + isListGone: false, + copyLeft: null as boolean | null, + scrollWrites: 0, + }; + record.__unmount = state; + const scroll = Object.getOwnPropertyDescriptor( + Element.prototype, + 'scrollTop', + ); + Object.defineProperty(Element.prototype, 'scrollTop', { + configurable: true, + get(this: Element) { + return scroll?.get?.call(this); + }, + set(this: Element, value: number) { + if (state.isListGone) { + state.scrollWrites += 1; + } + scroll?.set?.call(this, value); + }, + }); + new MutationObserver(() => { + if ( + state.scheduled && + !state.isListGone && + document.querySelector('[data-refresh-content]:not([inert])') == null + ) { + state.isListGone = true; + requestAnimationFrame(() => { + state.copyLeft = + document.querySelector('[data-refresh-content][inert]') != null; + }); + } + }).observe(document.body, {childList: true, subtree: true}); + const animate = Element.prototype.animate; + Element.prototype.animate = function ( + this: Element, + ...args: Parameters + ) { + if ( + !state.scheduled && + this.hasAttribute('data-refresh-content') && + this.hasAttribute('inert') + ) { + state.scheduled = true; + setTimeout(() => { + window.dispatchEvent(new Event('refreshcontrol-story-unmount')); + }, 60); + } + return animate.apply(this, args); + }; + }); + const unmount = () => + page.evaluate( + () => + ( + window as unknown as { + __unmount: {copyLeft: boolean | null; scrollWrites: number}; + } + ).__unmount, + ); + await endRefresh(page); + await expect + .poll(async () => (await unmount()).copyLeft, {timeout: 8000}) + .not.toBeNull(); + // Past the cross-fade's 200 ms. + await page.waitForTimeout(400); + const after = await unmount(); + expect(after.copyLeft, 'the copy outlived the list').toBe(false); + expect(await page.locator('[data-refresh-content][inert]').count()).toBe(0); + expect(after.scrollWrites, 'a finish ran after the list unmounted').toBe(0); +}); + test('under Reduce Motion a release cross-fades onto the inset: opacity only, within 200 ms', async ({ page, }) => { diff --git a/packages/lab/src/RefreshControl/refreshTouchController.ts b/packages/lab/src/RefreshControl/refreshTouchController.ts index 465846678bca5..9f84e11a5bf60 100644 --- a/packages/lab/src/RefreshControl/refreshTouchController.ts +++ b/packages/lab/src/RefreshControl/refreshTouchController.ts @@ -39,6 +39,10 @@ // theme's tempo scales it. Finger tracking runs on the main thread, because the // browser has no refresh pull to ride. Every release, settle and end runs on // the compositor. +// +// Under Reduce Motion, a settle and the end cross-fade through a copy of the +// content. The copy fades out where the list shows, as the list lands and +// fades in. So the list shows on every frame. import { useCallback, @@ -55,6 +59,9 @@ import type {MotionCurve} from '@astryxdesign/core/internal/touch'; import {cubicBezier} from '@astryxdesign/core/internal/touch'; import {mapProgress} from '@astryxdesign/core/internal/touch'; import {scroll} from '@astryxdesign/core/internal/touch'; +import {playReducedMotionCrossFade} from '@astryxdesign/core/internal/touch'; +import type {ReducedMotionCrossFade} from '@astryxdesign/core/internal/touch'; +import {reducedMotionFade} from '@astryxdesign/core/internal/touch'; import {observeResize} from '@astryxdesign/core/utils'; import {useMotionEngine} from '../internal/useMotionEngine'; import { @@ -120,6 +127,20 @@ function scrollContainersOf(start: HTMLElement): HTMLElement[] { return containers; } +/** + * How near its target the content counts as there, in px. A move this small + * shows nothing. + */ +const AT_TARGET_PX = 0.05; + +/** Ends the cross-fade in flight, if any: its copy goes, and its finish never runs. */ +function cancelCrossFade(crossFade: { + current: ReducedMotionCrossFade | null; +}): void { + crossFade.current?.cancel(); + crossFade.current = null; +} + function overflows(element: HTMLElement): boolean { return element.scrollHeight > element.clientHeight; } @@ -255,10 +276,60 @@ export function useRefreshTouchController({ }, [content.animator, indicator.animator], ); + // A cross-fade in flight. Stopping it lands the list where it was heading. + const crossFade = useRef(null); const stopPlacing = useCallback(() => { + cancelCrossFade(crossFade); content.animator.stop(['y']); indicator.animator.stop(['y']); }, [content.animator, indicator.animator]); + /** + * Cross-fades the content into what `land` writes, when Reduce Motion turns + * the move into a cross-fade. The animator's own form for a move is a dip, + * which blanks the list between the two states. A move of `travel` px that + * shows nothing lands at once, with no copy. Returns null when motion + * plays, when the change is instant, or when the content is too large to + * copy: the animator then plays the change. + */ + const crossFadeContent = useCallback( + ( + land: () => void, + travel: number, + touchRelease: boolean, + ): Promise | null => { + const element = contentElement.current; + const fade = + element == null || + content.animator.reducedMotion({touchRelease}) !== 'crossfade' + ? null + : reducedMotionFade(element, {touchRelease}); + if (element == null || fade == null) { + return null; + } + stopPlacing(); + if (Math.abs(travel) <= AT_TARGET_PX) { + land(); + return Promise.resolve(true); + } + const played = playReducedMotionCrossFade( + element, + fade, + land, + owner.current, + ); + if (played == null) { + return null; + } + crossFade.current = played; + played.finished.then(() => { + if (crossFade.current === played) { + crossFade.current = null; + } + }); + return played.finished; + }, + [content.animator, stopPlacing], + ); /** * Puts the indicator back to opaque, and writes only if it changed. Each @@ -458,12 +529,27 @@ export function useRefreshTouchController({ // caught settle that resumes starts from rest. const velocity = releaseVelocity.current; releaseVelocity.current = 0; - // No start time: the animator starts the settle when the compositor - // does, so its first frame is the curve's start. A finger's release - // starts it as a touch release. So under Reduce Motion the animator - // cross-fades it instead of moving it, as it does for any release under - // a coarse primary pointer. A trackpad's release lands at once. + // A finger's release starts the settle as a touch release. So under + // Reduce Motion it cross-fades instead of moving, as any release does + // under a coarse primary pointer. A trackpad's release lands at once. const touchRelease = pullPointer.current === 'touch'; + const crossFaded = crossFadeContent( + () => place(target), + target - from, + touchRelease, + ); + if (crossFaded != null) { + if (to === 'top' && !model.current.isRefreshing && from > 0) { + crossFaded.then(done => { + if (done && !model.current.isRefreshing) { + resetIndicator(); + } + }); + } + return; + } + // No start time: the animator starts the settle when the compositor + // does, so its first frame is the curve's start. const contentSettle = content.animator.animate( {y: target}, {spring: scroll.bounce, velocity: {y: velocity}}, @@ -477,8 +563,8 @@ export function useRefreshTouchController({ if (to === 'top' && !model.current.isRefreshing && from > 0) { // The indicator fades as the content covers it, along the content's // own settle curve. Started in the same task, the two start on the - // same compositor frame. Under Reduce Motion the settle has no curve, - // and the indicator resets once the settle ends. + // same compositor frame. A settle with no curve (an instant one, or + // the animator's cross-fade) resets the indicator once it ends. const curve = contentSettle.curve('y'); const {dimension} = pull.current; const start = revealProgress(from, dimension) || 1; @@ -501,7 +587,13 @@ export function useRefreshTouchController({ }); } }, - [content.animator, indicator.animator, resetIndicator], + [ + content.animator, + crossFadeContent, + indicator.animator, + place, + resetIndicator, + ], ); const settle = useCallback( @@ -551,7 +643,7 @@ export function useRefreshTouchController({ pendingEnd.current = () => { // The indicator stays opaque while the content slides up over its gap // (UIKit holds it at opacity 1 for nearly the whole end). Under Reduce - // Motion, the animator cross-fades the slide. + // Motion, the slide cross-fades. const from = content.animator.get('y'); const element = contentElement.current; const finish = () => { @@ -570,6 +662,22 @@ export function useRefreshTouchController({ finish(); return; } + // Under Reduce Motion, the list cross-fades onto where the slide ends. + // It takes the scroll back once the cross-fade ends, as the slide does, + // so the task that lays the copy reads no scroll. + const crossFaded = crossFadeContent( + () => place(animateTo), + animateTo - from, + false, + ); + if (crossFaded != null) { + crossFaded.then(done => { + if (done) { + finish(); + } + }); + return; + } const {ms, points} = timing; indicator.animator.play({ y: bezierCurve( @@ -590,6 +698,7 @@ export function useRefreshTouchController({ setEndTick(tick => tick + 1); }, [ content.animator, + crossFadeContent, indicator.animator, place, resetIndicator, @@ -615,11 +724,14 @@ export function useRefreshTouchController({ }); }); }, [endTick]); + // Effect: at unmount, cancels the end's frame and a cross-fade in flight, + // so no copy and no deferred finish outlive the controller. useEffect( () => () => { if (endFrame.current != null) { cancelAnimationFrame(endFrame.current); } + cancelCrossFade(crossFade); }, [], ); @@ -637,7 +749,7 @@ export function useRefreshTouchController({ return; } const target = releaseTarget(model.current.isRefreshing); - if (Math.abs(content.animator.get('y') - target) > 0.05) { + if (Math.abs(content.animator.get('y') - target) > AT_TARGET_PX) { settle(model.current.isRefreshing ? 'inset' : 'top'); } }, [content.animator, model, settle]); @@ -798,6 +910,15 @@ export function useRefreshTouchController({ const contentRef = useCallback( (element: HTMLElement | null) => { + if (element == null) { + // The list left the page. React attaches an element that takes its + // place in the same commit, so a cross-fade ends only if none did. + queueMicrotask(() => { + if (contentElement.current == null) { + cancelCrossFade(crossFade); + } + }); + } contentElement.current = element; content.ref(element); setUpEdge.current?.(); @@ -821,14 +942,23 @@ export function useRefreshTouchController({ const begin = useCallback(() => { showIndicator(); if (!model.current.isPulling) { - // The inset arrives with no visible motion, as beginRefreshing(). + // The inset arrives with no visible motion, as beginRefreshing(). An + // end still playing stops first, so its finish cannot drop the inset. cancelPendingEnd(); + stopPlacing(); const current = resolveOwner(); place(REFRESH_HEIGHT); scrollOwnerBy(current, REFRESH_HEIGHT); hasInset.current = true; } - }, [cancelPendingEnd, model, place, resolveOwner, showIndicator]); + }, [ + cancelPendingEnd, + model, + place, + resolveOwner, + showIndicator, + stopPlacing, + ]); return useMemo( () => ({ diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjs index 5c23738d9c1af..fffe0a4efb1a3 100644 --- a/scripts/touch-support-bundle.test.mjs +++ b/scripts/touch-support-bundle.test.mjs @@ -172,7 +172,8 @@ function exportsOf(entry) { * helpers that follow the last input. Lab components that watch a finger's * scroll read the finger-scroll watch. PageControl reads an element's shared * animator, the Reduce Motion cross-fade, and the touch hit area's hook and - * layer. SearchField reads UIKit's timing table. + * layer. RefreshControl also plays the Reduce Motion cross-fade through a + * copy. SearchField reads UIKit's timing table. */ const LAB_ONLY_NAMES = [ 'PanGestureRecognizer', @@ -208,6 +209,7 @@ const LAB_ONLY_NAMES = [ 'useTouchHitArea', 'touchHitAreaStyles', 'measureLogicalScrollAxis', + 'playReducedMotionCrossFade', 'useFocusAcrossSwap', 'timing', 'useGroupPressTracking',