From 3dd581e9cf96efc699363fc686e340c14b884132 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 3 Nov 2026 06:35:52 -0800 Subject: [PATCH 01/73] feat(core): one progress module for the motion foundation progressCurve, mapProgress, mapRange and presentedProgressVelocity in motion/progress.ts, internal, one velocity unit (progress per second). Rebuilt on main from the pull request's own change, without the open dependency chain it no longer needs. Co-authored-by: Cindy Zhang --- .changeset/motion-progress.md | 7 + packages/core/src/motion/README.md | 1 + packages/core/src/motion/progress.test.ts | 172 ++++++++++++++++++++++ packages/core/src/motion/progress.ts | 155 +++++++++++++++++++ 4 files changed, 335 insertions(+) create mode 100644 .changeset/motion-progress.md create mode 100644 packages/core/src/motion/progress.test.ts create mode 100644 packages/core/src/motion/progress.ts diff --git a/.changeset/motion-progress.md b/.changeset/motion-progress.md new file mode 100644 index 0000000000000..d7d9d896ba1ff --- /dev/null +++ b/.changeset/motion-progress.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: one progress module for the motion foundation. `progressCurve` gives a spring's progress from 0 to 1 as a closed-form curve, `mapProgress` maps any curve from another (a companion's dim following a sheet, a clamped range), `mapRange` is the clamped linear map they share, and `presentedProgressVelocity` reads the velocity an interrupted motion continues from. One velocity unit throughout: progress per second. Nothing public changes; no component imports it yet. + +@vjeux diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md index 05e5a15d629a1..19ef169b0e573 100644 --- a/packages/core/src/motion/README.md +++ b/packages/core/src/motion/README.md @@ -38,6 +38,7 @@ roles through `resolveMotion`. | `resolveSnapPoint.ts` | Release policy: the snap point a release lands on (flick, back-out cancel, step limit), on `selectSnapPoint`. Internal. | | `bezier.ts` | Cubic-bézier timing functions (Core Animation's named curves). | | `animator.ts` | Compositor animator: springs, coasts and any closed-form curve compiled to Web Animations, read back analytically. | +| `progress.ts` | A spring's progress, one curve mapped from another (companions, clamped ranges), the velocity that continues a motion. | | `presentation.ts` | Where each moving element is drawn relative to where the engine hit-tests it, reported by the animator while translate runs; read by the gesture host at touch-down. | | `reducedMotionPlan.ts` | The animator's Reduce Motion planner: what one call becomes, a cross-fade whose travel lands while transparent or at once. | | `__tests__/animator.interaction.browser.spec.ts` | Browser proofs on the interaction harness (Chromium and WebKit): busy main thread, end state through a block, no Layout / Paint, seeked curves, a dialog's backdrop. | diff --git a/packages/core/src/motion/progress.test.ts b/packages/core/src/motion/progress.test.ts new file mode 100644 index 0000000000000..4de3fa57df8de --- /dev/null +++ b/packages/core/src/motion/progress.test.ts @@ -0,0 +1,172 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +import {describe, expect, it} from 'vitest'; +import type {MotionProperty} from './animator'; +import { + mapProgress, + mapRange, + presentedProgressVelocity, + progressCurve, + type ProgressChannel, +} from './progress'; +import {solveSpring, toSpring} from './spring'; + +const SPRING = {response: 0.4, dampingRatio: 0.85}; + +/** An animator stand-in that presents fixed velocities. */ +const presenting = (velocities: Partial>) => ({ + getVelocity: (property: MotionProperty) => velocities[property] ?? 0, +}); + +describe('progressCurve', () => { + it('follows the spring from 0 to 1 and lands exactly on 1 once settled', () => { + const curve = progressCurve(SPRING, {velocity: 2}); + const spring = solveSpring(toSpring(SPRING), {from: 0, to: 1, velocity: 2}); + expect(curve.at(0)).toBe(0); + expect(curve.velocity(0)).toBeCloseTo(2, 9); + for (const t of [0.05, 0.1, 0.2, 0.3]) { + expect(curve.at(t)).toBeCloseTo(spring.value(t), 12); + expect(curve.velocity(t)).toBeCloseTo(spring.velocity(t), 12); + } + expect(curve.duration).toBeGreaterThan(0.3); + expect(curve.at(curve.duration)).toBe(1); + expect(curve.velocity(curve.duration)).toBe(0); + }); +}); + +describe('mapProgress', () => { + it('maps the value through f and the velocity by the chain rule', () => { + const progress = progressCurve(SPRING); + const f = (p: number) => 100 + 300 * p * p; + const mapped = mapProgress(progress, f); + expect(mapped.duration).toBe(progress.duration); + for (const t of [0.02, 0.1, 0.25]) { + const p = progress.at(t); + expect(mapped.at(t)).toBeCloseTo(f(p), 9); + expect(mapped.velocity(t)).toBeCloseTo(600 * p * progress.velocity(t), 4); + } + expect(mapped.at(progress.duration)).toBe(400); + }); +}); + +describe('mapRange', () => { + it('maps linearly inside the input range, exactly at its ends', () => { + const dim = mapRange([600, 200], [0, 0.4]); + expect(dim(600)).toBe(0); + expect(dim(200)).toBe(0.4); + expect(dim(400)).toBeCloseTo(0.2, 12); + expect(dim(500)).toBeCloseTo(0.1, 12); + }); + + it('holds the output’s ends outside the input range, or runs on when not clamped', () => { + const dim = mapRange([600, 200], [0, 0.4]); + expect(dim(800)).toBe(0); + expect(dim(0)).toBe(0.4); + const open = mapRange([600, 200], [0, 0.4], {clamp: false}); + expect(open(800)).toBeCloseTo(-0.2, 12); + expect(open(0)).toBeCloseTo(0.6, 12); + }); + + it('steps at the input when its range is empty', () => { + const step = mapRange([10, 10], [0, 1]); + expect(step(9)).toBe(0); + expect(step(10)).toBe(1); + expect(step(11)).toBe(1); + }); +}); + +describe('mapProgress with a driving channel', () => { + // A sheet's y falling from 700 px to 100 px at a steady 1000 px/s. + const sheetY = { + duration: 0.6, + at: (t: number) => 700 - 1000 * t, + velocity: () => -1000, + }; + + it('follows any curve, not only a progress: the scrim’s dim along the sheet’s travel', () => { + const dim = mapProgress(sheetY, mapRange([600, 200], [0, 0.4])); + expect(dim.duration).toBe(0.6); + expect(dim.at(0.3)).toBeCloseTo(0.4 * (200 / 400), 12); + // Inside the range: 0.4 per 400 px at 1000 px/s, rising. + expect(dim.velocity(0.3)).toBeCloseTo(1, 4); + }); + + it('is still, velocity 0, outside the range on both sides', () => { + const dim = mapProgress(sheetY, mapRange([600, 200], [0, 0.4])); + // y = 650 (not yet in range) and y = 150 (past it). + for (const t of [0.05, 0.55]) { + expect(Math.abs(dim.velocity(t))).toBe(0); + } + expect(dim.at(0.05)).toBe(0); + expect(dim.at(0.55)).toBe(0.4); + }); +}); + +describe('presentedProgressVelocity', () => { + const line = ( + from: Partial>, + to: Partial>, + weights: Partial> = {}, + ): ProgressChannel[] => + (Object.keys(to) as MotionProperty[]).map(property => ({ + property, + at: p => from[property]! + (to[property]! - from[property]!) * p, + weight: weights[property], + })); + + it('is the presented velocity over the path\u2019s tangent when they are parallel', () => { + // A path of 200 px on x and 100 px on y, presented at 400 and 200 px/s: + // two progress units per second. + const channels = line({x: 0, y: 0}, {x: 200, y: 100}); + expect( + presentedProgressVelocity(presenting({x: 400, y: 200}), channels), + ).toBeCloseTo(2, 6); + }); + + it('keeps only the part along the path (v\u00b7t / t\u00b7t)', () => { + // Moving across the path counts for nothing; against it, negatively. + const channels = line({x: 0, y: 0}, {x: 100, y: 0}); + expect( + presentedProgressVelocity(presenting({x: 0, y: 500}), channels), + ).toBeCloseTo(0, 9); + expect( + presentedProgressVelocity(presenting({x: -50, y: 500}), channels), + ).toBeCloseTo(-0.5, 6); + }); + + it('weighs each channel into one unit, so a scale counts in px', () => { + // A 300 px wide box growing from scale 0.5 to 1 while moving 50 px: in px + // the scale moves 150 px against 50 px of travel. + const channels = line( + {x: 0, scaleX: 0.5}, + {x: 50, scaleX: 1}, + {scaleX: 300}, + ); + // Presented: 100 px/s on x and 1 scale/s (300 px/s): (100·50 + 300·150) / + // (50² + 150²) = 2 progress units per second. + expect( + presentedProgressVelocity(presenting({x: 100, scaleX: 1}), channels), + ).toBeCloseTo(2, 6); + }); + + it('is 0 on a path that moves none of its channels, or from rest', () => { + expect( + presentedProgressVelocity(presenting({x: 100}), line({x: 10}, {x: 10})), + ).toBe(0); + expect( + presentedProgressVelocity(presenting({}), line({x: 0}, {x: 10})), + ).toBe(0); + }); + + it('reads every channel at the one time it is given', () => { + const times: (number | undefined)[] = []; + const animator = { + getVelocity: (_property: MotionProperty, time?: number) => { + times.push(time); + return 0; + }, + }; + presentedProgressVelocity(animator, line({x: 0, y: 0}, {x: 1, y: 1}), 1234); + expect(times).toEqual([1234, 1234]); + }); +}); diff --git a/packages/core/src/motion/progress.ts b/packages/core/src/motion/progress.ts new file mode 100644 index 0000000000000..8b97de255de90 --- /dev/null +++ b/packages/core/src/motion/progress.ts @@ -0,0 +1,155 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file progress.ts + * @input A spring, a normalized progress, an animator's presented velocities + * @output Exports `progressCurve` (a spring's progress from 0 to 1 as a + * MotionCurve), `mapProgress` (one curve as a function of another), + * `mapRange` (the clamped linear map most companions use) and + * `presentedProgressVelocity` (the progress velocity that continues what + * an animator shows) + * @position Shared by the motion building blocks that move several channels + * along one path and by companion motion (a + * scrim's dim following a sheet): one velocity unit, one curve mapping and + * one way to continue an interrupted motion + * + * A path is described by a normalized progress: 0 where it starts, 1 where + * it rests, beyond either end on a spring's overshoot. Its velocity is in + * progress per second; each channel's own velocity stays in the channel's + * units per second. + * + * An interrupted motion continues from what is on screen: the + * block reads the presented values and velocities from the animator at one + * `now` (`get`, `getVelocity`), restarts a path from those values, and starts + * its progress with the presented velocity projected on the path's tangent + * at its start, v·t / (t·t), where t = d(values)/dp. Channels are weighted + * into one unit first (px per unit of scale, say), so a scale and a + * translation count alike. + * + * A companion follows a driving curve through `mapProgress`, most often + * with `mapRange`: `mapProgress(sheetY, mapRange([closedY, openY], [0, dim]))` + * dims a scrim as a sheet rises. Played on another animator, it stays in + * lockstep only when it starts with its driver: pass the driver's start, + * `scrim.play({opacity}, {at: start})` with `start = await handle.started` + * (or one shared `at` for both calls); two calls from rest otherwise each + * start at their own commit. + * + * SYNC: When modified, update /packages/core/src/motion/progress.test.ts and + * /packages/core/src/motion/README.md. + */ + +import type {Animator, MotionCurve, MotionProperty} from './animator'; +import { + SETTLING_EPSILON, + solveSpring, + toSpring, + type SpringDescription, +} from './spring'; + +/** The step of the finite differences taken on a progress. */ +const STEP = 1e-4; + +/** + * The progress of `spring` from 0 to 1, starting with `velocity` (progress + * per second): exactly 1 once it settles within `epsilon`. + */ +export function progressCurve( + spring: SpringDescription, + { + velocity = 0, + epsilon = SETTLING_EPSILON, + }: {velocity?: number; epsilon?: number} = {}, +): MotionCurve { + const curve = solveSpring(toSpring(spring), {from: 0, to: 1, velocity}); + const duration = curve.settleTime(epsilon); + return { + duration, + at: t => (t >= duration ? 1 : curve.value(t)), + velocity: t => (t >= duration ? 0 : curve.velocity(t)), + }; +} + +/** + * The curve of `f(driver(t))`, its velocity by the chain rule: a channel + * following a path as its progress moves, or a companion following any + * driving curve (a sheet's `y` mapped onto its scrim's opacity). The driver + * is any MotionCurve, not only a progress from 0 to 1. A companion played on + * another animator starts with its driver (`{at: start}`; see the file + * header). + */ +export function mapProgress( + driver: MotionCurve, + f: (value: number) => number, +): MotionCurve { + return { + duration: driver.duration, + at: t => f(driver.at(t)), + velocity: t => { + const value = driver.at(t); + return ( + ((f(value + STEP) - f(value - STEP)) / (2 * STEP)) * driver.velocity(t) + ); + }, + }; +} + +/** + * The linear map from `input` to `output`, held at `output`'s ends outside + * `input` unless `clamp` is false: what most companions are (a scrim's dim + * along a sheet's travel, a parallax, a dismissal's fade). Either range may + * run backward (`[openY, closedY]`). + */ +export function mapRange( + input: readonly [number, number], + output: readonly [number, number], + {clamp = true}: {clamp?: boolean} = {}, +): (x: number) => number { + const [a, b] = input; + const [c, d] = output; + return x => { + let t = a === b ? (x < a ? 0 : 1) : (x - a) / (b - a); + if (clamp) { + t = Math.min(1, Math.max(0, t)); + } + // Exact at both ends. + return t === 0 ? c : t === 1 ? d : c + (d - c) * t; + }; +} + +/** + * One channel of a path: an animator property and its value at each + * progress. + */ +export interface ProgressChannel { + readonly property: MotionProperty; + /** The property's value at progress `p`. */ + at(p: number): number; + /** + * What one unit of the property weighs in the projection, in a unit the + * channels share (px per unit of scale for a box `weight` px wide). 1 by + * default. + */ + readonly weight?: number; +} + +/** + * The progress velocity, per second, that continues what `animator` + * presents at `now` along a path that starts there: the presented velocity + * projected on the path's tangent at progress 0, v·t / (t·t). 0 when the + * path does not move any of its channels. + */ +export function presentedProgressVelocity( + animator: Pick, + channels: ReadonlyArray, + now?: number, +): number { + let along = 0; + let squared = 0; + for (const channel of channels) { + const weight = channel.weight ?? 1; + const tangent = ((channel.at(STEP) - channel.at(0)) / STEP) * weight; + along += animator.getVelocity(channel.property, now) * weight * tangent; + squared += tangent * tangent; + } + return squared > 1e-12 ? along / squared : 0; +} From 3cfb3b108112669d2863cf34cfe4c50052b7d3a4 Mon Sep 17 00:00:00 2001 From: Cindy Zhang Date: Tue, 3 Nov 2026 07:21:50 -0800 Subject: [PATCH 02/73] refactor(animatedLayout): take the settle spring's progress from progressCurve CodeBunny on #9755: springProgress solved the same spring as progressCurve. It now reads progressCurve (remaining = 1 - progress), so one implementation remains. Same curve, same settle epsilon (0.001) and duration. --- packages/core/src/motion/animatedLayout.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.ts index 9d744f917fcd9..43c5ba9b34971 100644 --- a/packages/core/src/motion/animatedLayout.ts +++ b/packages/core/src/motion/animatedLayout.ts @@ -89,7 +89,8 @@ import { wrapText, } from './transientCopy'; import {isSpring} from './roleValue'; -import {solveSpring, toSpring, type SpringDescription} from './spring'; +import {progressCurve} from './progress'; +import type {SpringDescription} from './spring'; import {registerSpringsTable, SETTLE_SPRING} from './uikit/springs'; import {reducedMotionCrossFade} from './uikit/timing'; @@ -142,11 +143,11 @@ function settleSpring(): SpringDescription { } function springProgress(description: SpringDescription): SpringProgress { - const curve = solveSpring(toSpring(description), {from: 1, to: 0}); - const durationMs = Math.max(1, curve.settleTime(0.001) * 1000); + const curve = progressCurve(description, {epsilon: 0.001}); + const durationMs = Math.max(1, curve.duration * 1000); return { durationMs, - remaining: t => (t >= durationMs ? 0 : curve.value(t / 1000)), + remaining: t => (t >= durationMs ? 0 : 1 - curve.at(t / 1000)), }; } From 273da1e9d4fe603e81d4b68c513c6e5e26e68453 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 3 Nov 2026 07:42:10 -0800 Subject: [PATCH 03/73] feat(core): the rect morph's paths, the rect a grow-out presentation shows at each progress lerpPath, edgeGrowPath, each path's restartFrom and morphCurves in motion/morphPath.ts, internal. Pure geometry over a progress curve: the caller chooses the timing. Rebuilt on the progress module from the pull request's own change, without the open chain it no longer needs. Co-authored-by: Cindy Zhang --- .changeset/motion-morph-path.md | 7 + packages/core/src/motion/README.md | 1 + packages/core/src/motion/morphPath.test.ts | 437 +++++++++++++++++++++ packages/core/src/motion/morphPath.ts | 263 +++++++++++++ 4 files changed, 708 insertions(+) create mode 100644 .changeset/motion-morph-path.md create mode 100644 packages/core/src/motion/morphPath.test.ts create mode 100644 packages/core/src/motion/morphPath.ts diff --git a/.changeset/motion-morph-path.md b/.changeset/motion-morph-path.md new file mode 100644 index 0000000000000..0d0e272fecc67 --- /dev/null +++ b/.changeset/motion-morph-path.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: the rect morph's paths, the geometry touch presentations share when they grow out of a source rect and shrink back into it. `lerpPath` (a straight line between two rects) and `edgeGrowPath` (UIKit's popover, growing out of a point on its edge) name the rect an element shows at each progress, and say how an interrupted motion continues in their own law; `morphCurves` turns a path into compositor curves (`translate`, `scale` and a companion `opacity`). Not exported from the package entry point; no component uses them yet. + +@vjeux diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md index 19ef169b0e573..e0c672a1b1326 100644 --- a/packages/core/src/motion/README.md +++ b/packages/core/src/motion/README.md @@ -38,6 +38,7 @@ roles through `resolveMotion`. | `resolveSnapPoint.ts` | Release policy: the snap point a release lands on (flick, back-out cancel, step limit), on `selectSnapPoint`. Internal. | | `bezier.ts` | Cubic-bézier timing functions (Core Animation's named curves). | | `animator.ts` | Compositor animator: springs, coasts and any closed-form curve compiled to Web Animations, read back analytically. | +| `morphPath.ts` | The rect an element shows at each progress of a grow-out presentation: a straight line, a popover’s edge growth, and the curves that put it there. | | `progress.ts` | A spring's progress, one curve mapped from another (companions, clamped ranges), the velocity that continues a motion. | | `presentation.ts` | Where each moving element is drawn relative to where the engine hit-tests it, reported by the animator while translate runs; read by the gesture host at touch-down. | | `reducedMotionPlan.ts` | The animator's Reduce Motion planner: what one call becomes, a cross-fade whose travel lands while transparent or at once. | diff --git a/packages/core/src/motion/morphPath.test.ts b/packages/core/src/motion/morphPath.test.ts new file mode 100644 index 0000000000000..2f1f7e630da21 --- /dev/null +++ b/packages/core/src/motion/morphPath.test.ts @@ -0,0 +1,437 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file morphPath.test.ts + * @input vitest, the morph paths and the progress helpers, and the models of + * the presentations that move onto the morph, as their pull requests have + * them + * @output Checks that the morph's curves put an element on its path's rect + * every frame, and that each presentation's model (an anchored menu, a + * popover, a lifted preview, a zoom, a sub-menu's parent card) is the same + * rect at every progress, within 0.5 px + * @position Testing; the rect morph's player has its own tests + */ + +import {describe, expect, it} from 'vitest'; +import type {MotionCurve, MotionProperty} from './animator'; +import { + edgeGrowPath, + lerpPath, + morphCurves, + type MorphPath, + type MorphRect, +} from './morphPath'; +import {progressCurve} from './progress'; + +const SPRING = {response: 0.4, dampingRatio: 1}; +const BOUNCY = {response: 0.35, dampingRatio: 0.8}; + +/** Where translate and scale about the top-left corner put `box`. */ +function rectOf( + box: MorphRect, + values: {x: number; y: number; scaleX: number; scaleY: number}, +): MorphRect { + return { + x: box.x + values.x, + y: box.y + values.y, + width: box.width * values.scaleX, + height: box.height * values.scaleY, + }; +} + +function expectRect(actual: MorphRect, expected: MorphRect, tolerance: number) { + const gap = Math.max( + Math.abs(actual.x - expected.x), + Math.abs(actual.y - expected.y), + Math.abs(actual.width - expected.width), + Math.abs(actual.height - expected.height), + ); + expect(gap, JSON.stringify({actual, expected})).toBeLessThanOrEqual( + tolerance, + ); +} + +/** The rect `curves` show at `t` s for an element laid out in `box`. */ +function curvesRect( + box: MorphRect, + curves: Partial>, + t: number, +): MorphRect { + return rectOf(box, { + x: curves.x!.at(t), + y: curves.y!.at(t), + scaleX: curves.scaleX!.at(t), + scaleY: curves.scaleY!.at(t), + }); +} + +/** Every 1/120 s of `progress`, and its end. */ +function frames(progress: MotionCurve): number[] { + const times: number[] = []; + for (let t = 0; t < progress.duration; t += 1 / 120) { + times.push(t); + } + times.push(progress.duration); + return times; +} + +const SQUARE: MorphRect = {x: 179, y: 160, width: 22, height: 22}; + +const BOX: MorphRect = {x: 40, y: 204, width: 320, height: 253}; + +describe('morphCurves', () => { + it('puts the element on a straight path\u2019s rect every frame, each axis scaled to it', () => { + const path = lerpPath(SQUARE, BOX, {opacity: [0, 1]}); + const progress = progressCurve(BOUNCY); + const curves = morphCurves(path, progress); + let overshoot = false; + for (const t of frames(progress)) { + const p = progress.at(t); + overshoot ||= p > 1; + expectRect(curvesRect(BOX, curves, t), path.rectAt(p), 0.01); + expect(curves.opacity!.at(t)).toBeCloseTo(p, 9); + } + // Past 1 on the spring's overshoot, the rect runs past rest too. + expect(overshoot).toBe(true); + }); + + it('keeps the element\u2019s aspect under a uniform scale', () => { + const thumb = {x: 12, y: 300, width: 100, height: 75}; + const detail = {x: 0, y: 120, width: 390, height: 292.5}; + const path = lerpPath(thumb, detail, {scale: 'uniform'}); + const progress = progressCurve(SPRING); + const curves = morphCurves(path, progress); + for (const t of frames(progress)) { + expect(curves.scaleY!.at(t)).toBe(curves.scaleX!.at(t)); + expectRect( + curvesRect(detail, curves, t), + path.rectAt(progress.at(t)), + 0.01, + ); + } + expect(curves.opacity).toBeUndefined(); + }); + + it('moves the companion opacity on a progress of its own when given one', () => { + const path = lerpPath(SQUARE, BOX, {opacity: [1, 0]}); + const progress = progressCurve(SPRING); + const fade = progressCurve({response: 0.2, dampingRatio: 1}); + const curves = morphCurves(path, progress, fade); + for (const t of [0.01, 0.05, 0.1, 0.2]) { + expect(curves.opacity!.at(t)).toBeCloseTo(1 - fade.at(t), 9); + } + }); + + it('ends exactly on identity when the path ends on its box', () => { + const progress = progressCurve(BOUNCY); + for (const path of [ + lerpPath(SQUARE, BOX), + edgeGrowPath({ + box: BOX, + origin: {x: 160, y: 0}, + axis: 'y', + collapsedScale: 0.01, + collapsedLength: 100 / 253, + }), + ]) { + const curves = morphCurves(path, progress); + const end = progress.duration; + expect([ + curves.x!.at(end), + curves.y!.at(end), + curves.scaleX!.at(end), + curves.scaleY!.at(end), + ]).toEqual([0, 0, 1, 1]); + } + }); +}); + +// The models of the presentations that move onto the morph, as their pull +// requests have them; each migration checks the morph against its live code. + +/** Popover (#8187, popoverSurfaceMotion.ts): popoverCollapsedState, popoverFrame. */ +const POPOVER = {collapsedScale: 0.01, collapsedLengthPx: 100}; +function popoverModel(surface: MorphRect, source: MorphRect) { + const gaps = { + below: surface.y - (source.y + source.height), + above: source.y - (surface.y + surface.height), + right: surface.x - (source.x + source.width), + left: source.x - (surface.x + surface.width), + }; + let side: keyof typeof gaps = 'below'; + for (const candidate of ['above', 'right', 'left'] as const) { + if (gaps[candidate] > gaps[side]) { + side = candidate; + } + } + const clamp = (v: number, min: number, max: number) => + Math.min(Math.max(v, min), max); + const centerX = clamp( + source.x + source.width / 2 - surface.x, + 0, + surface.width, + ); + const centerY = clamp( + source.y + source.height / 2 - surface.y, + 0, + surface.height, + ); + const vertical = side === 'below' || side === 'above'; + const fullLength = vertical ? surface.height : surface.width; + const axis: 'x' | 'y' = vertical ? 'y' : 'x'; + const state = { + originX: vertical ? centerX : side === 'right' ? 0 : surface.width, + originY: vertical ? (side === 'below' ? 0 : surface.height) : centerY, + axis, + scale: POPOVER.collapsedScale, + length: Math.min(1, POPOVER.collapsedLengthPx / fullLength), + }; + // A frame of (scale, length, opacity), scaled about the origin. + const frameRect = (scale: number, length: number): MorphRect => { + const along = scale * length; + const scaleX = state.axis === 'x' ? along : scale; + const scaleY = state.axis === 'y' ? along : scale; + return { + x: surface.x + state.originX * (1 - scaleX), + y: surface.y + state.originY * (1 - scaleY), + width: surface.width * scaleX, + height: surface.height * scaleY, + }; + }; + return { + state, + rectAt: (p: number) => + frameRect( + state.scale + (1 - state.scale) * p, + state.length + (1 - state.length) * p, + ), + frameRect, + }; +} + +/** DropdownMenu (#8080, menuSurfaceMotion.ts): menuCollapsedState, scaled per axis about its origin. */ +function menuModel(surface: MorphRect, anchor: {x: number; y: number}) { + const collapsedSize = 22; + const scaleX0 = collapsedSize / surface.width; + const scaleY0 = collapsedSize / surface.height; + const originX = + (anchor.x - surface.x - (surface.width / 2) * scaleX0) / (1 - scaleX0); + const originY = + (anchor.y - surface.y - (surface.height / 2) * scaleY0) / (1 - scaleY0); + return (p: number): MorphRect => { + const scaleX = scaleX0 + (1 - scaleX0) * p; + const scaleY = scaleY0 + (1 - scaleY0) * p; + return { + x: surface.x + originX * (1 - scaleX), + y: surface.y + originY * (1 - scaleY), + width: surface.width * scaleX, + height: surface.height * scaleY, + }; + }; +} + +/** ContextMenu (#8201, ContextMenuLift.tsx): the preview laid out on its source, x, y and scale sprung together. */ +function liftModel(source: MorphRect, pressScale: number, lifted: MorphRect) { + const from = { + x: (source.width * (1 - pressScale)) / 2, + y: (source.height * (1 - pressScale)) / 2, + scale: pressScale, + }; + const to = { + x: lifted.x - source.x, + y: lifted.y - source.y, + scale: lifted.width / source.width, + }; + return (p: number): MorphRect => { + const scale = from.scale + (to.scale - from.scale) * p; + return { + x: source.x + from.x + (to.x - from.x) * p, + y: source.y + from.y + (to.y - from.y) * p, + width: source.width * scale, + height: source.height * scale, + }; + }; +} + +/** Lightbox (#8231, zoomTransition.ts): zoomFramesAt's detail, centred, and its fade gain. */ +function zoomModel(source: MorphRect, detail: MorphRect) { + const aspect = detail.height / detail.width; + const startHeight = source.width * aspect; + const start = { + x: source.x, + y: source.y + source.height / 2 - startHeight / 2, + width: source.width, + height: startHeight, + }; + return { + rectAt: (p: number): MorphRect => { + const lerp = (a: number, b: number) => a + (b - a) * p; + const width = lerp(start.width, detail.width); + const anchor = lerp( + start.y + start.height / 2, + detail.y + detail.height / 2, + ); + const height = width * aspect; + return { + x: lerp(start.x, detail.x), + y: anchor - height / 2, + width, + height, + }; + }, + opacityAt: (p: number) => Math.min(1, Math.max(0, 1.56 * p)), + }; +} + +/** DropdownMenu sub-menu (#8220, menuDrillInMotion.ts): the parent card, scaled about its centre and dropped. */ +function cardModel(box: MorphRect) { + const parentScale = 0.97; + const dropPx = 3; + return (p: number): MorphRect => { + const scale = 1 + (parentScale - 1) * p; + return { + x: box.x + (box.width * (1 - scale)) / 2, + y: box.y + (box.height * (1 - scale)) / 2 + dropPx * p, + width: box.width * scale, + height: box.height * scale, + }; + }; +} + +/** Progresses 0 to 1.1 (a spring's overshoot) and a little below 0. */ +const PROGRESSES = Array.from({length: 24}, (_, i) => -0.05 + i * 0.05); + +describe('the presentations that move onto the morph are the same rect at every progress', () => { + it('an anchored menu (#8080): a straight line from the collapsed square on its control', () => { + const anchor = {x: 190, y: 171}; + const model = menuModel(BOX, anchor); + const path = lerpPath( + {x: anchor.x - 11, y: anchor.y - 11, width: 22, height: 22}, + BOX, + {opacity: [0, 1]}, + ); + for (const p of PROGRESSES) { + expectRect(path.rectAt(p), model(p), 0.5); + expect(path.opacityAt!(p)).toBeCloseTo(p, 9); + } + }); + + it('a popover (#8187): UIKit\u2019s edge growth, on each side of its source', () => { + const source = {x: 141, y: 160, width: 120, height: 44}; + const surfaces: Record = { + below: {x: 41, y: 204, width: 320, height: 253}, + above: {x: 41, y: -93, width: 320, height: 253}, + right: {x: 261, y: 100, width: 200, height: 160}, + left: {x: -59, y: 100, width: 200, height: 160}, + }; + for (const surface of Object.values(surfaces)) { + const model = popoverModel(surface, source); + const path = edgeGrowPath({ + box: surface, + origin: {x: model.state.originX, y: model.state.originY}, + axis: model.state.axis, + collapsedScale: model.state.scale, + collapsedLength: model.state.length, + }); + for (const p of PROGRESSES) { + expectRect(path.rectAt(p), model.rectAt(p), 0.5); + expect(path.opacityAt!(p)).toBeCloseTo(p, 9); + } + } + }); + + it('a popover (#8187) continues an interrupted motion in its own law: scale and length from the frame on screen', () => { + const surface = {x: 41, y: 204, width: 320, height: 253}; + const model = popoverModel(surface, { + x: 141, + y: 160, + width: 120, + height: 44, + }); + const path = edgeGrowPath({ + box: surface, + origin: {x: model.state.originX, y: model.state.originY}, + axis: model.state.axis, + collapsedScale: model.state.scale, + collapsedLength: model.state.length, + }); + // Mid-dismissal: scale 0.4, length 0.6 (readState), opacity 0.5. + const onScreen = model.frameRect(0.4, 0.6); + const back = path.restartFrom!(onScreen, 0.5, 'rest'); + const away = path.restartFrom!(onScreen, 0.5, 'source'); + for (const p of [0, 0.25, 0.5, 0.75, 1, 1.05]) { + // #8187's surfaceCurves: each of scale, length and opacity on a line. + expectRect( + back.rectAt(p), + model.frameRect(0.4 + 0.6 * p, 0.6 + 0.4 * p), + 0.5, + ); + expect(back.opacityAt!(p)).toBeCloseTo(0.5 + 0.5 * p, 9); + expectRect( + away.rectAt(p), + model.frameRect( + 0.4 + (model.state.scale - 0.4) * p, + 0.6 + (model.state.length - 0.6) * p, + ), + 0.5, + ); + expect(away.opacityAt!(p)).toBeCloseTo(0.5 - 0.5 * p, 9); + } + }); + + it('a lifted preview (#8201): its source box, scaled about its centre by the press, to its lifted box', () => { + const source = {x: 60, y: 300, width: 270, height: 64}; + const pressScale = 0.96; + const lifted = {x: 50.5, y: 297.75, width: 289, height: 68.5}; + const model = liftModel(source, pressScale, lifted); + const pressed = { + x: source.x + (source.width * (1 - pressScale)) / 2, + y: source.y + (source.height * (1 - pressScale)) / 2, + width: source.width * pressScale, + height: source.height * pressScale, + }; + const path = lerpPath(pressed, lifted, {box: source, scale: 'uniform'}); + const progress = progressCurve(SPRING); + const curves = morphCurves(path, progress); + for (const p of PROGRESSES) { + expectRect(path.rectAt(p), model(p), 0.5); + } + for (const t of frames(progress)) { + expectRect(curvesRect(source, curves, t), model(progress.at(t)), 0.5); + } + }); + + it('a zoom (#8231): the detail on its portal\u2019s frame, with its fade gain', () => { + const source = {x: 130, y: 400, width: 120, height: 120}; + const detail = {x: 0, y: 160, width: 390, height: 292.5}; + const model = zoomModel(source, detail); + const path: MorphPath = { + box: detail, + scale: 'uniform', + rectAt: model.rectAt, + opacityAt: model.opacityAt, + }; + const progress = progressCurve(SPRING); + const curves = morphCurves(path, progress); + for (const t of frames(progress)) { + const p = progress.at(t); + // zoomElementCurves: x and y from the box, scale by the width. + const frame = model.rectAt(p); + expect(curves.x!.at(t)).toBeCloseTo(frame.x - detail.x, 6); + expect(curves.y!.at(t)).toBeCloseTo(frame.y - detail.y, 6); + expect(curves.scaleX!.at(t)).toBeCloseTo(frame.width / detail.width, 9); + expect(curves.opacity!.at(t)).toBeCloseTo(model.opacityAt(p), 9); + expectRect(curvesRect(detail, curves, t), frame, 0.5); + } + }); + + it('a sub-menu\u2019s parent card (#8220): scaled about its centre and dropped', () => { + const box = {x: 40, y: 204, width: 250, height: 300}; + const model = cardModel(box); + const card = model(1); + const path = lerpPath(box, card, {box, scale: 'uniform'}); + for (const p of PROGRESSES) { + expectRect(path.rectAt(p), model(p), 0.5); + } + }); +}); diff --git a/packages/core/src/motion/morphPath.ts b/packages/core/src/motion/morphPath.ts new file mode 100644 index 0000000000000..622f2720b4215 --- /dev/null +++ b/packages/core/src/motion/morphPath.ts @@ -0,0 +1,263 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file morphPath.ts + * @input The progress helpers (progress.ts) and the animator's curve types + * @output Exports `lerpPath` and `edgeGrowPath` (the rect an element shows at + * each progress), `morphCurves` (the curves that put it there) and + * `travelAt` (the transform for one progress, for the rect morph's player) + * @position Motion foundation building block, internal to core: the geometry + * of "grow out of a source rect, shrink back into it" that touch + * presentations share (an anchored menu, a popover, a context menu's + * lifted preview, a photo's zoom, a sub-menu's parent card); a rect morph + * plays it + * + * A path names the rect an element shows at each progress: 0 on its source, + * 1 at rest, beyond either end on a spring's overshoot. The element stays + * laid out in the path's `box`; `translate` and `scale` about + * `transform-origin: 0 0` put it on the path's rect every frame, scaling each + * axis to the rect (`'axes'`) or both by the rect's width (`'uniform'`, which + * keeps the element's aspect), and a companion opacity follows a progress of + * its own or the same one. Only `translate`, `scale` and `opacity` move, so + * the motion runs on the compositor with no layout or paint per frame. + * + * Two laws cover the presentations: `lerpPath`, a straight line from one rect + * to another (position and size move together), and `edgeGrowPath`, UIKit's + * popover, which grows out of a point on its edge facing the source with its + * length along the axis away from the source growing with its scale. A path + * also says how an interrupted motion continues in its own law + * (`restartFrom`), so a popover turning around keeps its edge growth. + * + * SYNC: When modified, update: + * - /packages/core/src/motion/morphPath.test.ts + * - /packages/core/src/motion/README.md + */ + +import type {MotionCurve, MotionProperty} from './animator'; +import {mapProgress} from './progress'; + +/** + * A box in viewport px. + */ +export interface MorphRect { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; +} + +/** + * How the element is scaled onto a path's rect: each axis to the rect + * (`'axes'`), or both by the rect's width (`'uniform'`, keeping the + * element's aspect). + */ +export type MorphScale = 'axes' | 'uniform'; + +/** + * The end of a path a restarted path heads for. + */ +export type MorphEnd = 'source' | 'rest'; + +/** + * The rect an element shows at each progress of a presentation: 0 on its + * source, 1 at rest. + */ +export interface MorphPath { + /** The element's box as laid out: its rect with no transform. */ + readonly box: MorphRect; + /** @default 'axes' */ + readonly scale?: MorphScale; + /** The rect at progress `p`. */ + rectAt(p: number): MorphRect; + /** The companion opacity at progress `p`; opacity is left alone without it. */ + opacityAt?(p: number): number; + /** + * The path from `rect`, shown at `opacity`, to this path's `end`, in its + * own law: how an interrupted motion continues. A straight line to that + * end without it. + */ + restartFrom?(rect: MorphRect, opacity: number, end: MorphEnd): MorphPath; +} + +// Exact at both ends, so a path that ends on its box ends on identity. +const lerp = (a: number, b: number, p: number) => + p === 0 ? a : p === 1 ? b : a + (b - a) * p; + +/** + * A straight line from `from` (progress 0) to `to` (progress 1): position and + * size move together, as an anchored menu grows out of a square on its + * control, a lifted preview grows to its box, a sub-menu's parent card + * shrinks back. + */ +export function lerpPath( + from: MorphRect, + to: MorphRect, + { + box = to, + scale = 'axes', + opacity, + }: { + /** The element's box as laid out; `to` by default. */ + box?: MorphRect; + scale?: MorphScale; + /** The companion opacity at progress 0 and 1; none by default. */ + opacity?: readonly [number, number]; + } = {}, +): MorphPath { + return { + box, + scale, + rectAt: p => ({ + x: lerp(from.x, to.x, p), + y: lerp(from.y, to.y, p), + width: lerp(from.width, to.width, p), + height: lerp(from.height, to.height, p), + }), + ...(opacity != null + ? {opacityAt: (p: number) => lerp(opacity[0], opacity[1], p)} + : null), + }; +} + +interface GrowState { + /** The scale across the axis. */ + scale: number; + /** The share of the full length along the axis, before `scale`. */ + length: number; + opacity: number; +} + +const GROWN: GrowState = {scale: 1, length: 1, opacity: 1}; + +function growPath( + box: MorphRect, + origin: {x: number; y: number}, + axis: 'x' | 'y', + collapsed: GrowState, + from: GrowState, + to: GrowState, +): MorphPath { + const stateAt = (p: number): GrowState => ({ + scale: lerp(from.scale, to.scale, p), + length: lerp(from.length, to.length, p), + opacity: lerp(from.opacity, to.opacity, p), + }); + return { + box, + scale: 'axes', + rectAt(p) { + const state = stateAt(p); + const along = state.scale * state.length; + const scaleX = axis === 'x' ? along : state.scale; + const scaleY = axis === 'y' ? along : state.scale; + return { + x: box.x + origin.x * (1 - scaleX), + y: box.y + origin.y * (1 - scaleY), + width: box.width * scaleX, + height: box.height * scaleY, + }; + }, + opacityAt: p => stateAt(p).opacity, + restartFrom(rect, opacity, end) { + const scaleX = box.width > 0 ? rect.width / box.width : 1; + const scaleY = box.height > 0 ? rect.height / box.height : 1; + const across = axis === 'x' ? scaleY : scaleX; + const along = axis === 'x' ? scaleX : scaleY; + return growPath( + box, + origin, + axis, + collapsed, + {scale: across, length: across > 0 ? along / across : 1, opacity}, + end === 'rest' ? GROWN : collapsed, + ); + }, + }; +} + +/** + * UIKit's popover (UIPopoverPresentationController, iOS 26.2): it grows out of + * `origin`, the point of its edge facing the source, from a uniform + * `collapsedScale` and `collapsedLength` of its own length along `axis` (the + * axis pointing away from the source). At progress p its scale is + * s = s₀ + (1 − s₀)·p across the axis and s·(L₀ + (1 − L₀)·p) along it, + * about `origin`, and its opacity p, so it widens before it lengthens. An + * interrupted motion continues from the scale and length on screen. + */ +export function edgeGrowPath({ + box, + origin, + axis, + collapsedScale, + collapsedLength, +}: { + /** The element's box as laid out, at rest. */ + box: MorphRect; + /** The point it grows out of, px from the box's top-left corner. */ + origin: {x: number; y: number}; + /** The axis pointing away from the source: `y` above or below it. */ + axis: 'x' | 'y'; + /** The uniform scale it grows out of. */ + collapsedScale: number; + /** The share of its own length along `axis` it grows out of. */ + collapsedLength: number; +}): MorphPath { + const collapsed = { + scale: collapsedScale, + length: collapsedLength, + opacity: 0, + }; + return growPath(box, origin, axis, collapsed, collapsed, GROWN); +} + +/** The transform channels a path drives. */ +export type TravelProperty = 'x' | 'y' | 'scaleX' | 'scaleY'; + +/** + * The transform that puts an element laid out in `path.box` on its rect. + * + * @internal Read by the rect morph's player for its start + * values and its velocity projection; not exported from the package. + */ +export function travelAt( + path: MorphPath, + p: number, +): Record { + const rect = path.rectAt(p); + const {box} = path; + const scaleX = box.width > 0 ? rect.width / box.width : 1; + const scaleY = + path.scale === 'uniform' + ? scaleX + : box.height > 0 + ? rect.height / box.height + : 1; + return {x: rect.x - box.x, y: rect.y - box.y, scaleX, scaleY}; +} + +/** + * Curves for `Animator.play` that put an element laid out in `path.box`, with + * `transform-origin: 0 0`, on the path's rect as `progress` moves, and its + * opacity on `path.opacityAt` as `fade` moves (`progress` by default). + */ +export function morphCurves( + path: MorphPath, + progress: MotionCurve, + fade: MotionCurve = progress, +): Partial> { + const travel = (property: TravelProperty) => + mapProgress(progress, p => travelAt(path, p)[property]); + const curves: Partial> = { + x: travel('x'), + y: travel('y'), + scaleX: travel('scaleX'), + scaleY: travel('scaleY'), + }; + const {opacityAt} = path; + if (opacityAt != null) { + curves.opacity = mapProgress(fade, p => opacityAt(p)); + } + return curves; +} From 131ca142ce0e251357ca615c2b40dca5794f321c Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 3 Nov 2026 08:23:51 -0800 Subject: [PATCH 04/73] feat(core): one rect morph for touch presentations that grow out of a source rect createRectMorph in motion/rectMorph.ts, internal: present along a path and dismiss back onto a copy or the element, each continuing the other from the rect on screen. Rebuilt on main from the pull request's own change and ported to main's engine (createMotionAnimator). Timing follows the owner's rule for touch motion: present and dismiss take a motion, either a theme duration and easing (a tap, a key, the program) or a spring (a gesture's release, from its velocity). timedProgressCurve joins the progress helpers. architecture:react-component-runtime INV12 records the implementation gap: the size-change glide moves onto the morph next. Co-authored-by: Cindy Zhang --- .changeset/motion-rect-morph.md | 7 + docs/architecture/react-component-runtime.md | 4 +- packages/core/src/motion/README.md | 1 + .../core/src/motion/__tests__/motionBundle.ts | 2 + .../rectMorph.interaction.browser.spec.ts | 444 +++++++++++ packages/core/src/motion/progress.test.ts | 20 + packages/core/src/motion/progress.ts | 31 +- packages/core/src/motion/rectMorph.test.ts | 695 ++++++++++++++++++ packages/core/src/motion/rectMorph.ts | 501 +++++++++++++ 9 files changed, 1703 insertions(+), 2 deletions(-) create mode 100644 .changeset/motion-rect-morph.md create mode 100644 packages/core/src/motion/__tests__/rectMorph.interaction.browser.spec.ts create mode 100644 packages/core/src/motion/rectMorph.test.ts create mode 100644 packages/core/src/motion/rectMorph.ts diff --git a/.changeset/motion-rect-morph.md b/.changeset/motion-rect-morph.md new file mode 100644 index 0000000000000..0192c46f8c2cd --- /dev/null +++ b/.changeset/motion-rect-morph.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: the rect morph, one way for a touch presentation to grow out of a source rect and shrink back into it. `createRectMorph` presents an element along a path (`lerpPath`, `edgeGrowPath`) and dismisses it back on a copy or on itself, each continuing the other from the rect on screen. A motion a tap or a key starts plays a theme duration and easing; a gesture's release plays a spring from its velocity. Reduced Motion is left to the animator. `timedProgressCurve` joins the progress helpers. Not exported from the package entry point; no component uses it yet. + +@vjeux diff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.md index 56838fde56f98..37e9e4bc3fbcc 100644 --- a/docs/architecture/react-component-runtime.md +++ b/docs/architecture/react-component-runtime.md @@ -198,7 +198,9 @@ those contracts. change and moves shifted content with a compositor-only translate played through the shared rectangle morph (`architecture:layer-runtime` INV15; `spec:AST-094` FR5) once Core has that morph; until then, the module plays - its own compositor translate. It never animates height. Its walk visits only + its own compositor translate. (Implementation gap: Core has the shared + rectangle morph, but the size-change glide still plays its own compositor + translate; it moves onto the morph next.) It never animates height. Its walk visits only the changed element's ancestors up to the area and the element siblings on either side at each of their levels, through `parentElement`, `nextElementSibling` and `previousElementSibling`, descending only into an diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md index e0c672a1b1326..89ae755675ad3 100644 --- a/packages/core/src/motion/README.md +++ b/packages/core/src/motion/README.md @@ -39,6 +39,7 @@ roles through `resolveMotion`. | `bezier.ts` | Cubic-bézier timing functions (Core Animation's named curves). | | `animator.ts` | Compositor animator: springs, coasts and any closed-form curve compiled to Web Animations, read back analytically. | | `morphPath.ts` | The rect an element shows at each progress of a grow-out presentation: a straight line, a popover’s edge growth, and the curves that put it there. | +| `rectMorph.ts` | Grow out of a source rect and shrink back into it along a path: present and dismiss, each continuing the other from the rect on screen. | | `progress.ts` | A spring's progress, one curve mapped from another (companions, clamped ranges), the velocity that continues a motion. | | `presentation.ts` | Where each moving element is drawn relative to where the engine hit-tests it, reported by the animator while translate runs; read by the gesture host at touch-down. | | `reducedMotionPlan.ts` | The animator's Reduce Motion planner: what one call becomes, a cross-fade whose travel lands while transparent or at once. | diff --git a/packages/core/src/motion/__tests__/motionBundle.ts b/packages/core/src/motion/__tests__/motionBundle.ts index 874fb5e2a8d38..0b50a74857f91 100644 --- a/packages/core/src/motion/__tests__/motionBundle.ts +++ b/packages/core/src/motion/__tests__/motionBundle.ts @@ -9,6 +9,8 @@ */ export {createMotionAnimator} from '../animator'; +export {progressCurve} from '../progress'; +export {createRectMorph, edgeGrowPath, lerpPath} from '../rectMorph'; export {solveSpring, toSpring} from '../spring'; export {registerSpringsTable, springs} from '../uikit/springs'; export {motionRoleOf} from '../roles'; diff --git a/packages/core/src/motion/__tests__/rectMorph.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/rectMorph.interaction.browser.spec.ts new file mode 100644 index 0000000000000..f4305542366ce --- /dev/null +++ b/packages/core/src/motion/__tests__/rectMorph.interaction.browser.spec.ts @@ -0,0 +1,444 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file rectMorph.interaction.browser.spec.ts + * @input The rect morph and the motion source bundled with esbuild onto a + * blank fixture page; the interaction harness's busy-main-thread, + * screencast and trace instruments; Chromium and WebKit on the phone + * profile + * @output Proof that the engine shows the morph's path: seeked frame by + * frame, a present and a dismissal put the element's box on screen on the + * path's rect within 0.5 px (a straight line with a fade, a popover's edge + * growth); the morph keeps moving through a 1 s main-thread block; no + * Layout or Paint runs while it animates (Chromium trace) + * @position Browser proof for rectMorph.ts, run by `pnpm test:interaction`; + * jsdom runs no animations + */ + +import {fileURLToPath} from 'node:url'; +import { + blockMainThread, + busyWindowProof, + countBetween, + markElement, + startScreencast, + traceRendering, + trackMarker, +} from '@astryxdesign/interaction-harness'; +import {expect, test, type Page} from '@playwright/test'; +import {build} from 'esbuild'; +// The page's `Motion` global (the bundle) is declared beside the animator's +// proofs, in animator.interaction.browser.spec.ts. + +let script = ''; + +test.beforeAll(async () => { + const result = await build({ + entryPoints: [fileURLToPath(new URL('./motionBundle.ts', import.meta.url))], + bundle: true, + write: false, + format: 'iife', + globalName: 'Motion', + target: 'es2022', + }); + script = result.outputFiles[0].text; +}); + +/** The surface at rest, and the 22 px square on its control it grows from. */ +const BOX = {x: 40, y: 204, width: 320, height: 253}; +const SQUARE = {x: 179, y: 160, width: 22, height: 22}; +/** UIKit's popover numbers (#8187): 1 % scale, 100 px of length. */ +const POPOVER = {origin: {x: 160, y: 0}, collapsedScale: 0.01}; +const SPRING = {response: 0.45, dampingRatio: 0.8}; +/** A slow spring for the block: well over a px per frame throughout. */ +const SLOW = {response: 2, dampingRatio: 1}; +const MARKER_INSET = 8; + +// A real navigation (not setContent): the page keeps its own window. +async function open(page: Page) { + const html = ` + +
+`; + await page.route('http://motion.test/', async route => + route.fulfill({contentType: 'text/html', body: html}), + ); + await page.goto('http://motion.test/'); +} + +type PathKind = 'line' | 'edge'; + +/** + * Plays a present (or, after it, a dismissal on a copy) of `kind`, pauses + * the engine, seeks it every 1/60 s, and returns the worst gap between the + * box on screen and the path's rect, px, and between the opacity on screen + * and the path's. + */ +async function seekedGap( + page: Page, + kind: PathKind, + phase: 'present' | 'dismiss', +) { + return page.evaluate( + async ({kind, phase, box, square, popover, spring}) => { + const surface = document.getElementById('surface') as HTMLElement; + const morph = Motion.createRectMorph(surface); + const path = + kind === 'line' + ? Motion.lerpPath(square, box, {opacity: [0, 1]}) + : Motion.edgeGrowPath({ + box, + origin: popover.origin, + axis: 'y', + collapsedScale: popover.collapsedScale, + collapsedLength: 100 / box.height, + }); + let target = surface; + let handle = morph.present(path, {spring: spring}); + if (phase === 'dismiss') { + await handle.finished; + target = surface.cloneNode(true) as HTMLElement; + target.id = 'copy'; + surface.after(target); + handle = morph.dismiss(path, {spring: spring}, {target}); + } + await handle.started; + const animations = target.getAnimations(); + const progress = Motion.progressCurve(spring); + for (const animation of animations) { + animation.pause(); + } + let worstRect = 0; + let worstOpacity = 0; + const step = 1000 / 60; + for (let t = 0; t <= progress.duration * 1000 + step; t += step) { + for (const animation of animations) { + animation.currentTime = t; + } + const p = progress.at(t / 1000); + // The dismissal runs the path backward, rest to source. + const at = phase === 'present' ? p : 1 - p; + // Past the source on an overshoot the scale crosses 0 (the copy is + // transparent there): the box on screen is the flipped rect. + const raw = path.rectAt(at); + const expected = { + x: Math.min(raw.x, raw.x + raw.width), + y: Math.min(raw.y, raw.y + raw.height), + width: Math.abs(raw.width), + height: Math.abs(raw.height), + }; + const rect = target.getBoundingClientRect(); + worstRect = Math.max( + worstRect, + Math.abs(rect.x - expected.x), + Math.abs(rect.y - expected.y), + Math.abs(rect.width - expected.width), + Math.abs(rect.height - expected.height), + ); + const opacity = Number.parseFloat(getComputedStyle(target).opacity); + const expectedOpacity = Math.min( + 1, + Math.max(0, path.opacityAt?.(at) ?? 1), + ); + worstOpacity = Math.max( + worstOpacity, + Math.abs(opacity - expectedOpacity), + ); + } + return { + animations: animations.length, + worstRect, + worstOpacity, + origin: getComputedStyle(target).transformOrigin, + }; + }, + {kind, phase, box: BOX, square: SQUARE, popover: POPOVER, spring: SPRING}, + ); +} + +for (const kind of ['line', 'edge'] as const) { + for (const phase of ['present', 'dismiss'] as const) { + test(`the engine shows the path\u2019s rect at every frame: ${kind === 'line' ? 'a straight line with a fade' : 'a popover\u2019s edge growth'}, ${phase}`, async ({ + page, + }) => { + await open(page); + const result = await seekedGap(page, kind, phase); + test.info().annotations.push({ + type: 'seeked gap', + description: JSON.stringify(result), + }); + // translate, scale and opacity, one animation each. + expect(result.animations).toBe(3); + expect(result.origin).toBe('0px 0px'); + expect(result.worstRect).toBeLessThanOrEqual(0.5); + expect(result.worstOpacity).toBeLessThanOrEqual(0.005); + }); + } +} + +// FR6 is verified in a browser too: an interrupted motion continues from the +// box on screen. Two readings: reads on either side of the switch in one +// task, and the composited frames across it. + +// One task, two reads either side of the switch: nothing is presented in +// between, so the second read is the new motion's first value. The morph +// reads the document timeline here, the clock the compositor presents on, +// so both reads see one instant whatever the frame timing; on its default +// clock the new motion's start would sit up to the time since the last frame +// ahead of the first read. +async function readAcrossSwitch(page: Page, restart: boolean) { + return page.evaluate( + async ({box, square, spring, restart}) => { + const element = document.getElementById('surface') as HTMLElement; + const morph = Motion.createRectMorph(element, { + now: () => Number(document.timeline.currentTime), + }); + const path = Motion.lerpPath(square, box); + const read = () => { + const r = element.getBoundingClientRect(); + return {x: r.x, y: r.y, width: r.width, height: r.height}; + }; + await morph.present(path, {spring: spring}).started; + // Partway up the present, with the box well away from both ends. + await new Promise(resolve => setTimeout(resolve, 160)); + // Read and switch inside a frame callback: there the timeline's time is + // the frame's, the time the browser samples the running animation at. + // In a timer task WebKit can hand out a timeline time a frame stale + // while the box is sampled fresher, which a loaded page shows as a + // step of a few px. + const frame = async () => + new Promise(resolve => requestAnimationFrame(resolve)); + await frame(); + const previous = read(); + const previousAt = Number(document.timeline.currentTime); + await frame(); + const before = read(); + const at = Number(document.timeline.currentTime); + if (restart) { + // What a morph that did not continue would do: start the path over. + morph.reset(); + morph.present(path, {spring: spring}); + } else { + // On the element itself: no copy, so the switch alone moves the box. + morph.dismiss(path, {spring: spring}, {target: element}); + } + const after = read(); + const change = (a: typeof before, b: typeof before) => + Math.max( + Math.abs(a.x - b.x), + Math.abs(a.y - b.y), + Math.abs(a.width - b.width), + Math.abs(a.height - b.height), + ); + return { + before, + after, + step: change(after, before), + // The reads share a clock that WebKit counts in whole milliseconds, + // so they can only agree to the box's travel in one of them, + // measured over the frame before. + clockTick: change(before, previous) / Math.max(1, at - previousAt), + }; + }, + {box: BOX, square: SQUARE, spring: SLOW, restart}, + ); +} + +// The composited frames across a switch, on the morph's default clock. The +// box rises 240 px along a path with no fade, so the marker is tracked in +// every frame; the dismissal (or the restart) takes over 600 ms in, near the +// middle of the travel. The screencast starts once the present has started: +// before that the box sits at rest, and its first step onto the path is not +// the switch. +type Switching = { + morph: ReturnType; + path: ReturnType; + from: {x: number; y: number; width: number; height: number}; +}; +async function trackAcrossSwitch(page: Page, restart: boolean) { + const surface = page.locator('#surface'); + await markElement(surface, {inset: MARKER_INSET}); + await page.evaluate( + async ({box, spring}) => { + const element = document.getElementById('surface') as HTMLElement; + const morph = Motion.createRectMorph(element); + const from = { + x: box.x, + y: box.y + 240, + width: box.width * 0.8, + height: box.height * 0.8, + }; + const path = Motion.lerpPath(from, box); + await morph.present(path, {spring: spring}).started; + (window as unknown as {switching: Switching}).switching = { + morph, + path, + from, + }; + }, + {box: BOX, spring: SLOW}, + ); + const cast = await startScreencast(page); + const geometry = await page.evaluate( + async ({box, spring, restart}) => { + const element = document.getElementById('surface') as HTMLElement; + const {morph, path, from} = (window as unknown as {switching: Switching}) + .switching; + await new Promise(resolve => setTimeout(resolve, 600)); + const at = element.getBoundingClientRect().y; + if (restart) { + morph.reset(); + morph.present(path, {spring: spring}); + } else { + morph.dismiss(path, {spring: spring}, {target: element}); + } + await new Promise(resolve => setTimeout(resolve, 600)); + // The smallest move a discontinuity would make from here: back to the + // path's start (a restart), or to the box at rest (a frame presented + // without the morph's transform). + return {jump: Math.min(Math.abs(at - from.y), Math.abs(at - box.y))}; + }, + {box: BOX, spring: SLOW, restart}, + ); + await page.waitForTimeout(100); + const seen = (await trackMarker(page, await cast.stop())).filter( + frame => frame.box != null, + ); + // A loaded page can open the screencast on the last frame composited before + // the present's first, with the box at rest; its step onto the path is not + // the switch. The present starts 240 px below rest, so the frames from the + // first one off the rest position on are the present's. + const onPath = seen.findIndex( + frame => (frame.box?.y ?? 0) > BOX.y + MARKER_INSET + 1, + ); + const tracked = onPath < 0 ? seen : seen.slice(onPath); + let rising = 0; + let falling = 0; + let worstStep = 0; + for (let i = 1; i < tracked.length; i++) { + const dy = tracked[i].box!.y - tracked[i - 1].box!.y; + if (dy < -0.5) { + rising++; + } + if (dy > 0.5) { + falling++; + } + worstStep = Math.max(worstStep, Math.abs(dy)); + } + return {tracked: tracked.length, rising, falling, worstStep, ...geometry}; +} + +const SUBPIXEL = 0.5; + +test('a dismissal mid-present starts from the box: reads either side of the switch, in one task', async ({ + page, +}) => { + await open(page); + const reading = await readAcrossSwitch(page, false); + test + .info() + .annotations.push({type: 'switch', description: JSON.stringify(reading)}); + expect(reading.step).toBeLessThanOrEqual(SUBPIXEL + reading.clockTick); +}); + +test('on screen, the box keeps moving through the switch without a jump', async ({ + page, +}) => { + await open(page); + const reading = await trackAcrossSwitch(page, false); + test + .info() + .annotations.push({type: 'track', description: JSON.stringify(reading)}); + // Frames on both sides of the switch: the box was tracked rising under the + // present and falling under the dismissal. + expect(reading.rising).toBeGreaterThanOrEqual(5); + expect(reading.falling).toBeGreaterThanOrEqual(5); + // A frame's own travel is a few px; a discontinuity moves the box by at + // least `jump`. Half of it separates the two. + expect(reading.worstStep).toBeLessThan(reading.jump / 2); +}); + +test('a restart fails both readings, so they have teeth', async ({page}) => { + await open(page); + const read = await readAcrossSwitch(page, true); + await open(page); + const track = await trackAcrossSwitch(page, true); + test.info().annotations.push({ + type: 'restart', + description: JSON.stringify({read, track}), + }); + expect(read.step).toBeGreaterThan(SUBPIXEL + read.clockTick); + expect(track.worstStep).toBeGreaterThanOrEqual(track.jump / 2); +}); + +test('a present keeps growing every frame through a 1 s main-thread block', async ({ + page, +}) => { + await open(page); + const surface = page.locator('#surface'); + await markElement(surface, {inset: MARKER_INSET}); + const cast = await startScreencast(page); + await page.evaluate( + async ({box, spring}) => { + const element = document.getElementById('surface') as HTMLElement; + const morph = Motion.createRectMorph(element); + // From 80 % of its size, 240 px lower (on screen the whole way): the + // marker in the box's corner rises the whole way, over a px a frame. + const from = { + x: box.x, + y: box.y + 240, + width: box.width * 0.8, + height: box.height * 0.8, + }; + await morph.present(Motion.lerpPath(from, box), {spring: spring}).started; + }, + {box: BOX, spring: SLOW}, + ); + const busy = await blockMainThread(page, 1000, { + during: surface, + minProgressMs: 40, + }); + await page.waitForTimeout(200); + const tracked = await trackMarker(page, await cast.stop()); + const proof = busyWindowProof(tracked, busy, {axis: 'y', settledWithin: 2}); + test + .info() + .annotations.push({type: 'busy window', description: proof.summary}); + expect(busy.to - busy.from).toBeGreaterThanOrEqual(1000); + expect(proof.verdict.failures, proof.summary).toEqual([]); + expect(proof.monotonic).toBe(true); +}); + +test('no Layout or Paint runs while it animates', async ({ + page, + browserName, +}) => { + test.skip(browserName !== 'chromium', 'tracing is a Chromium protocol'); + await open(page); + let start = 0; + const trace = await traceRendering(page, async () => { + start = await page.evaluate( + ({box, square, spring}) => { + const element = document.getElementById('surface') as HTMLElement; + const morph = Motion.createRectMorph(element); + morph.present(Motion.lerpPath(square, box, {opacity: [0, 1]}), { + spring: spring, + }); + return performance.timeOrigin + performance.now(); + }, + {box: BOX, square: SQUARE, spring: SLOW}, + ); + await page.waitForTimeout(1900); + }); + // After the frame that starts the animation. + const counts = countBetween(trace, start + 50, trace.window.to); + test.info().annotations.push({ + type: 'rendering work while animating', + description: JSON.stringify(counts), + }); + expect(counts.Layout ?? 0).toBe(0); + expect(counts.Paint ?? 0).toBe(0); +}); diff --git a/packages/core/src/motion/progress.test.ts b/packages/core/src/motion/progress.test.ts index 4de3fa57df8de..a56ce3a5b74bf 100644 --- a/packages/core/src/motion/progress.test.ts +++ b/packages/core/src/motion/progress.test.ts @@ -7,6 +7,7 @@ import { mapRange, presentedProgressVelocity, progressCurve, + timedProgressCurve, type ProgressChannel, } from './progress'; import {solveSpring, toSpring} from './spring'; @@ -170,3 +171,22 @@ describe('presentedProgressVelocity', () => { expect(times).toEqual([1234, 1234]); }); }); + +describe('timedProgressCurve', () => { + it('runs from 0 to 1 over the duration on the easing, then holds 1', () => { + const curve = timedProgressCurve(300, [0.25, 0.1, 0.25, 1]); + expect(curve.duration).toBeCloseTo(0.3, 9); + expect(curve.at(0)).toBeCloseTo(0, 9); + expect(curve.at(0.15)).toBeGreaterThan(0.5); + expect(curve.at(0.3)).toBe(1); + expect(curve.at(1)).toBe(1); + expect(curve.velocity(0.3)).toBe(0); + expect(curve.velocity(0.1)).toBeGreaterThan(0); + }); + + it('lands at once for a zero duration', () => { + const curve = timedProgressCurve(0, [0, 0, 1, 1]); + expect(curve.duration).toBe(0); + expect(curve.at(0)).toBe(1); + }); +}); diff --git a/packages/core/src/motion/progress.ts b/packages/core/src/motion/progress.ts index 8b97de255de90..11aec62e51d24 100644 --- a/packages/core/src/motion/progress.ts +++ b/packages/core/src/motion/progress.ts @@ -4,7 +4,8 @@ * @file progress.ts * @input A spring, a normalized progress, an animator's presented velocities * @output Exports `progressCurve` (a spring's progress from 0 to 1 as a - * MotionCurve), `mapProgress` (one curve as a function of another), + * MotionCurve), `timedProgressCurve` (the same over a duration and + * easing), `mapProgress` (one curve as a function of another), * `mapRange` (the clamped linear map most companions use) and * `presentedProgressVelocity` (the progress velocity that continues what * an animator shows) @@ -39,6 +40,7 @@ */ import type {Animator, MotionCurve, MotionProperty} from './animator'; +import {cubicBezier, type BezierPoints} from './bezier'; import { SETTLING_EPSILON, solveSpring, @@ -69,6 +71,33 @@ export function progressCurve( }; } +/** + * A progress from 0 to 1 over `durationMs`, eased by the cubic-bézier + * `easing`: the curve a timed motion (a theme duration and easing) plays. + * Its velocity is in progress per second. + */ +export function timedProgressCurve( + durationMs: number, + easing: BezierPoints, +): MotionCurve { + const duration = Math.max(0, durationMs) / 1000; + const ease = cubicBezier(easing); + const at = (t: number) => + duration === 0 || t >= duration ? 1 : ease(Math.max(0, t) / duration); + return { + duration, + at, + velocity: t => { + if (duration === 0 || t >= duration) { + return 0; + } + const t0 = Math.max(0, t - STEP); + const t1 = Math.min(duration, t + STEP); + return (at(t1) - at(t0)) / (t1 - t0); + }, + }; +} + /** * The curve of `f(driver(t))`, its velocity by the chain rule: a channel * following a path as its progress moves, or a companion following any diff --git a/packages/core/src/motion/rectMorph.test.ts b/packages/core/src/motion/rectMorph.test.ts new file mode 100644 index 0000000000000..15b836b616039 --- /dev/null +++ b/packages/core/src/motion/rectMorph.test.ts @@ -0,0 +1,695 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file rectMorph.test.ts + * @input vitest (jsdom), the rect morph, a recording stand-in for + * Element.animate (jsdom runs no animations), and the models of the + * presentations that move onto the morph, as their pull requests have them + * @output Checks that present and dismiss continue each other from the rect + * on screen with its velocity; the dismissal's target; the inline state + * left behind; Reduced Motion through the animator (the paths and the + * presentations' models are checked in morphPath.test.ts) + * @position Testing; the compositor side is proven in + * __tests__/rectMorph.interaction.browser.spec.ts + */ + +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {createMotionAnimator} from './animator'; +import {progressCurve, timedProgressCurve} from './progress'; +import { + createRectMorph, + edgeGrowPath, + lerpPath, + type MorphRect, +} from './rectMorph'; +import {timing} from './uikit/timing'; +import {registerSpringsTable, springs} from './uikit/springs'; +import {resolveMotion} from './resolveMotion'; + +interface Recorded { + element: Element; + keyframes: Keyframe[]; + options: KeyframeAnimationOptions; + cancelled: boolean; + startTime: number | null; + readonly playState: 'idle' | 'running'; + ready: Promise; + cancel(): void; +} + +let clock = 1000; +let recorded: Recorded[] = []; +// The animator's frames: a call reads the browser's start for its curves in +// the frame after it, never in the task that makes them, so a test plays that +// frame before it reads where the element is. +let frameQueue: (() => void)[] = []; +const requestFrame = (callback: () => void) => { + frameQueue.push(callback); +}; +async function playFrame() { + const frames = frameQueue; + frameQueue = []; + for (const callback of frames) { + callback(); + } + await Promise.resolve(); + await Promise.resolve(); +} + +beforeEach(() => { + clock = 1000; + recorded = []; + frameQueue = []; + vi.useFakeTimers(); + HTMLElement.prototype.animate = function (keyframes, options) { + const animation: Recorded = { + element: this, + keyframes: keyframes as Keyframe[], + options: options as KeyframeAnimationOptions, + cancelled: false, + // The browser starts it at once: its first frame is committed at the + // call, so the animator's model starts the curve then. + startTime: clock, + get playState() { + return this.cancelled ? 'idle' : 'running'; + }, + ready: new Promise(() => {}), + cancel() { + this.cancelled = true; + }, + }; + recorded.push(animation); + return animation as unknown as Animation; + }; +}); + +afterEach(() => { + Reflect.deleteProperty(HTMLElement.prototype, 'animate'); + vi.useRealTimers(); + vi.unstubAllGlobals(); + document.body.replaceChildren(); +}); + +/** + * The person's settings, through `matchMedia` as the animator reads them: no + * option overrides them. + */ +function stubMedia(reduced: boolean, coarse: boolean) { + vi.stubGlobal('matchMedia', (query: string) => ({ + matches: query.includes('prefers-reduced-motion') + ? reduced + : query.includes('pointer: coarse') + ? coarse + : false, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + })); +} + +const SPRING = {response: 0.4, dampingRatio: 1}; +const BOUNCY = {response: 0.35, dampingRatio: 0.8}; + +function expectRect(actual: MorphRect, expected: MorphRect, tolerance: number) { + const gap = Math.max( + Math.abs(actual.x - expected.x), + Math.abs(actual.y - expected.y), + Math.abs(actual.width - expected.width), + Math.abs(actual.height - expected.height), + ); + expect(gap, JSON.stringify({actual, expected})).toBeLessThanOrEqual( + tolerance, + ); +} + +const SQUARE: MorphRect = {x: 179, y: 160, width: 22, height: 22}; +const BOX: MorphRect = {x: 40, y: 204, width: 320, height: 253}; + +// The popover's model, as #8187 has it, for the present that turns around +// on its edge growth. +/** Popover (#8187, popoverSurfaceMotion.ts): popoverCollapsedState, popoverFrame. */ +const POPOVER = {collapsedScale: 0.01, collapsedLengthPx: 100}; +function popoverModel(surface: MorphRect, source: MorphRect) { + const gaps = { + below: surface.y - (source.y + source.height), + above: source.y - (surface.y + surface.height), + right: surface.x - (source.x + source.width), + left: source.x - (surface.x + surface.width), + }; + let side: keyof typeof gaps = 'below'; + for (const candidate of ['above', 'right', 'left'] as const) { + if (gaps[candidate] > gaps[side]) { + side = candidate; + } + } + const clamp = (v: number, min: number, max: number) => + Math.min(Math.max(v, min), max); + const centerX = clamp( + source.x + source.width / 2 - surface.x, + 0, + surface.width, + ); + const centerY = clamp( + source.y + source.height / 2 - surface.y, + 0, + surface.height, + ); + const vertical = side === 'below' || side === 'above'; + const fullLength = vertical ? surface.height : surface.width; + const axis: 'x' | 'y' = vertical ? 'y' : 'x'; + const state = { + originX: vertical ? centerX : side === 'right' ? 0 : surface.width, + originY: vertical ? (side === 'below' ? 0 : surface.height) : centerY, + axis, + scale: POPOVER.collapsedScale, + length: Math.min(1, POPOVER.collapsedLengthPx / fullLength), + }; + // A frame of (scale, length, opacity), scaled about the origin. + const frameRect = (scale: number, length: number): MorphRect => { + const along = scale * length; + const scaleX = state.axis === 'x' ? along : scale; + const scaleY = state.axis === 'y' ? along : scale; + return { + x: surface.x + state.originX * (1 - scaleX), + y: surface.y + state.originY * (1 - scaleY), + width: surface.width * scaleX, + height: surface.height * scaleY, + }; + }; + return { + state, + rectAt: (p: number) => + frameRect( + state.scale + (1 - state.scale) * p, + state.length + (1 - state.length) * p, + ), + frameRect, + }; +} + +describe('createRectMorph', () => { + const setup = (options: {reducedMotion?: boolean; coarse?: boolean} = {}) => { + const element = document.createElement('div'); + document.body.appendChild(element); + stubMedia(options.reducedMotion ?? false, options.coarse ?? true); + const morph = createRectMorph(element, {now: () => clock, requestFrame}); + return {element, morph}; + }; + const copyOf = (element: HTMLElement) => { + const copy = element.cloneNode(true) as HTMLElement; + copy.setAttribute('data-copy', ''); + element.after(copy); + return copy; + }; + const live = (target: Element, property: string) => + recorded.filter( + animation => + !animation.cancelled && + animation.element === target && + animation.keyframes.some(frame => property in frame), + ); + const settle = async (ms: number) => { + await playFrame(); + clock += ms; + await vi.advanceTimersByTimeAsync(ms); + }; + + it('plays the table value, since a motion role is internal (DEC-11)', () => { + // A registered table's leaf is a motion role, but a role resolves to its + // table value: touch motion stays internal and no `--motion-*` variable + // retunes it. Writing one on the scope therefore changes nothing. + const {element, morph} = setup(); + const scope = document.createElement('div'); + scope.setAttribute('data-astryx-theme', 'brisk'); + document.body.appendChild(scope); + scope.appendChild(element); + registerSpringsTable(); + vi.spyOn(window, 'getComputedStyle').mockImplementation( + (node: Element) => + ({ + getPropertyValue: (name: string) => + node === scope && name === '--motion-springs-menu-open' + ? '0.9s 0.25' + : '', + }) as CSSStyleDeclaration, + ); + expect(resolveMotion(element, springs.menuOpen)).toBe(springs.menuOpen); + + const path = lerpPath(SQUARE, BOX, {opacity: [0, 1]}); + morph.present(path, {spring: springs.menuOpen}); + const [presenting] = live(element, 'scale'); + const withVariable = Number(presenting.options.duration); + vi.restoreAllMocks(); + + const plain = setup(); + plain.morph.present(lerpPath(SQUARE, BOX, {opacity: [0, 1]}), { + spring: springs.menuOpen, + }); + const [plainPresenting] = live(plain.element, 'scale'); + expect(withVariable).toBeCloseTo( + Number(plainPresenting.options.duration), + 6, + ); + }); + + it('presents the element from its source to rest on the spring', async () => { + const {element, morph} = setup(); + const path = lerpPath(SQUARE, BOX, {opacity: [0, 1]}); + morph.present(path, {spring: BOUNCY}); + await playFrame(); + expect(element.style.getPropertyValue('transform-origin')).toBe('0px 0px'); + expect(live(element, 'scale').length).toBe(1); + expect(live(element, 'translate').length).toBe(1); + const progress = progressCurve(BOUNCY); + const start = clock; + for (const t of [0, 0.03, 0.08, 0.15, 0.3]) { + clock = start + t * 1000; + expectRect(morph.presentedRect()!, path.rectAt(progress.at(t)), 0.01); + } + }); + + it('presents on a theme timing: its duration and easing as given, from rest', async () => { + const {element, morph} = setup(); + const path = lerpPath(SQUARE, BOX, {opacity: [0, 1]}); + const easing = [0.2, 0, 0, 1] as const; + // A tap has no velocity: a timed present starts from rest even when + // one is given. + morph.present(path, {duration: 300, easing}, {velocity: 6}); + await playFrame(); + expect(live(element, 'scale').length).toBe(1); + const progress = timedProgressCurve(300, easing); + const start = clock; + for (const t of [0, 0.05, 0.12, 0.2, 0.29]) { + clock = start + t * 1000; + expectRect(morph.presentedRect()!, path.rectAt(progress.at(t)), 0.01); + } + }); + + it('plays on an animator it is handed, and leaves it to its owner when disposed', async () => { + // A zoom stage already drives the photo with its own animator (pinch, + // pan, settle): the morph plays on it, so the two share the channels. + const element = document.createElement('div'); + document.body.appendChild(element); + stubMedia(false, true); + const stage = createMotionAnimator(element, { + now: () => clock, + requestFrame, + }); + const morph = createRectMorph(element, { + animator: stage, + now: () => clock, + requestFrame, + }); + const path = lerpPath(SQUARE, BOX, {opacity: [0, 1]}); + morph.present(path, {spring: BOUNCY}); + await playFrame(); + expect(live(element, 'scale')).toHaveLength(1); + clock += 50; + expect(stage.get('scaleX', clock)).toBeCloseTo( + morph.presentedRect()!.width / BOX.width, + 9, + ); + expect(stage.get('scaleX', clock)).not.toBeCloseTo(1, 3); + morph.dispose(); + // Still the stage's: it moves the element after the morph is gone. + stage.set({x: 12}); + expect(stage.get('x')).toBe(12); + }); + + it('holds the element at its first values until two frames present it, when asked for the presented start', async () => { + const {element, morph} = setup(); + const path = lerpPath(SQUARE, BOX, {opacity: [0, 1]}); + morph.present(path, {spring: BOUNCY}, {start: 'presented'}); + expect(live(element, 'scale')).toHaveLength(0); + expectRect(morph.presentedRect()!, path.rectAt(0), 0.01); + await playFrame(); + expect(live(element, 'scale')).toHaveLength(0); + await playFrame(); + expect(live(element, 'scale')).toHaveLength(1); + }); + + it('leaves nothing of its own inline once the present settles', async () => { + const {element, morph} = setup(); + morph.present(lerpPath(SQUARE, BOX, {opacity: [0, 1]}), {spring: SPRING}); + await settle(progressCurve(SPRING).duration * 1000 + 50); + for (const property of [ + 'translate', + 'scale', + 'transform-origin', + 'opacity', + ]) { + expect(element.style.getPropertyValue(property), property).toBe(''); + } + expectRect(morph.presentedRect()!, BOX, 1e-9); + }); + + it('leaves a component\u2019s own opacity alone when its path has none', async () => { + const {element, morph} = setup(); + element.style.setProperty('opacity', '0.5'); + morph.present(lerpPath(SQUARE, BOX), {spring: SPRING}); + await settle(progressCurve(SPRING).duration * 1000 + 50); + expect(element.style.getPropertyValue('opacity')).toBe('0.5'); + expect(live(element, 'opacity').length).toBe(0); + }); + + it('dismisses on its target from the rect on screen, leaves the element as laid out, then releases the target', async () => { + const {element, morph} = setup(); + const path = lerpPath(SQUARE, BOX, {opacity: [0, 1]}); + morph.present(path, {spring: SPRING}); + await settle(progressCurve(SPRING).duration * 1000 + 50); + const copy = copyOf(element); + const dismissing = morph.dismiss(path, {spring: BOUNCY}, {target: copy}); + expect(copy.style.getPropertyValue('transform-origin')).toBe('0px 0px'); + expect(live(copy, 'scale').length).toBe(1); + for (const property of [ + 'translate', + 'scale', + 'transform-origin', + 'opacity', + ]) { + expect(element.style.getPropertyValue(property), property).toBe(''); + } + // It runs from rest back to the square, fading out. + await playFrame(); + const progress = progressCurve(BOUNCY); + const back = lerpPath(BOX, SQUARE, {opacity: [1, 0]}); + const start = clock; + for (const t of [0, 0.05, 0.1, 0.2]) { + clock = start + t * 1000; + expectRect(morph.presentedRect()!, back.rectAt(progress.at(t)), 0.01); + } + clock = start; + await settle(progress.duration * 1000 + 50); + expect(await dismissing.finished).toBe(true); + expect(copy.isConnected).toBe(false); + }); + + it('lets the element go of its compositing layer as a dismissal on a copy starts, so no style write reaches it during the dismissal', async () => { + const {element, morph} = setup(); + const path = lerpPath(SQUARE, BOX, {opacity: [0, 1]}); + morph.present(path, {spring: SPRING}); + // Dismissed about 100 ms after the present's curve ended, while the + // animator still keeps the element promoted (its promotion linger). + await settle(progressCurve(SPRING).duration * 1000 + 100); + const copy = copyOf(element); + morph.dismiss(path, {spring: BOUNCY}, {target: copy}); + // The dismissal's own task. + await Promise.resolve(); + await Promise.resolve(); + const writes: string[] = []; + const observer = new MutationObserver(records => { + for (const record of records) { + writes.push(record.oldValue ?? ''); + } + }); + observer.observe(element, { + attributes: true, + attributeFilter: ['style'], + attributeOldValue: true, + }); + // The dismissal's whole run, and any linger past it. + for (let ms = 0; ms < 1200; ms += 50) { + await settle(50); + } + writes.push(...observer.takeRecords().map(record => record.oldValue ?? '')); + observer.disconnect(); + expect(writes).toEqual([]); + expect(element.style.getPropertyValue('will-change')).toBe(''); + }); + + it('presents the element again after a dismissal on a copy', async () => { + const {element, morph} = setup(); + const path = lerpPath(SQUARE, BOX, {opacity: [0, 1]}); + morph.present(path, {spring: SPRING}); + await settle(progressCurve(SPRING).duration * 1000 + 100); + morph.dismiss(path, {spring: BOUNCY}, {target: copyOf(element)}); + await settle(progressCurve(BOUNCY).duration * 1000 + 50); + const presenting = morph.present(path, {spring: SPRING}); + expect(live(element, 'scale').length).toBe(1); + await settle(progressCurve(SPRING).duration * 1000 + 50); + expect(await presenting.finished).toBe(true); + expect(element.style.getPropertyValue('scale')).toBe(''); + }); + + it('hands its target to the caller\u2019s release, and dismisses the element itself when it is the target', async () => { + const {element, morph} = setup(); + const path = lerpPath(SQUARE, BOX); + morph.present(path, {spring: SPRING}); + await settle(1000); + const released: HTMLElement[] = []; + const copy = copyOf(element); + morph.dismiss( + path, + {spring: SPRING}, + { + target: copy, + release: target => released.push(target), + }, + ); + await settle(1000); + expect(released).toEqual([copy]); + expect(copy.isConnected).toBe(true); + + morph.present(path, {spring: SPRING}); + await settle(1000); + morph.dismiss(path, {spring: SPRING}, {target: element}); + expect(live(element, 'scale').length).toBe(1); + await settle(1000); + expect(element.isConnected).toBe(true); + expectRect(morph.presentedRect()!, SQUARE, 0.01); + }); + + it('a second dismissal on the copy in flight keeps the copy and continues from its rect', async () => { + // A dismissal continues the dismissal in flight, so a caller that hands + // the same copy again (a retargeted shrink) keeps it: its release runs + // once, when the dismissal that is still running ends. + const {element, morph} = setup(); + const path = lerpPath(SQUARE, BOX, {opacity: [0, 1]}); + morph.present(path, {spring: SPRING}); + await settle(progressCurve(SPRING).duration * 1000 + 50); + const released: HTMLElement[] = []; + const release = (target: HTMLElement) => { + released.push(target); + target.remove(); + }; + const copy = copyOf(element); + morph.dismiss(path, {spring: BOUNCY}, {target: copy, release}); + clock += 60; + await vi.advanceTimersByTimeAsync(60); + const onScreen = morph.presentedRect()!; + + const again = morph.dismiss( + path, + {spring: SPRING}, + {target: copy, release}, + ); + expect(copy.isConnected).toBe(true); + expect(released).toEqual([]); + expect(live(copy, 'scale').length).toBe(1); + expectRect(morph.presentedRect()!, onScreen, 0.01); + + await settle(progressCurve(SPRING).duration * 1000 + 50); + expect(await again.finished).toBe(true); + expect(released).toEqual([copy]); + expect(copy.isConnected).toBe(false); + }); + + it('a dismissal during the present starts from the rect on screen, with its velocity', async () => { + const {element, morph} = setup(); + const path = lerpPath(SQUARE, BOX, {opacity: [0, 1]}); + morph.present(path, {spring: SPRING}); + await playFrame(); + const progress = progressCurve(SPRING); + clock += 60; + await vi.advanceTimersByTimeAsync(60); + const p = progress.at(0.06); + const dp = progress.velocity(0.06); + const onScreen = morph.presentedRect()!; + expectRect(onScreen, path.rectAt(p), 0.01); + const copy = copyOf(element); + morph.dismiss(path, {spring: BOUNCY}, {target: copy}); + // The same rect, now on the copy, and the same velocity: the dismissal's + // path is the rest of the line back to the square, so the growth's + // velocity carries on along it. + expectRect(morph.presentedRect()!, onScreen, 0.01); + await playFrame(); + const before = morph.presentedRect()!; + clock += 0.01; + const after = morph.presentedRect()!; + const expectedWidthSpeed = (BOX.width - SQUARE.width) * dp; // px/s + expect((after.width - before.width) / 0.01e-3).toBeCloseTo( + expectedWidthSpeed, + -1, + ); + }); + + it('a present during the dismissal starts from the copy\u2019s rect with its velocity and takes the copy away', async () => { + const {element, morph} = setup(); + const surface = {x: 41, y: 204, width: 320, height: 253}; + const model = popoverModel(surface, { + x: 141, + y: 160, + width: 120, + height: 44, + }); + const path = edgeGrowPath({ + box: surface, + origin: {x: model.state.originX, y: model.state.originY}, + axis: model.state.axis, + collapsedScale: model.state.scale, + collapsedLength: model.state.length, + }); + morph.present(path, {spring: SPRING}); + await settle(1000); + const copy = copyOf(element); + morph.dismiss(path, {spring: SPRING}, {target: copy}); + await playFrame(); + clock += 80; + await vi.advanceTimersByTimeAsync(80); + const onScreen = morph.presentedRect()!; + const before = {...onScreen}; + clock += 1; + const moving = morph.presentedRect()!; + clock -= 1; + morph.present(path, {spring: SPRING}); + expect(copy.isConnected).toBe(false); + expectRect(morph.presentedRect()!, onScreen, 0.01); + await playFrame(); + // It keeps shrinking for a moment (the dismissal's velocity), then grows. + clock += 1; + const next = morph.presentedRect()!; + expect(Math.sign(next.width - before.width)).toBe( + Math.sign(moving.width - before.width), + ); + await settle(1000); + expectRect(morph.presentedRect()!, surface, 1e-6); + }); + + it('takes a release velocity as given (progress per second)', async () => { + const {morph} = setup(); + const path = lerpPath(SQUARE, BOX); + morph.present(path, {spring: SPRING}, {velocity: 6}); + await playFrame(); + const before = morph.presentedRect()!; + clock += 0.01; + const after = morph.presentedRect()!; + expect((after.x - before.x) / 0.01e-3).toBeCloseTo( + (BOX.x - SQUARE.x) * 6, + -1, + ); + }); + + it('reset after a settled present writes nothing back inline', async () => { + const {element, morph} = setup(); + morph.present(lerpPath(SQUARE, BOX, {opacity: [0, 1]}), {spring: SPRING}); + await settle(progressCurve(SPRING).duration * 1000 + 50); + morph.reset(); + for (const property of [ + 'translate', + 'scale', + 'transform-origin', + 'opacity', + ]) { + expect(element.style.getPropertyValue(property), property).toBe(''); + } + }); + + it('reset ends every motion, takes the target away and leaves the element as laid out', () => { + const {element, morph} = setup(); + const path = lerpPath(SQUARE, BOX, {opacity: [0, 1]}); + morph.present(path, {spring: SPRING}); + const copy = copyOf(element); + morph.dismiss(path, {spring: SPRING}, {target: copy}); + morph.reset(); + expect(copy.isConnected).toBe(false); + for (const property of [ + 'translate', + 'scale', + 'transform-origin', + 'opacity', + ]) { + expect(element.style.getPropertyValue(property), property).toBe(''); + } + expect(morph.presentedRect()).toBeNull(); + }); + + describe('under Reduced Motion (the animator\u2019s, design:reduced-motion)', () => { + /** When `animation`'s opacity reaches `target` for good, ms after its start. */ + const fadeEndMs = (animation: Recorded, target: number) => { + const duration = Number(animation.options.duration); + let end = 0; + for (const frame of animation.keyframes) { + if (Math.abs(Number(frame.opacity) - target) > 1e-3) { + end = (frame.offset as number) * duration; + } + } + const index = animation.keyframes.findIndex( + frame => (frame.offset as number) * duration > end, + ); + return (animation.keyframes[index].offset as number) * duration; + }; + + it('on a coarse pointer, a present lands at rest and fades in, a dismissal fades out where it stands, in 200 ms', async () => { + const {element, morph} = setup({reducedMotion: true, coarse: true}); + const path = lerpPath(SQUARE, BOX, {opacity: [0, 1]}); + morph.present(path, {spring: SPRING}); + const [fadeIn] = live(element, 'opacity'); + expect(fadeEndMs(fadeIn, 1)).toBeLessThanOrEqual( + timing.reducedMotionCrossFadeMs + 1, + ); + // Nothing grows: it stands at rest while it fades. + expectRect(morph.presentedRect()!, BOX, 0.01); + await settle(1000); + + const copy = copyOf(element); + morph.dismiss(path, {spring: SPRING}, {target: copy}); + const [fadeOut] = live(copy, 'opacity'); + const fadeMs = fadeEndMs(fadeOut, 0); + expect(fadeMs).toBeLessThanOrEqual(timing.reducedMotionCrossFadeMs + 1); + const start = clock; + for (const t of [0, 50, 100, 150]) { + clock = start + t; + expectRect(morph.presentedRect()!, BOX, 0.01); + } + }); + + it('lands a path with no opacity at rest, instead of starting on its source rect', () => { + // With no opacity of its own the path gives the cross-fade nothing to + // read, so the morph says which way it goes: a present lands at rest + // (design:reduced-motion), it does not dip to the source and grow. + const {element, morph} = setup({reducedMotion: true, coarse: true}); + const path = lerpPath(SQUARE, BOX); + morph.present(path, {spring: SPRING}); + expectRect(morph.presentedRect()!, BOX, 0.01); + expect(live(element, 'scale').length).toBe(0); + expect(live(element, 'translate').length).toBe(0); + }); + + it('keeps the animator’s dip for an element that only moves, when the caller says so', () => { + // A sub-menu's parent card stays visible and only moves: treated as an + // entrance it would cut out and fade in, so its caller asks for a move, + // and the animator dips it: out, the travel lands, back in. + const {element, morph} = setup({reducedMotion: true, coarse: true}); + const path = lerpPath(SQUARE, BOX); + morph.present(path, {spring: SPRING}, {crossfadeAs: 'move'}); + const [dip] = live(element, 'opacity'); + expect(dip).toBeDefined(); + expect(Number(dip.keyframes[0].opacity)).toBeCloseTo(1, 6); + expect( + Math.min(...dip.keyframes.map(frame => Number(frame.opacity))), + ).toBeLessThan(0.5); + }); + + it('on any other pointer, it completes at once', () => { + const {element, morph} = setup({reducedMotion: true, coarse: false}); + morph.present(lerpPath(SQUARE, BOX, {opacity: [0, 1]}), {spring: SPRING}); + expect(live(element, 'scale').length).toBe(0); + expect(live(element, 'opacity').length).toBe(0); + expectRect(morph.presentedRect()!, BOX, 0.01); + }); + }); +}); diff --git a/packages/core/src/motion/rectMorph.ts b/packages/core/src/motion/rectMorph.ts new file mode 100644 index 0000000000000..af8464004a3f6 --- /dev/null +++ b/packages/core/src/motion/rectMorph.ts @@ -0,0 +1,501 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file rectMorph.ts + * @input An element laid out at rest in its box, a path it grows along + * (morphPath.ts), its timing (a duration and easing, or a spring), the + * compositor animator and the progress helpers (progress.ts) + * @output Exports `createRectMorph` (present and dismiss, each interrupting + * the other), and re-exports the paths it plays (`lerpPath`, + * `edgeGrowPath`, `morphCurves`) from morphPath.ts + * @position Motion foundation building block, internal to core: the one + * "grow out of a source rect, shrink back into it" that touch + * presentations share: an anchored menu, a popover, a context menu's + * lifted preview, a photo's zoom, a sub-menu's parent card + * + * A path (morphPath.ts) names the rect an element shows at each progress, + * and its curves put the element there with `translate` and `scale` about + * `transform-origin: 0 0` and a companion `opacity`, on the compositor. + * `createRectMorph` plays a path on its element + * (`present`) and back to the source on a target the caller gives + * (`dismiss`): a copy placed where the element stands, since the browser + * hides a closing popover at once, or the element itself. Each interrupts + * the other: the new motion starts from the rect the animator presents at + * that moment, on the path restarted there in its own law (`restartFrom`), + * with the presented velocity projected on it (progress.ts). Once a present settles nothing of the morph's is left inline: iOS + * Safari will not scroll a finger through a popover that keeps a `scale`, + * even at 1. + * + * A present or a dismissal takes its timing as a motion: the theme's + * duration and easing for a motion that a tap, a key or the program starts, + * or a spring for a gesture's release, which starts at the gesture's + * velocity. Only a spring carries a velocity into the motion. + * + * Reduced Motion is the animator's: on a coarse + * pointer a present lands at rest and fades in, a dismissal fades out where + * it stands, opacity only, in 200 ms; on any other pointer the change + * completes at once. + * + * SYNC: When modified, update: + * - /packages/core/src/motion/rectMorph.test.ts + * - /packages/core/src/motion/README.md + * - /packages/core/src/motion/morphPath.ts (the paths it plays) + */ + +import { + createMotionAnimator, + type AnimateOptions, + type Animator, + type AnimatorOptions, + type MotionHandle, + type MotionValues, +} from './animator'; +import { + presentedProgressVelocity, + progressCurve, + timedProgressCurve, + type ProgressChannel, +} from './progress'; +import { + lerpPath, + morphCurves, + travelAt, + type MorphEnd, + type MorphPath, + type MorphRect, + type TravelProperty, +} from './morphPath'; +import type {MotionCurvePoints} from './roles'; +import type {SpringDescription} from './spring'; +import {resolveMotion} from './resolveMotion'; + +// The paths the morph plays, where its callers have always imported them. +export {edgeGrowPath, lerpPath, morphCurves} from './morphPath'; +export type {MorphEnd, MorphPath, MorphRect, MorphScale} from './morphPath'; + +/** The path from what is on screen to `path`'s `end`. */ +function restart( + path: MorphPath, + rect: MorphRect, + opacity: number, + end: MorphEnd, +): MorphPath { + if (path.restartFrom != null) { + return path.restartFrom(rect, opacity, end); + } + const p = end === 'rest' ? 1 : 0; + const {opacityAt} = path; + return lerpPath(rect, path.rectAt(p), { + box: path.box, + scale: path.scale, + ...(opacityAt != null ? {opacity: [opacity, opacityAt(p)] as const} : null), + }); +} + +/** The rect an animator shows for an element laid out in `box`, at `now`. */ +function presentedRectOf( + animator: Animator, + box: MorphRect, + now: number, +): MorphRect { + return { + x: box.x + animator.get('x', now), + y: box.y + animator.get('y', now), + width: box.width * animator.get('scaleX', now), + height: box.height * animator.get('scaleY', now), + }; +} + +/** The travel channels of `path`, weighted in px for the projection. */ +function channelsOf(path: MorphPath): ProgressChannel[] { + const at = (property: TravelProperty) => (p: number) => + travelAt(path, p)[property]; + return [ + {property: 'x', at: at('x')}, + {property: 'y', at: at('y')}, + {property: 'scaleX', at: at('scaleX'), weight: path.box.width}, + {property: 'scaleY', at: at('scaleY'), weight: path.box.height}, + ]; +} + +function startValues(path: MorphPath, opacity?: number): MotionValues { + const values: MotionValues = {...travelAt(path, 0)}; + if (path.opacityAt != null) { + values.opacity = opacity ?? path.opacityAt(0); + } + return values; +} + +/** The morph's own inline properties, left on an element only while it moves. */ +const INLINE_PROPERTIES = ['translate', 'scale', 'transform-origin'] as const; + +/** + * How a present or a dismissal is timed. A motion that a tap, a key or the + * program starts plays the theme's duration (ms) and easing. A gesture's + * release plays a spring, which starts at the gesture's velocity + * (`RectMorphPlayOptions.velocity`). + */ +export type RectMorphMotion = + | {readonly duration: number; readonly easing: MotionCurvePoints} + | {readonly spring: SpringDescription}; + +/** + * How a present or a dismissal plays. + */ +export interface RectMorphPlayOptions { + /** + * Progress per second a spring starts with (a finger's release). By + * default the velocity of what is on screen, projected on the path. A + * timed motion starts from rest. + */ + velocity?: number; + /** + * A timing of its own for the companion opacity (a zoom's closing fade); + * the frame's timing by default. + */ + fade?: RectMorphMotion; + /** For the animator's Reduced Motion: a touch drag's release starts it. */ + touchRelease?: AnimateOptions['touchRelease']; + /** + * For the animator's Reduced Motion: what a cross-fade treats it as. A path + * with no opacity of its own is an entrance on a present and an exit on a + * dismissal by default; `'move'` keeps the animator's own dip for an + * element that stays visible and only moves (a sub-menu's parent card), so + * it fades out, lands and fades back in instead of cutting out. + */ + crossfadeAs?: AnimateOptions['crossfadeAs'] | 'move'; + /** + * When the curves start: `'presented'` holds the element at its first + * values until two frames have presented it, so a surface that appears + * late plays the whole curve (the animator's `start`). + */ + start?: AnimateOptions['start']; +} + +/** + * Where a dismissal plays. + */ +export interface RectMorphDismissOptions extends RectMorphPlayOptions { + /** + * The element the dismissal plays on: a copy of the element laid out in the + * path's box (a closing popover is hidden at once), or the element itself. + */ + target: HTMLElement; + /** + * Takes `target` away once the dismissal ends or a present interrupts it: + * `target.remove()` by default, nothing when it is the element. + */ + release?: (target: HTMLElement) => void; +} + +/** + * The present and the dismissal of one element. + */ +export interface RectMorph { + /** + * Plays `path` on the element from its source to rest on `motion`. While a + * dismissal or a present plays, it starts from the rect on screen instead, + * restarted on `path` toward rest with the presented velocity. + */ + present( + path: MorphPath, + motion: RectMorphMotion, + options?: RectMorphPlayOptions, + ): MotionHandle; + /** + * Plays `path` back to its source on `options.target` on `motion`, from the + * rect the element presents now (or the dismissal in flight) with its + * velocity. The element is left as laid out unless it is the target. + */ + dismiss( + path: MorphPath, + motion: RectMorphMotion, + options: RectMorphDismissOptions, + ): MotionHandle; + /** The rect on screen now (the dismissal's while one plays); null before any. */ + presentedRect(): MorphRect | null; + /** + * Ends every motion, takes a dismissal's target away and leaves the element + * as laid out, with none of the morph's inline properties. + */ + reset(): void; + /** `reset`, then releases the element's animator unless the caller handed it. */ + dispose(): void; +} + +function defaultNow(): number { + return typeof performance === 'undefined' ? Date.now() : performance.now(); +} + +/** + * The rect morph of `element`. + * + * @example + * ``` + * const morph = createRectMorph(menu); + * const path = lerpPath(square, box, {opacity: [0, 1]}); + * // A tap opened the menu: the theme's entrance duration and easing. + * morph.present(path, {duration: enterMs, easing: enterEasing}); + * // …a finger flicked it closed, with a copy placed where the menu stands: + * morph.dismiss(path, {spring: springs.menuClose}, {target: copy, velocity}); + * ``` + * + * An element that already has an animator (a zoom stage's pinch and pan) + * hands it in `animator`: the morph plays on it, so the two share the + * element's channels, and `dispose` leaves it to its owner. + */ +export function createRectMorph( + element: HTMLElement, + { + animator: given, + ...options + }: Pick & {animator?: Animator} = {}, +): RectMorph { + const now = options.now ?? defaultNow; + const animator = given ?? createMotionAnimator(element, options); + /** The box the element's transform is relative to, once it has one. */ + let box: MorphRect | null = null; + let presenting: MotionHandle | null = null; + /** Whether a path has animated the element's opacity. */ + let ownsOpacity = false; + let exiting: { + target: HTMLElement; + animator: Animator; + box: MorphRect; + release: (target: HTMLElement) => void; + } | null = null; + + const clearInline = () => { + for (const property of INLINE_PROPERTIES) { + element.style.removeProperty(property); + } + }; + + // Leaves the element as laid out: identity, and none of the morph's inline + // properties (an opacity only when a path animated it). At rest it needs no + // compositing layer, so the values go in without promoting it. + const restoreElement = () => { + animator.set( + ownsOpacity + ? {x: 0, y: 0, scaleX: 1, scaleY: 1, opacity: 1} + : {x: 0, y: 0, scaleX: 1, scaleY: 1}, + {promote: false}, + ); + clearInline(); + if (ownsOpacity) { + element.style.removeProperty('opacity'); + ownsOpacity = false; + } + box = null; + }; + + const endExit = () => { + if (exiting == null) { + return; + } + const {target, animator: closing, release} = exiting; + exiting = null; + if (closing !== animator) { + closing.dispose(); + } + release(target); + }; + + // Once a present settles on identity, nothing of the morph's stays inline. + const retire = () => { + const at = now(); + const identity = + Math.abs(animator.get('x', at)) < 1e-6 && + Math.abs(animator.get('y', at)) < 1e-6 && + Math.abs(animator.get('scaleX', at) - 1) < 1e-9 && + Math.abs(animator.get('scaleY', at) - 1) < 1e-9; + if (identity) { + clearInline(); + } + if (ownsOpacity && Math.abs(animator.get('opacity', at) - 1) < 1e-9) { + element.style.removeProperty('opacity'); + ownsOpacity = false; + } + }; + + // A path with no opacity of its own gives the animator's Reduced Motion + // cross-fade nothing to read, and it would start the motion on the source + // rect and dip. Such a path says which way it goes, so the cross-fade + // lands at rest on a present and fades out in place on a dismissal; a caller's own `crossfadeAs` still wins, and + // `'move'` keeps the animator's dip for an element that only moves. + const playOptions = ( + play: RectMorphPlayOptions, + path: MorphPath, + direction: 'entrance' | 'exit' = 'entrance', + ): AnimateOptions => ({ + ...(play.touchRelease != null ? {touchRelease: play.touchRelease} : null), + ...(play.start != null ? {start: play.start} : null), + ...(play.crossfadeAs === 'move' + ? null + : play.crossfadeAs != null + ? {crossfadeAs: play.crossfadeAs} + : path.opacityAt == null + ? {crossfadeAs: direction} + : null), + }); + + // A spring goes through `resolveMotion` on the element that plays it: a + // touch motion role resolves to its table value and reads no style, and a + // caller's bare spring comes back as given. A timed motion is the caller's + // duration and easing, already resolved from the theme. + const progressFor = ( + on: Element, + motion: RectMorphMotion, + velocity: number, + ) => + 'spring' in motion + ? progressCurve(resolveMotion(on, motion.spring), {velocity}) + : timedProgressCurve(motion.duration, motion.easing); + + const curvesFor = ( + on: Element, + path: MorphPath, + motion: RectMorphMotion, + play: RectMorphPlayOptions, + velocity: number, + ) => { + const progress = progressFor(on, motion, velocity); + const fade = + play.fade != null ? progressFor(on, play.fade, velocity) : progress; + return morphCurves(path, progress, fade); + }; + + const present: RectMorph['present'] = (path, motion, play = {}) => { + const at = now(); + const from = + exiting ?? (presenting != null && box != null ? {animator, box} : null); + let start = path; + let velocity = play.velocity ?? 0; + let opacity: number | undefined; + if (from != null) { + opacity = from.animator.get('opacity', at); + start = restart( + path, + presentedRectOf(from.animator, from.box, at), + opacity, + 'rest', + ); + velocity = + play.velocity ?? + presentedProgressVelocity(from.animator, channelsOf(start), at); + } + endExit(); + box = start.box; + ownsOpacity ||= start.opacityAt != null; + // A dismissal on a copy let the element go (dismiss, below). + animator.attach(element); + element.style.setProperty('transform-origin', '0px 0px'); + animator.set(startValues(start, opacity)); + const handle = animator.play( + curvesFor(element, start, motion, play, velocity), + playOptions(play, start), + ); + presenting = handle; + void handle.finished.then(done => { + if (done && presenting === handle) { + presenting = null; + retire(); + } + }); + return handle; + }; + + const dismiss: RectMorph['dismiss'] = (path, motion, play) => { + const {target} = play; + const at = now(); + const from = exiting ?? {animator, box: box ?? path.box}; + const opacity = from.animator.get('opacity', at); + const back = restart( + path, + presentedRectOf(from.animator, from.box, at), + opacity, + 'source', + ); + const velocity = + play.velocity ?? + presentedProgressVelocity(from.animator, channelsOf(back), at); + // The same copy handed again continues on it: it keeps its animator, and + // its release runs once, when the dismissal still running ends. Any other + // target ends the dismissal in flight first. + const continuing = + exiting != null && exiting.target === target ? exiting : null; + if (continuing != null) { + exiting = null; + } else { + endExit(); + } + presenting = null; + const onElement = target === element; + if (onElement) { + // A dismissal on a copy may have let the element go (below). + animator.attach(element); + box = back.box; + ownsOpacity ||= back.opacityAt != null; + } else { + // The element is hidden as it closes: leave it as laid out, and let go + // of the layer its presentation promoted, in this task. Kept, the + // promotion would end its linger after the element's last motion: a + // style write on an element that no longer paints, landing inside the + // dismissal's frames. The next present attaches the element again. + restoreElement(); + animator.attach(null); + } + const closing = onElement + ? animator + : (continuing?.animator ?? createMotionAnimator(target, options)); + target.style.setProperty('transform-origin', '0px 0px'); + // The copy starts as the element shows now, whatever its clone kept. + closing.set(startValues(back, opacity)); + const handle = closing.play( + curvesFor(target, back, motion, play, velocity), + playOptions(play, back, 'exit'), + ); + const current = { + target, + animator: closing, + box: back.box, + release: + play.release ?? + (onElement ? () => {} : (copy: HTMLElement) => copy.remove()), + }; + exiting = current; + void handle.finished.then(() => { + if (exiting === current) { + endExit(); + } + }); + return handle; + }; + + // `set` ends whatever still moves; nothing is frozen inline on the way. + const reset = () => { + endExit(); + presenting = null; + restoreElement(); + }; + + return { + present, + dismiss, + presentedRect() { + if (exiting != null) { + return presentedRectOf(exiting.animator, exiting.box, now()); + } + return box == null ? null : presentedRectOf(animator, box, now()); + }, + reset, + dispose() { + reset(); + if (given == null) { + animator.dispose(); + } + }, + }; +} From b9b630a49585da7c04070875f76ccee5fc57b506 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Tue, 3 Nov 2026 08:38:54 -0800 Subject: [PATCH 05/73] feat(TextInput, TextArea, NumberInput): fields stay above the keyboard Each passes its input to `useMobileKeyboard` from its own render, with no prop and no Effect of its own. On focus the field decides where it is: inside a keyboard target such as a Tall BottomSheet it moves nothing; in an app's bar docked at the viewport's bottom, the bar rides the keyboard, its bottom on the keyboard's top; in scrolling content, its nearest scroller, the document included, scrolls it 10 px above the keyboard in the keyboard's report. In a fixed container the app positions itself, a scroller around the field reveals it, and with none the browser's own reveal stays. Its first tap and focus moves into it arrive without the browser's reveal where the module places the field, so the page never pans there. A scroll area does not gain the range it lacks at its end yet. Where a field's scroll area cannot place it, the document reveals it, in the page and in a fixed container where the document's scroll moves the container, as in Safari while its keyboard shows; elsewhere Core scrolls the document back. Where the document cannot scroll far enough, as at a short page's end in Chrome, a pan of the visual viewport takes the rest in the same frame (`panVisualViewportTo`): a probe fixed in the layout viewport is scrolled into view, as the reveal-pan watch puts a pan back. The watch takes Core's own pan as the new rest. Firefox for Android does not pan for the probe. A page with nothing to scroll keeps the browser's own reveal. On Chrome's show, a docked bar first sets its field 4 px above the keyboard's top at once, as the Tall sheet does, and only the rest rides, so Chrome's own pan finds the field clear. Every viewport report now feeds the ride's reveal-pan watch, so a pan Chrome still makes is put back, and a pan made at one keyboard height goes back at the next. Under Remove animations, Gboard first reports a keyboard 48 px tall, and Chrome may then reveal the bar's field itself: it scrolls the page behind the bar, then pans. In Chrome, the ride's watch scrolls the document back as well, when the scroll and the pan centre the field as Chrome's reveal does; the app's own scroll to another element stays. On iOS, a reveal that places the field rises on the browser's smooth scroll from the keyboard's first report, which comes as the keyboard starts to slide, so the field rises beside it (`risesSmoothly`, which reads Core's iOS WebKit check, `isIosWebKit`). The scroll back records where the rise is headed, and a rise still on its way when the keyboard changes height carries on from its target. Under Reduce Motion, in a theme that reduces motion for everyone, and in Chrome, which checks the field in the resize's own commit, the reveal moves at once. The rise and the scroll back ask the motion module's new `reducesMotion`, beside `reducedMotionFade`, which now uses it, so a theme that reduces motion for everyone counts as the setting for both. A scroll area's reveal goes through its own `scrollBy` with an explicit behavior where it has one, so a smooth `scroll-behavior` on the area cannot slow an instant reveal, as the Tall sheet's reveal already does. When the keyboard closes, each scroller a reveal moved scrolls back to where it was (keyboardScrollBack.ts), on the browser's smooth scroll. Safari on iOS reports the keyboard gone about half a second after the blur that closes it, once it is down. There the scroll back starts at that blur, once the focus change settles on nothing that brings up a keyboard with no finger on the screen, and slides down beside the keyboard; the report only confirms it. A finger then can be a tap that brings the keyboard back, so the report decides, as elsewhere and under Reduce Motion, where the scroll lands at once. Safari applies a scripted scroll a frame late, so a scroll set each frame jitters. A scroller the person scrolled meanwhile keeps their scroll. A field that gains focus during the slide stops the scroll back where the page is (`stopKeyboardScrollBack`), and its reveal goes on from there as Core's own scroll. A sandbox page puts three fields in the middle of a page that scrolls the document. Each field's `.keyboard.test.tsx` drives the keyboard module's test double. Mobile keyboard stories on TextInput place the fields low in the page, a TextInput in a toolbar fixed at the bottom (docked, floating above the edge, or with its own `translate`), a last field at the end of a short page and of a scroll area, a scroll area low on the page, a scroll area in a floating panel and in a full-viewport panel, and a field in a sheet of a set height. Firefox for Android can carry the reveal's document scroll as a visual-viewport offset, show the document where it was before the reveal at the keyboard's hide report, and turn the offset back into a document scroll only after it. The scroll back then waits up to a second for the first document scroll: one that lands where Core left the document is the browser's own, and the scroll back follows it. A touch, a keyboard that comes back, the field's page going, or the wait's end puts nothing back. The reveal-pan watch's touch flag now holds through a report that comes while a finger is on the screen. In Firefox the toolbar hides in a drag, which changes the measured keyboard height mid-drag; the watch then took the drag's own pan for the browser's and put it back. The input stream now counts the fingers on the screen from touch events (`isTouchOnScreen`), only while `touchend` and `touchcancel` are heard. A native pan keeps a finger there, though its `pointercancel` drops the press from `getDownPresses`, so that record cannot serve. The watch's shared touch subscription hears those two types, and a report reads the count. After the show's first reveal, a keyboard report reveals nothing while a press that started after the last reveal is down. In Firefox the toolbar hides in a drag, and the reveal re-applied itself with small scrolls under the person's finger. The report's height is kept, so the field stays where the person put it, and a later report with the finger up reveals it as before. The press that focused the field holds nothing: a long press focuses with the finger still down, and Gboard can report a 48 px keyboard first, then its full height. The input stream also counts the touches that start (`getTouchStartCount`), and each reveal notes that count. The keyboard module reads the finger count through `isFingerOnScreen`: a finger down at the keyboard's last hide counts no more until a touch starts, since a touch whose target leaves the page ends at a node the window never hears. The count includes a stylus, whose drag moves the page as a finger does. Nine unit tests cover the scroll back from the blur on iOS: it starts at the blur and the report moves nothing more; focus that moves on to another field or into a frame keeps the page; a finger on the screen at the blur leaves it to the report; a person's scroll stands; Reduce Motion waits for the report; a field focused again during the slide stops the scroll back and rises from where the page is, or stays where a touch stopped it with nothing left to raise; and the next close goes back to the first place, at a blur or at a report. Six unit tests cover the scroll back: the page's smooth scroll at the report (nothing before it), Reduce Motion, a theme that reduces motion, a person's scroll kept, a scroll area after Back, and a focus move to another field. Firefox-shaped cases carry the reveal as an offset and close the keyboard before the fold: the scroll back follows the fold, a touch-drag control keeps the page, only the first document scroll counts, and each way the wait ends leaves no scroll listener. Safari's and Chrome's close sequences still decide at the report, with no wait. A Firefox-shaped drag grows the viewport twice with the finger down and finds no put-back; after the finger is up, a browser pan is put back. Another drags the page with the toolbar hiding twice and finds no reveal scroll until the finger is up. A long press focuses the field while Gboard grows from 48 to 290 px, and the field is revealed at 290; the next show's first reveal runs again under the same press, and a press that starts after the reveal holds the next report until it lifts. After the keyboard goes with no finger down, a long press that brings it back is revealed with that press still down. Another holds a report while the long press's finger stays down after a second finger tapped and lifted. Another misses a touch's end, as when its target leaves the page, and finds a browser pan put back once the keyboard has hidden and shown again. The input stream's tests count fingers through a second finger, a cancel and a native pan's `pointercancel`, count nothing while a touch end could go unheard, and count the touches that start. Six cover the rise on iOS: its smooth scroll, Reduce Motion, a theme that reduces motion, the scroll back after a rise drawn later, a rise carried on at a new height, and no second reveal while a scroll area's rise is drawn. Their CSS.supports stub answers both of Safari's forms, a property and value or a condition. Another drives a scroll area with a smooth `scroll-behavior` and finds its own `scrollBy` called at once. Two in the motion module cover `reducesMotion`: the setting, and a theme that reduces motion for everyone. --- .changeset/inputs-stay-above-keyboard.md | 7 + apps/sandbox/scripts/next-export-routes.json | 1 + .../pages/mobile-keyboard-fields/page.tsx | 46 + apps/storybook/stories/TextInput.stories.tsx | 362 +++++ .../core/src/BottomSheet/BottomSheet.doc.mjs | 2 +- .../NumberInput/NumberInput.keyboard.test.tsx | 185 +++ packages/core/src/NumberInput/NumberInput.tsx | 2 + .../src/TextArea/TextArea.keyboard.test.tsx | 185 +++ packages/core/src/TextArea/TextArea.tsx | 2 + .../src/TextInput/TextInput.keyboard.test.tsx | 185 +++ packages/core/src/TextInput/TextInput.tsx | 2 + packages/core/src/keyboard/README.md | 73 +- .../keyboard/__tests__/keyboardTestDouble.ts | 15 +- .../core/src/keyboard/keyboardHeight.test.ts | 12 +- packages/core/src/keyboard/keyboardHeight.ts | 160 ++- .../core/src/keyboard/keyboardScrollBack.ts | 298 ++++ .../src/keyboard/keyboardTarget.guide.test.ts | 160 ++- .../core/src/keyboard/keyboardTarget.test.ts | 1234 ++++++++++++++++- packages/core/src/keyboard/keyboardTarget.ts | 437 +++++- .../core/src/keyboard/useMobileKeyboard.ts | 8 +- packages/core/src/motion/README.md | 3 +- .../core/src/motion/reducedMotion.test.ts | 27 +- packages/core/src/motion/reducedMotion.ts | 15 +- packages/core/src/utils/inputStream.test.ts | 73 + packages/core/src/utils/inputStream.ts | 82 +- packages/core/src/utils/touchQueries.ts | 5 +- 26 files changed, 3440 insertions(+), 141 deletions(-) create mode 100644 .changeset/inputs-stay-above-keyboard.md create mode 100644 apps/sandbox/src/app/(raw)/pages/mobile-keyboard-fields/page.tsx create mode 100644 packages/core/src/NumberInput/NumberInput.keyboard.test.tsx create mode 100644 packages/core/src/TextArea/TextArea.keyboard.test.tsx create mode 100644 packages/core/src/TextInput/TextInput.keyboard.test.tsx create mode 100644 packages/core/src/keyboard/keyboardScrollBack.ts diff --git a/.changeset/inputs-stay-above-keyboard.md b/.changeset/inputs-stay-above-keyboard.md new file mode 100644 index 0000000000000..4826218a47b89 --- /dev/null +++ b/.changeset/inputs-stay-above-keyboard.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[feat] On a phone or tablet, TextInput, TextArea and NumberInput keep themselves above the on-screen keyboard, with nothing to turn on. A field in a page that scrolls is scrolled 10 px above the keyboard as it opens, rising with the keyboard on iOS and at once under Reduce Motion; on a page with nothing to scroll, the browser's own reveal stays. When the keyboard closes, the page or scroll area goes back to where it was, sliding down with the keyboard on iOS, unless the person scrolled it meanwhile. A field in a scrolling area is scrolled 10 px above the keyboard when the area can bring it there; otherwise the page brings it into view. A field in a bar fixed at the bottom of the viewport rides up with the keyboard, the bar's bottom on the keyboard's top, and back down when it closes, even in a bar the app owns. A field inside a fully expanded Tall BottomSheet leaves that to the sheet. In a fixed container the app positions itself, such as a full-viewport dialog, a floating bar or a bar with its own `translate`, a scroller around the field brings it above the keyboard when it can; otherwise the page brings it into view, or the browser's own reveal does. In Firefox for Android, where the page cannot scroll further, a field the page should bring into view can stay under the keyboard. Nothing changes under a mouse or a trackpad. + +@vjeux diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json index 0f338a474bee2..a1fbf9ab3f411 100644 --- a/apps/sandbox/scripts/next-export-routes.json +++ b/apps/sandbox/scripts/next-export-routes.json @@ -24,6 +24,7 @@ "/pages/markdown-perf/", "/pages/media-mode/", "/pages/mega-menu/", + "/pages/mobile-keyboard-fields/", "/pages/mobile-prototypes/", "/pages/mobile-spacing/", "/pages/mobile-type/", diff --git a/apps/sandbox/src/app/(raw)/pages/mobile-keyboard-fields/page.tsx b/apps/sandbox/src/app/(raw)/pages/mobile-keyboard-fields/page.tsx new file mode 100644 index 0000000000000..98ff59056072c --- /dev/null +++ b/apps/sandbox/src/app/(raw)/pages/mobile-keyboard-fields/page.tsx @@ -0,0 +1,46 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file page.tsx + * @position Mobile keyboard fields: an unframed page for checking fields with + * a phone's on-screen keyboard. The document itself scrolls, with no inner + * scroll box, and the fields sit in the middle of the page. + * @input TextInput, NumberInput and TextArea + * @output A tall page with three fields between an intro and a tail + */ + +'use client'; + +import {useState} from 'react'; +import * as stylex from '@stylexjs/stylex'; +import {VStack} from '@astryxdesign/core/Layout'; +import {NumberInput} from '@astryxdesign/core/NumberInput'; +import {Heading, Text} from '@astryxdesign/core/Text'; +import {TextArea} from '@astryxdesign/core/TextArea'; +import {TextInput} from '@astryxdesign/core/TextInput'; + +const styles = stylex.create({ + intro: {minHeight: '60dvh'}, + tail: {minHeight: '60dvh'}, +}); + +export default function MobileKeyboardFieldsPage() { + const [title, setTitle] = useState(''); + const [quantity, setQuantity] = useState(null); + const [notes, setNotes] = useState(''); + return ( + + + Mobile keyboard + + Focus a field in the middle of the page, then close the keyboard. The + page scrolls the field above the keyboard, and back when it closes. + + + + +